repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/RsNamesValidator.kt | 2 | 1152 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import com.intellij.lang.refactoring.NamesValidator
import com.intellij.openapi.project.Project
import org.rust.lang.core.lexer.getRustLexerTokenType
import org.rust.lang.core.psi.RS_KEYWORDS
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER
class RsNamesValidator : NamesValidator {
override fun isKeyword(name: String, project: Project?): Boolean = isKeyword(name)
override fun isIdentifier(name: String, project: Project?): Boolean = isIdentifier(name)
companion object {
val RESERVED_LIFETIME_NAMES: Set<String> = setOf("'static", "'_")
fun isIdentifier(name: String): Boolean = when (name.getRustLexerTokenType()) {
IDENTIFIER, QUOTE_IDENTIFIER -> true
else -> false
}
fun isKeyword(name: String): Boolean = name.getRustLexerTokenType() in RS_KEYWORDS
}
}
fun isValidRustVariableIdentifier(name: String): Boolean = name.getRustLexerTokenType() == IDENTIFIER
| mit | 6f8e1e35df4c92504d8ba06ac5fb2ff2 | 33.909091 | 101 | 0.733507 | 4.114286 | false | false | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/reports/tags/TagsReportView.kt | 1 | 3204 | /*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.reports.tags
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.FrameLayout
import com.mvcoding.expensius.extension.doNotInEditMode
import com.mvcoding.expensius.extension.setGone
import com.mvcoding.expensius.extension.setVisible
import com.mvcoding.expensius.feature.BaseAdapter
import com.mvcoding.expensius.feature.ViewHolder
import com.mvcoding.expensius.feature.reports.provideTagsReportPresenter
import com.mvcoding.expensius.model.GroupedMoney
import com.mvcoding.expensius.model.NullModels.noMoney
import com.mvcoding.expensius.model.Tag
import com.mvcoding.expensius.model.TagsReport
import kotlinx.android.synthetic.main.view_tags_report.view.*
import java.math.BigDecimal
class TagsReportView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr), TagsReportPresenter.View {
private val presenter by lazy { provideTagsReportPresenter() }
private val adapter by lazy { Adapter() }
override fun onFinishInflate() {
super.onFinishInflate()
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean = !isEnabled
override fun onAttachedToWindow() {
super.onAttachedToWindow()
doNotInEditMode { presenter.attach(this) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
presenter.detach(this)
}
override fun showTagsReport(tagsReport: TagsReport) {
adapter.maxMoneyAmount = (tagsReport.currentMoneys.firstOrNull()?.money ?: noMoney).amount
adapter.setItems(tagsReport.currentMoneys)
}
override fun showEmptyView(): Unit = emptyTextView.setVisible()
override fun hideEmptyView(): Unit = emptyTextView.setGone()
private class Adapter : BaseAdapter<GroupedMoney<Tag>, ViewHolder>() {
var maxMoneyAmount: BigDecimal = BigDecimal.ONE
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(TagMoneyItemView.inflate(parent))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val view = holder.getView<TagMoneyItemView>()
val item = getItem(position)
view.setTag(item.group)
view.setMoney(item.money)
view.setProgress(item.money.amount.toFloat() / maxMoneyAmount.toFloat())
}
}
} | gpl-3.0 | 33734ed731bc5b9b8b4fb51a81d9fd22 | 38.567901 | 120 | 0.751248 | 4.643478 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/fragments/__DisplayHttpBlockFragment.kt | 1 | 12336 | package com.exyui.android.debugbottle.components.fragments
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.annotation.IdRes
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.*
import com.exyui.android.debugbottle.components.R
import com.exyui.android.debugbottle.components.okhttp.HttpBlock
import com.exyui.android.debugbottle.components.okhttp.HttpBlockDetailAdapter
import com.exyui.android.debugbottle.components.okhttp.HttpBlockFileMgr
import com.exyui.android.debugbottle.components.okhttp.DisplayHttpBlockActivity
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/**
* Created by yuriel on 9/3/16.
*/
class __DisplayHttpBlockFragment: __ContentFragment() {
private var rootView: ViewGroup? = null
private val mBlockEntries: MutableList<HttpBlock> by lazy { ArrayList<HttpBlock>() }
private var mBlockStartTime: String? = null
private val mListView by lazy { findViewById(R.id.__dt_canary_display_leak_list) as ListView }
private val mFailureView by lazy { findViewById(R.id.__dt_canary_display_leak_failure) as TextView }
private val mActionButton by lazy { findViewById(R.id.__dt_canary_action) as Button }
private val mMaxStoredBlockCount by lazy { resources.getInteger(R.integer.__block_canary_max_stored_count) }
companion object {
private val TAG = "__DisplayBlockActivity"
private val SHOW_BLOCK_EXTRA = "show_latest"
val SHOW_BLOCK_EXTRA_KEY = "BlockStartTime"
@JvmOverloads fun createPendingIntent(context: Context, blockStartTime: String? = null): PendingIntent {
val intent = Intent(context, DisplayHttpBlockActivity::class.java)
intent.putExtra(SHOW_BLOCK_EXTRA, blockStartTime)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
return PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
internal fun classSimpleName(className: String): String {
val separator = className.lastIndexOf('.')
return if (separator == -1) {
className
} else {
className.substring(separator + 1)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (savedInstanceState != null) {
mBlockStartTime = savedInstanceState.getString(SHOW_BLOCK_EXTRA_KEY)
} else {
val intent = context?.intent
if (intent?.hasExtra(SHOW_BLOCK_EXTRA) == true) {
mBlockStartTime = intent!!.getStringExtra(SHOW_BLOCK_EXTRA)
}
}
val rootView = inflater.inflate(R.layout.__dt_canary_display_leak_light, container, false)
this.rootView = rootView as ViewGroup
setHasOptionsMenu(true)
updateUi()
return rootView
}
// No, it's not deprecated. Android lies.
// override fun onRetainNonConfigurationInstance(): Any {
// return mBlockEntries as Any
// }
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(SHOW_BLOCK_EXTRA_KEY, mBlockStartTime)
}
override fun onResume() {
super.onResume()
LoadBlocks.load(this)
}
override fun onDestroy() {
super.onDestroy()
LoadBlocks.forgetActivity()
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
val block = getBlock(mBlockStartTime)
if (block != null) {
menu.add(R.string.__block_canary_share_leak).setOnMenuItemClickListener {
shareBlock(block)
true
}
menu.add(R.string.__block_canary_share_stack_dump).setOnMenuItemClickListener {
shareHeapDump(block)
true
}
//return true
}
//return false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
mBlockStartTime = null
updateUi()
}
return true
}
override fun onBackPressed(): Boolean {
return if (mBlockStartTime != null) {
mBlockStartTime = null
updateUi()
true
} else {
super.onBackPressed()
}
}
private fun shareBlock(block: HttpBlock) {
val leakInfo = block.toString()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, leakInfo)
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun shareHeapDump(block: HttpBlock) {
val heapDumpFile = block.file
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
heapDumpFile?.setReadable(true, false)
}
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/octet-stream"
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(heapDumpFile))
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun updateUi() {
val block = getBlock(mBlockStartTime)
if (block == null) {
mBlockStartTime = null
}
// Reset to defaults
mListView.visibility = View.VISIBLE
mFailureView.visibility = View.GONE
if (block != null) {
renderBlockDetail(block)
} else {
renderBlockList()
}
}
private fun renderBlockList() {
val listAdapter = mListView.adapter
if (listAdapter is BlockListAdapter) {
listAdapter.notifyDataSetChanged()
} else {
val adapter = BlockListAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
mBlockStartTime = mBlockEntries[position].timeStart.toString()
updateUi()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(false)
}
//title = "Http Listener"
mActionButton.setText(R.string.__block_canary_delete_all)
mActionButton.setOnClickListener {
HttpBlockFileMgr.deleteLogFiles()
mBlockEntries.clear()
updateUi()
}
}
mActionButton.visibility = if (mBlockEntries.isEmpty()) View.GONE else View.VISIBLE
}
private fun renderBlockDetail(block: HttpBlock?) {
val listAdapter = mListView.adapter
val adapter: HttpBlockDetailAdapter
if (listAdapter is HttpBlockDetailAdapter) {
adapter = listAdapter
} else {
adapter = HttpBlockDetailAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
adapter.toggleRow(position)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(true)
}
mActionButton.visibility = View.VISIBLE
mActionButton.setText(R.string.__block_canary_delete)
mActionButton.setOnClickListener {
if (block != null) {
block.file?.delete()
mBlockStartTime = null
mBlockEntries.remove(block)
updateUi()
}
}
}
adapter.update(block)
//title = "${block?.method}: ${block?.url}"
}
private fun getBlock(startTime: String?): HttpBlock? {
if (TextUtils.isEmpty(startTime)) {
return null
}
return mBlockEntries.firstOrNull { it.timeStart.toString() == startTime }
}
private fun findViewById(@IdRes id: Int): View? = rootView?.findViewById(id)
internal inner class BlockListAdapter : BaseAdapter() {
override fun getCount(): Int = mBlockEntries.size
override fun getItem(position: Int): HttpBlock = mBlockEntries[position]
override fun getItemId(position: Int): Long = position.toLong()
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_block_row, parent, false)
}
val titleView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView
val timeView = view.findViewById(R.id.__dt_canary_row_time) as TextView
val block = getItem(position)
val index: String = if (position == 0 && mBlockEntries.size == mMaxStoredBlockCount) {
"MAX. "
} else {
"${mBlockEntries.size - position}. "
}
val title = "${block.responseCode}. ${block.method} ${block.url.split("?")[0].replace("http://", "").replace("https://", "")}"
titleView.text = title
timeView.text = "${block.time}ms"
if (block.responseCode.startsWith("2")) {
titleView.setTextColor(Color.parseColor("#DE1B5E20"))
} else if (block.responseCode.startsWith("4") || block.responseCode.startsWith("5")) {
titleView.setTextColor(Color.parseColor("#DED50000"))
} else if (block.responseCode.startsWith("3")) {
titleView.setTextColor(Color.parseColor("#DEFF6D00"))
}
return view
}
}
internal class LoadBlocks(private var fragmentOrNull: __DisplayHttpBlockFragment?) : Runnable {
private val mainHandler: Handler = Handler(Looper.getMainLooper())
override fun run() {
val blocks = ArrayList<HttpBlock>()
val files = HttpBlockFileMgr.logFiles
if (files != null) {
for (blockFile in files) {
try {
blocks.add(HttpBlock.newInstance(blockFile))
} catch (e: Exception) {
// Likely a format change in the blockFile
blockFile.delete()
Log.e(TAG, "Could not read block log file, deleted :" + blockFile, e)
}
}
Collections.sort(blocks) { lhs, rhs ->
rhs.file?.lastModified()?.compareTo((lhs.file?.lastModified())?: 0L)?: 0
}
}
mainHandler.post {
inFlight.remove(this@LoadBlocks)
if (fragmentOrNull != null) {
fragmentOrNull!!.mBlockEntries.clear()
fragmentOrNull!!.mBlockEntries.addAll(blocks)
//Log.d("BlockCanary", "load block entries: " + blocks.size());
fragmentOrNull!!.updateUi()
}
}
}
companion object {
val inFlight: MutableList<LoadBlocks> = ArrayList()
private val backgroundExecutor: Executor = Executors.newSingleThreadExecutor()
fun load(activity: __DisplayHttpBlockFragment) {
val loadBlocks = LoadBlocks(activity)
inFlight.add(loadBlocks)
backgroundExecutor.execute(loadBlocks)
}
fun forgetActivity() {
for (loadBlocks in inFlight) {
loadBlocks.fragmentOrNull = null
}
inFlight.clear()
}
}
}
} | apache-2.0 | 07b629676638b04c2ef4a31636ce6c06 | 36.49848 | 138 | 0.599303 | 4.968184 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-data/src/main/java/android/support/wearable/watchface/WatchFaceStyle.kt | 3 | 5807 | /*
* Copyright 2020 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 android.support.wearable.watchface
import android.content.ComponentName
import android.graphics.Color
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.ColorInt
import androidx.annotation.RestrictTo
/**
* A style descriptor for watch faces.
*
* <p>Parameters here affect how the system UI will be drawn over a watch face. An instance of this
* class should be passed in to [WatchFaceService.Engine.setWatchFaceStyle] in the `onCreate`
* method of your [WatchFaceService.Engine.onCreate] override.
*
* <p>To construct a WatchFaceStyle use [WatchFaceStyle.Builder].
*
* @hide
*/
@SuppressWarnings("BanParcelableUsage")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open class WatchFaceStyle(
public val component: ComponentName,
public val viewProtectionMode: Int,
public val statusBarGravity: Int,
@ColorInt public val accentColor: Int,
public val showUnreadCountIndicator: Boolean,
public val hideNotificationIndicator: Boolean,
public val acceptsTapEvents: Boolean,
/**
* Escape hatch needed by WearOS to implement backwards compatibility. Note WearOS support for
* obsolete WatchFaceStyle properties may be removed without notice.
*/
public val compatBundle: Bundle? = null
) : Parcelable {
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeBundle(
Bundle().apply {
putParcelable(Constants.KEY_COMPONENT, component)
putInt(Constants.KEY_VIEW_PROTECTION_MODE, viewProtectionMode)
putInt(Constants.KEY_STATUS_BAR_GRAVITY, statusBarGravity)
putInt(Constants.KEY_ACCENT_COLOR, accentColor)
putBoolean(Constants.KEY_SHOW_UNREAD_INDICATOR, showUnreadCountIndicator)
putBoolean(Constants.KEY_HIDE_NOTIFICATION_INDICATOR, hideNotificationIndicator)
putBoolean(Constants.KEY_ACCEPTS_TAPS, acceptsTapEvents)
compatBundle?.let {
putAll(compatBundle)
}
}
)
}
override fun describeContents(): Int = 0
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as WatchFaceStyle
if (component != other.component) return false
if (viewProtectionMode != other.viewProtectionMode) return false
if (statusBarGravity != other.statusBarGravity) return false
if (accentColor != other.accentColor) return false
if (showUnreadCountIndicator != other.showUnreadCountIndicator) return false
if (hideNotificationIndicator != other.hideNotificationIndicator) return false
if (acceptsTapEvents != other.acceptsTapEvents) return false
return true
}
override fun hashCode(): Int {
var result = component.hashCode()
result = 31 * result + viewProtectionMode
result = 31 * result + statusBarGravity
result = 31 * result + accentColor
result = 31 * result + showUnreadCountIndicator.hashCode()
result = 31 * result + hideNotificationIndicator.hashCode()
result = 31 * result + acceptsTapEvents.hashCode()
return result
}
public companion object {
public const val DEFAULT_ACCENT_COLOR: Int = Color.WHITE
/**
* Whether to put a semi-transparent black background behind the status bar to make it visible
* on white backgrounds.
*/
public const val PROTECT_STATUS_BAR: Int = 0x1
/**
* Whether to put a semi-transparent black background behind the "Ok Google" string to make it
* visible on a white background.
*/
public const val PROTECT_HOTWORD_INDICATOR: Int = 0x2
/**
* Whether to dim the entire watch face background slightly so the time and icons are always
* visible.
*/
public const val PROTECT_WHOLE_SCREEN: Int = 0x4
/** Parcelable Creator */
@JvmField
@Suppress("DEPRECATION")
public val CREATOR: Parcelable.Creator<WatchFaceStyle> =
object : Parcelable.Creator<WatchFaceStyle> {
override fun createFromParcel(parcel: Parcel): WatchFaceStyle {
val bundle = parcel.readBundle(this::class.java.classLoader)!!
return WatchFaceStyle(
bundle.getParcelable(Constants.KEY_COMPONENT)!!,
bundle.getInt(Constants.KEY_VIEW_PROTECTION_MODE),
bundle.getInt(Constants.KEY_STATUS_BAR_GRAVITY),
bundle.getInt(Constants.KEY_ACCENT_COLOR, DEFAULT_ACCENT_COLOR),
bundle.getBoolean(Constants.KEY_SHOW_UNREAD_INDICATOR),
bundle.getBoolean(Constants.KEY_HIDE_NOTIFICATION_INDICATOR),
bundle.getBoolean(Constants.KEY_ACCEPTS_TAPS),
bundle
)
}
override fun newArray(size: Int) = arrayOfNulls<WatchFaceStyle?>(size)
}
}
}
| apache-2.0 | 6fb62021f9add9e4cb4dd5b9434eb4e5 | 38.773973 | 102 | 0.659549 | 4.883936 | false | false | false | false |
androidx/androidx | compose/lint/internal-lint-checks/src/main/java/androidx/compose/lint/UnnecessaryLambdaCreationDetector.kt | 3 | 7959 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.compose.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.uast.ULambdaExpression
import org.jetbrains.uast.UVariable
import org.jetbrains.uast.kotlin.KotlinUBlockExpression
import org.jetbrains.uast.kotlin.KotlinUFunctionCallExpression
import org.jetbrains.uast.kotlin.KotlinUImplicitReturnExpression
import org.jetbrains.uast.kotlin.UnknownKotlinExpression
import org.jetbrains.uast.skipParenthesizedExprDown
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.tryResolve
/**
* Lint [Detector] to ensure that we are not creating extra lambdas just to emit already captured
* lambdas inside Compose code. For example:
* ```
* val lambda = @Composable {}
* Foo {
* lambda()
* }
* ```
*
* Can just be inlined to:
* ```
* Foo(lambda)
* ```
*
* This helps avoid object allocation but more importantly helps us avoid extra code generation
* around composable lambdas.
*/
class UnnecessaryLambdaCreationDetector : Detector(), SourceCodeScanner {
override fun createUastHandler(context: JavaContext) = UnnecessaryLambdaCreationHandler(context)
override fun getApplicableUastTypes() = listOf(ULambdaExpression::class.java)
/**
* This handler visits every lambda expression and reports an issue if the following criteria
* (in order) hold true:
*
* 1. There is only one expression inside the lambda.
* 2. The expression is a function call
* 3. The lambda is being invoked as part of a function call, and not as a property assignment
* such as val foo = @Composable {}
* 4. The receiver type of the function call is `Function0` (i.e, we are invoking something
* that matches `() -> Unit` - this both avoids non-lambda invocations but also makes sure
* that we don't warn for lambdas that have parameters, such as @Composable (Int) -> Unit
* - this cannot be inlined.)
* 5. The outer function call that contains this lambda is not a call to a `LayoutNode`
* (because these are technically constructor invocations that we just intercept calls to
* there is no way to avoid using a trailing lambda for this)
* 6. The lambda is not being passed as a parameter, for example `Foo { lambda -> lambda() }`
*/
class UnnecessaryLambdaCreationHandler(private val context: JavaContext) : UElementHandler() {
override fun visitLambdaExpression(node: ULambdaExpression) {
val expressions = (node.body as? KotlinUBlockExpression)?.expressions ?: return
if (expressions.size != 1) return
val expression = when (val expr = expressions.first().skipParenthesizedExprDown()) {
is KotlinUFunctionCallExpression -> expr
is KotlinUImplicitReturnExpression ->
expr.returnExpression as? KotlinUFunctionCallExpression
else -> null
} ?: return
// This is the parent function call that contains the lambda expression.
// I.e in Foo { bar() } this will be the call to `Foo`.
// We want to make sure this lambda is being invoked in the context of a function call,
// and not as a property assignment - so we cast to KotlinUFunctionCallExpression to
// filter out such cases.
val parentExpression = (node.uastParent as? KotlinUFunctionCallExpression) ?: return
// If we can't resolve the parent call, then the parent function is defined in a
// separate module, so we don't have the right metadata - and hence the argumentType
// below will be Function0 even if in the actual source it has a scope. Return early to
// avoid false positives.
parentExpression.resolve() ?: return
// If the expression has no receiver, it is not a lambda invocation
val functionType = expression.receiverType as? PsiClassReferenceType ?: return
// Find the functional type of the parent argument, for example () -> Unit (Function0)
val argumentType = node.getExpressionType() as? PsiClassReferenceType ?: return
// Return if the receiver of the lambda argument and the lambda itself don't match. This
// happens if the functional types are different, for example a lambda with 0 parameters
// (Function0) and a lambda with 1 parameter (Function1). Similarly for two lambdas
// with 0 parameters, but one that has a receiver scope (SomeScope.() -> Unit).
if (functionType != argumentType) return
val expectedComposable = node.isComposable
// Try and get the UElement for the source of the lambda
val resolvedLambdaSource = expression.sourcePsi.calleeExpression?.toUElement()
?.tryResolve()?.toUElement()
// Sometimes the above will give us a method (representing the getter for a
// property), when the actual backing element is a property. Going to the source
// and back should give us the actual UVariable we are looking for.
?.sourcePsi.toUElement()
val isComposable = when (resolvedLambdaSource) {
is UVariable -> resolvedLambdaSource.isComposable
// TODO: if the resolved source is a parameter in a local function, it
// incorrectly returns an UnknownKotlinExpression instead of a UParameter
// https://youtrack.jetbrains.com/issue/KTIJ-19125
is UnknownKotlinExpression -> return
else -> error(parentExpression.asSourceString())
}
if (isComposable != expectedComposable) return
context.report(
ISSUE,
node,
context.getNameLocation(expression),
"Creating an unnecessary lambda to emit a captured lambda"
)
}
}
companion object {
private const val Explanation =
"Creating this extra lambda instead of just passing the already captured lambda means" +
" that during code generation the Compose compiler will insert code around " +
"this lambda to track invalidations. This adds some extra runtime cost so you" +
" should instead just directly pass the lambda as a parameter to the function."
val ISSUE = Issue.create(
"UnnecessaryLambdaCreation",
"Creating an unnecessary lambda to emit a captured lambda",
Explanation,
Category.PERFORMANCE, 5, Severity.ERROR,
Implementation(
UnnecessaryLambdaCreationDetector::class.java,
Scope.JAVA_FILE_SCOPE
)
)
}
}
| apache-2.0 | ab7dd456180da8d7a3dfd330df98678a | 46.375 | 100 | 0.678603 | 5.053333 | false | false | false | false |
mikrobi/TransitTracker_android | app/src/main/java/de/jakobclass/transittracker/services/vehicles/VehicleParsingTask.kt | 1 | 3489 | package de.jakobclass.transittracker.services.vehicles
import android.os.AsyncTask
import de.jakobclass.transittracker.models.Position
import de.jakobclass.transittracker.models.Vehicle
import de.jakobclass.transittracker.models.VehicleType
import de.jakobclass.transittracker.utilities.LatLng
import de.jakobclass.transittracker.utilities.let
import org.json.JSONException
import org.json.JSONObject
import java.lang.ref.WeakReference
import java.util.*
interface VehicleParsingTaskDelegate {
val vehicles: Map<String, Vehicle>
fun addOrUpdateVehiclesAndPositions(vehiclesAndPositions: Map<Vehicle, LinkedList<Position>>)
}
class VehicleParsingTask(delegate: VehicleParsingTaskDelegate): AsyncTask<JSONObject, Void, Map<Vehicle, LinkedList<Position>>>() {
var delegate: VehicleParsingTaskDelegate?
get() = delegateReference.get()
set(value) { delegateReference = WeakReference<VehicleParsingTaskDelegate>(value)
}
private var delegateReference = WeakReference<VehicleParsingTaskDelegate>(null)
init {
this.delegate = delegate
}
override fun doInBackground(vararg data: JSONObject?): Map<Vehicle, LinkedList<Position>>? {
return data.first()?.let { parseVehiclePositionsFromJSON(it) }
}
override fun onPostExecute(vehiclesAndPositions: Map<Vehicle, LinkedList<Position>>?) {
vehiclesAndPositions?.let { delegate?.addOrUpdateVehiclesAndPositions(it) }
}
private fun parseVehiclePositionsFromJSON(data: JSONObject): Map<Vehicle, LinkedList<Position>>? {
var vehiclePositions = mutableMapOf<Vehicle, LinkedList<Position>>()
val vehiclesData = data.getJSONArray("t")
for (i in 0..(vehiclesData.length() - 1)) {
if (isCancelled) {
return null
}
val vehicleData = vehiclesData.getJSONObject(i)
findOrCreateVehicle(vehicleData)?.let {
vehiclePositions[it] = getPositionsFromJSON(vehicleData)
}
}
return vehiclePositions
}
private fun findOrCreateVehicle(data: JSONObject): Vehicle? {
val vehicleId = data.getString("i")
return delegate?.vehicles?.get(vehicleId) ?: Vehicle(vehicleId, data)
}
private fun getPositionsFromJSON(data: JSONObject): LinkedList<Position> {
val positionsData = data.getJSONArray("p")
val positions = LinkedList<Position>()
for (i in 0..(positionsData.length() - 1)) {
val positionData = positionsData.getJSONObject(i)
Position(positionData)?.let { positions.add(it) }
}
return positions
}
}
fun Vehicle(vehicleId: String, data: JSONObject): Vehicle? {
try {
val vehicleType = VehicleType.fromCode(data.getInt("c"))
val position = Position(data)
return let(vehicleType, position) { vehicleType, position ->
val name = data.getString("n").trim()
val destination = data.getString("l")
return@let Vehicle(vehicleId, vehicleType, name, destination, position)
}
} catch (e: JSONException) {
return null
}
}
fun Position(data: JSONObject): Position? {
try {
val x = data.getInt("x")
val y = data.getInt("y")
var direction: Int? = null
if (data.has("d")) {
direction = data.getInt("d")
}
return Position(LatLng(x, y), direction)
} catch (e: JSONException) {
return null
}
} | gpl-3.0 | 22ba45d94108ca2923544fbca2031ca5 | 34.979381 | 131 | 0.672686 | 4.394207 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCBucketsFilled.kt | 1 | 2701 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.magic.BucketCode
import com.demonwav.statcraft.querydsl.QBucketFill
import com.demonwav.statcraft.querydsl.QPlayers
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCBucketsFilled(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("bucketsfilled", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.bucketsfilled")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Buckets Filled" }
stats["Total"] = "0"
stats["Water"] = "0"
stats["Lava"] = "0"
stats["Milk"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val f = QBucketFill.bucketFill
val results = query.from(f).where(f.id.eq(id)).list(f)
var water = 0
var lava = 0
var milk = 0
for (bucketFill in results) {
val code = BucketCode.fromCode(bucketFill.type) ?: continue
when (code) {
BucketCode.WATER -> water += bucketFill.amount
BucketCode.LAVA -> lava += bucketFill.amount
BucketCode.MILK -> milk += bucketFill.amount
}
}
val total = water + lava + milk
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Buckets Filled" }
stats["Total"] = df.format(total)
stats["Water"] = df.format(water)
stats["Lava"] = df.format(lava)
stats["Milk"] = df.format(milk)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val f = QBucketFill.bucketFill
val p = QPlayers.players
val result = query
.from(f)
.innerJoin(p)
.on(f.id.eq(p.id))
.groupBy(p.name)
.orderBy(f.amount.sum().desc())
.limit(num)
.list(p.name, f.amount.sum())
return topListResponse("Buckets Filled", result)
}
}
| mit | ff8c3e0957af5fb57db3fb939ca0f9d8 | 30.406977 | 134 | 0.608663 | 4.200622 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/navigation/StringStorage.kt | 1 | 1417 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.navigation
import org.eclipse.core.resources.IStorage
import org.eclipse.core.runtime.IPath
import java.io.InputStream
data class StringStorage(
private val content: String,
private val name: String,
private val packageFqName: String) : IStorage {
override fun getName(): String = name
override fun getContents(): InputStream? = content.byteInputStream()
override fun getFullPath(): IPath? = null
override fun <T> getAdapter(adapter: Class<T>?): T? = null
override fun isReadOnly(): Boolean = true
val fqName: String
get() = "$packageFqName/$name"
} | apache-2.0 | 8d14086552353b5f928263034179e465 | 34.45 | 81 | 0.637968 | 4.787162 | false | false | false | false |
vmiklos/vmexam | osm/addr-osmify-kotlin/src/test/kotlin/MockUrlopener.kt | 1 | 1363 | /*
* Copyright 2020 Miklos Vajna. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package hu.vmiklos.addr_osmify
import java.net.URLEncoder
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
/**
* Test urlopen(), using mocking.
*/
class MockUrlopener internal constructor(var urlopenSuffix: String) : Urlopener {
override fun urlopen(urlString: String, data: String): String {
if (!data.isEmpty()) {
var path = URLEncoder.encode(urlString, "UTF-8")
path = "mock/$path$urlopenSuffix.overpassql"
val content = readFile(path, StandardCharsets.UTF_8)
require(data == content) {
"data vs content mismatch: data is '" + data +
"', content is '" + content + "'"
}
}
var path = URLEncoder.encode(urlString, "UTF-8")
path = "mock/$path$urlopenSuffix"
return readFile(path, StandardCharsets.UTF_8)
}
companion object {
fun readFile(path: String, encoding: Charset): String {
val encoded = Files.readAllBytes(Paths.get(path))
return String(encoded, encoding)
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| mit | f0bf994f70227a0219ae7b5c6dd93cb5 | 31.452381 | 81 | 0.634629 | 3.883191 | false | false | false | false |
soulnothing/HarmonyGen | src/main/kotlin/HarmonyGen/Util/launcher.kt | 1 | 2571 | package HarmonyGen.Util
import HarmonyGen.HTTP.PlayList
import HarmonyGen.MusicAbstractor.getSimilarArtists
import com.wrapper.spotify.models.Track as SpotifyTrack
fun harmonizePlayList(playListConfig: PlayList) {
var usedArtist = listOf<String>("Empty")
var TrackList = emptyArray<SpotifyTrack>()
/*
var basePlayList = api.getPlaylistsForUser(user.id).build().get().items.filter { it.name == SpotifyPlaylist }.firstOrNull()
var playlist: com.wrapper.spotify.models.Playlist? = null
if (basePlayList == null) {
println("Playlist Doesn't exist creating")
playlist = api.createPlaylist(user.id, SpotifyPlaylist).build().get()
} else {
playlist = api.getPlaylist(user.id, basePlayList.id).build().get()
}
println("Using Playlist ${playlist.name} with an ID of ${playlist.id}")
if (config.get("HarmonyGen", "artists").trim() !== "") {
logger.info("Artists provided via config searching for similar artists")
val artists = config.get("HarmonyGen", "artists").split(",")
var SimilarArtist = emptyArray<Artist>()
for (artist in artists) {
var artist = artist.trim()
logger.info("\tSearching for ($artist)")
val similar = getSimilarArtists(artist, LastFMAPIKey)
SimilarArtist += similar
}
var usedIndice = listOf<Int>(-1)
println("\n\n\n\n\n\n\n\n")
println("========")
var allocated = false
for (i in 1..MaxTracks) {
if (allocated == true) break
var artist = Artist(Name = "Empty", Tracks = emptyList<Track>(), Genres = emptyList<String>())
while (artist.Name in usedArtist) {
val indice = getUnusedIndice(ceiling = SimilarArtist.size, unusedIndice = usedIndice)
if (indice in usedIndice) continue
usedIndice += indice
artist = SimilarArtist[indice]
if ((usedIndice.size - 1) == SimilarArtist.size) {
allocated = true
}
continue
}
val trackIndice = getUnusedIndice(ceiling = artist.Tracks.size, unusedIndice = listOf<Int>(-1))
val track = artist.Tracks[trackIndice]
val request = api.searchTracks("artist:${artist.Name} ${track.Name}").build()
println("${artist.Name}\t${track.Name}")
var trackSearchResult = request.get()
if (trackSearchResult.items.size > 0) {
TrackList += trackSearchResult.items.first()
}
}
TrackList.forEach {
println("\t\t${it.name} ${it.artists.first().name}")
}
api.addTracksToPlaylist(user.id, playlist.id, TrackList.map { it.uri }).position(0).build().get()
println("Exiting")
}
*/
} | bsd-3-clause | 2600af0c93147cd5dd08264305cd0c0b | 39.825397 | 125 | 0.661221 | 3.808889 | false | true | false | false |
CarlosEsco/tachiyomi | core/src/main/java/eu/kanade/tachiyomi/util/system/WebViewUtil.kt | 1 | 2010 | package eu.kanade.tachiyomi.util.system
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import logcat.LogPriority
object WebViewUtil {
const val SPOOF_PACKAGE_NAME = "org.chromium.chrome"
const val MINIMUM_WEBVIEW_VERSION = 102
fun supportsWebView(context: Context): Boolean {
try {
// May throw android.webkit.WebViewFactory$MissingWebViewPackageException if WebView
// is not installed
CookieManager.getInstance()
} catch (e: Throwable) {
logcat(LogPriority.ERROR, e)
return false
}
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)
}
}
fun WebView.isOutdated(): Boolean {
return getWebViewMajorVersion() < WebViewUtil.MINIMUM_WEBVIEW_VERSION
}
@SuppressLint("SetJavaScriptEnabled")
fun WebView.setDefaultSettings() {
with(settings) {
javaScriptEnabled = true
domStorageEnabled = true
databaseEnabled = true
useWideViewPort = true
loadWithOverviewMode = true
cacheMode = WebSettings.LOAD_DEFAULT
}
}
private fun WebView.getWebViewMajorVersion(): Int {
val uaRegexMatch = """.*Chrome/(\d+)\..*""".toRegex().matchEntire(getDefaultUserAgentString())
return if (uaRegexMatch != null && uaRegexMatch.groupValues.size > 1) {
uaRegexMatch.groupValues[1].toInt()
} else {
0
}
}
// Based on https://stackoverflow.com/a/29218966
private fun WebView.getDefaultUserAgentString(): String {
val originalUA: String = settings.userAgentString
// Next call to getUserAgentString() will get us the default
settings.userAgentString = null
val defaultUserAgentString = settings.userAgentString
// Revert to original UA string
settings.userAgentString = originalUA
return defaultUserAgentString
}
| apache-2.0 | ee6d74f35352465e23639068c82acfbf | 29 | 98 | 0.710448 | 4.685315 | false | false | false | false |
da1z/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/JavadocHtmlLintInspectionTest.kt | 5 | 3153 | // Copyright 2000-2017 JetBrains s.r.o.
// Use of this source code is governed by the Apache 2.0 license that can be
// found in the LICENSE file.
package com.intellij.java.codeInsight.daemon
import com.intellij.codeInspection.javaDoc.JavadocHtmlLintInspection
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import java.io.File
private val DESCRIPTOR = object : DefaultLightProjectDescriptor() {
override fun getSdk(): Sdk? {
val jreHome = File(System.getProperty("java.home"))
val jdkHome = if (jreHome.name == "jre") jreHome.parentFile else jreHome
return (JavaSdk.getInstance() as JavaSdkImpl).createMockJdk("java version \"1.8.0\"", jdkHome.path, false)
}
}
class JavadocHtmlLintInspectionTest : LightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = DESCRIPTOR
fun testNoComment() = doTest("class C { }")
fun testEmptyComment() = doTest("/** */\nclass C { }")
fun testCommonErrors() = doTest("""
package pkg;
/**
* <ul><error descr="Tag not allowed here: <p>"><p></error>Paragraph inside a list</p></ul>
*
* Empty paragraph: <error descr="Self-closing element not allowed"><p/></error>
*
* Line break: <error descr="Self-closing element not allowed"><br/></error>
* Another one: <br><error descr="Invalid end tag: </br>"></br></error>
* And the last one: <br> <error descr="Invalid end tag: </br>"></br></error>
*
* Missing open tag: <error descr="Unexpected end tag: </i>"></i></error>
*
* Unescaped angle brackets for generics: List<error descr="Unknown tag: String"><String></error>
* (closing it here to avoid further confusion: <error descr="Unknown tag: String"></String></error>)
* Correct: {@code List<String>}
*
* Unknown attribute: <br <error descr="Unknown attribute: a">a</error>="">
*
* <p <error descr="Invalid name for anchor: \"1\"">id</error>="1" <error descr="Repeated attribute: id">id</error>="2">Some repeated attributes</p>
*
* <p>Empty ref: <a <error descr="Attribute lacks value">href</error>="">link</a></p>
*
* <error descr="Header used out of sequence: <H4>"><h4></error>Incorrect header</h4>
*
* Unknown entity: <error descr="Invalid entity &wtf;">&wtf;</error>
*
* @see bad_link should report no error
*/
class C { }""".trimIndent())
fun testPackageInfo() = doTest("""
/**
* Another self-closed paragraph: <error descr="Self-closing element not allowed"><p/></error>
*/
package pkg;""".trimIndent(), "package-info.java")
private fun doTest(text: String, name: String? = null) {
myFixture.enableInspections(JavadocHtmlLintInspection())
myFixture.configureByText(name ?: "${getTestName(false)}.java", text)
myFixture.checkHighlighting(true, false, false)
}
} | apache-2.0 | 3fb6cbf0265d624f25ed0dc9fc7db85e | 42.805556 | 152 | 0.686013 | 4.042308 | false | true | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/domain/ui/UiPreferences.kt | 1 | 1593 | package eu.kanade.domain.ui
import android.os.Build
import eu.kanade.domain.ui.model.AppTheme
import eu.kanade.domain.ui.model.TabletUiMode
import eu.kanade.domain.ui.model.ThemeMode
import eu.kanade.tachiyomi.core.preference.PreferenceStore
import eu.kanade.tachiyomi.core.preference.getEnum
import eu.kanade.tachiyomi.util.system.DeviceUtil
import eu.kanade.tachiyomi.util.system.isDynamicColorAvailable
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Locale
class UiPreferences(
private val preferenceStore: PreferenceStore,
) {
fun sideNavIconAlignment() = preferenceStore.getInt("pref_side_nav_icon_alignment", 0)
fun themeMode() = preferenceStore.getEnum(
"pref_theme_mode_key",
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ThemeMode.SYSTEM } else { ThemeMode.LIGHT },
)
fun appTheme() = preferenceStore.getEnum(
"pref_app_theme",
if (DeviceUtil.isDynamicColorAvailable) { AppTheme.MONET } else { AppTheme.DEFAULT },
)
fun themeDarkAmoled() = preferenceStore.getBoolean("pref_theme_dark_amoled_key", false)
fun relativeTime() = preferenceStore.getInt("relative_time", 7)
fun dateFormat() = preferenceStore.getString("app_date_format", "")
fun tabletUiMode() = preferenceStore.getEnum("tablet_ui_mode", TabletUiMode.AUTOMATIC)
companion object {
fun dateFormat(format: String): DateFormat = when (format) {
"" -> DateFormat.getDateInstance(DateFormat.SHORT)
else -> SimpleDateFormat(format, Locale.getDefault())
}
}
}
| apache-2.0 | 336fdef83082afff1085956a2e4111fd | 34.4 | 106 | 0.730069 | 3.9825 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/slli.kt | 1 | 256 | package venus.riscv.insts
import venus.riscv.insts.dsl.ShiftImmediateInstruction
val slli = ShiftImmediateInstruction(
name = "slli",
funct3 = 0b001,
funct7 = 0b0000000,
eval32 = { a, b -> if (b == 0) a else (a shl b) }
)
| mit | ee802098204f5eafcc9b63a36ebafc20 | 24.6 | 57 | 0.621094 | 3.240506 | false | false | false | false |
Maccimo/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/CodeWithMeClientDownloader.kt | 1 | 30905 | package com.intellij.remoteDev.downloader
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileSystemUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.remoteDev.RemoteDevSystemSettings
import com.intellij.remoteDev.RemoteDevUtilBundle
import com.intellij.remoteDev.connection.CodeWithMeSessionInfoProvider
import com.intellij.remoteDev.connection.StunTurnServerInfo
import com.intellij.remoteDev.util.*
import com.intellij.util.application
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.EdtScheduledExecutorService
import com.intellij.util.io.*
import com.intellij.util.io.HttpRequests.HttpStatusException
import com.intellij.util.system.CpuArch
import com.intellij.util.text.VersionComparatorUtil
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifier
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifierLogger
import com.jetbrains.infra.pgpVerifier.Sha256ChecksumSignatureVerifier
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.fire
import com.sun.jna.platform.win32.Kernel32
import com.sun.jna.platform.win32.WinBase
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.ptr.IntByReference
import org.jetbrains.annotations.ApiStatus
import java.io.ByteArrayInputStream
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.FileTime
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import kotlin.io.path.*
import kotlin.math.min
@ApiStatus.Experimental
object CodeWithMeClientDownloader {
private val LOG = logger<CodeWithMeClientDownloader>()
private const val extractDirSuffix = "-ide"
private val config get () = service<JetBrainsClientDownloaderConfigurationProvider>()
private fun isJbrSymlink(file: Path): Boolean = file.name == "jbr" && isSymlink(file)
private fun isSymlink(file: Path): Boolean = FileSystemUtil.getAttributes(file.toFile())?.isSymLink == true
val cwmGuestManifestFilter: (Path) -> Boolean = { !isJbrSymlink(it) && (!it.isDirectory() || isSymlink(it)) }
val cwmJbrManifestFilter: (Path) -> Boolean = { !it.isDirectory() || isSymlink(it) }
private data class DownloadableFileData(
val fileName: String,
val url: URI,
val archivePath: Path,
val targetPath: Path,
val includeInManifest: (Path) -> Boolean,
val downloadFuture: CompletableFuture<Boolean> = CompletableFuture(),
var status: DownloadableFileState = DownloadableFileState.Downloading
)
private enum class DownloadableFileState {
Downloading,
Extracting,
Done
}
val buildNumberRegex = Regex("""[0-9]{3}\.(([0-9]+(\.[0-9]+)?)|SNAPSHOT)""")
private fun getClientDistributionName(clientBuildVersion: String) = when {
VersionComparatorUtil.compare(clientBuildVersion, "211.6167") < 0 -> "IntelliJClient"
VersionComparatorUtil.compare(clientBuildVersion, "213.5318") < 0 -> "CodeWithMeGuest"
else -> "JetBrainsClient"
}
fun createSessionInfo(clientBuildVersion: String, jreBuild: String, unattendedMode: Boolean): CodeWithMeSessionInfoProvider {
if ("SNAPSHOT" in clientBuildVersion) {
LOG.warn(
"Thin client download from sources may result in failure due to different sources on host and client, don't forget to update your locally built archive")
}
val hostBuildNumber = buildNumberRegex.find(clientBuildVersion)!!.value
val platformSuffix = when {
SystemInfo.isLinux && CpuArch.isIntel64() -> "-no-jbr.tar.gz"
SystemInfo.isLinux && CpuArch.isArm64() -> "-no-jbr-aarch64.tar.gz"
SystemInfo.isWindows -> ".win.zip"
SystemInfo.isMac && CpuArch.isIntel64() -> "-no-jdk.sit"
SystemInfo.isMac && CpuArch.isArm64() -> "-no-jdk-aarch64.sit"
else -> error("Current platform is not supported")
}
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientDownloadUrl = "${config.clientDownloadUrl}$clientDistributionName-$hostBuildNumber$platformSuffix"
val platformString = when {
SystemInfo.isLinux -> "linux-x64"
SystemInfo.isWindows -> "windows-x64"
SystemInfo.isMac && CpuArch.isIntel64() -> "osx-x64"
SystemInfo.isMac && CpuArch.isArm64() -> "osx-aarch64"
else -> error("Current platform is not supported")
}
val jreBuildParts = jreBuild.split("b")
require(jreBuildParts.size == 2) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuild}" }
require(jreBuildParts[0].matches(Regex("^[0-9_.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuild}" }
require(jreBuildParts[1].matches(Regex("^[0-9.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuild}" }
val jdkVersion = jreBuildParts[0]
val jdkBuild = jreBuildParts[1]
val jreDownloadUrl = "${config.jreDownloadUrl}jbr_jcef-$jdkVersion-$platformString-b${jdkBuild}.tar.gz"
val clientName = "$clientDistributionName-$hostBuildNumber"
val jreName = jreDownloadUrl.substringAfterLast('/').removeSuffix(".tar.gz")
val pgpPublicKeyUrl = if (unattendedMode) {
RemoteDevSystemSettings.getPgpPublicKeyUrl().value
} else null
val sessionInfo = object : CodeWithMeSessionInfoProvider {
override val hostBuildNumber = hostBuildNumber
override val compatibleClientName = clientName
override val compatibleClientUrl = clientDownloadUrl
override val compatibleJreName = jreName
override val isUnattendedMode = unattendedMode
override val compatibleJreUrl = jreDownloadUrl
override val hostFeaturesToEnable: Set<String>? = null
override val stunTurnServers: List<StunTurnServerInfo>? = null
override val downloadPgpPublicKeyUrl: String? = pgpPublicKeyUrl
}
LOG.info("Generated session info: $sessionInfo")
return sessionInfo
}
private val currentlyDownloading = ConcurrentHashMap<Path, CompletableFuture<Boolean>>()
@ApiStatus.Experimental
fun downloadClientAndJdk(clientBuildVersion: String,
progressIndicator: ProgressIndicator): Pair<Path, Path>? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
LOG.info("Downloading Thin Client jdk-build.txt")
val jdkBuildProgressIndicator = progressIndicator.createSubProgress(0.1)
jdkBuildProgressIndicator.text = RemoteDevUtilBundle.message("thinClientDownloader.checking")
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientJdkDownloadUrl = "${config.clientDownloadUrl}$clientDistributionName-$clientBuildVersion-jdk-build.txt"
LOG.info("Downloading from $clientJdkDownloadUrl")
val tempFile = Files.createTempFile("jdk-build", "txt")
val jdkBuild = try {
downloadWithRetries(URI(clientJdkDownloadUrl), tempFile, EmptyProgressIndicator()).let {
tempFile.readText()
}
} finally {
Files.delete(tempFile)
}
val sessionInfo = createSessionInfo(clientBuildVersion, jdkBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator.createSubProgress(0.9))
}
/**
* @param clientBuildVersion format: 213.1337[.23]
* @param jreBuild format: 11_0_11b1536.1
* where 11_0_11 is jdk version, b1536.1 is the build version
* @returns Pair(path/to/thin/client, path/to/jre)
*
* Update this method (any jdk-related stuff) together with:
* `org/jetbrains/intellij/build/impl/BundledJreManager.groovy`
*/
fun downloadClientAndJdk(clientBuildVersion: String,
jreBuild: String,
progressIndicator: ProgressIndicator): Pair<Path, Path>? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val sessionInfo = createSessionInfo(clientBuildVersion, jreBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator)
}
/**
* @returns Pair(path/to/thin/client, path/to/jre)
*/
fun downloadClientAndJdk(sessionInfoResponse: CodeWithMeSessionInfoProvider,
progressIndicator: ProgressIndicator): Pair<Path, Path>? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val tempDir = FileUtil.createTempDirectory("jb-cwm-dl", null).toPath()
LOG.info("Downloading Thin Client in $tempDir...")
fun archiveExtensionFromUrl(url: String) = when {
url.endsWith(".zip") -> "zip"
url.endsWith(".sit") -> "sit"
url.endsWith(".tar.gz") -> "tar.gz"
else -> error("Don't know how to extract archive downloaded from url $url")
}
val guestName = sessionInfoResponse.compatibleClientName
val guestFileName = "$guestName.${archiveExtensionFromUrl(sessionInfoResponse.compatibleClientUrl)}"
val guestData = DownloadableFileData(
fileName = guestFileName,
url = URI(sessionInfoResponse.compatibleClientUrl),
archivePath = tempDir.resolve(guestFileName),
targetPath = config.clientCachesDir / (guestName + extractDirSuffix),
includeInManifest = cwmGuestManifestFilter
)
val jdkFullName = sessionInfoResponse.compatibleJreName
val jdkFileName = "$jdkFullName.${archiveExtensionFromUrl(sessionInfoResponse.compatibleJreUrl)}"
val jdkData = DownloadableFileData(
fileName = jdkFileName,
url = URI(sessionInfoResponse.compatibleJreUrl),
archivePath = tempDir.resolve(jdkFileName),
targetPath = config.clientCachesDir / (jdkFullName + extractDirSuffix),
includeInManifest = cwmJbrManifestFilter
)
val dataList = arrayOf(jdkData, guestData)
val activity: StructuredIdeActivity? =
if (dataList.isNotEmpty()) RemoteDevStatisticsCollector.onGuestDownloadStarted()
else null
fun updateStateText() {
val downloadList = dataList.filter { it.status == DownloadableFileState.Downloading }.joinToString(", ") { it.fileName }
val extractList = dataList.filter { it.status == DownloadableFileState.Extracting }.joinToString(", ") { it.fileName }
progressIndicator.text =
if (downloadList.isNotBlank() && extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading.and.extracting", downloadList, extractList)
else if (downloadList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading", downloadList)
else if (extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.extracting", extractList)
else RemoteDevUtilBundle.message("thinClientDownloader.ready")
}
updateStateText()
val dataProgressIndicators = MultipleSubProgressIndicator.create(progressIndicator, dataList.size)
for ((index, data) in dataList.withIndex()) {
// download
val future = data.downloadFuture
// Update only fraction via progress indicator API, text will be updated by updateStateText function
val dataProgressIndicator = dataProgressIndicators[index]
AppExecutorUtil.getAppScheduledExecutorService().execute {
try {
val existingDownloadFuture = synchronized(currentlyDownloading) {
val existingDownloadInnerFuture = currentlyDownloading[data.targetPath]
if (existingDownloadInnerFuture != null) {
existingDownloadInnerFuture
}
else {
currentlyDownloading[data.targetPath] = data.downloadFuture
null
}
}
// TODO: how to merge progress indicators in this case?
if (existingDownloadFuture != null) {
LOG.warn("Already downloading and extracting to ${data.targetPath}, will wait until download finished")
existingDownloadFuture.whenComplete { res, ex ->
if (ex != null) {
future.completeExceptionally(ex)
}
else {
future.complete(res)
}
}
return@execute
}
if (isAlreadyDownloaded(data)) {
LOG.info("Already downloaded and extracted ${data.fileName} to ${data.targetPath}")
data.status = DownloadableFileState.Done
dataProgressIndicator.fraction = 1.0
updateStateText()
future.complete(true)
return@execute
}
val downloadingDataProgressIndicator = dataProgressIndicator.createSubProgress(0.5)
try {
fun download(url: URI, path: Path) {
downloadWithRetries(url, path, downloadingDataProgressIndicator)
}
download(data.url, data.archivePath)
LOG.info("Signature verification is ${if (config.verifySignature) "ON" else "OFF"}")
if (config.verifySignature) {
val pgpKeyRingFile = Files.createTempFile(tempDir, "KEYS", "")
download(URI(sessionInfoResponse.downloadPgpPublicKeyUrl ?: JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_SUB_KEYS_URL), pgpKeyRingFile)
val checksumPath = data.archivePath.addSuffix(SHA256_SUFFIX)
val signaturePath = data.archivePath.addSuffix(SHA256_ASC_SUFFIX)
download(data.url.addPathSuffix(SHA256_SUFFIX), checksumPath)
download(data.url.addPathSuffix(SHA256_ASC_SUFFIX), signaturePath)
val pgpVerifier = PgpSignaturesVerifier(object : PgpSignaturesVerifierLogger {
override fun info(message: String) {
LOG.info("Verifying ${data.url} PGP signature: $message")
}
})
LOG.info("Running checksum signature verifier for ${data.archivePath}")
Sha256ChecksumSignatureVerifier(pgpVerifier).verifyChecksumAndSignature(
file = data.archivePath,
detachedSignatureFile = signaturePath,
checksumFile = checksumPath,
expectedFileName = data.url.path.substringAfterLast('/'),
untrustedPublicKeyRing = ByteArrayInputStream(Files.readAllBytes(pgpKeyRingFile)),
trustedMasterKey = ByteArrayInputStream(JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY.toByteArray()),
)
LOG.info("Signature verified for ${data.archivePath}")
}
}
catch (ex: IOException) {
future.complete(false)
LOG.warn(ex)
return@execute
}
// extract
dataProgressIndicator.fraction = 0.75
data.status = DownloadableFileState.Extracting
updateStateText()
// downloading a .zip file will get a VirtualFile with a path of `jar://C:/Users/ivan.pashchenko/AppData/Local/Temp/CodeWithMeGuest-212.2033-windows-x64.zip!/`
// see FileDownloaderImpl.findVirtualFiles making a call to VfsUtil.getUrlForLibraryRoot(ioFile)
val archivePath = data.archivePath
LOG.info("Extracting $archivePath to ${data.targetPath}...")
FileUtil.delete(data.targetPath)
require(data.targetPath.notExists()) { "Target path \"${data.targetPath}\" for $archivePath already exists" }
FileManifestUtil.decompressWithManifest(archivePath, data.targetPath, data.includeInManifest)
require(FileManifestUtil.isUpToDate(data.targetPath, data.includeInManifest)) {
"Manifest verification failed for archive: $archivePath -> ${data.targetPath}"
}
dataProgressIndicator.fraction = 1.0
data.status = DownloadableFileState.Done
updateStateText()
Files.delete(archivePath)
future.complete(true)
}
catch (e: Throwable) {
future.complete(false)
LOG.warn(e)
}
finally {
synchronized(currentlyDownloading) {
currentlyDownloading.remove(data.targetPath)
}
}
}
}
try {
val guestSucceeded = guestData.downloadFuture.get()
val jdkSucceeded = jdkData.downloadFuture.get()
if (guestSucceeded && jdkSucceeded) {
RemoteDevStatisticsCollector.onGuestDownloadFinished(activity, isSucceeded = true)
LOG.info("Download of guest and jdk succeeded")
return guestData.targetPath to jdkData.targetPath
}
else {
LOG.warn("Some of downloads failed: guestSucceeded=$guestSucceeded, jdkSucceeded=$jdkSucceeded")
RemoteDevStatisticsCollector.onGuestDownloadFinished(activity, isSucceeded = false)
return null
}
}
catch(e: ProcessCanceledException) {
LOG.info("Download was canceled")
return null
}
catch (e: Throwable) {
LOG.warn(e)
return null
}
}
private fun isAlreadyDownloaded(fileData: DownloadableFileData): Boolean {
val extractDirectory = FileManifestUtil.getExtractDirectory(fileData.targetPath, fileData.includeInManifest)
return extractDirectory.isUpToDate && !fileData.targetPath.fileName.toString().contains("SNAPSHOT")
}
private fun downloadWithRetries(url: URI, path: Path, progressIndicator: ProgressIndicator) {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val MAX_ATTEMPTS = 5
val BACKOFF_INITIAL_DELAY_MS = 500L
var delayMs = BACKOFF_INITIAL_DELAY_MS
for (i in 1..MAX_ATTEMPTS) {
try {
LOG.info("Downloading from $url to ${path.absolutePathString()}, attempt $i of $MAX_ATTEMPTS")
when (url.scheme) {
"http", "https" -> {
HttpRequests.request(url.toString()).saveToFile(path, progressIndicator)
}
"file" -> {
Files.copy(url.toPath(), path, StandardCopyOption.REPLACE_EXISTING)
}
else -> {
error("scheme ${url.scheme} is not supported")
}
}
LOG.info("Download from $url to ${path.absolutePathString()} succeeded on attempt $i of $MAX_ATTEMPTS")
return
}
catch (e: Throwable) {
if (e is ControlFlowException) throw e
if (e is HttpStatusException) {
if (e.statusCode in 400..499) {
LOG.warn("Received ${e.statusCode} with message ${e.message}, will not retry")
throw e
}
}
if (i < MAX_ATTEMPTS) {
LOG.warn("Attempt $i of $MAX_ATTEMPTS to download from $url to ${path.absolutePathString()} failed, retrying in $delayMs ms", e)
Thread.sleep(delayMs)
delayMs = (delayMs * 1.5).toLong()
} else {
LOG.warn("Failed to download from $url to ${path.absolutePathString()} in $MAX_ATTEMPTS attempts", e)
throw e
}
}
}
}
private fun findCwmGuestHome(guestRoot: Path): Path {
// maxDepth 2 for Mac OS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
if (dir.resolve("bin").exists() && dir.resolve("lib").exists()) {
return dir
}
}
}
error("JetBrains Client home is not found under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherNames: List<String>): Pair<Path, List<String>> {
val launcher = launcherNames.firstNotNullOfOrNull {
val launcherRelative = Path.of("bin", it)
val launcher = findLauncher(guestRoot, launcherRelative)
launcher?.let {
launcher to listOf(launcher.toString())
}
}
return launcher ?: error("Could not find launchers (${launcherNames.joinToString { "'$it'" }}) under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherName: Path): Path? {
// maxDepth 2 for Mac OS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
val candidate = dir.resolve(launcherName)
if (candidate.exists()) {
return candidate
}
}
}
return null
}
private fun findLauncherUnderCwmGuestRoot(guestRoot: Path): Pair<Path, List<String>> {
when {
SystemInfo.isWindows -> {
val launcherNames = listOf("jetbrains_client64.exe", "cwm_guest64.exe", "intellij_client64.exe", "intellij_client.bat")
return findLauncher(guestRoot, launcherNames)
}
SystemInfo.isUnix -> {
if (SystemInfo.isMac) {
val app = guestRoot.toFile().listFiles { file -> file.name.endsWith(".app") && file.isDirectory }!!.singleOrNull()
if (app != null) {
return app.toPath() to listOf("open", "-n", "-W", "-a", app.toString(), "--args")
}
}
val shLauncherNames = listOf("jetbrains_client.sh", "cwm_guest.sh", "intellij_client.sh")
return findLauncher(guestRoot, shLauncherNames)
}
else -> error("Unsupported OS: ${SystemInfo.OS_NAME}")
}
}
/**
* Launches client and returns process's lifetime (which will be terminated on process exit)
*/
fun runCwmGuestProcessFromDownload(lifetime: Lifetime,
url: String,
guestRoot: Path,
jdkRoot: Path): Lifetime {
val (executable, fullLauncherCmd) = findLauncherUnderCwmGuestRoot(guestRoot)
createSymlinkToJdkFromGuest(guestRoot, jdkRoot)
// Update mtime on JRE & CWM Guest roots. The cleanup process will use it later.
listOf(guestRoot, jdkRoot).forEach { path ->
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()))
}
val parameters = listOf("thinClient", url)
val processLifetimeDef = lifetime.createNested()
val vmOptionsFile = executable.resolveSibling("jetbrains_client64.vmoptions")
service<JetBrainsClientDownloaderConfigurationProvider>().patchVmOptions(vmOptionsFile)
if (SystemInfo.isWindows) {
val hProcess = WindowsFileUtil.windowsShellExecute(
executable = executable,
workingDirectory = guestRoot,
parameters = parameters
)
val STILL_ACTIVE = 259
application.executeOnPooledThread {
val exitCode = IntByReference(STILL_ACTIVE)
while (exitCode.value == STILL_ACTIVE) {
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
Thread.sleep(1000)
}
processLifetimeDef.terminate()
}
lifetime.onTerminationOrNow {
val exitCode = IntByReference(WinBase.INFINITE)
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
if (exitCode.value == STILL_ACTIVE)
LOG.info("Terminating cwm guest process")
else return@onTerminationOrNow
if (!Kernel32.INSTANCE.TerminateProcess(hProcess, 1)) {
val error = Kernel32.INSTANCE.GetLastError()
val hResult = WinNT.HRESULT(error)
LOG.error("Failed to terminate cwm guest process, HRESULT=${"0x%x".format(hResult)}")
}
}
}
else {
// Mac gets multiple start attempts because starting it fails occasionally (CWM-2244, CWM-1733)
var attemptCount = if (SystemInfo.isMac) 5 else 1
var lastProcessStartTime: Long
fun doRunProcess() {
val commandLine = GeneralCommandLine(fullLauncherCmd + parameters)
config.modifyClientCommandLine(commandLine)
LOG.info("Starting JetBrains Client process (attempts left: $attemptCount): ${commandLine}")
attemptCount--
lastProcessStartTime = System.currentTimeMillis()
val processHandler = object : OSProcessHandler(commandLine) {
override fun readerOptions(): BaseOutputReader.Options = BaseOutputReader.Options.forMostlySilentProcess()
}
val listener = object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
super.onTextAvailable(event, outputType)
LOG.info("GUEST OUTPUT: ${event.text}")
}
override fun processTerminated(event: ProcessEvent) {
super.processTerminated(event)
LOG.info("Guest process terminated, exit code " + event.exitCode)
if (event.exitCode == 0) {
application.invokeLater {
processLifetimeDef.terminate()
}
} else {
// if process exited abnormally but took longer than 10 seconds, it's likely to be an issue with connection instead of Mac-specific bug
if ((System.currentTimeMillis() - lastProcessStartTime) < 10_000 ) {
if (attemptCount > 0) {
LOG.info("Previous attempt to start guest process failed, will try again in one second")
EdtScheduledExecutorService.getInstance().schedule({ doRunProcess() }, ModalityState.any(), 1, TimeUnit.SECONDS)
}
else {
LOG.warn("Running client process failed after specified number of attempts")
application.invokeLater {
processLifetimeDef.terminate()
}
}
}
}
}
}
processHandler.addProcessListener(listener)
processHandler.startNotify()
config.clientLaunched.fire()
lifetime.onTerminationOrNow {
processHandler.process.children().forEach {
it.destroyForcibly()
}
processHandler.process.destroyForcibly()
}
}
doRunProcess()
}
return processLifetimeDef.lifetime
}
private fun detectMacOsJbrDirectory(root: Path): Path {
val jbrDirectory = root.listDirectoryEntries().find { it.nameWithoutExtension.startsWith("jbr") }
LOG.debug { "JBR directory: $jbrDirectory" }
return jbrDirectory ?: error("Unable to find target content directory starts with 'jbr' inside MacOS package: '$root'")
}
fun createSymlinkToJdkFromGuest(guestRoot: Path, jdkRoot: Path) {
val linkTarget = if (SystemInfo.isMac) detectMacOsJbrDirectory(jdkRoot) else detectTrueJdkRoot(jdkRoot)
val guestHome = findCwmGuestHome(guestRoot)
createSymlink(guestHome / "jbr", linkTarget)
}
private fun createSymlink(link: Path, target: Path) {
val targetRealPath = target.toRealPath()
if (link.exists() && link.toRealPath() == targetRealPath) {
LOG.info("Symlink/junction '$link' is UP-TO-DATE and points to '$target'")
}
else {
Files.deleteIfExists(link)
LOG.info("Creating symlink/junction '$link' -> '$target'")
try {
if (SystemInfo.isWindows) {
WindowsFileUtil.createJunction(junctionFile = link, targetFile = target.absolute())
}
else {
Files.createSymbolicLink(link, target.absolute())
}
}
catch (e: IOException) {
if (link.exists() && link.toRealPath() == targetRealPath) {
LOG.warn("Creating symlink/junction to already existing target. '$link' -> '$target'")
}
else {
throw e
}
}
try {
val linkRealPath = link.toRealPath()
if (linkRealPath != targetRealPath) {
LOG.error("Symlink/junction '$link' should point to '$targetRealPath', but points to '$linkRealPath' instead")
}
}
catch (e: Throwable) {
LOG.error(e)
throw e
}
}
}
private fun detectTrueJdkRoot(jdkDownload: Path): Path {
jdkDownload.toFile().walk(FileWalkDirection.TOP_DOWN).forEach {
if (File(it, "bin").isDirectory && File(it, "lib").isDirectory) {
return it.toPath()
}
}
error("JDK root (bin/lib directories) was not found under $jdkDownload")
}
fun versionsMatch(hostBuildNumberString: String, localBuildNumberString: String): Boolean {
try {
val hostBuildNumber = BuildNumber.fromString(hostBuildNumberString)!!
val localBuildNumber = BuildNumber.fromString(localBuildNumberString)!!
// Any guest in that branch compatible with SNAPSHOT version (it's used by IDEA developers mostly)
if ((localBuildNumber.isSnapshot || hostBuildNumber.isSnapshot) && hostBuildNumber.baselineVersion == localBuildNumber.baselineVersion) {
return true
}
return hostBuildNumber.asStringWithoutProductCode() == localBuildNumber.asStringWithoutProductCode()
}
catch (t: Throwable) {
LOG.error("Error comparing versions $hostBuildNumberString and $localBuildNumberString: ${t.message}", t)
return false
}
}
private fun Path.addSuffix(suffix: String) = resolveSibling(fileName.toString() + suffix)
private const val SHA256_SUFFIX = ".sha256"
private const val SHA256_ASC_SUFFIX = ".sha256.asc"
private val urlAllowedChars = Regex("^[._\\-a-zA-Z0-9:/]+$")
fun isValidDownloadUrl(url: String): Boolean {
return urlAllowedChars.matches(url) && !url.contains("..")
}
private class MultipleSubProgressIndicator(parent: ProgressIndicator,
private val onFractionChange: () -> Unit) : SubProgressIndicatorBase(parent) {
companion object {
fun create(parent: ProgressIndicator, count: Int): List<MultipleSubProgressIndicator> {
val result = mutableListOf<MultipleSubProgressIndicator>()
val parentBaseFraction = parent.fraction
for (i in 0..count) {
val element = MultipleSubProgressIndicator(parent) {
val subFraction = result.sumOf { it.subFraction }
parent.fraction = min(parentBaseFraction + subFraction * (1.0 / count), 1.0)
}
result.add(element)
}
return result
}
}
private var subFraction = 0.0
override fun getFraction() = subFraction
override fun setFraction(fraction: Double) {
subFraction = fraction
onFractionChange()
}
}
} | apache-2.0 | d8ad5bd0e78eb18a763a471d5ce0a37a | 39.4 | 172 | 0.678563 | 4.768554 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/FrameInfoHelper.kt | 2 | 4099 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
package com.intellij.openapi.wm.impl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.wm.impl.FrameBoundsConverter.convertToDeviceSpace
import com.intellij.openapi.wm.impl.FrameInfoHelper.Companion.isFullScreenSupportedInCurrentOs
import com.intellij.ui.ScreenUtil
import sun.awt.AWTAccessor
import java.awt.Frame
import java.awt.Point
import java.awt.Rectangle
import java.awt.peer.ComponentPeer
import java.awt.peer.FramePeer
import javax.swing.JFrame
internal class FrameInfoHelper {
companion object {
@JvmStatic
fun isFullScreenSupportedInCurrentOs(): Boolean {
return SystemInfoRt.isMac || SystemInfoRt.isWindows || (SystemInfoRt.isXWindow && X11UiUtil.isFullScreenSupported())
}
@JvmStatic
val isFloatingMenuBarSupported: Boolean
get() = !SystemInfoRt.isMac && isFullScreenSupportedInCurrentOs()
@JvmStatic
fun isMaximized(state: Int): Boolean {
return state and Frame.MAXIMIZED_BOTH == Frame.MAXIMIZED_BOTH
}
}
// in device space
var info: FrameInfo? = null
private set
@Volatile
var isDirty = false
fun setInfoInDeviceSpace(info: FrameInfo) {
this.info = info
}
fun updateFrameInfo(frameHelper: ProjectFrameHelper, frame: JFrame) {
info = updateFrameInfo(frameHelper, frame, null, info)
}
fun getModificationCount(): Long {
return info?.modificationCount ?: 0
}
fun update(project: Project, lastNormalFrameBounds: Rectangle?, windowManager: WindowManagerImpl) {
val frameHelper = windowManager.getFrameHelper(project) ?: return
updateAndGetInfo(frameHelper, frameHelper.frame ?: return, lastNormalFrameBounds, windowManager)
}
fun updateAndGetInfo(frameHelper: ProjectFrameHelper,
frame: JFrame,
lastNormalFrameBounds: Rectangle?,
windowManager: WindowManagerImpl): FrameInfo {
val newInfo = updateFrameInfo(frameHelper, frame, lastNormalFrameBounds, info)
windowManager.defaultFrameInfoHelper.copyFrom(newInfo)
info = newInfo
isDirty = false
return newInfo
}
fun copyFrom(newInfo: FrameInfo) {
if (info == null) {
info = FrameInfo()
}
info!!.copyFrom(newInfo)
isDirty = false
}
}
internal fun updateFrameInfo(frameHelper: ProjectFrameHelper, frame: JFrame, lastNormalFrameBounds: Rectangle?, oldFrameInfo: FrameInfo?): FrameInfo {
var extendedState = frame.extendedState
if (SystemInfoRt.isMac) {
// java 11
val peer = AWTAccessor.getComponentAccessor().getPeer(frame) as ComponentPeer?
if (peer is FramePeer) {
// frame.state is not updated by jdk so get it directly from peer
extendedState = peer.state
}
}
val isInFullScreen = isFullScreenSupportedInCurrentOs() && frameHelper.isInFullScreen
val isMaximized = FrameInfoHelper.isMaximized(extendedState) || isInFullScreen
val oldBounds = oldFrameInfo?.bounds
val newBounds = convertToDeviceSpace(frame.graphicsConfiguration,
if (isMaximized && lastNormalFrameBounds != null) lastNormalFrameBounds else frame.bounds)
val usePreviousBounds = lastNormalFrameBounds == null && isMaximized &&
oldBounds != null &&
newBounds.contains(Point(oldBounds.centerX.toInt(), oldBounds.centerY.toInt()))
// don't report if was already reported
if (!usePreviousBounds && oldBounds != newBounds && !ScreenUtil.intersectsVisibleScreen(frame)) {
logger<WindowInfoImpl>().error("Frame bounds are invalid: $newBounds")
}
val frameInfo = oldFrameInfo ?: FrameInfo()
if (!usePreviousBounds) {
frameInfo.bounds = newBounds
}
frameInfo.extendedState = extendedState
if (isFullScreenSupportedInCurrentOs()) {
frameInfo.fullScreen = isInFullScreen
}
return frameInfo
} | apache-2.0 | 5a10b2a07d1be7a170b73ea86846cd9c | 34.344828 | 150 | 0.727251 | 4.663254 | false | false | false | false |
raflop/kotlin-android-presentation | samples/kotlinsample/app/src/main/java/com/example/rlopatka/kotlinsamples/MainActivity.kt | 1 | 3943 | package com.example.rlopatka.kotlinsamples
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.R.attr.duration
import android.opengl.Visibility
import android.view.View
import android.widget.Toast
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
class MainActivity : AppCompatActivity() {
val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// implicit property for java getters and setters
txtTest.text = getString(R.string.TxtTest)
// access layout elements directly without inflating or butterknife
btnTest.setOnClickListener {
// lambda instead of event listener implementations
val toast = Toast.makeText(this, "Test", Toast.LENGTH_SHORT)
toast.show()
}
// call java classes from kotlin
btnDialog.setOnClickListener {
val dialog = JavaDialog()
dialog.show(this)
}
// rx java state management
val service = SampleDataService()
val loadDataObservable = service
.callSlowService()
.map { if (it.isFailure) LoadingState.Failure else LoadingState.Success }
.startWith(LoadingState.Loading)
.onErrorReturn{ LoadingState.Failure }
val sampleSubscription = btnTogle
.clickObservable()
.switchMap { loadDataObservable }
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
when(it){
LoadingState.NotStarted -> {
this.btnTogle.isEnabled = true
this.pgrLoading.visibility = View.GONE
}
LoadingState.Loading -> {
this.btnTogle.isEnabled = false
this.pgrLoading.visibility = View.VISIBLE
}
LoadingState.Success -> {
this.btnTogle.isEnabled = true
this.pgrLoading.visibility = View.GONE
val toast = Toast.makeText(this, "Success", Toast.LENGTH_SHORT)
toast.show()
}
LoadingState.Failure -> {
this.btnTogle.isEnabled = true
this.pgrLoading.visibility = View.GONE
val toast = Toast.makeText(this, "Error", Toast.LENGTH_SHORT)
toast.show()
}
}
}
disposables.addAll(sampleSubscription)
// retrofit service call
val peopleService = PeopleService()
val restSubscription = btnRest
.clickObservable()
.observeOn(Schedulers.io())
.switchMap { peopleService.getPersonalInfo("russellwhyte") }
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
val toast = Toast.makeText(this, it.firstName, Toast.LENGTH_SHORT)
toast.show()
}
disposables.add(restSubscription)
}
override fun onDestroy() {
disposables.dispose()
super.onDestroy()
}
}
fun View.clickObservable(): Observable<Unit> {
return Observable.create {
val stream = it
this.setOnClickListener {
stream.onNext(Unit)
}
}
}
enum class LoadingState {
NotStarted,
Loading,
Success,
Failure
} | gpl-3.0 | 860866834141feb4d504a60fe1687d29 | 32.142857 | 91 | 0.561755 | 5.530154 | false | false | false | false |
mdaniel/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListPanelFactory.kt | 1 | 9694 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBList
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener
import com.intellij.vcs.log.ui.frame.ProgressStripe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.data.GHListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRListUpdatesChecker
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRRepositoryDataService
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRSecurityService
import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.component.GHHandledErrorPanelModel
import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel
import java.awt.FlowLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants
import javax.swing.event.ChangeEvent
internal class GHPRListPanelFactory(private val project: Project,
private val repositoryDataService: GHPRRepositoryDataService,
private val securityService: GHPRSecurityService,
private val listLoader: GHPRListLoader,
private val listUpdatesChecker: GHPRListUpdatesChecker,
private val account: GithubAccount,
private val disposable: Disposable) {
private val scope = MainScope().also { Disposer.register(disposable) { it.cancel() } }
fun create(list: JBList<GHPullRequestShort>, avatarIconsProvider: GHAvatarIconsProvider): JComponent {
val actionManager = ActionManager.getInstance()
val historyModel = GHPRSearchHistoryModel(scope, project.service())
val searchVm = GHPRSearchPanelViewModel(scope, repositoryDataService, historyModel, avatarIconsProvider)
scope.launch {
searchVm.searchState.collectLatest {
listLoader.searchQuery = it.toQuery()
}
}
ListEmptyTextController(scope, listLoader, searchVm, list.emptyText, disposable)
val searchPanel = GHPRSearchPanelFactory(searchVm).create(scope, createQuickFilters())
val outdatedStatePanel = JPanel(FlowLayout(FlowLayout.LEFT, JBUIScale.scale(5), 0)).apply {
background = UIUtil.getPanelBackground()
border = JBUI.Borders.empty(4, 0)
add(JLabel(GithubBundle.message("pull.request.list.outdated")))
add(ActionLink(GithubBundle.message("pull.request.list.refresh")) {
listLoader.reset()
})
isVisible = false
}
OutdatedPanelController(listLoader, listUpdatesChecker, outdatedStatePanel, disposable)
val errorHandler = GHApiLoadingErrorHandler(project, account) {
listLoader.reset()
}
val errorModel = GHHandledErrorPanelModel(GithubBundle.message("pull.request.list.cannot.load"), errorHandler).apply {
error = listLoader.error
}
listLoader.addErrorChangeListener(disposable) {
errorModel.error = listLoader.error
}
val errorPane = GHHtmlErrorPanel.create(errorModel)
val controlsPanel = JPanel(VerticalLayout(0)).apply {
isOpaque = false
add(searchPanel)
add(outdatedStatePanel)
add(errorPane)
}
val listLoaderPanel = createListLoaderPanel(listLoader, list, disposable)
return JBUI.Panels.simplePanel(listLoaderPanel).addToTop(controlsPanel).andTransparent().also {
DataManager.registerDataProvider(it) { dataId ->
if (GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId)) {
if (list.isSelectionEmpty) null else list.selectedValue
}
else null
}
actionManager.getAction("Github.PullRequest.List.Reload").registerCustomShortcutSet(it, disposable)
}
}
private fun createQuickFilters() = listOf(
GithubBundle.message("pull.request.list.filter.quick.open") to
GHPRListSearchValue(state = GHPRListSearchValue.State.OPEN),
GithubBundle.message("pull.request.list.filter.quick.yours") to
GHPRListSearchValue(state = GHPRListSearchValue.State.OPEN, author = securityService.currentUser.login),
GithubBundle.message("pull.request.list.filter.quick.assigned") to
GHPRListSearchValue(state = GHPRListSearchValue.State.OPEN, assignee = securityService.currentUser.login)
)
private fun createListLoaderPanel(loader: GHListLoader<*>, list: JComponent, disposable: Disposable): JComponent {
val scrollPane = ScrollPaneFactory.createScrollPane(list, true).apply {
isOpaque = false
viewport.isOpaque = false
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
val model = verticalScrollBar.model
val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) {
override fun onThresholdReached() {
if (!loader.loading && loader.canLoadMore()) {
loader.loadMore()
}
}
}
model.addChangeListener(listener)
loader.addLoadingStateChangeListener(disposable) {
if (!loader.loading) listener.stateChanged(ChangeEvent(loader))
}
}
loader.addDataListener(disposable, object : GHListLoader.ListDataListener {
override fun onAllDataRemoved() {
if (scrollPane.isShowing) loader.loadMore()
}
})
val progressStripe = ProgressStripe(scrollPane, disposable,
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
if (loader.loading) startLoadingImmediately() else stopLoading()
}
loader.addLoadingStateChangeListener(disposable) {
if (loader.loading) progressStripe.startLoading() else progressStripe.stopLoading()
}
return progressStripe
}
private class ListEmptyTextController(scope: CoroutineScope,
private val listLoader: GHListLoader<*>,
private val searchVm: GHPRSearchPanelViewModel,
private val emptyText: StatusText,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
scope.launch {
searchVm.searchState.collect {
update()
}
}
}
private fun update() {
emptyText.clear()
if (listLoader.loading || listLoader.error != null) return
val search = searchVm.searchState.value
if (search == GHPRListSearchValue.DEFAULT) {
emptyText.appendText(GithubBundle.message("pull.request.list.no.matches"))
.appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters"),
SimpleTextAttributes.LINK_ATTRIBUTES) {
searchVm.searchState.update { GHPRListSearchValue.EMPTY }
}
}
else if (search.filterCount == 0) {
emptyText.appendText(GithubBundle.message("pull.request.list.nothing.loaded"))
}
else {
emptyText.appendText(GithubBundle.message("pull.request.list.no.matches"))
.appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters.to.default",
GHPRListSearchValue.DEFAULT.toQuery().toString()),
SimpleTextAttributes.LINK_ATTRIBUTES) {
searchVm.searchState.update { GHPRListSearchValue.DEFAULT }
}
}
}
}
private class OutdatedPanelController(private val listLoader: GHListLoader<*>,
private val listChecker: GHPRListUpdatesChecker,
private val panel: JPanel,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
listLoader.addErrorChangeListener(listenersDisposable, ::update)
listChecker.addOutdatedStateChangeListener(listenersDisposable, ::update)
}
private fun update() {
panel.isVisible = listChecker.outdated && (!listLoader.loading && listLoader.error == null)
}
}
} | apache-2.0 | 3115e721fee19a954823fab7a802667f | 44.093023 | 122 | 0.713018 | 4.971282 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/MoreSquareStripeButton.kt | 1 | 2890 | // 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.toolWindow
import com.intellij.icons.AllIcons
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.ToolwindowSwitcher
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.ScalableIcon
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.impl.SquareStripeButtonLook
import com.intellij.ui.UIBundle
import com.intellij.ui.awt.RelativePoint
import java.awt.Dimension
import java.awt.Point
import java.awt.event.MouseEvent
import java.util.function.Predicate
internal class MoreSquareStripeButton(toolWindowToolbar: ToolWindowLeftToolbar) :
ActionButton(createAction(toolWindowToolbar), createPresentation(), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) {
init {
setLook(SquareStripeButtonLook(this))
}
override fun updateToolTipText() {
HelpTooltip()
.setTitle(UIBundle.message("tool.window.new.stripe.more.title"))
.setLocation(HelpTooltip.Alignment.RIGHT)
.setInitialDelay(0).setHideDelay(0)
.installOn(this)
}
override fun checkSkipPressForEvent(e: MouseEvent) = e.button != MouseEvent.BUTTON1
companion object {
private val notVisibleOnStripePredicate: Predicate<ToolWindow> = Predicate { !it.isShowStripeButton }
private fun createPresentation(): Presentation {
val presentation = Presentation()
presentation.icon = IconLoader.loadCustomVersionOrScale(AllIcons.Actions.MoreHorizontal as ScalableIcon, 20f)
presentation.isEnabledAndVisible = true
return presentation
}
private fun createAction(toolWindowToolbar: ToolWindowLeftToolbar): DumbAwareAction {
return object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val moreSquareStripeButton = toolWindowToolbar.moreButton
ToolwindowSwitcher.invokePopup(e.project!!, Comparator.comparing { it.stripeTitle },
e.dataContext, notVisibleOnStripePredicate,
RelativePoint(toolWindowToolbar, Point(toolWindowToolbar.width, moreSquareStripeButton.y)))
}
override fun update(e: AnActionEvent) {
val toolWindowManager = ToolWindowManagerEx.getInstanceEx(e.project ?: return)
e.presentation.isEnabledAndVisible = ToolwindowSwitcher.getToolWindows(toolWindowManager, notVisibleOnStripePredicate).isNotEmpty()
}
}
}
}
}
| apache-2.0 | d63802d30c1415b90c9a365de9dad6b8 | 42.134328 | 141 | 0.763668 | 4.86532 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/IndexedFileSystem.kt | 1 | 6485 | package rs.emulate.legacy
import com.google.common.base.Preconditions
import com.google.common.collect.ImmutableList
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import rs.emulate.legacy.archive.Archive
import rs.emulate.legacy.archive.ArchiveCodec
import rs.emulate.util.getUnsignedByte
import rs.emulate.util.getUnsignedShort
import rs.emulate.util.getUnsignedTriByte
import java.io.Closeable
import java.io.FileNotFoundException
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.zip.CRC32
/**
* A file system based on top of the operating system's file system. It consists of a data file and multiple index
* files. Index files point to blocks in the data file, which contain the actual data.
*
* @param base The base directory.
* @param mode The [AccessMode].
* @throws FileNotFoundException If the data files could not be found.
*/
class IndexedFileSystem(base: Path, private val mode: AccessMode) : Closeable {
private val data: RandomAccessFile?
private val indices: List<RandomAccessFile>
/**
* The cached CRC table.
*/
private var crcs: ByteBuf? = null
val crcTable: ByteBuf
get() {
if (readOnly) {
synchronized(this) {
crcs?.let { return it.duplicate() }
}
val archives = getFileCount(0)
var hash = 1234
val buffer = Unpooled.buffer((archives + 1) * Integer.BYTES)
val crc = CRC32()
for (file in 1 until archives) {
val bytes = get(0, file).readableBytes()
crc.update(bytes)
val value = crc.value.toInt()
buffer.writeInt(value)
hash = (hash shl 1) + value
}
buffer.writeInt(hash)
synchronized(this) {
crcs = buffer
}
return buffer.asReadOnly()
}
throw IOException("Cannot get CRC table from a writable file system.")
}
val indexCount: Int
get() = indices.size
val readOnly: Boolean
get() = mode === AccessMode.READ
init {
indices = getIndexFiles(base)
data = getDataFile(base)
}
fun getArchive(type: Int, file: Int): Archive {
return ArchiveCodec.decode(get(type, file))
}
operator fun get(type: Int, file: Int): ByteBuf {
val (size, block) = getIndex(type, file)
val buffer = ByteBuffer.allocate(size)
var position = (block * FileSystemConstants.BLOCK_SIZE).toLong()
var read = 0
var blocks = size / FileSystemConstants.CHUNK_SIZE
if (size % FileSystemConstants.CHUNK_SIZE != 0) {
blocks++
}
for (id in 0 until blocks) {
val header = ByteBuffer.allocate(FileSystemConstants.HEADER_SIZE)
synchronized(data!!) {
data.seek(position)
data.readFully(header.array())
}
position += FileSystemConstants.HEADER_SIZE.toLong()
val nextFile = header.getUnsignedShort()
val currentChunk = header.getUnsignedShort()
val nextBlock = header.getUnsignedTriByte()
val nextType = header.getUnsignedByte()
check(id == currentChunk) { "Chunk id mismatch: id=$id, chunk=$currentChunk, type=$type, file=$file." }
val chunkSize = Math.min(FileSystemConstants.CHUNK_SIZE, size - read)
val chunk = ByteBuffer.allocate(chunkSize)
synchronized(data) {
data.seek(position)
data.readFully(chunk.array())
}
buffer.put(chunk)
read += chunkSize
position = (nextBlock * FileSystemConstants.BLOCK_SIZE).toLong()
if (size > read) {
check(nextType == type + 1) { "File type mismatch." }
check(nextFile == file) { "File id mismatch." }
}
}
buffer.flip()
return Unpooled.wrappedBuffer(buffer) // TODO do this properly
}
fun getIndex(type: Int, file: Int): Index {
Preconditions.checkElementIndex(type, indices.size, "File descriptor type ($type) out of bounds.")
val index = indices[type]
val position = (file * Index.BYTES).toLong()
require(position >= 0 && index.length() >= position + Index.BYTES) {
"Could not find find index for $file (maximum ${index.length() / Index.BYTES})."
}
val bytes = ByteArray(Index.BYTES)
synchronized(index) {
index.seek(position)
index.readFully(bytes)
}
return IndexCodec.decode(Unpooled.wrappedBuffer(bytes))
}
fun getFileCount(type: Int): Int {
require(type in indices.indices) { "File type out of bounds." }
val index = indices[type]
synchronized(index) {
return (index.length() / Index.BYTES).toInt()
}
}
override fun close() {
if (data != null) {
synchronized(data) {
data.close()
}
}
for (index in indices) {
synchronized(index) {
index.close()
}
}
}
private fun getDataFile(base: Path): RandomAccessFile {
val resources = base.resolve("main_file_cache.dat")
if (!Files.exists(resources) || Files.isDirectory(resources)) {
throw FileNotFoundException("No data file present.")
}
return RandomAccessFile(resources.toFile(), mode.asUnix())
}
private fun getIndexFiles(base: Path): List<RandomAccessFile> {
val indices = ArrayList<RandomAccessFile>()
for (id in 0 until INDEX_COUNT) {
val index = base.resolve("main_file_cache.idx$id")
if (Files.exists(index) && !Files.isDirectory(index)) {
indices.add(RandomAccessFile(index.toFile(), mode.asUnix()))
}
}
if (indices.isEmpty()) {
throw FileNotFoundException("No index files present.")
}
return ImmutableList.copyOf(indices)
}
companion object {
/**
* The maximum amount of indices.
*/
private const val INDEX_COUNT = 256
}
}
| isc | b12e18ee8351664a212bf91703948ed1 | 28.884793 | 115 | 0.581958 | 4.547686 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/command/CommandHandler.kt | 1 | 1515 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexlib.command
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class CommandHandler (
/**
* The path for executing the command (base label and subcommand labels).
*/
val command: String,
/**
* The aliases for the command.
*/
val aliases: Array<String> = arrayOf(),
/**
* The description of the command.
*/
val description: String = "",
/**
* The permission required to run this command.
*/
val permission: String = "",
/**
* True indicates that the command handler is the default for the parent.
*/
val isDefault: Boolean = false,
/**
* True indicates that the command handler is a placeholder and contains no logic.
*/
val dummy: Boolean = false
)
| apache-2.0 | 49fc72e8b0929ce3c407beae05c272d9 | 27.584906 | 86 | 0.681188 | 4.429825 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinRuntimeTypeEvaluator.kt | 1 | 4048 | // 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.debugger.evaluate
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.debugger.engine.ContextUtil
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.ui.EditorEvaluationCommand
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.psi.CommonClassNames
import com.intellij.psi.search.GlobalSearchScope
import com.sun.jdi.ClassType
import com.sun.jdi.Value
import org.jetbrains.eval4j.jdi.asValue
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Type as AsmType
abstract class KotlinRuntimeTypeEvaluator(
editor: Editor?,
expression: KtExpression,
context: DebuggerContextImpl,
indicator: ProgressIndicator
) : EditorEvaluationCommand<KotlinType>(editor, expression, context, indicator) {
override fun threadAction(suspendContext: SuspendContextImpl) {
var type: KotlinType? = null
try {
type = evaluate()
} catch (ignored: ProcessCanceledException) {
} catch (ignored: EvaluateException) {
} finally {
typeCalculationFinished(type)
}
}
protected abstract fun typeCalculationFinished(type: KotlinType?)
override fun evaluate(evaluationContext: EvaluationContextImpl): KotlinType? {
val project = evaluationContext.project
val evaluator = DebuggerInvocationUtil.commitAndRunReadAction<ExpressionEvaluator>(project) {
val codeFragment = KtPsiFactory(myElement.project).createExpressionCodeFragment(
myElement.text, myElement.containingFile.context
)
KotlinEvaluatorBuilder.build(codeFragment, ContextUtil.getSourcePosition(evaluationContext))
}
val value = evaluator.evaluate(evaluationContext)
if (value != null) {
return runReadAction { getCastableRuntimeType(evaluationContext.debugProcess.searchScope, value) }
}
throw EvaluateExceptionUtil.createEvaluateException(JavaDebuggerBundle.message("evaluation.error.surrounded.expression.null"))
}
companion object {
private fun getCastableRuntimeType(scope: GlobalSearchScope, value: Value): KotlinType? {
val myValue = value.asValue()
var psiClass = myValue.asmType.getClassDescriptor(scope)
if (psiClass != null) {
return psiClass.defaultType
}
val type = value.type()
if (type is ClassType) {
val superclass = type.superclass()
if (superclass != null && CommonClassNames.JAVA_LANG_OBJECT != superclass.name()) {
psiClass = AsmType.getType(superclass.signature()).getClassDescriptor(scope)
if (psiClass != null) {
return psiClass.defaultType
}
}
for (interfaceType in type.interfaces()) {
psiClass = AsmType.getType(interfaceType.signature()).getClassDescriptor(scope)
if (psiClass != null) {
return psiClass.defaultType
}
}
}
return null
}
}
}
| apache-2.0 | d19e18425415c83b86285dce99c976ac | 41.610526 | 158 | 0.70331 | 5.298429 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt | 4 | 23087 | // 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.completion.smart
import com.intellij.codeInsight.completion.EmptyDeclarativeInsertHandler
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.OffsetKey
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.*
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.isAlmostEverything
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addIfNotNull
interface InheritanceItemsSearcher {
fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit)
}
class SmartCompletion(
private val expression: KtExpression,
private val resolutionFacade: ResolutionFacade,
private val bindingContext: BindingContext,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val indicesHelper: KotlinIndicesHelper,
private val prefixMatcher: PrefixMatcher,
private val inheritorSearchScope: GlobalSearchScope,
private val toFromOriginalFileMapper: ToFromOriginalFileMapper,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>,
private val isJvmModule: Boolean,
private val forBasicCompletion: Boolean = false
) {
private val expressionWithType = when (callTypeAndReceiver) {
is CallTypeAndReceiver.DEFAULT ->
expression
is CallTypeAndReceiver.DOT,
is CallTypeAndReceiver.SAFE,
is CallTypeAndReceiver.SUPER_MEMBERS,
is CallTypeAndReceiver.INFIX,
is CallTypeAndReceiver.CALLABLE_REFERENCE ->
expression.parent as KtExpression
else -> // actually no smart completion for such places
expression
}
val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected()
val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
SmartCastCalculator(
bindingContext,
resolutionFacade.moduleDescriptor,
expression,
callTypeAndReceiver.receiver as? KtExpression,
resolutionFacade
)
}
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
filterDescriptor(descriptor, factory).map { postProcess(it) }
}.takeIf { expectedInfos.isNotEmpty() }
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)
val postProcessedItems = items.map { postProcess(it) }
//TODO: could not use "let" because of KT-8754
val postProcessedSearcher = if (inheritanceSearcher != null)
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearcher.search(nameFilter) { consumer(postProcess(it)) }
}
}
else
null
return postProcessedItems to postProcessedSearcher
}
val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>> {
when (val parent = expressionWithType.parent) {
is KtBinaryExpression -> {
if (parent.right == expressionWithType) {
val operationToken = parent.operationToken
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
val left = parent.left
if (left is KtReferenceExpression) {
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left]?.let(::setOf).orEmpty()
}
}
}
}
is KtWhenConditionWithExpression -> {
val entry = parent.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
if (subject is KtSimpleNameExpression) {
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject] as? VariableDescriptor
if (variable != null) {
descriptorsToSkip.add(variable)
}
}
val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet()
val classDescriptor = TypeUtils.getClassDescriptor(subjectType)
if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) {
val conditions =
whenExpression.entries.flatMap { it.conditions.toList() }.filterIsInstance<KtWhenConditionWithExpression>()
for (condition in conditions) {
val selectorExpr =
(condition.expression as? KtDotQualifiedExpression)?.selectorExpression as? KtReferenceExpression ?: continue
val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue
if (DescriptorUtils.isEnumEntry(target)) {
descriptorsToSkip.add(target)
}
}
}
return@lazy descriptorsToSkip
}
}
return@lazy emptySet()
}
private fun filterDescriptor(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
): Collection<LookupElement> {
ProgressManager.checkCanceled()
if (descriptor in descriptorsToSkip) return emptyList()
val result = SmartList<LookupElement>()
val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext)
val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
result.addLookupElements(
descriptor,
expectedInfos,
infoMatcher,
noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT
) { declarationDescriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
result.addCallableReferenceLookupElements(descriptor, lookupElementFactory)
}
return result
}
private fun additionalItemsNoPostProcess(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val asTypePositionItems = buildForAsTypePosition(lookupElementFactory.basicFactory)
if (asTypePositionItems != null) {
assert(expectedInfos.isEmpty())
return Pair(asTypePositionItems, null)
}
val items = ArrayList<LookupElement>()
val inheritanceSearchers = ArrayList<InheritanceItemsSearcher>()
if (!forBasicCompletion) { // basic completion adds keyword values on its own
val keywordValueConsumer = object : KeywordValues.Consumer {
override fun consume(
lookupString: String,
expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch,
suitableOnPsiLevel: PsiElement.() -> Boolean,
priority: SmartCompletionItemPriority,
factory: () -> LookupElement
) {
items.addLookupElements(null, expectedInfos, expectedInfoMatcher) {
val lookupElement = factory()
lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority)
listOf(lookupElement)
}
}
}
KeywordValues.process(
keywordValueConsumer,
callTypeAndReceiver,
bindingContext,
resolutionFacade,
moduleDescriptor,
isJvmModule
)
}
if (expectedInfos.isNotEmpty()) {
items.addArrayLiteralsInAnnotationsCompletions()
if (!forBasicCompletion && (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT || callTypeAndReceiver is CallTypeAndReceiver.UNKNOWN /* after this@ */)) {
items.addThisItems(expression, expectedInfos, smartCastCalculator)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
TypeInstantiationItems(
resolutionFacade,
bindingContext,
visibilityFilter,
toFromOriginalFileMapper,
inheritorSearchScope,
lookupElementFactory,
forBasicCompletion,
indicesHelper
).addTo(items, inheritanceSearchers, expectedInfos)
if (expression is KtSimpleNameExpression) {
StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor).addToCollection(
items,
expectedInfos,
expression,
descriptorsToSkip
)
}
ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule)
items.addNamedArgumentsWithLiteralValueItems(expectedInfos)
LambdaSignatureItems.addToCollection(items, expressionWithType, bindingContext, resolutionFacade)
if (!forBasicCompletion) {
LambdaItems.addToCollection(items, expectedInfos)
val whenCondition = expressionWithType.parent as? KtWhenConditionWithExpression
if (whenCondition != null) {
val entry = whenCondition.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val entries = whenExpression.entries
if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) {
val lookupElement = LookupElementBuilder.create("else")
.bold()
.withTailText(" ->")
.withInsertHandler(
WithTailInsertHandler("->", spaceBefore = true, spaceAfter = true).asPostInsertHandler
)
items.add(lookupElement)
}
}
}
MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade).addToCollection(
items,
expectedInfos,
expression
)
}
}
val inheritanceSearcher = if (inheritanceSearchers.isNotEmpty())
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearchers.forEach { it.search(nameFilter, consumer) }
}
}
else
null
return Pair(items, inheritanceSearcher)
}
private fun postProcess(item: LookupElement): LookupElement {
if (forBasicCompletion) return item
return if (item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) == null) {
LookupElementDecorator.withDelegateInsertHandler(
item,
InsertHandler { context, element ->
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
val offset = context.offsetMap.tryGetOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
if (offset != null) {
context.document.deleteString(context.tailOffset, offset)
}
}
element.handleInsert(context)
}
)
} else {
item
}
}
private fun MutableCollection<LookupElement>.addThisItems(
place: KtExpression,
expectedInfos: Collection<ExpectedInfo>,
smartCastCalculator: SmartCastCalculator
) {
if (shouldCompleteThisItems(prefixMatcher)) {
val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade)
for (item in items) {
val types = smartCastCalculator.types(item.receiverParameter).map { it.toFuzzyType(emptyList()) }
val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
addLookupElements(null, expectedInfos, matcher) {
listOf(item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS))
}
}
}
}
private fun MutableCollection<LookupElement>.addNamedArgumentsWithLiteralValueItems(expectedInfos: Collection<ExpectedInfo>) {
data class NameAndValue(val name: Name, val value: String, val priority: SmartCompletionItemPriority)
val nameAndValues = HashMap<NameAndValue, MutableList<ExpectedInfo>>()
fun addNameAndValue(name: Name, value: String, priority: SmartCompletionItemPriority, expectedInfo: ExpectedInfo) {
nameAndValues.getOrPut(NameAndValue(name, value, priority)) { ArrayList() }.add(expectedInfo)
}
for (expectedInfo in expectedInfos) {
val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue
if (argumentData.namedArgumentCandidates.isEmpty()) continue
val parameters = argumentData.function.valueParameters
if (argumentData.argumentIndex >= parameters.size) continue
val parameterName = parameters[argumentData.argumentIndex].name
if (expectedInfo.fuzzyType?.type?.isBooleanOrNullableBoolean() == true) {
addNameAndValue(parameterName, "true", SmartCompletionItemPriority.NAMED_ARGUMENT_TRUE, expectedInfo)
addNameAndValue(parameterName, "false", SmartCompletionItemPriority.NAMED_ARGUMENT_FALSE, expectedInfo)
}
if (expectedInfo.fuzzyType?.type?.isMarkedNullable == true) {
addNameAndValue(parameterName, "null", SmartCompletionItemPriority.NAMED_ARGUMENT_NULL, expectedInfo)
}
}
for ((nameAndValue, infos) in nameAndValues) {
var lookupElement = createNamedArgumentWithValueLookupElement(nameAndValue.name, nameAndValue.value, nameAndValue.priority)
lookupElement = lookupElement.addTail(mergeTails(infos.map { it.tail }))
add(lookupElement)
}
}
private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement {
val lookupElement = LookupElementBuilder.create("${name.asString()} = $value")
.withIcon(KotlinIcons.PARAMETER)
.withInsertHandler { context, _ ->
context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value")
}
lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit)
lookupElement.assignSmartCompletionPriority(priority)
return lookupElement
}
private fun calcExpectedInfos(expression: KtExpression): Collection<ExpectedInfo> {
// if our expression is initializer of implicitly typed variable - take type of variable from original file (+ the same for function)
val declaration = implicitlyTypedDeclarationFromInitializer(expression)
if (declaration != null) {
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
if (originalDeclaration != null) {
val originalDescriptor = originalDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val returnType = originalDescriptor?.returnType
if (returnType != null && !returnType.isError) {
return listOf(ExpectedInfo(returnType, declaration.name, null))
}
}
}
// if expected types are too general, try to use expected type from outer calls
var count = 0
while (true) {
val infos =
ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count).calculate(expression)
if (count == 2 /* use two outer calls maximum */ || infos.none { it.fuzzyType?.isAlmostEverything() == true }) {
return if (forBasicCompletion)
infos.map { it.copy(tail = null) }
else
infos
}
count++
}
//TODO: we could always give higher priority to results with outer call expected type used
}
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
when (val parent = expression.parent) {
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
}
return null
}
private fun MutableCollection<LookupElement>.addCallableReferenceLookupElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
) {
if (callableTypeExpectedInfo.isEmpty()) return
fun toLookupElement(descriptor: CallableDescriptor): LookupElement? {
val callableReferenceType = descriptor.callableReferenceType(resolutionFacade, null) ?: return null
val matchedExpectedInfos = callableTypeExpectedInfo.filter { it.matchingSubstitutor(callableReferenceType) != null }
if (matchedExpectedInfos.isEmpty()) return null
var lookupElement =
lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true)
?: return null
lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() = "::" + delegate.lookupString
override fun getAllLookupStrings() = setOf(lookupString)
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = "::" + presentation.itemText
}
override fun getDelegateInsertHandler() = EmptyDeclarativeInsertHandler
}
return lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE)
.addTailAndNameSimilarity(matchedExpectedInfos)
}
when (descriptor) {
is CallableDescriptor -> {
// members and extensions are not supported after "::" currently
if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) {
addIfNotNull(toLookupElement(descriptor))
}
}
is ClassDescriptor -> {
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
descriptor.constructors.filter(visibilityFilter).mapNotNullTo(this, ::toLookupElement)
}
}
}
}
private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection<LookupElement>? {
val binaryExpression =
((expression.parent as? KtUserType)?.parent as? KtTypeReference)?.parent as? KtBinaryExpressionWithTypeRHS ?: return null
val elementType = binaryExpression.operationReference.getReferencedNameElementType()
if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null
val expectedInfos = calcExpectedInfos(binaryExpression)
val expectedInfosGrouped: Map<KotlinType?, List<ExpectedInfo>> = expectedInfos.groupBy { it.fuzzyType?.type?.makeNotNullable() }
val items = ArrayList<LookupElement>()
for ((type, infos) in expectedInfosGrouped) {
if (type == null) continue
val lookupElement = lookupElementFactory.createLookupElementForType(type) ?: continue
items.add(lookupElement.addTailAndNameSimilarity(infos))
}
return items
}
private fun MutableCollection<LookupElement>.addArrayLiteralsInAnnotationsCompletions() {
this.addAll(ArrayLiteralsInAnnotationItems.collect(expectedInfos, expression))
}
companion object {
val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
}
}
| apache-2.0 | b10b1af66c5229517f5661ed4e55baf0 | 46.799172 | 166 | 0.6482 | 6.248173 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingInspection.kt | 3 | 3016 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.incorrectFormatting
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ui.InspectionOptionsPanel
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.LangBundle
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
val INSPECTION_KEY = Key.create<IncorrectFormattingInspection>(IncorrectFormattingInspection().shortName)
class IncorrectFormattingInspection(
@JvmField var reportPerFile: Boolean = false, // generate only one warning per file
@JvmField var kotlinOnly: Boolean = false // process kotlin files normally even in silent mode, compatibility
) : LocalInspectionTool() {
val isKotlinPlugged: Boolean by lazy { PluginManagerCore.getPlugin(PluginId.getId("org.jetbrains.kotlin")) != null }
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
// Skip files we are not able to fix
if (!file.isWritable) return null
// Skip injections
val host = InjectedLanguageManager.getInstance(file.project).getInjectionHost(file)
if (host != null) {
return null
}
// Perform only for main PSI tree
val baseLanguage: Language = file.viewProvider.baseLanguage
val mainFile = file.viewProvider.getPsi(baseLanguage)
if (file != mainFile) {
return null
}
if (isKotlinPlugged && kotlinOnly && file.language.id != "kotlin") {
return null
}
val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null
val formattingChanges = detectFormattingChanges(file) ?: return null
if (formattingChanges.mismatches.isEmpty()) return null
val helper = IncorrectFormattingInspectionHelper(formattingChanges, file, document, manager, isOnTheFly)
return if (reportPerFile) {
arrayOf(helper.createGlobalReport())
}
else {
helper.createAllReports()
}
}
override fun createOptionsPanel() = object : InspectionOptionsPanel(this) {
init {
addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.report.per.file"), "reportPerFile")
if (isKotlinPlugged) {
addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.kotlin.only"), "kotlinOnly")
}
}
}
override fun runForWholeFile() = true
override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.WEAK_WARNING
override fun isEnabledByDefault() = false
}
| apache-2.0 | e53fe756388c4097815e844d246b2c64 | 38.684211 | 158 | 0.767241 | 4.810207 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildEntityImpl.kt | 2 | 9105 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildEntityImpl(val dataSource: ChildEntityData) : ChildEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val childData: String
get() = dataSource.childData
override val parentEntity: ParentEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildEntityData?) : ModifiableWorkspaceEntityBase<ChildEntity, ChildEntityData>(result), ChildEntity.Builder {
constructor() : this(ChildEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildDataInitialized()) {
error("Field ChildEntity#childData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.childData != dataSource.childData) this.childData = dataSource.childData
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<ParentEntity>().single()
if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData(true).childData = value
changedProperty.add("childData")
}
override var parentEntity: ParentEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as ParentEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityClass(): Class<ChildEntity> = ChildEntity::class.java
}
}
class ChildEntityData : WorkspaceEntityData<ChildEntity>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildEntity> {
val modifiable = ChildEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildEntity {
return getCached(snapshot) {
val entity = ChildEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildEntity(childData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ParentEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildEntityData
if (this.entitySource != other.entitySource) return false
if (this.childData != other.childData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildEntityData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 8baa9fe31fadd2d6c8b4af05fba02c38 | 35.2749 | 149 | 0.695991 | 5.337046 | false | false | false | false |
GunoH/intellij-community | java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDirectiveTest.kt | 4 | 3389 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.daemon.impl.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiJavaModule
class AddModuleDirectiveTest : LightJava9ModulesCodeInsightFixtureTestCase() {
fun testNewRequires() = doRequiresTest(
"module M { }",
"module M {\n" +
" requires M2;\n" +
"}")
fun testRequiresAfterOther() = doRequiresTest(
"module M {\n" +
" requires other;\n" +
"}",
"module M {\n" +
" requires other;\n" +
" requires M2;\n" +
"}")
fun testNoDuplicateRequires() = doRequiresTest(
"module M { requires M2; }",
"module M { requires M2; }")
fun testRequiresInIncompleteModule() = doRequiresTest(
"module M {",
"module M {\n" +
" requires M2;")
fun testNewExports() = doExportsTest(
"module M { }",
"module M {\n" +
" exports pkg.m;\n" +
"}")
fun testExportsAfterOther() = doExportsTest(
"module M {\n" +
" exports pkg.other;\n" +
"}",
"module M {\n" +
" exports pkg.other;\n" +
" exports pkg.m;\n" +
"}")
fun testNoNarrowingExports() = doExportsTest(
"module M { exports pkg.m; }",
"module M { exports pkg.m; }")
fun testNoDuplicateExports() = doExportsTest(
"module M { exports pkg.m to M1, M2; }",
"module M { exports pkg.m to M1, M2; }")
fun testNoExportsToUnnamed() = doExportsTest(
"module M { exports pkg.m to M1; }",
"module M { exports pkg.m to M1; }",
target = "")
fun testExportsExtendsOther() = doExportsTest(
"module M {\n" +
" exports pkg.m to M1;\n" +
"}",
"module M {\n" +
" exports pkg.m to M1, M2;\n" +
"}")
fun testExportsExtendsIncompleteOther() = doExportsTest(
"module M {\n" +
" exports pkg.m to M1\n" +
"}",
"module M {\n" +
" exports pkg.m to M1, M2\n" +
"}")
fun testNewUses() = doUsesTest(
"module M { }",
"module M {\n" +
" uses pkg.m.C;\n" +
"}")
fun testUsesAfterOther() = doUsesTest(
"module M {\n" +
" uses pkg.m.B;\n" +
"}",
"module M {\n" +
" uses pkg.m.B;\n" +
" uses pkg.m.C;\n" +
"}")
fun testNoDuplicateUses() = doUsesTest(
"module M { uses pkg.m.C; }",
"module M { uses pkg.m.C; }")
private fun doRequiresTest(text: String, expected: String) = doTest(text, { AddRequiresDirectiveFix(it, "M2") }, expected)
private fun doExportsTest(text: String, expected: String, target: String = "M2") = doTest(text, { AddExportsDirectiveFix(it, "pkg.m", target) }, expected)
private fun doUsesTest(text: String, expected: String) = doTest(text, { AddUsesDirectiveFix(it, "pkg.m.C") }, expected)
private fun doTest(text: String, fix: (PsiJavaModule) -> IntentionAction, expected: String) {
val file = myFixture.configureByText("module-info.java", text) as PsiJavaFile
val action = fix(file.moduleDeclaration!!)
WriteCommandAction.writeCommandAction(file).run<RuntimeException> { action.invoke(project, editor, file) }
assertEquals(expected, file.text)
}
} | apache-2.0 | c96523330488f37426fd5311c7e8aa46 | 30.388889 | 156 | 0.623783 | 3.571128 | false | true | false | false |
ftomassetti/kolasu | emf/src/test/kotlin/com/strumenta/kolasu/emf/simple/kolasu_classes.kt | 1 | 2375 | package com.strumenta.kolasu.emf.simple
import com.strumenta.kolasu.model.*
import java.math.BigDecimal
abstract class Expression(specifiedPosition: Position? = null) : Node(specifiedPosition) {
open fun render(): String = this.javaClass.simpleName
}
// /
// / Literals
// /
sealed class NumberLiteral(specifiedPosition: Position? = null) : Expression(specifiedPosition)
data class IntLiteral(val value: Long, val specifiedPosition: Position? = null) : NumberLiteral(
specifiedPosition
) {
override fun render() = value.toString()
}
data class RealLiteral(val value: BigDecimal, val specifiedPosition: Position? = null) : NumberLiteral(
specifiedPosition
) {
override fun render() = value.toString()
}
data class StringLiteral(val value: String, val specifiedPosition: Position? = null) : Expression(
specifiedPosition
) {
override fun render() = "\"$value\""
}
data class DataDefinition(
override val name: String,
override val type: Type,
var fields: List<FieldDefinition> = emptyList(),
val initializationValue: Expression? = null,
val inz: Boolean = false,
val specifiedPosition: Position? = null
) :
AbstractDataDefinition(name, type, specifiedPosition)
data class FieldDefinition(
override val name: String,
override val type: Type,
val explicitStartOffset: Int? = null,
val explicitEndOffset: Int? = null,
val calculatedStartOffset: Int? = null,
val calculatedEndOffset: Int? = null,
// In case of using LIKEDS we reuse a FieldDefinition, but specifying a different
// container. We basically duplicate it
@property:Link
var overriddenContainer: DataDefinition? = null,
val initializationValue: Expression? = null,
val descend: Boolean = false,
val specifiedPosition: Position? = null,
// true when the FieldDefinition contains a DIM keyword on its line
val declaredArrayInLineOnThisField: Int? = null
) :
AbstractDataDefinition(name, type, specifiedPosition)
abstract class AbstractDataDefinition(
override val name: String,
open val type: Type,
specifiedPosition: Position? = null,
private val hashCode: Int = name.hashCode()
) : Node(specifiedPosition), Named
sealed class Type {
@Derived
abstract val size: Int
}
object FigurativeType : Type() {
@Derived
override val size: Int
get() = 0
}
| apache-2.0 | 307656a991d78c1225757e6f2ffe17c0 | 28.320988 | 103 | 0.717474 | 4.188713 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/DefaultTransformJvmTest.kt | 1 | 1670 | /*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.tests
import io.ktor.client.call.*
import io.ktor.client.engine.mock.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
import java.io.*
import kotlin.test.*
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
class DefaultTransformJvmTest {
@Test
fun testSendInputStream() = testWithEngine(MockEngine) {
config {
engine {
addHandler {
val text = (it.body as OutgoingContent.ReadChannelContent).readFrom().readRemaining().readText()
respond(text)
}
}
}
test { client ->
val response = client.post("/post") {
val stream = ByteArrayInputStream("""{"x": 123}""".toByteArray())
contentType(ContentType.Application.Json)
setBody(stream)
}.bodyAsText()
assertEquals("""{"x": 123}""", response)
}
}
@Test
fun testReceiveInputStream() = testWithEngine(MockEngine) {
config {
engine {
addHandler {
respond("""{"x": 123}""")
}
}
}
test { client ->
val response = client.get("/").body<InputStream>()
assertEquals("""{"x": 123}""", response.bufferedReader().readText())
}
}
}
| apache-2.0 | fae9217b7992dcf888c70884c5775958 | 27.305085 | 119 | 0.55988 | 4.677871 | false | true | false | false |
adrianswiatek/price-comparator | PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/adapters/CardsViewHolder.kt | 1 | 5717 | package com.aswiatek.pricecomparator.adapters
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.aswiatek.pricecomparator.R
import com.aswiatek.pricecomparator.buisinesslogic.Mode
import com.aswiatek.pricecomparator.buisinesslogic.formatters.CurrencyFormatter
import com.aswiatek.pricecomparator.buisinesslogic.formatters.DecimalFormatter
import com.aswiatek.pricecomparator.buisinesslogic.formatters.Formatter
import com.aswiatek.pricecomparator.events.CardsEvent
import com.aswiatek.pricecomparator.events.ModeChangedEvent
import com.aswiatek.pricecomparator.events.ScreenValueChanged
import com.aswiatek.pricecomparator.model.Card
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe
class CardsViewHolder(val context: Context, view: View, private val bus: Bus)
: RecyclerView.ViewHolder(view), View.OnClickListener {
val mDecimalFormatter: Formatter = DecimalFormatter()
val mCurrencyFormatter: Formatter = CurrencyFormatter()
lateinit var mCard: Card
init {
bus.register(this)
}
private val currentQuantity = view.findViewById<TextView>(R.id.current_quantity)
private val currentPrice = view.findViewById<TextView>(R.id.current_price)
private val targetQuantity = view.findViewById<TextView>(R.id.target_quantity)
private val targetPrice = view.findViewById<TextView>(R.id.target_price)
private val cardView = view.findViewById<CardView>(R.id.card)
private val cardHeader = view.findViewById<LinearLayout>(R.id.card_header)
private val editableTextViews = listOf(currentQuantity, currentPrice, targetQuantity)
fun set(card: Card) {
mCard = card
refreshCard()
applyToEditableTextViews { it.setOnClickListener(this) }
cardView.setOnClickListener(this)
onClick(currentQuantity)
}
fun refreshCard() {
currentQuantity.text = getFormattedValue(mCard.currentQuantity, mDecimalFormatter)
currentPrice.text = getFormattedValue(mCard.currentPrice, mCurrencyFormatter)
targetQuantity.text = getFormattedValue(mCard.targetQuantity, mDecimalFormatter)
targetPrice.text = getFormattedValue(mCard.targetPrice, mCurrencyFormatter)
}
private fun getFormattedValue(value: Double, formatter: Formatter): String {
if (formatter is DecimalFormatter && value.toString().endsWith(".0"))
return value.toString().removeSuffix(".0")
return formatter.getFormattedValue(value.toString())
}
override fun onClick(view: View) {
if (view is TextView) {
selectView(view)
bus.post(CardsEvent(this, Mode.getByTag(view.tag), view.text.toString()))
} else {
selectView(currentQuantity)
bus.post(CardsEvent(this, Mode.CurrentQuantity, currentQuantity.text.toString()))
}
setCardAsSelected()
}
private fun selectView(textView: TextView) {
resetTextViews()
val selectedColor: Int = ContextCompat.getColor(context, R.color.accent)
textView.setTextColor(selectedColor)
textView.textScaleX = 1.15f
textView.scaleY = 1.15f
}
private fun resetTextViews() {
applyToEditableTextViews {
val regularColor = ContextCompat.getColor(context, R.color.primary)
it.setTextColor(regularColor)
it.textScaleX = 1f
it.scaleY = 1f
}
}
private fun applyToEditableTextViews(action: (TextView) -> Unit) {
for (textView in editableTextViews) {
action(textView)
}
}
private fun setCardAsSelected() {
val selectedColor = ContextCompat.getColor(context, R.color.primary_dark)
cardHeader.setBackgroundColor(selectedColor)
mCard.isActive = true
}
private fun setCardAsNotSelected() {
val notSelectedColor = ContextCompat.getColor(context, R.color.primary)
cardHeader.setBackgroundColor(notSelectedColor)
mCard.isActive = false
}
@Subscribe
fun cardClicked(event: CardsEvent) {
if (event.viewHolder === this) return
resetTextViews()
setCardAsNotSelected()
}
@Subscribe
fun screenValueChanged(event: ScreenValueChanged) {
if (event.viewHolder !== this) return
when (event.mode) {
Mode.CurrentQuantity -> {
mCard.currentQuantity = event.value.toDouble()
currentQuantity.text = event.value
currentQuantity
}
Mode.CurrentPrice -> {
mCard.currentPrice = event.value.toDouble()
currentPrice.text = event.value
currentPrice
}
Mode.TargetQuantity -> {
mCard.targetQuantity = event.value.toDouble()
targetQuantity.text = event.value
targetQuantity
}
else -> return
}
targetPrice.text = mCurrencyFormatter.getFormattedValue(mCard.targetPrice.toString())
}
@Subscribe
fun modeChanged(event: ModeChangedEvent) {
resetTextViews()
if (event.viewHolder !== this) return
val view = when (event.mode) {
Mode.CurrentQuantity -> currentQuantity
Mode.CurrentPrice -> currentPrice
Mode.TargetQuantity -> targetQuantity
else -> return
}
selectView(view)
refreshCard()
bus.post(CardsEvent(this, event.mode, view.text.toString()))
}
} | mit | caef3e56a263e9bd3c4a0255b73c180d | 34.296296 | 93 | 0.681826 | 4.682228 | false | false | false | false |
beyondeye/graphkool | graphkool-core/src/main/kotlin/com/beyondeye/graphkool/core.kt | 1 | 2549 | package com.beyondeye.graphkool
import graphql.GraphQL
import graphql.execution.ExecutionStrategy
import graphql.schema.*
/**
* Created by daely on 12/8/2016.
*/
fun newGraphQL(schemaBuilder: GraphQLSchema.Builder, executionStrategy: ExecutionStrategy?=null) = GraphQL(schemaBuilder.build(),executionStrategy)
fun newGraphQL(schema: GraphQLSchema, executionStrategy: ExecutionStrategy?=null) = GraphQL(schema,executionStrategy)
fun newObject(name:String)= GraphQLObjectType.newObject().name(name)
fun newEnum(name:String)= GraphQLEnumType.newEnum().name(name)
fun newInterface(name:String)=GraphQLInterfaceType.newInterface().name(name)
infix fun String.ofType(type_: GraphQLOutputType): GraphQLFieldDefinition.Builder {
return GraphQLFieldDefinition.newFieldDefinition().type(type_).name(this)
}
operator fun String.rangeTo(type_: GraphQLOutputType) = this.ofType(type_)
fun GraphQLType.nonNull() = GraphQLNonNull(this)
operator fun GraphQLType.not() = GraphQLNonNull(this)
infix fun GraphQLFieldDefinition.Builder.staticValue(value:Any) = this.staticValue(value)
infix fun GraphQLFieldDefinition.Builder.description(d:String) = this.description(d)
infix fun GraphQLFieldDefinition.Builder.dataFetcher(fetcher:DataFetcher) = this.dataFetcher(fetcher)
fun newGraphQLSchema( query: GraphQLObjectType.Builder)= GraphQLSchema.newSchema().query(query)
fun listOfRefs(typeName:String)=GraphQLList(GraphQLTypeReference(typeName))
fun listOfObjs(wrappedType: GraphQLType) = GraphQLList(wrappedType)
infix fun GraphQLFieldDefinition.Builder.argument(builder: GraphQLArgument.Builder) = this.argument(builder)
infix fun GraphQLFieldDefinition.Builder.argument(newa: GQLArgumentBuilder) = this.argument(newa.build())
operator fun String.unaryPlus()= GQLArgumentBuilder(this)
operator fun GQLArgumentBuilder.rangeTo(type_: GraphQLInputType) = this.type(type_)
class GQLArgumentBuilder(val name:String) {
private var type: GraphQLInputType? = null
private var defaultValue: Any? = null
private var description: String? = null
infix fun description(description: String): GQLArgumentBuilder {
this.description = description
return this
}
infix fun type(type: GraphQLInputType): GQLArgumentBuilder {
this.type = type
return this
}
infix fun defaultValue(defaultValue: Any): GQLArgumentBuilder {
this.defaultValue = defaultValue
return this
}
fun build(): GraphQLArgument {
return GraphQLArgument(name, description, type, defaultValue)
}
}
| apache-2.0 | e874f7ab9d54ff7d670eaf72ea2059af | 37.621212 | 147 | 0.781483 | 4.364726 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterProgressPutResolver.kt | 2 | 1405 | package eu.kanade.tachiyomi.data.database.resolvers
import androidx.core.content.contentValuesOf
import com.pushtorefresh.storio.sqlite.StorIOSQLite
import com.pushtorefresh.storio.sqlite.operations.put.PutResolver
import com.pushtorefresh.storio.sqlite.operations.put.PutResult
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import eu.kanade.tachiyomi.data.database.inTransactionReturn
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.tables.ChapterTable
class ChapterProgressPutResolver : PutResolver<Chapter>() {
override fun performPut(db: StorIOSQLite, chapter: Chapter) = db.inTransactionReturn {
val updateQuery = mapToUpdateQuery(chapter)
val contentValues = mapToContentValues(chapter)
val numberOfRowsUpdated = db.lowLevel().update(updateQuery, contentValues)
PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table())
}
fun mapToUpdateQuery(chapter: Chapter) = UpdateQuery.builder()
.table(ChapterTable.TABLE)
.where("${ChapterTable.COL_ID} = ?")
.whereArgs(chapter.id)
.build()
fun mapToContentValues(chapter: Chapter) =
contentValuesOf(
ChapterTable.COL_READ to chapter.read,
ChapterTable.COL_BOOKMARK to chapter.bookmark,
ChapterTable.COL_LAST_PAGE_READ to chapter.last_page_read
)
}
| apache-2.0 | 399280998db5a571d4199398cd87fe8a | 40.323529 | 90 | 0.753025 | 4.390625 | false | false | false | false |
pureal-code/pureal-os | android.backend/src/net/pureal/android/backend/GlText.kt | 1 | 6161 | package net.pureal.android.backend
import net.pureal.traits.graphics.TextElement
import net.pureal.traits.graphics.Font
import net.pureal.traits.graphics.Fill
import net.pureal.traits.math.Shape
import android.content.res.Resources
import java.util.HashMap
import java.io.InputStreamReader
import android.opengl.GLES20
import android.graphics.BitmapFactory
import android.opengl.GLUtils
//TODO: override val original (runtime compiler barf)
class GlTextElement(val originalText: TextElement, screen: GlScreen) : TextElement, GlColoredElement(originalText, screen) {
override val shader = screen.fontShader
override val shape: GlShape get() = super<GlColoredElement>.shape
override val font: GlFont get() = glFont(originalText.font)
override val size: Number get() = originalText.size
override val fill: Fill get() = originalText.fill
override val content: String get() = originalText.content
}
class GlFont(resources: Resources) : Font {
class Page(val id: Int, val file: String)
class Glyph(val id: Int, val x: Int, val y: Int, val width: Int, val height: Int,
val xOffset: Int, val yOffset: Int, val xAdvance: Int, val page: Int)
val pages = HashMap<Int, Page>()
val glyphs = HashMap<Char, Glyph>()
val kernings = HashMap<Int, HashMap<Int, Int>>()
init {
val stream = resources.openRawResource(R.raw.roboto_regular)
try {
val reader = InputStreamReader(stream, "UTF-8")
reader.forEachLine {
val entries = (it.split(' ') filter { it.any() }).toList()
if (entries.any()) {
val tag = entries[0]
val values = (entries drop 1 map {
val strings = it.split("=")
Pair(strings.first(), strings.last())
}).toMap()
// TODO: use "when" instead (causes compiler barf right now)
val id = values["id"]?.toInt() ?: 0
if (tag == ("page")) {
pages.put(id, Page(id, values["file"] ?: ""))
} else if (tag == ("char")) {
glyphs.put(id.toChar(), Glyph(id,
values["x"]?.toInt() ?: 0, values["y"]?.toInt() ?: 0,
values["width"]?.toInt() ?: 0, values["height"]?.toInt() ?: 0,
values["xoffset"]?.toInt() ?: 0, values["yoffset"]?.toInt() ?: 0,
values["xadvance"]?.toInt() ?: 0, values["page"]?.toInt() ?: 0))
} else if (tag == ("kerning")) {
val first = values["first"]?.toInt() ?: 0
val second = values["second"]?.toInt() ?: 0
val amount = values["amount"]?.toInt() ?: 0
val map = kernings.getOrPut(first) { -> HashMap<Int, Int>() }
map.put(second, amount)
}
}
}
} finally {
stream.close()
}
}
private val textureNames: IntArray = IntArray(1);
val textureName : Int get() = textureNames[0]
init {
GLES20.glGenTextures(textureNames.size, textureNames, 0);
val bmp = BitmapFactory.decodeResource(resources, R.drawable.roboto_regular)!!;
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureName);
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// Load the bitmap into the bound texture.
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
// We are done using the bitmap so we should recycle it.
bmp.recycle();
}
override fun shape(text: String): Shape {
return GlGlyphs(this, text)
}
private fun measureString(text: String): Number {
return text.length // TODO: fix this
}
}
fun glFont(original: Font): GlFont {
return when (original) {
is GlFont -> original
else -> throw UnsupportedOperationException("No OpenGL implementation for font '${original}'.")
}
}
class GlGlyphs(val font: GlFont, val text: String) : GlShape() {
override val textureName: Int = font.textureName
override val vertexCoordinates = FloatArray(text.length * 2 * 4)
override val textureCoordinates = FloatArray(text.length * 2 * 4)
override val drawOrder = ShortArray(text.length * 6)
override val glVertexMode: Int = GLES20.GL_TRIANGLES
init {
var ic = 0
var it = 0
var n : Short = 0
fun addVertex(x: Float, y: Float, tx: Float, ty: Float): Short {
vertexCoordinates[ic++] = x / 40
vertexCoordinates[ic++] = y / 40
textureCoordinates[it++] = tx / 1024
textureCoordinates[it++] = ty / 1024
return n++
}
var id = 0
fun addQuad(x: Float, y: Float, w: Float, h: Float, tx: Float, ty: Float) {
var bl = addVertex(x, y, tx, ty + h)
var br = addVertex(x + w, y, tx + w, ty + h)
var tr = addVertex(x + w, y + h, tx + w, ty)
var tl = addVertex(x, y + h, tx, ty)
drawOrder[id++] = bl
drawOrder[id++] = br
drawOrder[id++] = tl
drawOrder[id++] = tr
drawOrder[id++] = tl
drawOrder[id++] = br
}
var cx = 0f
var cy = 0f
for (char in text) {
val glyph = font.glyphs[char] ?: font.glyphs[' ']!!
addQuad(cx + glyph.xOffset, cy - glyph.height - glyph.yOffset,
glyph.width.toFloat(), glyph.height.toFloat(),
glyph.x.toFloat(), glyph.y.toFloat())
cx += glyph.xAdvance
if (char == 10.toChar()) {
cx = 0f
cy -= 40
}
}
}
//override fun contains(location: Vector2): Boolean = //TODO
} | bsd-3-clause | 313cefe4c6b057c5d6681860a2999830 | 39.27451 | 124 | 0.55267 | 4.115564 | false | false | false | false |
zhclwr/YunWeatherKotlin | app/src/main/java/com/victor/yunweatherkotlin/activity/WeatherActivity.kt | 1 | 9012 | package com.victor.yunweatherkotlin.activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.support.v4.view.GravityCompat
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.victor.yunweatherkotlin.R
import com.victor.yunweatherkotlin.db.County
import com.victor.yunweatherkotlin.gson.HeWeather
import com.victor.yunweatherkotlin.gson.Weather
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.aqi.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.now.*
import kotlinx.android.synthetic.main.suggestion.*
import kotlinx.android.synthetic.main.title.*
import org.jetbrains.anko.*
import org.litepal.crud.DataSupport
import java.net.URL
/**
* https://free-api.heweather.com/v5/weather?city=yourcity&key=yourkey
*
* key: ac4cceaa37be4d7099f04b2b0b456041
*
* such as : https://free-api.heweather.com/v5/weather?city=CN101191303&key=ac4cceaa37be4d7099f04b2b0b456041
*
* bingPic: http://guolin.tech/api/bing_pic
*
* bg: http://116.196.93.90/png/bg.png
* */
class WeatherActivity : BaseActivity() {
private val key = "ac4cceaa37be4d7099f04b2b0b456041"
private lateinit var cityCode: String
private lateinit var weatherStr: String
private lateinit var sp: SharedPreferences
private lateinit var handler: Handler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather)
sp = defaultSharedPreferences
handler = Handler()
setLinstener()
judgeIf()
requestWeather()
bingPic()
// bgPic()
}
/**
* 点返回按钮时,关闭drawer_layout
* */
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event?.repeatCount == 0) {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
return super.onKeyDown(keyCode, event)
}
/**
* SingleTask模式再次启动Activity时调用
* */
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent?.getBooleanExtra("update", false)!!) {
swipe_refresh.isRefreshing = true
requestWeather()
}
}
/**bg背景图*/
private fun bgPic(){
Glide.with(applicationContext).load("http://116.196.93.90/png/bg1.png").into(iv_bing)
}
/**Bing背景图*/
private fun bingPic() {
doAsync {
val imageUrl = URL("http://guolin.tech/api/bing_pic").readText()
uiThread {
Glide.with(applicationContext).load(imageUrl).into(iv_bing)
}
}
}
/**是否需要存入数据库和显示天气*/
private fun judgeIf() {
//判断china-city-list是否有写到数据库,没有就欢迎启动导入数据库
if (sp.getBoolean("data", true)) {
startActivity(Intent(this, LoadActivity::class.java))
finish()
}
//判断是否有缓存的天气
if ("" != sp.getString("weatherStr", "")) {
showWeather()
} else {
can_gone.visibility = View.GONE
title_city.text = "暂无天气"
image_add.visibility = View.VISIBLE
}
cityCode = sp.getString("cityCode", "")
if ("" != cityCode) {
requestWeather()
}
}
/**
* 将从服务器查询到的天气展示出来
* */
private fun showWeather() {
weatherStr = sp.getString("weatherStr", "")
if (weatherStr == "") return
else {
can_gone.visibility = View.VISIBLE
image_add.visibility = View.GONE
val gson = Gson()
val weather: Weather = gson.fromJson(weatherStr, Weather::class.java)
val heWeather = weather.HeWeather5[0]
//将城市信息和天气情况保存到数据库
saveCounty(heWeather)
title_city.text = heWeather.basic.city
title_update_time.text = heWeather.basic.update.loc.split(" ")[1]+"发布"
degree_text.text = heWeather.now.tmp + "℃"
weather_info_text.text = heWeather.now.cond.txt
aqi_text.text = heWeather.aqi?.city?.aqi
pm25_text.text = heWeather.aqi?.city?.pm25
comfort_title.text = "综合 "+heWeather.suggestion.comf.brf
comfort_text.text = heWeather.suggestion.comf.txt
cw_title.text = "洗车 "+heWeather.suggestion.cw.brf
cw_text.text = heWeather.suggestion.cw.txt
drsg_title.text = "穿衣 "+heWeather.suggestion.drsg.brf
drsg_text.text = heWeather.suggestion.comf.txt
flu_title.text = "感冒 "+heWeather.suggestion.flu.brf
flu_text.text = heWeather.suggestion.flu.txt
sport_title.text = "运动 "+heWeather.suggestion.sport.brf
sport_text.text = heWeather.suggestion.sport.txt
trav_title.text = "旅游 "+heWeather.suggestion.trav.brf
trav_text.text = heWeather.suggestion.trav.txt
uv_title.text = "紫外线 "+heWeather.suggestion.comf.brf
uv_text.text = heWeather.suggestion.comf.txt
forecast_layout.removeAllViews()
for ((date, tmp, cond) in heWeather.daily_forecast) {
val view = LayoutInflater.from(applicationContext).inflate(R.layout.forecast_item, forecast_layout, false)
val dateText = view.find<TextView>(R.id.date_text)
val infoText = view.find<TextView>(R.id.info_text) as TextView
val maxText = view.find<TextView>(R.id.max_text) as TextView
val minText = view.find<TextView>(R.id.min_text) as TextView
dateText.text = date
infoText.text = cond.txt_d
maxText.text = tmp.max
minText.text = tmp.min
forecast_layout.addView(view)
}
}
swipe_refresh.isRefreshing = false
}
/**
* 保存曾经查询过的城市名和天气信息,以便管理
* */
private fun saveCounty(weather: HeWeather) {
val county = County(weather.basic.city, weather.now.cond.txt, sp.getString("cityCode", ""))
val counties = DataSupport.findAll(County::class.java)
var temp = ArrayList<String>()
counties.mapTo(temp) { it.name }
if (county.name in temp) return else county.save()
}
private fun setLinstener() {
nav_button.setOnClickListener { drawer_layout.openDrawer(GravityCompat.START) }
nav_view.setNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.edit_location -> {
startActivity(Intent(this, EditCitysActivity::class.java))
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
handler.postDelayed({
drawer_layout.closeDrawer(GravityCompat.START)
}, 100)
}
}
R.id.nav_about -> {
startActivity(Intent(this, AboutActivity::class.java))
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
handler.postDelayed({
drawer_layout.closeDrawer(GravityCompat.START)
}, 100)
}
longToast("有隐藏内容待发现!")
}
}
true
}
swipe_refresh.setOnRefreshListener {
requestWeather()
bingPic()
// bgPic()
}
image_add.setOnClickListener {
startActivity(Intent(applicationContext, AddCityActivity::class.java))
}
}
/**请求天气*/
private fun requestWeather() {
cityCode = sp.getString("cityCode", "")
if ("" != cityCode) {
doAsync {
var url = "https://free-api.heweather.com/v5/weather?city=$cityCode&key=$key"
var resultStr = URL(url).readText()
defaultSharedPreferences
.edit()
.putString("weatherStr", resultStr)
.apply()
uiThread { showWeather() }
}
}
}
}
| apache-2.0 | 87fc9c67cbce3c0fa2e8d2612c830f82 | 35.004255 | 122 | 0.574172 | 4.040892 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTestCase.kt | 22 | 1800 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.testIntergration
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo
import com.intellij.testIntegration.RecentTestsData
import com.intellij.testIntegration.SingleTestEntry
import com.intellij.testIntegration.SuiteEntry
import org.mockito.Mockito
import java.util.*
abstract class RecentTestsTestCase {
private val data = RecentTestsData()
private val allTests: RunnerAndConfigurationSettings = mockConfiguration("all tests", "JUnit.all tests")
protected val now = Date()
protected fun mockConfiguration(name: String, uniqueID: String): RunnerAndConfigurationSettings {
val settings = Mockito.mock(RunnerAndConfigurationSettings::class.java)
Mockito.`when`(settings.uniqueID).thenAnswer { uniqueID }
Mockito.`when`(settings.name).thenAnswer { name }
return settings
}
protected fun addSuite(suiteName: String, date: Date, runConfiguration: RunnerAndConfigurationSettings = allTests) =
data.addSuite(SuiteEntry("java:suite://$suiteName", date, runConfiguration))
protected fun addPassedTest(testName: String, date: Date, runConfiguration: RunnerAndConfigurationSettings = allTests) =
data.addTest(SingleTestEntry("java:test://$testName", date, runConfiguration, TestStateInfo.Magnitude.PASSED_INDEX))
protected fun addFailedTest(testName: String, date: Date, runConfiguration: RunnerAndConfigurationSettings = allTests) =
data.addTest(SingleTestEntry("java:test://$testName", date, runConfiguration, TestStateInfo.Magnitude.FAILED_INDEX))
protected fun getTestsToShow() = data.getTestsToShow()
} | apache-2.0 | ddce596768b0c1a2a2dfd085343bdfa1 | 49.027778 | 140 | 0.797778 | 4.651163 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/JavaContextDeclarationRenderer.kt | 6 | 4758 | // 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.conversion.copy
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
data class ContextDeclarations(
val localDeclarationsJavaStubs: String,
val memberDeclarationsJavaStubs: String
)
class JavaContextDeclarationRenderer {
private val KtElement.memberDeclarations
get() = parentsWithSelf
.flatMap { declaration ->
when (declaration) {
is KtClass -> declaration.resolveToDescriptorIfAny()
?.unsubstitutedMemberScope
?.getContributedDescriptors()
?.asSequence()
is KtDeclarationContainer ->
declaration.declarations.mapNotNull { it.resolveToDescriptorIfAny() }.asSequence()
else -> null
} ?: emptySequence()
}.filter { member ->
member !is DeserializedMemberDescriptor
&& !member.name.isSpecial
&& member.name.asString() != "dummy"
}
private val KtElement.localDeclarations
get() = getParentOfType<KtDeclaration>(strict = false)
?.safeAs<KtFunction>()
?.bodyExpression
?.blockExpressionsOrSingle()
?.filterIsInstance<KtDeclaration>()
?.mapNotNull { it.resolveToDescriptorIfAny() }
.orEmpty()
fun render(contextElement: KtElement): ContextDeclarations =
ContextDeclarations(
contextElement.localDeclarations.render(),
contextElement.memberDeclarations.render()
)
private fun Sequence<DeclarationDescriptor>.render() =
buildString {
for (member in this@render) {
renderJavaDeclaration(member)
appendLine()
}
}
private fun StringBuilder.renderJavaDeclaration(declaration: DeclarationDescriptor) {
when (declaration) {
is VariableDescriptorWithAccessors -> {
renderType(declaration.type)
append(' ')
append(declaration.name.asString())
append(" = null;")
}
is FunctionDescriptor -> {
renderType(declaration.returnType)
append(' ')
append(declaration.name.asString())
append('(')
for ((i, parameter) in declaration.valueParameters.withIndex()) {
renderType(parameter.type)
append(' ')
append(parameter.name.asString())
if (i != declaration.valueParameters.lastIndex) {
append(", ")
}
}
append(") {}")
}
}
}
private fun StringBuilder.renderType(type: KotlinType?) {
val fqName = type?.constructor?.declarationDescriptor?.fqNameUnsafe
if (fqName != null) {
renderFqName(fqName)
} else {
append("Object")
}
if (!type?.arguments.isNullOrEmpty()) {
append("<")
for (typeArgument in type!!.arguments) {
if (typeArgument.isStarProjection) {
append("?")
} else {
renderType(typeArgument.type)
}
}
append(">")
}
}
private fun StringBuilder.renderFqName(fqName: FqNameUnsafe) {
val stringFqName = when (fqName) {
StandardNames.FqNames.unit -> "void"
else -> JavaToKotlinClassMap.mapKotlinToJava(fqName)?.asSingleFqName() ?: fqName.asString()
}
append(stringFqName)
}
}
| apache-2.0 | c4e2b7a4505fe0b479489d5fb63d5890 | 37.064 | 158 | 0.605086 | 5.838037 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/BooleanLiteralArgumentInspection.kt | 2 | 4697 | // 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.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.intentions.AddNameToArgumentIntention
import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention
import org.jetbrains.kotlin.idea.intentions.AddNamesToFollowingArgumentsIntention
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import javax.swing.JComponent
class BooleanLiteralArgumentInspection(
@JvmField var reportSingle: Boolean = false
) : AbstractKotlinInspection() {
companion object {
private val ignoreConstructors = listOf("kotlin.Pair", "kotlin.Triple").map { FqName(it) }
}
private fun KtExpression.isBooleanLiteral(): Boolean =
this is KtConstantExpression && node.elementType == KtNodeTypes.BOOLEAN_CONSTANT
private fun KtValueArgument.isUnnamedBooleanLiteral(): Boolean =
!isNamed() && getArgumentExpression()?.isBooleanLiteral() == true
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
valueArgumentVisitor(fun(argument: KtValueArgument) {
if (argument.isNamed()) return
val argumentExpression = argument.getArgumentExpression() ?: return
if (!argumentExpression.isBooleanLiteral()) return
val call = argument.getStrictParentOfType<KtCallExpression>() ?: return
val valueArguments = call.valueArguments
if (argumentExpression.safeAnalyzeNonSourceRootCode().diagnostics.forElement(argumentExpression).any { it.severity == Severity.ERROR }) return
if (AddNameToArgumentIntention.detectNameToAdd(argument, shouldBeLastUnnamed = false) == null) return
val resolvedCall = call.resolveToCall() ?: return
if ((resolvedCall.resultingDescriptor as? ClassConstructorDescriptor)?.constructedClass?.fqNameOrNull() in ignoreConstructors) {
return
}
if (!resolvedCall.candidateDescriptor.hasStableParameterNames()) return
val languageVersionSettings = call.languageVersionSettings
if (valueArguments.any {
!AddNameToArgumentIntention.argumentMatchedAndCouldBeNamedInCall(it, resolvedCall, languageVersionSettings)
}
) return
val highlightType = if (reportSingle) {
GENERIC_ERROR_OR_WARNING
} else {
val hasNeighbourUnnamedBoolean = valueArguments.asSequence().windowed(size = 2, step = 1).any { (prev, next) ->
prev == argument && next.isUnnamedBooleanLiteral() ||
next == argument && prev.isUnnamedBooleanLiteral()
}
if (hasNeighbourUnnamedBoolean) GENERIC_ERROR_OR_WARNING else INFORMATION
}
val fix = if (argument != valueArguments.lastOrNull { !it.isNamed() }) {
if (argument == valueArguments.firstOrNull()) {
AddNamesToCallArgumentsIntention()
} else {
AddNamesToFollowingArgumentsIntention()
}
} else {
AddNameToArgumentIntention()
}
holder.registerProblemWithoutOfflineInformation(
argument, KotlinBundle.message("boolean.literal.argument.without.parameter.name"),
isOnTheFly, highlightType, IntentionWrapper(fix)
)
})
override fun createOptionsPanel(): JComponent {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(KotlinBundle.message("report.also.on.call.with.single.boolean.literal.argument"), "reportSingle")
return panel
}
}
| apache-2.0 | 03f78eae8cc590dbaff4efda1a6cffa0 | 51.188889 | 158 | 0.712795 | 5.480747 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/editor/actions/GroovyStringBackslashHandler.kt | 15 | 1483 | // 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.editor.actions
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.STRING_SQ
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.STRING_TSQ
class GroovyStringBackslashHandler : TypedHandlerDelegate() {
override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result {
if (c == '\\') {
val offset = editor.caretModel.offset
if (shouldInsertAdditionalSlash(file, offset - 1)) { // document is not committed yet, so we have to subtract 1
editor.document.insertString(offset, "\\")
editor.selectionModel.setSelection(offset, offset + 1)
return Result.DEFAULT
}
}
return super.charTyped(c, project, editor, file)
}
private fun shouldInsertAdditionalSlash(file: PsiFile, offset: Int): Boolean {
val literal = file.findElementAt(offset) ?: return false
val tokenType = literal.node.elementType
return tokenType == STRING_SQ && literal.textRange.endOffset - offset == 1 // 'bla bla <here>'
|| tokenType == STRING_TSQ && literal.textRange.endOffset - offset == 3 // '''bla bla <here>'''
}
}
| apache-2.0 | 87c8f90603721a069d90f9c06671cc65 | 46.83871 | 140 | 0.730951 | 4.201133 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/floating/FloatingToolbar.kt | 5 | 6743 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.floating
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parents
import com.intellij.ui.LightweightHint
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.jetbrains.annotations.ApiStatus
import java.awt.Point
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
import kotlin.properties.Delegates
@ApiStatus.Internal
open class FloatingToolbar(val editor: Editor, private val actionGroupId: String) : Disposable {
private val mouseListener = MouseListener()
private val keyboardListener = KeyboardListener()
private val mouseMotionListener = MouseMotionListener()
private var hint: LightweightHint? = null
private var buttonSize: Int by Delegates.notNull()
private var lastSelection: String? = null
init {
registerListeners()
}
fun isShown() = hint != null
fun hideIfShown() {
hint?.hide()
}
fun showIfHidden() {
if (hint != null || !canBeShownAtCurrentSelection()) {
return
}
val toolbar = createActionToolbar(editor.contentComponent) ?: return
buttonSize = toolbar.maxButtonHeight
val newHint = LightweightHint(toolbar.component)
newHint.setForceShowAsPopup(true)
showOrUpdateLocation(newHint)
newHint.addHintListener { this.hint = null }
this.hint = newHint
}
fun updateLocationIfShown() {
showOrUpdateLocation(hint ?: return)
}
override fun dispose() {
unregisterListeners()
hideIfShown()
hint = null
}
private fun createActionToolbar(targetComponent: JComponent): ActionToolbar? {
val group = CustomActionsSchema.getInstance().getCorrectedAction(actionGroupId) as? ActionGroup ?: return null
val toolbar = object: ActionToolbarImpl(ActionPlaces.EDITOR_TOOLBAR, group, true) {
override fun addNotify() {
super.addNotify()
updateActionsImmediately(true)
}
}
toolbar.targetComponent = targetComponent
toolbar.setReservePlaceAutoPopupIcon(false)
return toolbar
}
private fun showOrUpdateLocation(hint: LightweightHint) {
HintManagerImpl.getInstanceImpl().showEditorHint(
hint,
editor,
getHintPosition(hint),
HintManager.HIDE_BY_ESCAPE or HintManager.UPDATE_BY_SCROLLING,
0,
true
)
}
private fun registerListeners() {
editor.addEditorMouseListener(mouseListener)
editor.addEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.addKeyListener(keyboardListener)
}
private fun unregisterListeners() {
editor.removeEditorMouseListener(mouseListener)
editor.removeEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.removeKeyListener(keyboardListener)
}
private fun canBeShownAtCurrentSelection(): Boolean {
val file = PsiEditorUtil.getPsiFile(editor)
PsiDocumentManager.getInstance(file.project).commitDocument(editor.document)
val selectionModel = editor.selectionModel
val elementAtStart = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionStart)
val elementAtEnd = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionEnd)
return !(hasIgnoredParent(elementAtStart) || hasIgnoredParent(elementAtEnd))
}
protected open fun hasIgnoredParent(element: PsiElement): Boolean {
if (element.containingFile !is MarkdownFile) {
return true
}
return element.parents(withSelf = true).any { it.elementType in elementsToIgnore }
}
private fun getHintPosition(hint: LightweightHint): Point {
val hintPos = HintManagerImpl.getInstanceImpl().getHintPosition(hint, editor, HintManager.DEFAULT)
// because of `hint.setForceShowAsPopup(true)`, HintManager.ABOVE does not place the hint above
// the hint remains on the line, so we need to move it up ourselves
val dy = -(hint.component.preferredSize.height + verticalGap)
val dx = buttonSize * -2
hintPos.translate(dx, dy)
return hintPos
}
private fun updateOnProbablyChangedSelection(onSelectionChanged: (String) -> Unit) {
val newSelection = editor.selectionModel.selectedText
when (newSelection) {
null -> hideIfShown()
lastSelection -> Unit
else -> onSelectionChanged(newSelection)
}
lastSelection = newSelection
}
private inner class MouseListener : EditorMouseListener {
override fun mouseReleased(e: EditorMouseEvent) {
updateOnProbablyChangedSelection {
if (isShown()) {
updateLocationIfShown()
} else {
showIfHidden()
}
}
}
}
private inner class KeyboardListener : KeyAdapter() {
override fun keyReleased(e: KeyEvent) {
super.keyReleased(e)
if (e.source != editor.contentComponent) {
return
}
updateOnProbablyChangedSelection {
hideIfShown()
}
}
}
private inner class MouseMotionListener : EditorMouseMotionListener {
override fun mouseMoved(e: EditorMouseEvent) {
val visualPosition = e.visualPosition
val hoverSelected = editor.caretModel.allCarets.any {
val beforeSelectionEnd = it.selectionEndPosition.after(visualPosition)
val afterSelectionStart = visualPosition.after(it.selectionStartPosition)
beforeSelectionEnd && afterSelectionStart
}
if (hoverSelected) {
showIfHidden()
}
}
}
companion object {
private const val verticalGap = 2
private val elementsToIgnore = listOf(
MarkdownElementTypes.CODE_FENCE,
MarkdownElementTypes.CODE_BLOCK,
MarkdownElementTypes.CODE_SPAN,
MarkdownElementTypes.HTML_BLOCK,
MarkdownElementTypes.LINK_DESTINATION
)
}
}
| apache-2.0 | 02f6d9bf7437e621cd474229eb46fa05 | 32.715 | 158 | 0.749221 | 4.847592 | false | false | false | false |
zeapo/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/PasswordEntry.kt | 1 | 5125 | package com.zeapo.pwdstore
import android.net.Uri
import java.io.ByteArrayOutputStream
import java.io.UnsupportedEncodingException
/**
* A single entry in password store.
*/
class PasswordEntry(private val content: String) {
val password: String
val username: String?
val digits: String
val totpSecret: String?
val totpPeriod: Long
val totpAlgorithm: String
val hotpSecret: String?
val hotpCounter: Long?
var extraContent: String? = null
private set
private var isIncremented = false
@Throws(UnsupportedEncodingException::class)
constructor(os: ByteArrayOutputStream) : this(os.toString("UTF-8"))
init {
val passContent = content.split("\n".toRegex(), 2).toTypedArray()
password = passContent[0]
digits = findOtpDigits(content)
totpSecret = findTotpSecret(content)
totpPeriod = findTotpPeriod(content)
totpAlgorithm = findTotpAlgorithm(content)
hotpSecret = findHotpSecret(content)
hotpCounter = findHotpCounter(content)
extraContent = findExtraContent(passContent)
username = findUsername()
}
fun hasExtraContent(): Boolean {
return !extraContent.isNullOrEmpty()
}
fun hasUsername(): Boolean {
return username != null
}
fun hasTotp(): Boolean {
return totpSecret != null
}
fun hasHotp(): Boolean {
return hotpSecret != null && hotpCounter != null
}
fun hotpIsIncremented(): Boolean {
return isIncremented
}
fun incrementHotp() {
content.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://hotp/")) {
extraContent = extraContent?.replaceFirst("counter=[0-9]+".toRegex(), "counter=${hotpCounter!! + 1}")
isIncremented = true
}
}
}
private fun findUsername(): String? {
val extraLines = extraContent!!.split("\n".toRegex())
for (line in extraLines) {
for (field in USERNAME_FIELDS) {
if (line.toLowerCase().startsWith("$field:", ignoreCase = true)) {
return line.split(": *".toRegex(), 2).toTypedArray()[1]
}
}
}
return null
}
private fun findTotpSecret(decryptedContent: String): String? {
decryptedContent.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://totp/")) {
return Uri.parse(line).getQueryParameter("secret")
}
if (line.toLowerCase().startsWith("totp:")) {
return line.split(": *".toRegex(), 2).toTypedArray()[1]
}
}
return null
}
private fun findOtpDigits(decryptedContent: String): String {
decryptedContent.split("\n".toRegex()).forEach { line ->
if ((line.startsWith("otpauth://totp/") ||
line.startsWith("otpauth://hotp/")) &&
Uri.parse(line).getQueryParameter("digits") != null) {
return Uri.parse(line).getQueryParameter("digits")!!
}
}
return "6"
}
private fun findTotpPeriod(decryptedContent: String): Long {
decryptedContent.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://totp/") &&
Uri.parse(line).getQueryParameter("period") != null) {
return java.lang.Long.parseLong(Uri.parse(line).getQueryParameter("period")!!)
}
}
return 30
}
private fun findTotpAlgorithm(decryptedContent: String): String {
decryptedContent.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://totp/") &&
Uri.parse(line).getQueryParameter("algorithm") != null) {
return Uri.parse(line).getQueryParameter("algorithm")!!
}
}
return "sha1"
}
private fun findHotpSecret(decryptedContent: String): String? {
decryptedContent.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://hotp/")) {
return Uri.parse(line).getQueryParameter("secret")
}
}
return null
}
private fun findHotpCounter(decryptedContent: String): Long? {
decryptedContent.split("\n".toRegex()).forEach { line ->
if (line.startsWith("otpauth://hotp/")) {
return java.lang.Long.parseLong(Uri.parse(line).getQueryParameter("counter")!!)
}
}
return null
}
private fun findExtraContent(passContent: Array<String>): String {
val extraContent = if (passContent.size > 1) passContent[1] else ""
// if there is a HOTP URI, we must return the extra content with the counter incremented
return if (hasHotp()) {
extraContent.replaceFirst("counter=[0-9]+".toRegex(), "counter=" + (hotpCounter!!).toString())
} else extraContent
}
companion object {
private val USERNAME_FIELDS = arrayOf("login", "username")
}
}
| gpl-3.0 | 76486c4298f332895e40577737be6ad7 | 32.279221 | 117 | 0.584 | 4.571811 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Client.kt | 1 | 214651 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.objectweb.asm.tree.JumpInsnNode
import org.runestar.client.updater.mapper.*
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.std.*
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
import java.applet.Applet
import java.io.File
import java.lang.management.GarbageCollectorMXBean
import java.lang.reflect.Modifier
import java.net.URL
import java.security.SecureRandom
import java.util.*
import java.util.concurrent.ScheduledExecutorService
import java.util.zip.CRC32
import kotlin.collections.ArrayList
class Client : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.name == "client" }
@DependsOn(Player::class)
class localPlayer : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Player>() }
}
@DependsOn(Player::class)
class players : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Player>().withDimensions(1) }
}
@DependsOn(Npc::class)
class npcs : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Npc>().withDimensions(1) }
}
@DependsOn(Scenery::class)
class scenery : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Scenery>().withDimensions(1) }
}
@MethodParameters("id")
@DependsOn(NPCType::class)
class getNPCType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<NPCType>() }
}
@MethodParameters("id")
@DependsOn(EnumType::class)
class getEnumType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<EnumType>() }
}
// // @DependsOn(OverlayDefinition::class)
// class getOverlayDefinition : StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<OverlayDefinition>() }
// }
// @DependsOn(UnderlayDefinition::class)
// class getUnderlayDefinition : StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<UnderlayDefinition>() }
// }
// @MethodParameters("id")
// @DependsOn(HealthBarDefinition::class)
// class getHealthBarDefinition : StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<HealthBarDefinition>() }
// }
@DependsOn(IDKType::class)
class getIDKType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<IDKType>() }
}
// // @DependsOn(EnumType::class)
// class getEnumType : StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<EnumType>() }
// }
@DependsOn(SpotType::class)
class getSpotType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<SpotType>() }
}
@DependsOn(SeqType::class)
class getSeqType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<SeqType>() }
}
@MethodParameters("id")
@DependsOn(ObjType::class)
class getObjType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<ObjType>() }
}
@MethodParameters("id")
@DependsOn(LocType::class)
class getLocType : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<LocType>() }
}
@MethodParameters("argument1", "argument2", "opcode", "argument0", "action", "targetName", "mouseX", "mouseY")
class doAction : StaticMethod() {
override val predicate = predicateOf<Method2> {
it.arguments.startsWith(
INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE,
String::class.type, String::class.type, INT_TYPE, INT_TYPE)
}
}
@MethodParameters("targetVerb", "opbase", "opcode", "arg0", "arg1", "arg2", "b")
class addMiniMenuEntry : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(String::class.type, String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.opcode == GETSTATIC } }
}
@DependsOn(World::class)
class worlds : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<World>().withDimensions(1) }
}
@DependsOn(worlds::class)
@MethodParameters()
class loadWorlds : StaticMethod() {
override val predicate = predicateOf<Method2> {
it.instructions.any {
it.opcode == PUTSTATIC && it.fieldId == field<worlds>().id
}
}
}
@DependsOn(addMiniMenuEntry::class)
class menuActions : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == Array<String>::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuTargetNames : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == Array<String>::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuOpcodes : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuArguments0 : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuArguments1 : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuArguments2 : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(addMiniMenuEntry::class)
class menuShiftClick : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BooleanArray::class.type }
}
class worldToScreen : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.arguments.size in 3..4 }
.and { it.instructions.any { it.opcode == ISHR } }
.and { it.instructions.any { it.opcode == SIPUSH && it.intOperand == 13056 } }
}
@DependsOn(worldToScreen::class)
class plane : OrderMapper.InMethod.Field(worldToScreen::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class cameraX : OrderMapper.InMethod.Field(worldToScreen::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class cameraY : OrderMapper.InMethod.Field(worldToScreen::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class cameraZ : OrderMapper.InMethod.Field(worldToScreen::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class cameraPitch : OrderMapper.InMethod.Field(worldToScreen::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class cameraYaw : OrderMapper.InMethod.Field(worldToScreen::class, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class getTileHeight : OrderMapper.InMethod.Method(worldToScreen::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(getTileHeight::class)
class Tiles_renderFlags : OrderMapper.InMethod.Field(getTileHeight::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BYTE_TYPE.withDimensions(3) }
}
@DependsOn(getTileHeight::class)
class Tiles_heights : OrderMapper.InMethod.Field(getTileHeight::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE.withDimensions(3) }
}
@DependsOn(addMiniMenuEntry::class)
class isMiniMenuOpen : OrderMapper.InMethod.Field(addMiniMenuEntry::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(addMiniMenuEntry::class)
class menuOptionsCount : OrderMapper.InMethod.Field(addMiniMenuEntry::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doAction::class)
class mouseCrossX : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1004 }
.nextWithin(7) {it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doAction::class)
class mouseCrossY : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1004 }
.nextWithin(7) {it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(7) {it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// 0 none, 1 yellow, 2 red
@DependsOn(doAction::class)
class mouseCrossColor : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1004 }
.nextWithin(20) { it.opcode == ICONST_0 }
.prev {it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// 0 - 400
@DependsOn(doAction::class)
class mouseCrossState : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1004 }
.nextWithin(20) { it.opcode == ICONST_0 }
.next {it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
class visibleTiles : StaticField() {
override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE.withDimensions(2) }
}
@DependsOn(PacketBit::class)
class updateExternalPlayer : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
.and { it.arguments.startsWith(type<PacketBit>(), INT_TYPE) }
.and { it.arguments.size in 2..3 }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == 0xF_FF_FF_FF } }
}
@DependsOn(updateExternalPlayer::class)
class Players_regions : OrderMapper.InMethod.Field(updateExternalPlayer::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Scene::class)
class scene : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Scene>() }
}
@DependsOn(AbstractRasterProvider::class)
class rasterProvider : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<AbstractRasterProvider>() }
}
@DependsOn(GrandExchangeOffer::class)
class grandExchangeOffers : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<GrandExchangeOffer>().withDimensions(1) }
}
@MethodParameters("x", "y")
@DependsOn(isMiniMenuOpen::class)
class openMiniMenu : InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE) }
.and { it.arguments.size in 2..3 }
.and { it.instructions.any { it.opcode == PUTSTATIC && it.fieldId == field<isMiniMenuOpen>().id } }
}
@MethodParameters("x", "y")
@DependsOn(menuOptionsCount::class)
class openMenu0 : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE) }
.and { it.arguments.size in 2..3 }
.and { it.instructions.count { it.opcode == GETSTATIC && it.fieldId == field<menuOptionsCount>().id } == 3 }
}
@DependsOn(openMenu0::class)
class menuX : OrderMapper.InMethod.Field(openMenu0::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(openMenu0::class)
class menuY : OrderMapper.InMethod.Field(openMenu0::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(openMenu0::class)
class menuWidth : OrderMapper.InMethod.Field(openMenu0::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(openMenu0::class)
class menuHeight : OrderMapper.InMethod.Field(openMenu0::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("type", "sender", "text", "prefix")
class addMessage : StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, String::class.type, String::class.type, String::class.type) }
}
@DependsOn(ClanChat::class)
class clanChat : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<ClanChat>() }
}
@DependsOn(FriendSystem::class)
class friendSystem : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<FriendSystem>() }
}
@DependsOn(MouseHandler_currentButton0::class)
class MouseHandler_x : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton0>().id }
.nextIn(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_currentButton0::class)
class MouseHandler_y : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton0>().id }
.nextIn(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_currentButton0::class)
class MouseHandler_millis : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton0>().id }
.nextWithin(7) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(MouseHandler_currentButton0::class)
class MouseHandler_millis0 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton0>().id }
.nextWithin(7) { it.opcode == GETSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(ClientPreferences::class)
class clientPreferences : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<ClientPreferences>() }
}
@DependsOn(CollisionMap::class)
class collisionMaps : StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<CollisionMap>().withDimensions(1) }
}
@DependsOn(Projectile::class, NodeDeque::class)
class projectiles : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<Projectile>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == type<NodeDeque>() }
}
class displayFps : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "displayfps" }
.nextWithin(8) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(Component.width::class)
class rootComponentWidths : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.width>().id }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Component.height::class)
class rootComponentHeights : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.height>().id }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Component.x::class)
class rootComponentXs : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.x>().id }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Component.x::class)
class rootComponentCount : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.x>().id }
.prevWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.nextWithin(1) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Component.y::class)
class rootComponentYs : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.y>().id }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_sine : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.method.isClassInitializer }
.and { it.klass == klass<Rasterizer3D>() }
.and { it.opcode == INVOKESTATIC && it.methodId == Math::sin.id }
.prevWithin(7) { it.opcode == LDC && it.ldcCst == 65536.0 }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_cosine : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.method.isClassInitializer }
.and { it.klass == klass<Rasterizer3D>() }
.and { it.opcode == INVOKESTATIC && it.methodId == Math::cos.id }
.prevWithin(7) { it.opcode == LDC && it.ldcCst == 65536.0 }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(worldToScreen::class)
class viewportHeight : OrderMapper.InMethod.Field(worldToScreen::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_2 }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class viewportWidth : OrderMapper.InMethod.Field(worldToScreen::class, -2) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_2 }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class viewportZoom : OrderMapper.InMethod.Field(worldToScreen::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == ILOAD && it.varVar == 1 }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class viewportTempX : OrderMapper.InMethod.Field(worldToScreen::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_M1 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(worldToScreen::class)
class viewportTempY : OrderMapper.InMethod.Field(worldToScreen::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_M1 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(viewportHeight::class, viewportWidth::class)
class viewportOffsetY : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == RETURN }
.prev { it.opcode == PUTSTATIC && it.fieldId == field<viewportHeight>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldId == field<viewportWidth>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(viewportHeight::class, viewportWidth::class, viewportOffsetY::class)
class viewportOffsetX : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == RETURN }
.prev { it.opcode == PUTSTATIC && it.fieldId == field<viewportHeight>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldId == field<viewportWidth>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldId == field<viewportOffsetY>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// class pauseFontMetrics : IdentityMapper.StaticField() {
// override val predicate = predicateOf<Field2> { it.type == FontMetrics::class.type }
// }
//
// class pauseFont : IdentityMapper.StaticField() {
// override val predicate = predicateOf<Field2> { it.type == Font::class.type }
// }
//
// class pauseImage : IdentityMapper.StaticField() {
// override val predicate = predicateOf<Field2> { it.type == Image::class.type }
// }
@DependsOn(GameShell::class)
class gameShell : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<GameShell>() }
}
@DependsOn(NodeDeque::class)
class objStacks : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<NodeDeque>().withDimensions(3) }
}
@DependsOn(Component::class)
class interfaceComponents : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Component>().withDimensions(2) }
}
@DependsOn(MouseHandler::class)
class MouseHandler_instance : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MouseHandler>() }
}
@DependsOn(MouseWheel::class)
class mouseWheel : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MouseWheel>() }
}
@DependsOn(KeyHandler::class)
class KeyHandler_instance : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<KeyHandler>() }
}
@DependsOn(InterfaceParent::class, NodeHashTable::class)
class interfaceParents : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<InterfaceParent>() }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(Inventory::class, NodeHashTable::class)
class itemContainers : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<Inventory>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
class garbageCollector : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == GarbageCollectorMXBean::class.type }
}
@DependsOn(ReflectionCheck::class, IterableNodeDeque::class)
class reflectionChecks : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<ReflectionCheck>() }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == type<IterableNodeDeque>() }
}
@DependsOn(NPCType::class, EvictingDualNodeHashTable::class)
class NPCType_cached : CachedDefinitionMapper(NPCType::class)
@DependsOn(EnumType::class, EvictingDualNodeHashTable::class)
class EnumType_cached : CachedDefinitionMapper(EnumType::class)
@DependsOn(Sprite::class, EvictingDualNodeHashTable::class)
class Sprite_cached : CachedDefinitionMapper(Sprite::class)
@DependsOn(IDKType::class, EvictingDualNodeHashTable::class)
class IDKType_cached : CachedDefinitionMapper(IDKType::class)
// // @DependsOn(OverlayDefinition::class, EvictingDualNodeHashTable::class)
// class OverlayDefinition_cached : CachedDefinitionMapper(OverlayDefinition::class)
// @DependsOn(FloorUnderlayType::class, EvictingDualNodeHashTable::class)
// class FloorUnderlayType_cached : CachedDefinitionMapper(FloorUnderlayType::class)
@DependsOn(SpotType::class, EvictingDualNodeHashTable::class)
class SpotType_cached : CachedDefinitionMapper(SpotType::class)
@DependsOn(ObjType::class, EvictingDualNodeHashTable::class)
class ObjType_cached : CachedDefinitionMapper(ObjType::class)
@DependsOn(VarBitType::class, EvictingDualNodeHashTable::class)
class VarBitType_cached : CachedDefinitionMapper(VarBitType::class)
@DependsOn(SeqType::class, EvictingDualNodeHashTable::class)
class SeqType_cached : CachedDefinitionMapper(SeqType::class)
@DependsOn(LocType::class, EvictingDualNodeHashTable::class)
class LocType_cached : CachedDefinitionMapper(LocType::class)
@DependsOn(HitmarkType::class, EvictingDualNodeHashTable::class)
class HitmarkType_cached : CachedDefinitionMapper(HitmarkType::class)
@DependsOn(GzipDecompressor::class, EvictingDualNodeHashTable::class)
class gzipDecompressor : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<GzipDecompressor>() }
}
@DependsOn(PlatformInfoProvider::class)
class platformInfoProvider : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PlatformInfoProvider>() }
}
// class clanChatOwner : StaticUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3625 }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == String::class.type }
// }
class fps : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "Fps:" }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class worldToMinimap : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == 90_000 } }
}
class camAngleX : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5505 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class camAngleY : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5506 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class currentLevels : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3305 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
class levels : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3306 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
class experience : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3307 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
class isMembersWorld : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3312 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class staffModLevel : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3316 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class weight : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3322 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class runEnergy : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3321 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class worldId : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3318 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class worldProperties : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3324 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(plane::class)
class baseX : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3308 }
.nextWithin(10) { it.opcode == GETSTATIC && it.fieldId == field<plane>().id }
.nextWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(plane::class, baseX::class)
class baseY : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3308 }
.nextWithin(10) { it.opcode == GETSTATIC && it.fieldId == field<plane>().id }
.nextWithin(25) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE && it.fieldId != field<baseX>().id }
}
class cycle : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3300 }
.nextWithin(16) { it.isLabel }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(loadWorlds::class)
class worldsUrl : OrderMapper.InMethod.Field(loadWorlds::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == String::class.type }
}
@DependsOn(loadWorlds::class)
class worldsCount : OrderMapper.InMethod.Field(loadWorlds::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(AccessFile::class)
class getPreferencesFile : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<AccessFile>() }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == "preferences" } }
}
@MethodParameters
class init : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == Applet::init.mark }
}
@DependsOn(init::class)
class worldHost : OrderMapper.InMethod.Field(init::class, 0) {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == URL::getHost.id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@MethodParameters("gameState")
class updateGameState : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE) }
.and { it.arguments.size in 1..2 }
.and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 40 } }
.and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 45 } }
.and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 20 } }
.and { it.instructions.count() <= 200 }
}
@DependsOn(updateGameState::class)
class gameState : OrderMapper.InMethod.Field(updateGameState::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(AbstractRasterProvider.draw::class)
class draw : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.instructions.any { it.isMethod && it.methodId == method<AbstractRasterProvider.draw>().id } }
}
@DependsOn(draw::class, gameState::class)
class gameDrawingMode : UniqueMapper.InMethod.Field(draw::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 30 }
.nextWithin(10) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE && it.fieldId != field<gameState>().id }
}
class Login_username : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == String::class.type }
.next { it.isMethod && it.methodName == "trim" }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
.next { it.opcode == GETSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Login_username::class)
class Login_password : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "" }
.next { it.opcode == PUTSTATIC && it.fieldId == field<Login_username>().id }
.next { it.opcode == LDC && it.ldcCst == "" }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@MethodParameters("values", "ordinal")
@DependsOn(Enumerated::class)
class findEnumerated : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Enumerated>() }
}
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_pixels : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE.withDimensions(1) }
.and { it.klass == klass<Rasterizer2D>() }
}
@MethodParameters("x", "y", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_setPixel : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE) }
}
@MethodParameters("x0", "y0", "x1", "y1", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_drawLine : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.instructions.any { it.opcode == INVOKESTATIC && it.methodId == Math::floor.id } }
}
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_clear : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments.isEmpty() }
.and { it.instructions.any { it.opcode == GOTO } }
}
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_resetClip : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments.isEmpty() }
.and { it.instructions.none { it.opcode == GOTO } }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_xClipStart : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 0, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_yClipStart : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 1, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_xClipEnd : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 2, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_yClipEnd : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 3, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_width : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@DependsOn(Rasterizer2D_resetClip::class)
class Rasterizer2D_height : OrderMapper.InMethod.Field(Rasterizer2D_resetClip::class, 1, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@MethodParameters("x", "y", "length", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_drawHorizontalLine : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.count { it.opcode == IMUL } == 1 }
}
@MethodParameters("x", "y", "length", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_drawVerticalLine : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.count { it.opcode == IMUL } == 2 }
}
@MethodParameters("x", "y", "width", "height", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_drawRectangle : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.count { it.opcode == INVOKESTATIC } == 4 }
}
@MethodParameters("dst")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_getClipArray : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE.withDimensions(1)) }
.and { it.instructions.any { it.opcode == GETSTATIC } }
}
@MethodParameters("src")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_setClipArray : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE.withDimensions(1)) }
.and { it.instructions.any { it.opcode == PUTSTATIC } }
}
@MethodParameters("pixels", "width", "height")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_replace : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments.startsWith(IntArray::class.type, INT_TYPE, INT_TYPE) }
}
@MethodParameters("xStart", "yStart", "xEnd", "yEnd")
@DependsOn(Rasterizer2D_replace::class)
class Rasterizer2D_setClip : UniqueMapper.InMethod.Method(Rasterizer2D_replace::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@MethodParameters("xStart", "yStart", "xEnd", "yEnd")
@DependsOn(Rasterizer2D::class, Rasterizer2D_setClip::class)
class Rasterizer2D_expandClip : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.arguments.size in 4..5 }
.and { it != method<Rasterizer2D_setClip>() }
.and { it.instructions.none { it.opcode in setOf(ICONST_0, ICONST_1, ISUB) } }
}
@DependsOn(AttackOption::class)
class AttackOption_dependsOnCombatLevels : OrderMapper.InClassInitializer.Field(AttackOption::class, 0, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
@DependsOn(AttackOption::class)
class AttackOption_alwaysRightClick : OrderMapper.InClassInitializer.Field(AttackOption::class, 1, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
@DependsOn(AttackOption::class)
class AttackOption_leftClickWhereAvailable : OrderMapper.InClassInitializer.Field(AttackOption::class, 2, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
@DependsOn(AttackOption::class)
class AttackOption_hidden : OrderMapper.InClassInitializer.Field(AttackOption::class, 3, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
class localPlayerName : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "&u=" }
.nextWithin(2) { it.opcode == GETSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Clock::class)
class clock : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Clock>() }
}
class userHomeDirectory : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "user.home" }
.nextWithin(3) { it.isField && it.fieldType == String::class.type }
}
class osName : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "os.name" }
.nextWithin(3) { it.isField && it.fieldType == String::class.type }
}
@DependsOn(osName::class)
class osNameLowerCase : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<osName>().id }
.next { it.isMethod && it.methodName == "toLowerCase" }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
class Strings_membersObject : StringsUniqueMapper("Members object")
class Strings_hidden : StringsUniqueMapper("Hidden")
class Strings_space : StringsUniqueMapper(" ")
class Strings_loading : StringsUniqueMapper("Loading...")
class Strings_walkHere : StringsUniqueMapper("Walk here")
class Strings_cancel : StringsUniqueMapper("Cancel")
class Strings_take : StringsUniqueMapper("Take")
class Strings_close : StringsUniqueMapper("Close")
class Strings_examine : StringsUniqueMapper("Examine")
class Strings_attack : StringsUniqueMapper("Attack")
class Strings_drop : StringsUniqueMapper("Drop")
class Strings_unableToFind : StringsUniqueMapper("Unable to find ")
class Strings_fromYourFriendListFirst : StringsUniqueMapper(" from your friend list first")
class Strings_ok : StringsUniqueMapper("Ok")
class Strings_select : StringsUniqueMapper("Select")
class Strings_continue : StringsUniqueMapper("Continue")
class Strings_moreOptions : StringsUniqueMapper(" more options")
class Strings_hasLoggedIn : StringsUniqueMapper(" has logged in.")
class Strings_hasLoggedOut : StringsUniqueMapper(" has logged out.")
class Strings_level : StringsUniqueMapper("level-")
class Strings_skill : StringsUniqueMapper("skill-")
class Strings_use : StringsUniqueMapper("Use")
class Strings_yourIgnoreListIsFull : StringsUniqueMapper("Your ignore list is full. Max of 100 for free users, and 400 for members")
class Strings_yourFriendListIsFull : StringsUniqueMapper("Your friend list is full. Max of 200 for free users, and 400 for members")
class Strings_connectingToServer : StringsUniqueMapper("Connecting to server...")
class Strings_login : StringsUniqueMapper("Login: ")
class Strings_password : StringsUniqueMapper("Password: ")
class Strings_pin : StringsUniqueMapper("PIN: ")
class Strings_pleaseEnterYourUsername : StringsUniqueMapper("Please enter your username/email address.")
class Strings_pleaseEnterYourPassword : StringsUniqueMapper("Please enter your password.")
class Strings_welcomeToRuneScape : StringsUniqueMapper("Welcome to RuneScape")
class Strings_newUser : StringsUniqueMapper("New User")
class Strings_existingUser : StringsUniqueMapper("Existing User")
class Strings_almostEverywhere : StringsUniqueMapper("almost everywhere.")
class Strings_warning : StringsUniqueMapper("Warning!")
class Strings_thisIsAHighRiskWorld : StringsUniqueMapper("This is a <col=ffff00>High Risk<col=ffffff> world.")
class Strings_theProtectItemPrayerWill : StringsUniqueMapper("The Protect Item prayer will")
class Strings_notWorkOnThisWorld : StringsUniqueMapper("not work on this world.")
class Strings_thisIsAHighRiskPvpWorld : StringsUniqueMapper("This is a <col=ffff00>High Risk <col=ff0000>PvP<col=ffffff> world.")
class Strings_playersCanAttackEachOtherAlmostEverywhere : StringsUniqueMapper("Players can attack each other almost everywhere")
class Strings_andTheProtectItemPrayerWontWork : StringsUniqueMapper("and the Protect Item prayer won't work.")
class Strings_thisIsABetaWorld : StringsUniqueMapper("This is a <col=00ffff>Beta<col=ffffff> world.")
class Strings_yourNormalAccountWillNotBeAffected : StringsUniqueMapper("Your normal account will not be affected.")
class Strings_thisIsAPvpWorld : StringsUniqueMapper("This is a <col=ff0000>PvP<col=ffffff> world.")
class Strings_playersCanAttackEachOther : StringsUniqueMapper("Players can attack each other")
class Strings_preparedSoundEngine : StringsUniqueMapper("Prepared sound engine")
class Strings_connectingToUpdateServer : StringsUniqueMapper("Connecting to update server")
class Strings_startingGameEngine : StringsUniqueMapper("Starting game engine...")
class Strings_preparedVisibilityMap : StringsUniqueMapper("Prepared visibility map")
class Strings_checkingForUpdates : StringsUniqueMapper("Checking for updates - ")
class Strings_loadedUpdateList : StringsUniqueMapper("Loaded update list")
class Strings_loadingFonts : StringsUniqueMapper("Loading fonts - ")
class Strings_loadedFonts : StringsUniqueMapper("Loaded fonts")
class Strings_loadingTitleScreen : StringsUniqueMapper("Loading title screen - ")
class Strings_loadedTitleScreen : StringsUniqueMapper("Loaded title screen")
class Strings_loadingPleaseWait : StringsUniqueMapper("Loading - please wait.")
class Strings_connectionLost : StringsUniqueMapper("Connection lost")
class Strings_pleaseWaitAttemptingToReestablish : StringsUniqueMapper("Please wait - attempting to reestablish")
class Strings_isAlreadyOnYourFriendList : StringsUniqueMapper(" is already on your friend list")
class Strings_chooseOption : StringsUniqueMapper("Choose Option")
class Strings_pleaseWait : StringsUniqueMapper("Please wait...")
class Strings_fromYourIgnoreListFirst : StringsUniqueMapper(" from your ignore list first")
class Strings_loadedInputHandler : StringsUniqueMapper("Loaded input handler")
class Strings_loadedTextures : StringsUniqueMapper("Loaded textures")
class Strings_loadedConfig : StringsUniqueMapper("Loaded config")
class Strings_loadedSprites : StringsUniqueMapper("Loaded sprites")
class Strings_loadedWordpack : StringsUniqueMapper("Loaded wordpack")
class Strings_loadedInterfaces : StringsUniqueMapper("Loaded interfaces")
class Strings_loadingSprites : StringsUniqueMapper("Loading sprites - ")
class Strings_loadingConfig : StringsUniqueMapper("Loading config - ")
class Strings_loadingTextures : StringsUniqueMapper("Loading textures - ")
class Strings_loadingWordpack : StringsUniqueMapper("Loading wordpack - ")
class Strings_loadingInterfaces : StringsUniqueMapper("Loading interfaces - ")
class Strings_loadingWorldMap : StringsUniqueMapper("Loading world map - ")
class Strings_loadedWorldMap : StringsUniqueMapper("Loaded world map")
@DependsOn(Strings::class)
class Strings_pleaseRemoveFriend : OrderMapper.InClassInitializer.Field(Strings::class, 1, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "Please remove " }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Strings::class)
class Strings_pleaseRemoveIgnore : OrderMapper.InClassInitializer.Field(Strings::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "Please remove " }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
class Strings_null : StringsUniqueMapper("null")
@DependsOn(Component::class, Component.children::class)
class getComponentChild : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Component>() }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<Component.children>().id } }
}
@DependsOn(MiniMenuEntry::class)
class tempMenuAction : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MiniMenuEntry>() }
}
@DependsOn(IterableNodeHashTable::class)
class Messages_hashTable : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<IterableNodeHashTable>() }
}
@DependsOn(Client::class)
class client : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Client>() }
}
@DependsOn(Component.getFont::class, EvictingDualNodeHashTable::class)
class Component_cachedFonts : UniqueMapper.InMethod.Field(Component.getFont::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(Component.getModel::class, EvictingDualNodeHashTable::class)
class Component_cachedModels : UniqueMapper.InMethod.Field(Component.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(StudioGame::class)
class studioGame : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<StudioGame>() && it.klass != klass<StudioGame>() }
}
@DependsOn(LoginType::class)
class loginType : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() && it.klass != klass<LoginType>() }
}
@DependsOn(BufferedFile::class)
class randomDat : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "random.dat" }
.nextWithin(25) { it.opcode == PUTSTATIC && it.fieldType == type<BufferedFile>() }
}
@DependsOn(BufferedFile::class)
class dat2File : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "main_file_cache.dat2" }
.nextWithin(25) { it.opcode == PUTSTATIC && it.fieldType == type<BufferedFile>() }
}
@DependsOn(BufferedFile::class)
class idx255File : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "main_file_cache.idx255" }
.nextWithin(25) { it.opcode == PUTSTATIC && it.fieldType == type<BufferedFile>() }
}
@DependsOn(BufferedFile::class)
class idxFiles : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "main_file_cache.idx" }
.prevWithin(25) { it.opcode == GETSTATIC && it.fieldType == type<BufferedFile>().withDimensions(1) }
}
class idxCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "main_file_cache.idx255" }
.nextWithin(25) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("component")
@DependsOn(Component::class)
class alignComponent : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Component>()) }
}
@MethodParameters("id")
@DependsOn(alignComponent::class)
class getInterfaceComponent : UniqueMapper.InMethod.Method(alignComponent::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.jar[it.methodId].arguments.size in 1..2 }
}
class clDat : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst is String && (it.ldcCst as String).contains("ex_cl_") }
.nextWithin(25) { it.opcode == PUTSTATIC && it.fieldType == File::class.type }
}
@DependsOn(SoundEffect::class)
class soundEffects : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<SoundEffect>().withDimensions(1) }
}
@DependsOn(TaskHandler::class)
class javaVendor : OrderMapper.InConstructor.Field(TaskHandler::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(TaskHandler::class)
class javaVersion : OrderMapper.InConstructor.Field(TaskHandler::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(PcmPlayerProvider::class)
class pcmPlayerProvider : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PcmPlayerProvider>() }
}
@DependsOn(SoundSystem::class)
class soundSystem : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<SoundSystem>() }
}
class isLowDetail : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "Mem:" }
.prevWithin(30) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
// else mono
@DependsOn(DevicePcmPlayer.position::class)
class isStereo : UniqueMapper.InMethod.Field(DevicePcmPlayer.position::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters("color")
class colorStartTag : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.arguments.startsWith(INT_TYPE) }
.and { it.arguments.size in 1..2 }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == "<col=" } }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == ">" } }
}
class Formatting_colorEndTag : FormattingUniqueMapper("</col>")
class Formatting_lineBreakTag : FormattingUniqueMapper("<br>")
class Formatting_rightParenthesis : FormattingUniqueMapper(")")
class Formatting_spaceLeftParenthesis : FormattingUniqueMapper(" (")
class Formatting_true : FormattingUniqueMapper("true")
class Formatting_rightArrow : FormattingUniqueMapper("->")
class Formatting_comma : FormattingUniqueMapper(",")
class Formatting_pipe : FormattingUniqueMapper("|")
@DependsOn(ArchiveDisk::class)
class masterDisk : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<ArchiveDisk>() }
}
// @DependsOn(ClientPreferences::class)
// class readClientPreferences : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<ClientPreferences>() }
// }
@DependsOn(MouseWheel.useRotation::class)
class mouseWheelRotation : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<MouseWheel.useRotation>().id }
.nextWithin(10) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mouseMoved::class)
class MouseHandler_x0 : OrderMapper.InMethod.Field(MouseHandler.mouseMoved::class, 1, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mouseMoved::class)
class MouseHandler_y0 : OrderMapper.InMethod.Field(MouseHandler.mouseMoved::class, 2, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mousePressed::class)
class MouseHandler_lastPressedX0 : OrderMapper.InMethod.Field(MouseHandler.mousePressed::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mousePressed::class)
class MouseHandler_lastPressedY0 : OrderMapper.InMethod.Field(MouseHandler.mousePressed::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mousePressed::class)
class MouseHandler_lastPressedTimeMillis0 : OrderMapper.InMethod.Field(MouseHandler.mousePressed::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(MouseHandler.mousePressed::class)
class MouseHandler_lastButton0 : OrderMapper.InMethod.Field(MouseHandler.mousePressed::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler.mousePressed::class)
class MouseHandler_currentButton0 : OrderMapper.InMethod.Field(MouseHandler.mousePressed::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_lastPressedX0::class)
class MouseHandler_lastPressedX : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_lastPressedX0>().id }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_lastPressedY0::class)
class MouseHandler_lastPressedY : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_lastPressedY0>().id }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_currentButton0::class)
class MouseHandler_currentButton : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton0>().id }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_lastButton0::class)
class MouseHandler_lastButton : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_lastButton0>().id }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.and { it.klass != klass<MouseHandler>() }
}
@DependsOn(MouseHandler_lastPressedTimeMillis0::class)
class MouseHandler_lastPressedTimeMillis : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_lastPressedTimeMillis0>().id }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(MouseHandler_lastPressedTimeMillis::class)
class mouseLastLastPressedTimeMillis : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_lastPressedTimeMillis>().id }
.nextWithin(4) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(FontName::class)
class FontName_plain11 : OrderMapper.InClassInitializer.Field(FontName::class, 0, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName::class)
class FontName_plain12 : OrderMapper.InClassInitializer.Field(FontName::class, 1, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName::class)
class FontName_bold12 : OrderMapper.InClassInitializer.Field(FontName::class, 2, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName::class)
class FontName_verdana11 : OrderMapper.InClassInitializer.Field(FontName::class, 3, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName::class)
class FontName_verdana13 : OrderMapper.InClassInitializer.Field(FontName::class, 4, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName::class)
class FontName_verdana15 : OrderMapper.InClassInitializer.Field(FontName::class, 5, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
// // @DependsOn(FontName::class)
// class FontName_values : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<FontName>().withDimensions(1) }
// }
@DependsOn(Fonts::class)
class fonts : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Fonts>() }
}
class fontsMap : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == HashMap::class.type }
}
@DependsOn(Archive::class)
class newArchive : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Archive>() }
}
class archive0 : ArchiveFieldMapper(0)
class archive1 : ArchiveFieldMapper(1)
class archive2 : ArchiveFieldMapper(2)
class archive3 : ArchiveFieldMapper(3)
class archive4 : ArchiveFieldMapper(4)
class archive5 : ArchiveFieldMapper(5)
class archive6 : ArchiveFieldMapper(6)
class archive7 : ArchiveFieldMapper(7)
class archive8 : ArchiveFieldMapper(8)
class archive9 : ArchiveFieldMapper(9)
class archive10 : ArchiveFieldMapper(10)
class archive11 : ArchiveFieldMapper(11)
class archive12 : ArchiveFieldMapper(12)
class archive13 : ArchiveFieldMapper(13)
class archive14 : ArchiveFieldMapper(14)
class archive15 : ArchiveFieldMapper(15)
// class archive16 : ArchiveFieldMapper(16)
@DependsOn(MouseRecorder::class)
class mouseRecorder : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MouseRecorder>() }
}
@DependsOn(Font::class, FontName_plain11::class)
class fontPlain11 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_plain11>().id }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == type<Font>() }
}
@DependsOn(Font::class, FontName_plain12::class)
class fontPlain12 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_plain12>().id }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == type<Font>() }
}
@DependsOn(Font::class, FontName_bold12::class)
class fontBold12 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_bold12>().id }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == type<Font>() }
}
@DependsOn(FontName_verdana11::class, FontName::class)
class fontNameVerdana11 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_verdana11>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName_verdana13::class, FontName::class)
class fontNameVerdana13 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_verdana13>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(FontName_verdana15::class, FontName::class)
class fontNameVerdana15 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<FontName_verdana15>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == type<FontName>() }
}
@DependsOn(ArchiveDisk::class)
class ArchiveDisk_buffer : UniqueMapper.InClassInitializer.Field(ArchiveDisk::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 520 }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == ByteArray::class.type }
}
@DependsOn(ArchiveDiskActionHandler::class)
class ArchiveDiskActionHandler_lock : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == Any::class.type }
.and { it.klass == klass<ArchiveDiskActionHandler>() }
}
@DependsOn(ArchiveDiskActionHandler::class, NodeDeque::class)
class ArchiveDiskActionHandler_requestQueue : OrderMapper.InClassInitializer.Field(ArchiveDiskActionHandler::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<NodeDeque>() }
}
@DependsOn(ArchiveDiskActionHandler::class, NodeDeque::class)
class ArchiveDiskActionHandler_responseQueue : OrderMapper.InClassInitializer.Field(ArchiveDiskActionHandler::class, 1, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<NodeDeque>() }
}
@DependsOn(ArchiveDiskActionHandler::class)
class ArchiveDiskActionHandler_thread : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<ArchiveDiskActionHandler>() }
.nextWithin(4) { it.opcode == PUTSTATIC && it.fieldType == Thread::class.type }
}
@DependsOn(Archive.load::class)
class Archive_crc : UniqueMapper.InMethod.Field(Archive.load::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == CRC32::class.type }
}
// @MethodParameters("bytes", "copyArray")
// class byteArrayToObject : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == Any::class.type }
// .and { it.arguments.startsWith(ByteArray::class.type) }
// }
// @MethodParameters("o", "copyArray")
// class byteArrayFromObject : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == ByteArray::class.type }
// .and { it.arguments.startsWith(Any::class.type) }
// }
// @DependsOn(byteArrayToObject::class)
// class directBufferUnavailable : UniqueMapper.InMethod.Field(byteArrayToObject::class) {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
// }
@DependsOn(Archive::class)
class NetCache_archives : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Archive>().withDimensions(1) }
}
@DependsOn(NetCache::class)
class NetCache_crc : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.klass == klass<NetCache>() }
.and { it.type == CRC32::class.type }
}
@DependsOn(Archive::class)
class requestNetFile : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Archive>(), INT_TYPE, INT_TYPE, INT_TYPE, BYTE_TYPE, BOOLEAN_TYPE) }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingPriorityWrites : OrderMapper.InMethod.Field(requestNetFile::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingPriorityResponses : OrderMapper.InMethod.Field(requestNetFile::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingWrites : OrderMapper.InMethod.Field(requestNetFile::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingResponses : OrderMapper.InMethod.Field(requestNetFile::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(DualNodeDeque::class, requestNetFile::class)
class NetCache_pendingWritesQueue : UniqueMapper.InMethod.Field(requestNetFile::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<DualNodeDeque>() }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingWritesCount : OrderMapper.InMethod.Field(requestNetFile::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(NodeHashTable::class, requestNetFile::class)
class NetCache_pendingPriorityWritesCount : OrderMapper.InMethod.Field(requestNetFile::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(AbstractSocket::class, NetCache_pendingPriorityWritesCount::class)
class NetCache_socket : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<NetCache_pendingPriorityWritesCount>().id }
.prevWithin(3) { it.opcode == ISUB }
.prevWithin(20) { it.opcode == GETSTATIC && it.fieldType == type<AbstractSocket>() }
}
@DependsOn(NetCache_pendingPriorityWritesCount::class)
class NetCache_pendingPriorityResponsesCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == ISUB }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldId == field<NetCache_pendingPriorityWritesCount>().id }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(NetCache_pendingWritesCount::class, NetCache_pendingPriorityWritesCount::class)
class NetCache_pendingResponsesCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == ISUB }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldId == field<NetCache_pendingWritesCount>().id }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE && it.fieldId != field<NetCache_pendingPriorityWritesCount>().id }
}
@MethodParameters()
class currentTimeMs : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == LONG_TYPE }
.and { it.arguments.size in 0..1 }
.and { Modifier.isSynchronized(it.access) }
}
@DependsOn(currentTimeMs::class)
class currentTimeMsLast : OrderMapper.InMethod.Field(currentTimeMs::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@DependsOn(currentTimeMs::class)
class currentTimeMsOffset : OrderMapper.InMethod.Field(currentTimeMs::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@MethodParameters("chars")
@DependsOn(AbstractArchive.takeFileByNames::class)
class hashString : UniqueMapper.InMethod.Method(AbstractArchive.takeFileByNames::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@MethodParameters("c")
@DependsOn(hashString::class)
class charToByteCp1252 : UniqueMapper.InMethod.Method(hashString::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(Huffman::class)
class huffman : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Huffman>() }
}
@DependsOn(NetFileRequest::class)
class NetCache_currentResponse : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<NetFileRequest>() }
}
@DependsOn(Packet::class, NetCache::class)
class NetCache_responseHeaderBuffer : UniqueMapper.InClassInitializer.Field(NetCache::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 8 }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == type<Packet>() }
}
@DependsOn(Packet::class, NetCache_crc::class)
class NetCache_responseArchiveBuffer : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<NetCache_crc>().id }
.nextWithin(3) { it.isMethod && it.methodId == CRC32::reset.id }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == type<Packet>() }
}
@DependsOn(Bzip2State::class)
class Bzip2Decompressor_state : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Bzip2State>() }
}
@MethodParameters("src", "srcStart", "srcEnd", "dst", "dstStart")
class encodeStringCp1252 : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
.and { it.arguments.startsWith(CharSequence::class.type, INT_TYPE, INT_TYPE, ByteArray::class.type, INT_TYPE) }
}
@MethodParameters("src", "srcStart", "length")
@DependsOn(Packet.gjstr::class)
class decodeStringCp1252 : UniqueMapper.InMethod.Method(Packet.gjstr::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(decodeStringCp1252::class)
class cp1252AsciiExtension : UniqueMapper.InMethod.Field(decodeStringCp1252::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@DependsOn(gzipDecompressor::class)
class decompressBytes : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == ByteArray::class.type }
.and { it.arguments.size in 1..2 }
.and { it.arguments.startsWith(ByteArray::class.type) }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<gzipDecompressor>().id } }
}
@DependsOn(decompressBytes::class)
class Bzip2Decompressor_decompress : UniqueMapper.InMethod.Method(decompressBytes::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(Archive.loadIndex::class, Packet::class)
class NetCache_reference : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<Archive.loadIndex>().id }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == type<Packet>() }
}
@DependsOn(KeyHandler.keyPressed::class)
class KeyHandler_keyCodes : OrderMapper.InMethod.Field(KeyHandler.keyPressed::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@MethodParameters()
@DependsOn(ClientPreferences.windowMode::class)
class setUp : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<ClientPreferences.windowMode>().id } }
}
@DependsOn(setUp::class)
class port1 : OrderMapper.InMethod.Field(setUp::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(setUp::class)
class port2 : OrderMapper.InMethod.Field(setUp::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(setUp::class)
class port3 : OrderMapper.InMethod.Field(setUp::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// normal, rc, qa, wip, i, local
@DependsOn(setUp::class)
class gameBuild : OrderMapper.InMethod.Field(setUp::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(ServerBuild::class)
class serverBuild : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<ServerBuild>() && it.klass != klass<ServerBuild>() }
}
class ViewportMouse_x : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 50 }
.nextIn(2) { it.opcode == SIPUSH && it.intOperand == 3500 }
.nextWithin(5) { it.opcode == ISTORE }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(ViewportMouse_x::class)
class ViewportMouse_y : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 50 }
.nextIn(2) { it.opcode == SIPUSH && it.intOperand == 3500 }
.nextWithin(20) { it.opcode == GETSTATIC && it.fieldId == field<ViewportMouse_x>().id }
.nextWithin(10) { it.opcode == ISTORE }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(ViewportMouse_y::class)
class ViewportMouse_isInViewport : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<ViewportMouse_y>().id }
.next { it.opcode == ICONST_1 }
.next { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(ViewportMouse_y::class)
class ViewportMouse_entityCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<ViewportMouse_y>().id }
.next { it.opcode == ICONST_1 }
.next { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
.next { it.opcode == ICONST_0 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(ViewportMouse_y::class)
class ViewportMouse_false0 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<ViewportMouse_y>().id }
.nextWithin(5) { it.opcode == ICONST_0 }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_zoom : UniqueMapper.InClassInitializer.Field(Rasterizer3D::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 512 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// nullable, includes color tags
@DependsOn(Strings_use::class)
class selectedItemName : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_use>().id }
.nextIn(4) { it.opcode == GETSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Component.spellName::class)
class selectedSpellName : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.spellName>().id }
.nextWithin(10) { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
// "Cast"
@DependsOn(doAction::class, Component.opbase::class)
class selectedSpellActionName : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.opbase>().id }
.prevWithin(15) { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@MethodParameters("descriptor")
class loadClassFromDescriptor : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == java.lang.Class::class.type }
}
@DependsOn(SoundEffect::class)
class readSoundEffect : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<SoundEffect>() }
}
@DependsOn(Strings_thisIsAPvpWorld::class)
class Login_response1 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_thisIsAPvpWorld>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Strings_playersCanAttackEachOther::class)
class Login_response2 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_playersCanAttackEachOther>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Strings_almostEverywhere::class)
class Login_response3 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_almostEverywhere>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Strings_warning::class)
class Login_response0 : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_warning>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(getLocType::class, AbstractArchive::class)
class LocType_archive : UniqueMapper.InMethod.Field(getLocType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(getObjType::class, AbstractArchive::class)
class ObjType_archive : UniqueMapper.InMethod.Field(getObjType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(getNPCType::class, AbstractArchive::class)
class NPCType_archive : UniqueMapper.InMethod.Field(getNPCType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(getIDKType::class, AbstractArchive::class)
class IDKType_archive : UniqueMapper.InMethod.Field(getIDKType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
// // @DependsOn(getOverlayDefinition::class, AbstractIndexCache::class)
// class OverlayDefinition_archive : UniqueMapper.InMethod.Field(getOverlayDefinition::class) {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractIndexCache>() }
// }
@DependsOn(getSpotType::class, AbstractArchive::class)
class SpotType_archive : UniqueMapper.InMethod.Field(getSpotType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(getSeqType::class, AbstractArchive::class)
class SeqType_archive : UniqueMapper.InMethod.Field(getSeqType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(VarBitType::class, AbstractArchive::class)
class VarBitType_archive : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<VarBitType>() }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(EnumType::class, AbstractArchive::class)
class EnumType_archive : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<EnumType>() }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
// @DependsOn(FloorUnderlayType::class, AbstractArchive::class)
// class FloorUnderlayType_archive : StaticUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<FloorUnderlayType>() }
// .prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
// }
@DependsOn(LocType.decode0::class)
class LocType_isLowDetail : UniqueMapper.InMethod.Field(LocType.decode0::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class cacheDirectoryLocations : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "/tmp/" }
.nextWithin(10) { it.opcode == PUTSTATIC && it.fieldType == Array<String>::class.type }
}
// @DependsOn(ClientPreferences.windowMode::class)
// class isResizable : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<ClientPreferences.windowMode>().id }
// .nextWithin(15) { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
// }
@DependsOn(AttackOption::class, AttackOption_dependsOnCombatLevels::class)
class playerAttackOption : StaticOrderMapper.Field(0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<AttackOption_dependsOnCombatLevels>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
@DependsOn(AttackOption::class, AttackOption_dependsOnCombatLevels::class)
class npcAttackOption : StaticOrderMapper.Field(1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<AttackOption_dependsOnCombatLevels>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == type<AttackOption>() }
}
// @DependsOn(Strings_yourIgnoreListIsFull::class)
// class ignoreListCount : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_yourIgnoreListIsFull>().id }
// .prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
// @DependsOn(Strings_yourFriendListIsFull::class)
// class friendsListCount : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_yourFriendListIsFull>().id }
// .prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
// @DependsOn(Login_username::class)
// class Login_isUsernameRemembered : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<Login_username>().id }
// .next { it.opcode == ICONST_1 }
// .next { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
// }
@DependsOn(garbageCollector::class)
class garbageCollectorLastCheckTimeMs : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<garbageCollector>().id }
.nextWithin(4) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(garbageCollector::class)
class garbageCollectorLastCollectionTime : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<garbageCollector>().id }
.nextWithin(4) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
.nextWithin(4) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE }
}
@DependsOn(Model.draw::class)
class modelViewportXs : OrderMapper.InMethod.Field(Model.draw::class, -6) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Model.draw::class)
class modelViewportYs : OrderMapper.InMethod.Field(Model.draw::class, -5) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_method1 : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer3D>() }
.and { it.arguments.isEmpty() }
.and { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.isMethod } }
}
@MethodParameters("xStart", "yStart", "xEnd", "yEnd")
@DependsOn(Rasterizer3D_method1::class)
class Rasterizer3D_setClip : UniqueMapper.InMethod.Method(Rasterizer3D_method1::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@DependsOn(Rasterizer3D_setClip::class)
class Rasterizer3D_clipWidth : OrderMapper.InMethod.Field(Rasterizer3D_setClip::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_setClip::class)
class Rasterizer3D_clipHeight : OrderMapper.InMethod.Field(Rasterizer3D_setClip::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
// offsets into R2D.pixels for clip
@DependsOn(Rasterizer3D_setClip::class)
class Rasterizer3D_rowOffsets : UniqueMapper.InMethod.Field(Rasterizer3D_setClip::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Rasterizer3D_setClip::class)
class Rasterizer3D_method3 : OrderMapper.InMethod.Method(Rasterizer3D_setClip::class, 0) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
// @MethodParameters("n")
// @DependsOn(Rasterizer3D_setClip::class)
// class nextPowerOfTwo : OrderMapper.InMethod.Method(Rasterizer3D_setClip::class, 1) {
// override val predicate = predicateOf<Instruction2> { it.isMethod }
// }
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipMidX : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipMidY : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipNegativeMidX : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipMidX2 : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipNegativeMidY : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(Rasterizer3D_method3::class)
class Rasterizer3D_clipMidY2 : OrderMapper.InMethod.Field(Rasterizer3D_method3::class, 5) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@MethodParameters("x", "y", "width", "height", "color")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_fillRectangle : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.returnType == VOID_TYPE }
.and { it.arguments.size == 5 }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.none { it.opcode == BIPUSH || it.isMethod } }
}
@DependsOn(Model.rotateZ::class)
class Model_sine : OrderMapper.InMethod.Field(Model.rotateZ::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Model.rotateZ::class)
class Model_cosine : OrderMapper.InMethod.Field(Model.rotateZ::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(EvictingDualNodeHashTable::class, NPCType.getModel::class)
class NPCType_cachedModels : UniqueMapper.InMethod.Field(NPCType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(AbstractArchive::class, NPCType.getModel::class)
class NPCType_modelArchive : UniqueMapper.InMethod.Field(NPCType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
// @MethodParameters("strings")
// class prependIndices : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == Array<String>::class.type }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(Array<String>::class.type) }
// }
// @DependsOn(prependIndices::class)
// class numberMenuOptions : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<prependIndices>().id }
// .prevWithin(5) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
// }
@DependsOn(ObjType.getModel::class, EvictingDualNodeHashTable::class)
class ObjType_cachedModels : OrderMapper.InMethod.Field(ObjType.getModel::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(AbstractArchive::class, ObjType.getModel::class)
class ObjType_modelArchive : UniqueMapper.InMethod.Field(ObjType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@MethodParameters("x", "y", "width", "height", "rgb", "alpha")
@DependsOn(Rasterizer2D::class)
class Rasterizer2D_drawRectangleAlpha : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer2D>() }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.count { it.opcode == INVOKESTATIC } == 4 }
}
@MethodParameters("x", "y", "length", "rgb", "alpha")
@DependsOn(Rasterizer2D_drawRectangleAlpha::class)
class Rasterizer2D_drawHorizontalLineAlpha : OrderMapper.InMethod.Method(Rasterizer2D_drawRectangleAlpha::class, 0) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@MethodParameters("x", "y", "length", "rgb", "alpha")
@DependsOn(Rasterizer2D_drawRectangleAlpha::class)
class Rasterizer2D_drawVerticalLineAlpha : OrderMapper.InMethod.Method(Rasterizer2D_drawRectangleAlpha::class, -1) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
}
@DependsOn(EvictingDualNodeHashTable::class, SpotType.getModel::class)
class SpotType_cachedModels : UniqueMapper.InMethod.Field(SpotType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(AbstractArchive::class, SpotType.getModel::class)
class SpotType_modelArchive : UniqueMapper.InMethod.Field(SpotType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@MethodParameters("id")
@DependsOn(LocType.multiLoc::class)
class getVarbit : OrderMapper.InMethod.Method(LocType.multiLoc::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
// no 0, yes 1
@DependsOn(Client.doAction::class)
class isItemSelected : UniqueMapper.InMethod.Field(Client.doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 38 }
.nextWithin(2) { it.node is JumpInsnNode }
.nextWithin(10) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraPitchSine : OrderMapper.InMethod.Field(Scene.draw::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraPitchCosine : OrderMapper.InMethod.Field(Scene.draw::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraYawSine : OrderMapper.InMethod.Field(Scene.draw::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraYawCosine : OrderMapper.InMethod.Field(Scene.draw::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraX : OrderMapper.InMethod.Field(Scene.draw::class, 5) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraY : OrderMapper.InMethod.Field(Scene.draw::class, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraZ : OrderMapper.InMethod.Field(Scene.draw::class, 7) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraXTile : OrderMapper.InMethod.Field(Scene.draw::class, 8) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraYTile : OrderMapper.InMethod.Field(Scene.draw::class, 9) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_plane : OrderMapper.InMethod.Field(Scene.draw::class, 10) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraXTileMin : OrderMapper.InMethod.Field(Scene.draw::class, 11) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraYTileMin : OrderMapper.InMethod.Field(Scene.draw::class, 13) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraXTileMax : OrderMapper.InMethod.Field(Scene.draw::class, 15) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.draw::class)
class Scene_cameraYTileMax : OrderMapper.InMethod.Field(Scene.draw::class, 17) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("itemContainerId", "index", "itemId", "itemQuantity")
@DependsOn(itemContainers::class)
class itemContainerSetItem : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.arguments.size in 4..5 }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<itemContainers>().id } }
}
@DependsOn(UrlRequester::class)
class urlRequester : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<UrlRequester>() }
}
@MethodParameters("packet", "hashTable")
@DependsOn(IterableNodeHashTable::class)
class readStringIntParameters : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<IterableNodeHashTable>() }
}
// @MethodParameters("name")
// @DependsOn(Ignored.previousName::class)
// class isOnIgnoreList : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
// .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<Ignored.previousName>().id } }
// }
// @MethodParameters("c")
// class isUsernameWhiteSpace : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
// .and { it.arguments.startsWith(CHAR_TYPE) }
// .and { it.arguments.size in 1..2 }
// .and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 95 } }
// }
// @MethodParameters("name", "loginType")
// @DependsOn(isOnIgnoreList::class)
// class cleanUsername : OrderMapper.InMethod.Method(isOnIgnoreList::class, 0) {
// override val predicate = predicateOf<Instruction2> { it.isMethod }
// }
@MethodParameters("bytes")
@DependsOn(ClientScript::class)
class loadClientScript : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<ClientScript>() }
.and { it.arguments.startsWith(ByteArray::class.type) }
}
@DependsOn(Actor::class, Actor.targetIndex::class, Actor.orientation::class)
class Players_targetIndices : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldName == field<Actor.targetIndex>().name && it.fieldOwner == type<Actor>() }
.prevWithin(8) { it.opcode == PUTFIELD && it.fieldName == field<Actor.orientation>().name && it.fieldOwner == type<Actor>() }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor::class, Actor.targetIndex::class, Actor.orientation::class)
class Players_orientations : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldName == field<Actor.targetIndex>().name && it.fieldOwner == type<Actor>() }
.prevWithin(8) { it.opcode == PUTFIELD && it.fieldName == field<Actor.orientation>().name && it.fieldOwner == type<Actor>() }
.prevWithin(7) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(PacketBitNode::class)
class packetBitNodes : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PacketBitNode>().withDimensions(1) }
}
@DependsOn(AbstractArchive.takeFileEncrypted::class, Archive::class)
class xteaKeys : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Archive>() && it.methodMark == method<AbstractArchive.takeFileEncrypted>().mark }
.prevWithin(7) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE.withDimensions(2) }
}
@DependsOn(Varps::class)
class Varps_temp : OrderMapper.InClassInitializer.Field(Varps::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand >= 2000 }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE.withDimensions(1) }
}
@DependsOn(Varps::class)
class Varps_main : OrderMapper.InClassInitializer.Field(Varps::class, 1, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand >= 2000 }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE.withDimensions(1) }
}
@DependsOn(Varps::class)
class Varps_masks : OrderMapper.InClassInitializer.Field(Varps::class, 0, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 32 }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE.withDimensions(1) }
}
// @MethodParameters("bytes")
// @DependsOn(Sprite::class)
// class imageToSprite : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>() }
// .and { it.instructions.any { it.isMethod && it.methodName == "grabPixels" } }
// }
// @DependsOn(Script::class)
// class getScript : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<Script>() }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(INT_TYPE) }
// }
@DependsOn(ViewportMouse::class)
class ViewportMouse_entityTags : UniqueMapper.InClassInitializer.Field(ViewportMouse::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1000 }
.nextIn(2) { it.opcode == PUTSTATIC && it.fieldType == LONG_TYPE.withDimensions(1) }
}
@DependsOn(Npc::class)
class npcIndices : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<Npc>() }
.nextWithin(15) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Npc::class)
class npcCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESPECIAL && it.methodOwner == type<Npc>() }
.nextWithin(18) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Players::class)
class Players_indices : OrderMapper.InClassInitializer.Field(Players::class, 0, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 2048 }
.nextIn(2) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Players::class)
class Players_count : OrderMapper.InClassInitializer.Field(Players::class, 0, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_0 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
class publicChatMode : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5001 }
.skip(8)
.nextWithin(10) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Strings_attack::class)
class playerMenuActions : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_attack>().id }
.next { it.isMethod && it.methodName == "equalsIgnoreCase" }
.prevWithin(8) { it.opcode == GETSTATIC && it.fieldType == String::class.type.withDimensions(1) }
}
@DependsOn(playerMenuActions::class)
class playerMenuOpcodes : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.method.isClassInitializer }
.and { it.opcode == BIPUSH && it.intOperand == 7 }
.next { it.opcode == BIPUSH && it.intOperand == 51 }
.nextIn(2) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
// @DependsOn(IndexedSprite::class, AbstractIndexCache::class)
// class getIndexedSprites : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<IndexedSprite>().withDimensions(1) }
// .and { it.arguments.startsWith(type<AbstractIndexCache>(), String::class.type) }
// }
@DependsOn(IndexedSprite::class, GraphicsDefaults.mapscene::class)
class mapSceneSprites : IndexedSpriteArrayField(GraphicsDefaults.mapscene::class)
@DependsOn(IndexedSprite::class, GraphicsDefaults.modicons::class)
class modIconSprites : IndexedSpriteArrayField(GraphicsDefaults.modicons::class)
@DependsOn(IndexedSprite::class, GraphicsDefaults.scrollbar::class)
class scrollBarSprites : IndexedSpriteArrayField(GraphicsDefaults.scrollbar::class)
// class runeSprites : IndexedSpritesFieldMapper("runes")
// class titleMuteSprites : IndexedSpritesFieldMapper("title_mute")
// class slFlagSprites : IndexedSpritesFieldMapper("sl_flags")
// class slArrowSprites : IndexedSpritesFieldMapper("sl_arrows")
// class slStarSprites : IndexedSpritesFieldMapper("sl_stars")
@DependsOn(Sprite::class, GraphicsDefaults.headiconsprayer::class)
class headIconPrayerSprites : SpriteArrayField(GraphicsDefaults.headiconsprayer::class)
@DependsOn(Sprite::class, GraphicsDefaults.headiconspk::class)
class headIconPkSprites : SpriteArrayField(GraphicsDefaults.headiconspk::class)
@DependsOn(Sprite::class, GraphicsDefaults.headiconshint::class)
class headIconHintSprites : SpriteArrayField(GraphicsDefaults.headiconshint::class)
@DependsOn(Sprite::class, GraphicsDefaults.mapmarker::class)
class mapMarkerSprites : SpriteArrayField(GraphicsDefaults.mapmarker::class)
@DependsOn(Sprite::class, GraphicsDefaults.cross::class)
class crossSprites : SpriteArrayField(GraphicsDefaults.cross::class)
@DependsOn(Sprite::class, GraphicsDefaults.mapdots::class)
class mapDotSprites : SpriteArrayField(GraphicsDefaults.mapdots::class)
@DependsOn(GrandExchangeEvents::class)
class grandExchangeEvents : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<GrandExchangeEvents>() }
}
class Instrument_noise : InstrumentStaticIntArrayMapper(0)
class Instrument_sine : InstrumentStaticIntArrayMapper(1)
class Instrument_samples : InstrumentStaticIntArrayMapper(2)
class Instrument_phases : InstrumentStaticIntArrayMapper(3)
class Instrument_delays : InstrumentStaticIntArrayMapper(4)
class Instrument_volumeSteps : InstrumentStaticIntArrayMapper(5)
class Instrument_pitchSteps : InstrumentStaticIntArrayMapper(6)
class Instrument_pitchBaseSteps : InstrumentStaticIntArrayMapper(7)
@DependsOn(AbstractFont::class)
class AbstractFont_random : UniqueMapper.InClassInitializer.Field(AbstractFont::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == Random::class.type }
}
class AbstractFont_strike : AbstractFontStaticIntMapper(0)
class AbstractFont_underline : AbstractFontStaticIntMapper(1)
class AbstractFont_previousShadow : AbstractFontStaticIntMapper(2)
class AbstractFont_shadow : AbstractFontStaticIntMapper(3)
class AbstractFont_previousColor : AbstractFontStaticIntMapper(4)
class AbstractFont_color : AbstractFontStaticIntMapper(5)
class AbstractFont_alpha : AbstractFontStaticIntMapper(6)
class AbstractFont_justificationTotal : AbstractFontStaticIntMapper(7)
class AbstractFont_justificationCurrent : AbstractFontStaticIntMapper(8)
@MethodParameters("s")
class escapeBrackets : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.arguments.size in 1..2 }
.and { it.arguments.startsWith(String::class.type) }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == "<lt>" } }
}
@MethodParameters("itf")
@DependsOn(Component::class)
class loadInterface : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
.and { it.arguments.size in 1..2 }
.and { it.arguments.startsWith(INT_TYPE) }
.and { it.instructions.any { it.opcode == NEW && it.typeType == type<Component>() } }
}
@DependsOn(loadInterface::class)
class loadedInterfaces : OrderMapper.InMethod.Field(loadInterface::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BooleanArray::class.type }
}
// @DependsOn(Component::class, Component.isHidden::class)
// class isComponentHidden : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
// .and { it.arguments.startsWith(type<Component>()) }
// .and { it.arguments.size in 1..2 }
// .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<Component.isHidden>().id } }
// }
class rootInterface : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 2706 }
.nextWithin(25) { it.isLabel }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
// @DependsOn(Buffer::class)
// class decodeStringHuffman : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
// .and { it.arguments.size in 2..3 }
// .and { it.arguments.startsWith(type<Buffer>(), INT_TYPE) }
// }
@MethodParameters("node", "old")
@DependsOn(IterableNodeDeque::class, Node::class)
class IterableNodeDeque_addBefore : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<IterableNodeDeque>() }
.and { it.returnType == VOID_TYPE }
.and { it.arguments.size in 2..3 }
.and { it.arguments.startsWith(type<Node>(), type<Node>()) }
}
@DependsOn(GraphicsObject::class, NodeDeque::class)
class graphicsObjects : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<GraphicsObject>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == type<NodeDeque>() }
}
@DependsOn(Scene::class)
class Scene_isLowDetail : OrderMapper.InClassInitializer.Field(Scene::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class Skills_enabled : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 24 }
.next { it.opcode == ICONST_0 || it.opcode == ICONST_1 }
.next { it.opcode == BASTORE }
.next { it.opcode == PUTSTATIC && it.fieldType == BooleanArray::class.type }
}
@DependsOn(Skills_enabled::class)
class Skills_experienceTable : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<Skills_enabled>().id }
.nextIn(3) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
class PlayerType_normal : PlayerTypeInstance(0)
class PlayerType_playerModerator : PlayerTypeInstance(1)
class PlayerType_jagexModerator : PlayerTypeInstance(2)
class PlayerType_ironman : PlayerTypeInstance(3)
class PlayerType_ultimateIronman : PlayerTypeInstance(4)
class PlayerType_hardcoreIronman : PlayerTypeInstance(5)
@DependsOn(UnlitModel::class)
class UnlitModel_sine : OrderMapper.InClassInitializer.Field(UnlitModel::class, -2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(UnlitModel::class)
class UnlitModel_cosine : OrderMapper.InClassInitializer.Field(UnlitModel::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(PcmPlayer::class)
class newPcmPlayer : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<PcmPlayer>() }
}
@DependsOn(PcmPlayer::class)
class pcmPlayer0 : StaticOrderMapper.Field(0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<PcmPlayer>() }
}
@DependsOn(PcmPlayer::class)
class pcmPlayer1 : StaticOrderMapper.Field(1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<PcmPlayer>() }
}
class WorldMapCacheName_details : WorldMapCacheNameInstance(0)
class WorldMapCacheName_compositeMap : WorldMapCacheNameInstance(1)
class WorldMapCacheName_compositeTexture : WorldMapCacheNameInstance(2)
class WorldMapCacheName_area : WorldMapCacheNameInstance(3)
class WorldMapCacheName_labels : WorldMapCacheNameInstance(4)
@DependsOn(Rasterizer3D::class, TextureLoader::class)
class Rasterizer3D_textureLoader : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.klass == klass<Rasterizer3D>() }
.and { it.type == type<TextureLoader>() }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_isLowDetailTexture : OrderMapper.InClassInitializer.Field(Rasterizer3D::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(MapElementType::class)
class MapElementType_cached : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MapElementType>().withDimensions(1) }
}
@DependsOn(MapElementType::class, EvictingDualNodeHashTable::class)
class MapElementType_cachedSprites : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.klass == klass<MapElementType>() }
.and { it.type == type<EvictingDualNodeHashTable>() }
}
class ByteArrayPool_small : ByteArrayPoolArray(0)
class ByteArrayPool_medium : ByteArrayPoolArray(1)
class ByteArrayPool_large : ByteArrayPoolArray(2)
class ByteArrayPool_smallCount : ByteArrayPoolCount(0)
class ByteArrayPool_mediumCount : ByteArrayPoolCount(1)
class ByteArrayPool_largeCount : ByteArrayPoolCount(2)
@DependsOn(ByteArrayPool_large::class)
class ByteArrayPool_get : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { Modifier.isSynchronized(it.access) }
.and { it.returnType == ByteArray::class.type }
.and { it.instructions.any { it.isField && it.fieldId == field<ByteArrayPool_large>().id } }
}
// @DependsOn(ByteArrayPool_large::class)
// class ByteArrayPool_release : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { Modifier.isSynchronized(it.access) }
// .and { it.returnType == VOID_TYPE }
// .and { it.instructions.any { it.isField && it.fieldId == field<ByteArrayPool_large>().id } }
// }
@DependsOn(Strings_connectingToUpdateServer::class)
class Login_loadingText : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_connectingToUpdateServer>().id }
.next { it.opcode == PUTSTATIC && it.fieldType == String::class.type }
}
@DependsOn(Strings_connectingToUpdateServer::class)
class Login_loadingPercent : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_connectingToUpdateServer>().id }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Strings_connectingToUpdateServer::class)
class titleLoadingStage : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_connectingToUpdateServer>().id }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(3) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
// inlined
// @DependsOn(PacketBuffer::class, Npc::class, Actor.overheadTextCyclesRemaining::class)
// class updateNpcs : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(type<PacketBuffer>()) }
// .and { it.instructions.any { it.opcode == PUTFIELD && it.fieldOwner == type<Npc>() && it.fieldType == INT_TYPE &&
// it.fieldName == field<Actor.overheadTextCyclesRemaining>().name } }
// }
@DependsOn(Player::class, PacketBit::class)
class updatePlayer : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 1..2 }
.and { it.arguments.startsWith(type<PacketBit>()) }
.and { it.instructions.any { it.opcode == NEW && it.typeType == type<Player>() } }
}
@MethodParameters("packet", "plane", "x", "y", "x0", "y0", "n")
@DependsOn(Packet::class)
class loadTerrain : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 7..8 }
.and { it.arguments.startsWith(type<Packet>(), INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
}
// inlined
// class chatCommand : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(String::class.type) }
// .and { it.instructions.any { it.opcode == LDC && it.ldcCst == "displayfps" } }
// }
class isResizable : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_2 }
.next { it.node is JumpInsnNode }
.next { it.opcode == ICONST_1 }
.next { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters()
@DependsOn(cycle::class)
class doCycle : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 0..1 }
.and { it.instructions.any { it.opcode == PUTSTATIC && it.fieldId == field<cycle>().id } }
}
@DependsOn(PacketBit::class)
class PacketBit_masks : UniqueMapper.InClassInitializer.Field(PacketBit::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(PacketWriter::class)
class packetWriter : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PacketWriter>() }
}
@DependsOn(KeyHandler::class)
class KeyHandler_idleCycles : OrderMapper.InClassInitializer.Field(KeyHandler::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler::class)
class MouseHandler_idleCycles : OrderMapper.InClassInitializer.Field(MouseHandler::class, 0 ) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.prevWithin(7) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextLimit : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.prevWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextXOffsets : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.prevWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextAscents : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextXs : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.nextWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.nextWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextYs : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.nextWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.nextWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.nextWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadTextColor::class)
class overheadTextColors : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadTextColor>().id }
.prevIn(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadTextEffect::class)
class overheadTextEffects : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadTextEffect>().id }
.prevIn(3) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadText : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.nextWithin(70) { it.opcode == GETSTATIC && it.fieldType == String::class.type.withDimensions(1) }
}
@DependsOn(Actor.overheadText::class, AbstractFont.stringWidth::class)
class overheadTextCyclesRemaining : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Actor.overheadText>().id }
.next { it.isMethod && it.methodMark == method<AbstractFont.stringWidth>().mark }
.nextWithin(70) { it.opcode == GETSTATIC && it.fieldType == String::class.type.withDimensions(1) }
.prevWithin(11) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
// class clanChatCount : StaticUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3614 }
// .nextWithin(17) { it.opcode == GETSTATIC && it.fieldType == String::class.type }
// .nextWithin(7) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
// class clanChatName : StaticUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3614 }
// .nextWithin(17) { it.opcode == GETSTATIC && it.fieldType == String::class.type }
// }
// inlined
// @MethodParameters("l")
// class longToString : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(LONG_TYPE) }
// .and { it.instructions.none { it.isMethod && it.methodName == "toUpperCase" } }
// .and { it.instructions.any { it.opcode == LREM } }
// }
// inlined
// @MethodParameters("l")
// class longToTitleString : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
// .and { it.arguments.size in 1..2 }
// .and { it.arguments.startsWith(LONG_TYPE) }
// .and { it.instructions.any { it.isMethod && it.methodName == "toUpperCase" } }
// .and { it.instructions.any { it.opcode == LREM } }
// }
class base37Table : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 37 }
.next { it.opcode == NEWARRAY && it.intOperand == 5 }
.nextWithin(200) { it.opcode == PUTSTATIC && it.fieldType == CharArray::class.type }
}
@DependsOn(AbstractFont::class)
class AbstractFont_lines : UniqueMapper.InClassInitializer.Field(AbstractFont::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == String::class.type.withDimensions(1) }
}
@DependsOn(AbstractFont::class, IndexedSprite::class)
class AbstractFont_modIconSprites : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.klass == klass<AbstractFont>() }
.and { it.type == type<IndexedSprite>().withDimensions(1) }
}
@DependsOn(Font.drawGlyph::class)
class AbstractFont_placeGlyph : UniqueMapper.InMethod.Method(Font.drawGlyph::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
override fun resolve(instruction: Instruction2): Method2 {
return instruction.jar[Triple(instruction.jar[instruction.methodOwner].superType, instruction.methodName, instruction.methodType)]
}
}
@DependsOn(Font.drawGlyphAlpha::class)
class AbstractFont_placeGlyphAlpha : UniqueMapper.InMethod.Method(Font.drawGlyphAlpha::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod }
override fun resolve(instruction: Instruction2): Method2 {
return instruction.jar[Triple(instruction.jar[instruction.methodOwner].superType, instruction.methodName, instruction.methodType)]
}
}
@MethodParameters("pixels", "x", "y", "width", "height", "color")
@DependsOn(AbstractFont_placeGlyph::class)
class AbstractFont_drawGlyph : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.instructions.any { it.isMethod && it.methodId == method<AbstractFont_placeGlyph>().id } }
}
@MethodParameters("pixels", "x", "y", "width", "height", "color", "alpha")
@DependsOn(AbstractFont_placeGlyphAlpha::class)
class AbstractFont_drawGlyphAlpha : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.instructions.any { it.isMethod && it.methodId == method<AbstractFont_placeGlyphAlpha>().id } }
}
// // 0 - 27
// @DependsOn(Component.swapItems::class)
// class inventorySlotHovered : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<Component.swapItems>().id }
// .prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
//
// @DependsOn(Component.swapItems::class)
// class inventorySlotPressed : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<Component.swapItems>().id }
// .prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// .prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
@DependsOn(GameShell.focusGained::class)
class hasFocus : UniqueMapper.InMethod.Field(GameShell.focusGained::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(Usernamed.username::class)
class username : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<Usernamed.username>().mark }
}
@DependsOn(Varcs::class)
class varcs : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Varcs>() }
}
@DependsOn(Scene::class, NodeDeque::class)
class Scene_tilesDeque : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.klass == klass<Scene>() }
.and { it.type == type<NodeDeque>() }
}
@DependsOn(Rasterizer2D_setClip::class)
class minimapState : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<Rasterizer2D_setClip>().id }
.nextWithin(5) { it.opcode == ICONST_2 }
.nextWithin(10) { it.opcode == ICONST_5 }
.prevWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class visibilityMap : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE.withDimensions(4) }
}
@MethodParameters("a", "b", "c", "viewportWidth", "viewportHeight")
@DependsOn(Scene::class)
class Scene_buildVisiblityMap : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.klass == klass<Scene>() }
.and { it.arguments.startsWith(IntArray::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
}
class Scene_viewportXMin : SceneViewportField(0)
class Scene_viewportYMin : SceneViewportField(1)
class Scene_viewportXMax : SceneViewportField(2)
class Scene_viewportYMax : SceneViewportField(3)
class Scene_viewportXCenter : SceneViewportField(4)
class Scene_viewportYCenter : SceneViewportField(5)
@MethodParameters("isInInstance", "bit")
@DependsOn(xteaKeys::class)
class loadRegions : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.opcode == PUTSTATIC && it.fieldId == field<xteaKeys>().id } }
}
@DependsOn(loadRegions::class)
class isInInstance : OrderMapper.InMethod.Field(loadRegions::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class regions : LoadRegionPutStatic(IntArray::class.type, 0)
class regionMapArchiveIds : LoadRegionPutStatic(IntArray::class.type, 1)
class regionLandArchiveIds : LoadRegionPutStatic(IntArray::class.type, 2)
class regionMapArchives : LoadRegionPutStatic(BYTE_TYPE.withDimensions(2), 1)
class regionLandArchives : LoadRegionPutStatic(BYTE_TYPE.withDimensions(2), 2)
@DependsOn(updatePlayer::class)
class localPlayerIndex : OrderMapper.InMethod.Field(updatePlayer::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(alignComponent::class)
class canvasWidth : OrderMapper.InMethod.Field(alignComponent::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(alignComponent::class)
class canvasHeight : OrderMapper.InMethod.Field(alignComponent::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Component::class)
class viewportComponent : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 6203 }
.nextWithin(4) { it.opcode == GETSTATIC && it.fieldType == type<Component>() }
}
@DependsOn(doAction::class)
class destinationX : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1001 }
.nextWithin(15) { it.opcode == ICONST_0 }
.nextWithin(3) { it.opcode == ILOAD && it.varVar == 0 }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doAction::class)
class destinationY : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1001 }
.nextWithin(15) { it.opcode == ICONST_0 }
.nextWithin(10) { it.opcode == ILOAD && it.varVar == 1 }
.nextWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Sprite::class)
class mapIcons : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1000 }
.next { it.opcode == ANEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == type<Sprite>().withDimensions(1) }
}
@DependsOn(mapIcons::class)
class mapIconYs : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<mapIcons>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(mapIcons::class)
class mapIconXs : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<mapIcons>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(mapIcons::class)
class mapIconCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<mapIcons>().id }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(5) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
class instanceChunkTemplates : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_4 }
.next { it.opcode == BIPUSH && it.intOperand == 13 }
.next { it.opcode == BIPUSH && it.intOperand == 13 }
.nextIn(2) { it.opcode == PUTSTATIC }
}
@DependsOn(IntegerNode::class, NodeHashTable::class)
class componentClickMasks : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<IntegerNode>() }
.prev { it.opcode == GETSTATIC && it.fieldType == type<NodeHashTable>() }
}
@DependsOn(Scene.init::class)
class Tiles_minPlane : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<Scene.init>().id }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("w", "b")
@DependsOn(InterfaceParent::class)
class closeInterface : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<InterfaceParent>(), BOOLEAN_TYPE) }
}
// inlined
// @MethodParameters("key", "group", "type")
// @DependsOn(InterfaceParent::class)
// class openInterface : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<InterfaceParent>() }
// .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE) }
// }
@MethodParameters("id", "quantity", "n0", "n1", "n2", "b0")
@DependsOn(Sprite::class)
class getItemSprite : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>() }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, BOOLEAN_TYPE) }
}
@DependsOn(Sprite::class)
class sceneMinimapSprite : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 512 }
.next { it.opcode == SIPUSH && it.intOperand == 512 }
.nextIn(2) { it.opcode == PUTSTATIC && it.fieldType == type<Sprite>() }
}
@MethodParameters("w0", "w1", "mode", "b")
@DependsOn(World::class)
class compareWorlds : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
.and { it.arguments.size in 4..5 }
.and { it.arguments.startsWith(type<World>(), type<World>(), INT_TYPE, BOOLEAN_TYPE) }
}
@MethodParameters("actor", "a", "b", "c", "d", "e")
@DependsOn(Actor::class)
class drawActor2d : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Actor>(), INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
}
// inlined
// @DependsOn(drawActor2d::class)
// class drawActors2d : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.size in 4..5 }
// .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
// .and { it.instructions.any { it.isMethod && it.methodId == method<drawActor2d>().id } }
// }
class renderSelf : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "renderself" }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class showMouseOverText : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "mouseovertext" }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters("player", "b")
@DependsOn(Player::class)
class addPlayerToScene : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 2..3 }
.and { it.arguments.startsWith(type<Player>(), BOOLEAN_TYPE) }
}
@DependsOn(Sprite::class, AbstractArchive::class)
@MethodParameters("archive", "group", "file")
class readSprite : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>() }
.and { it.arguments.size in 3..4 }
.and { it.arguments.startsWith(type<AbstractArchive>(), INT_TYPE, INT_TYPE) }
}
@MethodParameters("player", "menuArg0", "menuArg1", "menuArg2")
@DependsOn(Player::class, Client.playerMenuOpcodes::class)
class addPlayerToMenu : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 4..5 }
.and { it.arguments.startsWith(type<Player>(), INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<Client.playerMenuOpcodes>().id } }
}
@MethodParameters("npc", "menuArg0", "menuArg1", "menuArg2")
@DependsOn(NPCType::class)
class addNpcToMenu : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 4..5 }
.and { it.arguments.startsWith(type<NPCType>(), INT_TYPE, INT_TYPE, INT_TYPE) }
}
@DependsOn(EvictingDualNodeHashTable::class, HeadbarType.getFrontSprite::class)
class HeadbarType_cachedSprites : UniqueMapper.InMethod.Field(HeadbarType.getFrontSprite::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(HeadbarType::class, EvictingDualNodeHashTable::class)
class HeadbarType_cached : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<HeadbarType>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
// @MethodParameters("id")
// @DependsOn(HitmarkType::class)
// class getHitmarkType : StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<HitmarkType>() }
// }
@DependsOn(HitmarkType.getFont::class, EvictingDualNodeHashTable::class)
class HitmarkType_cachedFonts : UniqueMapper.InMethod.Field(HitmarkType.getFont::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(WorldMap::class)
class worldMap0 : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<WorldMap>() }
}
@DependsOn(WorldMap::class)
class worldMap : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<WorldMap>() }
}
class WorldMapLabelSize_small : WorldMapLabelSizeConstant(0)
class WorldMapLabelSize_medium : WorldMapLabelSizeConstant(1)
class WorldMapLabelSize_large : WorldMapLabelSizeConstant(2)
@DependsOn(KeyHandler::class)
class KeyHandler_pressedKeys : UniqueMapper.InClassInitializer.Field(KeyHandler::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 112 }
.next { it.opcode == NEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == BooleanArray::class.type }
}
@DependsOn(doAction::class)
class selectedItemSlot : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 38 }
.nextWithin(2) { it.node is JumpInsnNode }
.nextWithin(15) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doAction::class)
class selectedItemComponent : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 38 }
.nextWithin(2) { it.node is JumpInsnNode }
.nextWithin(15) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doAction::class)
class selectedItemId : UniqueMapper.InMethod.Field(doAction::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 38 }
.nextWithin(2) { it.node is JumpInsnNode }
.nextWithin(15) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.nextWithin(6) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(MouseHandler_currentButton::class)
class itemDragDuration : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<MouseHandler_currentButton>().id }
.prevWithin(4) { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
.prev { it.opcode == IADD }
.prevWithin(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(clickComponent::class)
class componentClickX : OrderMapper.InMethod.Field(clickComponent::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(clickComponent::class)
class componentClickY : OrderMapper.InMethod.Field(clickComponent::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(clickComponent::class)
class componentDragDuration : OrderMapper.InMethod.Field(clickComponent::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(clickComponent::class)
class isDraggingComponent : OrderMapper.InMethod.Field(clickComponent::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(ChatChannel::class)
class Messages_channels : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<ChatChannel>() }
.prevIn(4) { it.opcode == GETSTATIC && it.fieldType == Map::class.type }
}
@DependsOn(addMessage::class, IterableDualNodeQueue::class)
class Messages_queue : UniqueMapper.InMethod.Field(addMessage::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<IterableDualNodeQueue>() }
}
@MethodParameters()
@DependsOn(draw::class)
class drawLoggedIn : UniqueMapper.InMethod.Method(draw::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 30 }
.nextWithin(10) { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Client>() }
}
@DependsOn(Component::class, Rasterizer2D_setClip::class)
class drawInterface : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 9..10 }
.and { it.arguments.startsWith(type<Component>().withDimensions(1)) }
.and { it.instructions.any { it.opcode == INVOKESTATIC && it.methodId == method<Rasterizer2D_setClip>().id } }
}
// @DependsOn(drawInterface::class)
// class drawInterface0 : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.size in 8..9 }
// .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) }
// .and { it.instructions.any { it.opcode == INVOKESTATIC && it.methodId == method<drawInterface0>().id } }
// }
@MethodParameters("component", "x", "y")
@DependsOn(Component::class, isMiniMenuOpen::class, minimapState::class)
class clickComponent : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<Component>(), INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<isMiniMenuOpen>().id } }
.and { it.instructions.none { it.opcode == GETSTATIC && it.fieldId == field<minimapState>().id } }
}
@DependsOn(clickComponent::class, Component::class)
class clickedComponent : OrderMapper.InMethod.Field(clickComponent::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<Component>() }
}
@DependsOn(clickComponent::class, Component::class)
class clickedComponentParent : OrderMapper.InMethod.Field(clickComponent::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<Component>() }
}
@MethodParameters()
@DependsOn(doCycle::class)
class doCycleLoggedIn : UniqueMapper.InMethod.Method(doCycle::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 30 }
.nextWithin(10) { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Client>() }
}
class TriBool_unknown : TriBoolConst(0)
class TriBool_true : TriBoolConst(1)
class TriBool_false : TriBoolConst(2)
// @DependsOn(getUnderlayDefinition::class)
// class underlays : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .prevWithin(20) { it.opcode == GETSTATIC && it.fieldType == BYTE_TYPE.withDimensions(3) }
// }
//
// @DependsOn(getUnderlayDefinition::class)
// class underlayHues : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// }
//
// @DependsOn(getUnderlayDefinition::class)
// class underlaySaturations : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// }
// @DependsOn(getUnderlayDefinition::class)
// class underlayLightnesses : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// }
//
// @DependsOn(getUnderlayDefinition::class)
// class underlayHueMultipliers : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// }
//
// @DependsOn(getUnderlayDefinition::class)
// class underlayCounts : AllUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<getUnderlayDefinition>().id }
// .nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// .nextWithin(12) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
// }
@DependsOn(Messages::class)
class Messages_count : OrderMapper.InClassInitializer.Field(Messages::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_0 }
.next { it.opcode == PUTSTATIC }
}
class Model_transformTempX : ModelTransformTempInt(0)
class Model_transformTempY : ModelTransformTempInt(1)
class Model_transformTempZ : ModelTransformTempInt(2)
@DependsOn(Model.toSharedSpotAnimationModel::class, Model::class)
class Model_sharedSpotAnimationModel : UniqueMapper.InMethod.Field(Model.toSharedSpotAnimationModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<Model>() }
}
@DependsOn(Model.toSharedSpotAnimationModel::class, Model::class)
class Model_sharedSpotAnimationModelFaceAlphas : UniqueMapper.InMethod.Field(Model.toSharedSpotAnimationModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == ByteArray::class.type }
}
@DependsOn(Model.toSharedSequenceModel::class, Model::class)
class Model_sharedSequenceModel : UniqueMapper.InMethod.Field(Model.toSharedSequenceModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<Model>() }
}
@DependsOn(Model.toSharedSequenceModel::class, Model::class)
class Model_sharedSequenceModelFaceAlphas : UniqueMapper.InMethod.Field(Model.toSharedSequenceModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == ByteArray::class.type }
}
@MethodParameters("id")
@DependsOn(AnimFrameset::class)
class getAnimFrameset : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<AnimFrameset>() }
.and { it.arguments.size in 1..2 }
}
@DependsOn(ClientScript::class, EvictingDualNodeHashTable::class)
class ClientScript_cached : CachedDefinitionMapper(ClientScript::class)
@DependsOn(ParamType::class, EvictingDualNodeHashTable::class)
class ParamType_cached : CachedDefinitionMapper(ParamType::class)
@MethodParameters("id")
@DependsOn(ParamType::class)
class getParamType : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<ParamType>() }
}
@DependsOn(VarType::class, EvictingDualNodeHashTable::class)
class VarType_cached : CachedDefinitionMapper(VarType::class)
@DependsOn(addPlayerToMenu::class, players::class)
class combatTargetPlayerIndex : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<addPlayerToMenu>().id }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldId == field<players>().id }
.nextWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("x", "y", "width", "height", "clear")
class setViewportShape : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 5..6 }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, BOOLEAN_TYPE) }
}
@DependsOn(addNpcToMenu::class, selectedSpellActionName::class)
class isSpellSelected : UniqueMapper.InMethod.Field(addNpcToMenu::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<selectedSpellActionName>().id }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(addNpcToMenu::class, selectedSpellActionName::class)
class selectedSpellFlags : UniqueMapper.InMethod.Field(addNpcToMenu::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<selectedSpellActionName>().id }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(mapMarkerSprites::class, players::class)
class hintArrowType : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<mapMarkerSprites>().id }
.prevWithin(35) { it.opcode == GETSTATIC && it.fieldId == field<players>().id }
.prevWithin(11) { it.isLabel }
.nextWithin(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(mapMarkerSprites::class, players::class)
class hintArrowPlayerIndex : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<mapMarkerSprites>().id }
.prevWithin(35) { it.opcode == GETSTATIC && it.fieldId == field<players>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(mapMarkerSprites::class, npcs::class)
class hintArrowNpcIndex : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<mapMarkerSprites>().id }
.prevWithin(35) { it.opcode == GETSTATIC && it.fieldId == field<npcs>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(mapMarkerSprites::class, baseY::class)
class hintArrowY : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<mapMarkerSprites>().id }
.prevWithin(18) { it.opcode == GETSTATIC && it.fieldId == field<baseY>().id }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(mapMarkerSprites::class, baseX::class)
class hintArrowX : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<mapMarkerSprites>().id }
.prevWithin(35) { it.opcode == GETSTATIC && it.fieldId == field<baseX>().id }
.prevWithin(4) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(hintArrowType::class)
class hintArrowSubX : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<hintArrowType>().id }
.nextWithin(3) { it.opcode == BIPUSH && it.intOperand == 64 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(hintArrowType::class)
class hintArrowSubY : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<hintArrowType>().id }
.nextWithin(3) { it.opcode == BIPUSH && it.intOperand == 64 }
.nextWithin(2) { it.opcode == BIPUSH && it.intOperand == 64 }
.next { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(hintArrowY::class, baseY::class)
class hintArrowHeight : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<hintArrowY>().id }
.next { it.opcode == GETSTATIC && it.fieldId == field<baseY>().id }
.nextWithin(15) { it.opcode == INVOKESTATIC }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(GameShell.startThread::class)
class revision : OrderMapper.InMethod.Field(GameShell.startThread::class, -1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(TaskHandler::class)
class taskHandler : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<TaskHandler>() }
}
@DependsOn(GameShell.startThread::class)
class applet : UniqueMapper.InMethod.Field(GameShell.startThread::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == Applet::class.type }
}
@DependsOn(GameShell.kill::class)
class isKilled : OrderMapper.InMethod.Field(GameShell.kill::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
// @MethodParameters()
// @DependsOn(componentDragDuration::class)
// class dragComponent : IdentityMapper.InstanceMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.isEmpty() }
// .and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<componentDragDuration>().id } }
// }
@MethodParameters("component")
@DependsOn(Component::class, Component.clickMask::class)
class getComponentClickMask : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
.and { it.arguments == listOf(type<Component>()) }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<Component.clickMask>().id } }
}
// @DependsOn(Component::class, clickedComponent::class, clickedComponentParent::class, dragComponent::class)
// class componentDragTarget : UniqueMapper.InMethod.Field(dragComponent::class) {
// override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<Component>() }
// .and { it.fieldId != field<clickedComponent>().id && it.fieldId != field<clickedComponentParent>().id }
// }
@MethodParameters("components", "parentId", "a", "b", "c", "d", "x", "y")
@DependsOn(Component::class)
class updateInterface : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<Component>().withDimensions(1), INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE,
INT_TYPE, INT_TYPE, INT_TYPE) }
}
@DependsOn(ArchiveLoader::class)
class archiveLoaders : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<ArchiveLoader>() }
.prevWithin(3) { it.opcode == GETSTATIC && it.fieldType == ArrayList::class.type }
}
@DependsOn(ArchiveLoader::class)
class archiveLoaderArchive : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<ArchiveLoader>() }
.prevWithin(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Timer::class)
class timer : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Timer>() }
}
@MethodParameters("component", "parentWidth", "parentHeight")
@DependsOn(Component::class, Component.xAlignment::class)
class alignComponentPosition : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<Component>(), INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.isField && it.fieldId == field<Component.xAlignment>().id } }
}
@MethodParameters("component", "parentWidth", "parentHeight", "b")
@DependsOn(Component::class, Component.widthAlignment::class)
class alignComponentSize : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<Component>(), INT_TYPE, INT_TYPE, BOOLEAN_TYPE) }
.and { it.instructions.any { it.isField && it.fieldId == field<Component.widthAlignment>().id } }
}
@DependsOn(newPcmPlayer::class)
class soundSystemExecutor : UniqueMapper.InMethod.Field(newPcmPlayer::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == ScheduledExecutorService::class.type }
}
// // class newSecureRandom : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == SecureRandom::class.type }
// }
@DependsOn(SecureRandomFuture::class)
class secureRandomFuture : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<SecureRandomFuture>() }
}
class secureRandom : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == SecureRandom::class.type }
}
// @MethodParameters("index", "archive", "record")
// // @DependsOn(Sprite::class, AbstractIndexCache::class)
// class readSprites : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<Sprite>().withDimensions(1) }
// .and { it.arguments == listOf(type<AbstractIndexCache>(), INT_TYPE, INT_TYPE) }
// }
@DependsOn(GraphicsDefaults::class)
class spriteIds : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<GraphicsDefaults>() }
}
// @MethodParameters("index", "archive", "record")
// // @DependsOn(IndexedSprite::class, AbstractIndexCache::class)
// class readIndexedSprites : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<IndexedSprite>().withDimensions(1) }
// .and { it.arguments == listOf(type<AbstractIndexCache>(), INT_TYPE, INT_TYPE) }
// }
// @MethodParameters("index", "archive", "record")
// // @DependsOn(AbstractIndexCache::class)
// class loadSprites : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
// .and { it.arguments == listOf(type<AbstractIndexCache>(), INT_TYPE, INT_TYPE) }
// }
@MethodParameters()
@DependsOn(GameShell.kill0::class)
class kill0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<GameShell.kill0>().mark }
}
class Interpreter_stringStack : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1000 }
.next { it.opcode == ANEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == Array<String>::class.type }
}
@DependsOn(Interpreter::class)
class Interpreter_intStack : UniqueMapper.InClassInitializer.Field(Interpreter::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 1000 }
.next { it.opcode == NEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Interpreter::class)
class Interpreter_arrays : UniqueMapper.InClassInitializer.Field(Interpreter::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5000 }
.next { it.opcode == MULTIANEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == Array<IntArray>::class.type }
}
@DependsOn(Interpreter::class)
class Interpreter_arrayLengths : UniqueMapper.InClassInitializer.Field(Interpreter::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_5 }
.next { it.opcode == NEWARRAY }
.next { it.opcode == PUTSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(ClientScriptFrame::class)
class Interpreter_frames : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<ClientScriptFrame>().withDimensions(1) }
}
@DependsOn(Interpreter_frames::class)
class Interpreter_frameDepth : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Interpreter_frames>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Interpreter_intStack::class)
class Interpreter_intStackSize : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Interpreter_intStack>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Interpreter_stringStack::class)
class Interpreter_stringStackSize : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Interpreter_stringStack>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(ClientScriptFrame.stringLocals::class)
class Interpreter_stringLocals : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<ClientScriptFrame.stringLocals>().id }
.next { it.opcode == PUTSTATIC }
}
@DependsOn(ClientScriptFrame.intLocals::class)
class Interpreter_intLocals : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<ClientScriptFrame.intLocals>().id }
.next { it.opcode == PUTSTATIC }
}
@MethodParameters("scriptEvent", "n")
@DependsOn(ClientScriptEvent::class)
class runClientScript0 : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<ClientScriptEvent>(), INT_TYPE) }
}
@MethodParameters("scriptEvent")
@DependsOn(ClientScriptEvent::class)
class runClientScript : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<ClientScriptEvent>()) }
}
@DependsOn(alignComponentSize::class, NodeDeque::class)
class clientScriptEvents : UniqueMapper.InMethod.Field(alignComponentSize::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<NodeDeque>() }
}
@MethodParameters("brightness")
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_setBrightness : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer3D>() }
.and { it.returnType == VOID_TYPE && it.arguments == listOf(DOUBLE_TYPE) }
}
@MethodParameters("brightness", "hsMin", "hsMax")
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_buildPalette : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer3D>() }
.and { it.returnType == VOID_TYPE && it.arguments == listOf(DOUBLE_TYPE, INT_TYPE, INT_TYPE) }
}
@DependsOn(Rasterizer3D_buildPalette::class)
class Rasterizer3D_colorPalette : UniqueMapper.InMethod.Field(Rasterizer3D_buildPalette::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(PlayerAppearance.getModel::class, EvictingDualNodeHashTable::class)
class PlayerAppearance_cachedModels : UniqueMapper.InMethod.Field(PlayerAppearance.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(LocType.getModel::class, EvictingDualNodeHashTable::class)
class LocType_cachedModels : UniqueMapper.InMethod.Field(LocType.getModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_alpha : OrderMapper.InClassInitializer.Field(Rasterizer3D::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(LocSound::class, NodeDeque::class)
class objectSounds : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == CHECKCAST && it.typeType == type<LocSound>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == type<NodeDeque>() }
}
@MethodParameters("textureLoader")
@DependsOn(Rasterizer3D::class, TextureLoader::class)
class Rasterizer3D_setTextureLoader : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer3D>() }
.and { it.arguments == listOf(type<TextureLoader>()) }
}
@DependsOn(TextureProvider::class)
class textureProvider : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<TextureProvider>() }
}
@DependsOn(PlatformInfo::class)
class platformInfo : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PlatformInfo>() }
}
@DependsOn(Scene.draw::class)
class Scene_drawnCount : OrderMapper.InMethod.Field(Scene.draw::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene::class, Occluder::class)
class Scene_addOccluder : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Scene>() }
.and { it.arguments.size == 8 }
.and { it.instructions.any { it.opcode == NEW && it.typeType == type<Occluder>() } }
}
@DependsOn(Occluder::class)
class Scene_planeOccluders : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Occluder>().withDimensions(2) }
}
@DependsOn(Occluder::class)
class Scene_currentOccluders : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Occluder>().withDimensions(1) }
}
@DependsOn(Scene_addOccluder::class)
class Scene_planeOccluderCounts : UniqueMapper.InMethod.Field(Scene_addOccluder::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(Scene::class)
class Scene_currentOccludersCount : UniqueMapper.InClassInitializer.Field(Scene::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 500 }
.prev { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("component")
@DependsOn(Component::class, Component.cs1Comparisons::class)
class runCs1 : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
.and { it.arguments == listOf(type<Component>()) }
.and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<Component.cs1Comparisons>().id } }
}
@DependsOn(loadInterface::class, AbstractArchive::class)
class Component_archive : UniqueMapper.InMethod.Field(loadInterface::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(drawInterface::class, Component.color2::class, Component::class)
class mousedOverComponentIf1 : UniqueMapper.InMethod.Field(drawInterface::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<Component.color2>().id }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == type<Component>() }
}
@DependsOn(Texture.animate::class)
class Texture_animatedPixels : UniqueMapper.InMethod.Field(Texture.animate::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(secureRandom::class)
@MethodParameters()
class doCycleLoggedOut : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.isEmpty() }
.and { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.opcode == PUTSTATIC && it.fieldId == field<secureRandom>().id } }
}
@DependsOn(doCycleLoggedOut::class)
class loginState : OrderMapper.InMethod.Field(doCycleLoggedOut::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class Interpreter_calendar : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> {
it.opcode == INVOKESTATIC &&
it.methodName == "getInstance" &&
it.methodOwner == Calendar::class.type &&
it.methodType.argumentTypes.isEmpty()
}.next { it.opcode == PUTSTATIC }
}
@DependsOn(doCycleLoggedOut::class, TaskHandler.newSocketTask::class)
class socketTask : UniqueMapper.InMethod.Field(doCycleLoggedOut::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<TaskHandler.newSocketTask>().id }
.next { it.opcode == PUTSTATIC }
}
@DependsOn(init::class)
class useBufferedSocket : UniqueMapper.InMethod.Field(init::class) {
override val predicate = predicateOf<Instruction2> { it.isLabel }
.next { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class clientType : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 6519 }
.nextWithin(20) { it.isLabel }
.prevWithin(8) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
// class language : StaticUniqueMapper.Field() {
// override val predicate = predicateOf<Instruction2> { it.opcode == LDC && it.ldcCst == "/l=" }
// .nextIn(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
@DependsOn(doCycleLoggedIn::class)
class rebootTimer : OrderMapper.InMethod.Field(doCycleLoggedIn::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(WorldMapEvent::class)
class worldMapEvent : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<WorldMapEvent>() }
}
@DependsOn(Client.addNpcToMenu::class, NPCType.isFollower::class)
class followerOpsLowPriority : OrderMapper.InMethod.Field(Client.addNpcToMenu::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldId == field<NPCType.isFollower>().id }
.next { it.opcode == IFEQ }
.next { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(Client.addNpcToMenu::class)
class followerIndex : OrderMapper.InMethod.Field(Client.addNpcToMenu::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
class shiftClickDrop : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3117 }
.nextWithin(18) { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(KeyHandler_pressedKeys::class)
class tapToDrop : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 81 }
.prev { it.opcode == GETSTATIC && it.fieldId == field<KeyHandler_pressedKeys>().id }
.prevIn(2) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class showMouseCross : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3125 }
.nextWithin(18) { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class showLoadingMessages : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3126 }
.nextWithin(18) { it.opcode == PUTSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(currentTimeMs::class, doCycleJs5Connect::class)
class js5StartTimeMs : OrderMapper.InMethod.Field(doCycleJs5Connect::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC && it.methodId == method<currentTimeMs>().id }
.next { it.opcode == PUTSTATIC }
}
@MethodParameters()
class doCycleJs5Connect : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == VOID_TYPE }
.and { it.instructions.any { it.opcode == LDC && it.ldcCst == "js5crc" } }
}
// @DependsOn(doCycleJs5Connect::class)
// class js5ConnectState : OrderMapper.InMethod.Field(doCycleJs5Connect::class, 0) {
// override val predicate = predicateOf<Instruction2> { it.opcode == ICONST_0 }
// .nextWithin(2) { it.opcode == IF_ICMPNE }
// .prevWithin(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
// }
@DependsOn(doCycleJs5Connect::class, TaskHandler.newSocketTask::class)
class js5SocketTask : UniqueMapper.InMethod.Field(doCycleJs5Connect::class) {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodId == method<TaskHandler.newSocketTask>().id }
.next { it.opcode == PUTSTATIC }
}
@DependsOn(doCycleJs5Connect::class, TaskHandler.newSocketTask::class)
class NetCache_crcMismatches : OrderMapper.InMethod.Field(doCycleJs5Connect::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doCycleJs5Connect::class, TaskHandler.newSocketTask::class)
class NetCache_ioExceptions : OrderMapper.InMethod.Field(doCycleJs5Connect::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doCycleJs5Connect::class, AbstractSocket::class)
class js5Socket : OrderMapper.InMethod.Field(doCycleJs5Connect::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == type<AbstractSocket>() }
}
@MethodParameters("code")
class js5Error : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments == listOf(INT_TYPE) }
.and { it.returnType == VOID_TYPE }
}
@DependsOn(js5Error::class)
class js5Errors : OrderMapper.InMethod.Field(js5Error::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == IADD }
.next { it.opcode == PUTSTATIC }
}
@DependsOn(overheadText::class, viewportTempY::class)
class chatEffects : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldId == field<viewportTempY>().id }
.next { it.opcode == GETSTATIC && it.fieldId == field<overheadText>().id }
.nextWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Strings_loadingPleaseWait::class, Rasterizer2D_fillRectangle::class)
class isLoading : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<Strings_loadingPleaseWait>().id }
.prev { it.isMethod && it.methodId == method<Rasterizer2D_fillRectangle>().id }
.prevWithin(9) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters()
@DependsOn(doCycle::class)
class doCycleJs5 : OrderMapper.InMethod.Method(doCycle::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL }
}
@DependsOn(showLoadingMessages::class)
class drawLoadingMessage : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(String::class.type, BOOLEAN_TYPE) }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<showLoadingMessages>().id } }
}
@MethodParameters("f1", "f2", "f3")
@DependsOn(Font::class)
class drawTitle : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<Font>(), type<Font>(), type<Font>()) }
}
class isCameraLocked : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5504 }
.nextWithin(18) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
@DependsOn(AbstractFont.drawCenteredWave::class)
class viewportDrawCount : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL && it.methodMark == method<AbstractFont.drawCenteredWave>().mark }
.prev { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(viewportDrawCount::class)
class tileLastDrawnActor : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<viewportDrawCount>().id }
.nextWithin(4) { it.opcode == GETSTATIC && it.fieldType == Array<IntArray>::class.type }
}
@MethodParameters("rgb", "brightness")
@DependsOn(Rasterizer3D::class)
class Rasterizer3D_brighten : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.klass == klass<Rasterizer3D>() }
.and { it.returnType == INT_TYPE }
.and { it.arguments == listOf(INT_TYPE, DOUBLE_TYPE) }
}
@DependsOn(VorbisSample::class)
class readVorbisSample : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<VorbisSample>() }
}
@MethodParameters("archive", "group", "file")
@DependsOn(MusicTrack::class)
class readTrack : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<MusicTrack>() }
}
// 22050
@DependsOn(DevicePcmPlayer.init::class)
class PcmPlayer_sampleRate : UniqueMapper.InMethod.Field(DevicePcmPlayer.init::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(newPcmPlayer::class, SoundSystem::class)
class pcmPlayerCount : UniqueMapper.InMethod.Field(newPcmPlayer::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<SoundSystem>() }
.prevWithin(6) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Decimator::class)
class decimator : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<Decimator>() }
}
@DependsOn(soundEffects::class)
class soundEffectCount : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<soundEffects>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(soundEffects::class)
class soundEffectIds : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<soundEffects>().id }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
.prevWithin(10) { it.opcode == GETSTATIC && it.fieldType == IntArray::class.type }
}
@DependsOn(soundEffects::class)
class queueSoundEffect : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(INT_TYPE, INT_TYPE, INT_TYPE) }
.and { it.instructions.any { it.opcode == GETSTATIC && it.fieldId == field<soundEffects>().id } }
}
@DependsOn(PcmStreamMixer::class)
class pcmStreamMixer : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<PcmStreamMixer>() }
}
@MethodParameters("stream")
@DependsOn(PcmStream::class)
class PcmStream_disable : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(type<PcmStream>()) }
}
class clearIntArray : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(IntArray::class.type, INT_TYPE, INT_TYPE) }
.and { it.instructions.count { it.opcode == ICONST_0 } == 9 }
}
@DependsOn(SoundCache::class)
class soundCache : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<SoundCache>() }
}
@DependsOn(MusicTrack::class)
class musicTrack : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MusicTrack>() }
}
@DependsOn(MidiPcmStream::class)
class midiPcmStream : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<MidiPcmStream>() }
}
@DependsOn(musicTrack::class, AbstractArchive::class)
class musicTrackGroupId : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<musicTrack>().id }
.nextIn(2) { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
.next { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(musicTrack::class, AbstractArchive::class)
class musicTrackFileId : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<musicTrack>().id }
.nextIn(2) { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
.nextIn(2) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(musicTrack::class)
class musicTrackBoolean : AllUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<musicTrack>().id }
.next { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
// @DependsOn(MusicPatch::class)
// class readMusicPatch : IdentityMapper.StaticMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<MusicPatch>() }
// }
@DependsOn(drawInterface::class, isItemSelected::class)
class dragItemSlotSource : UniqueMapper.InMethod.Field(drawInterface::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<isItemSelected>().id }
.prevWithin(5) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doCycleLoggedIn::class, dragItemSlotSource::class)
class dragItemSlotDestination : UniqueMapper.InMethod.Field(doCycleLoggedIn::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<dragItemSlotSource>().id }
.prev { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(doCycleLoggedIn::class, dragItemSlotDestination::class, Component::class)
class dragInventoryComponent : UniqueMapper.InMethod.Field(doCycleLoggedIn::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldId == field<dragItemSlotDestination>().id }
.nextWithin(3) { it.opcode == GETSTATIC && it.fieldType == type<Component>() }
}
@DependsOn(Scene.menuOpen::class)
class Scene_selectedPlane : OrderMapper.InMethod.Field(Scene.menuOpen::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.menuOpen::class)
class Scene_selectedScreenX : OrderMapper.InMethod.Field(Scene.menuOpen::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.menuOpen::class)
class Scene_selectedScreenY : OrderMapper.InMethod.Field(Scene.menuOpen::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.menuOpen::class)
class Scene_selectedX : OrderMapper.InMethod.Field(Scene.menuOpen::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(Scene.menuOpen::class)
class Scene_selectedY : OrderMapper.InMethod.Field(Scene.menuOpen::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("id")
@DependsOn(MapElementType::class)
class getMapElementType : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<MapElementType>() }
.and { it.arguments == listOf(INT_TYPE) }
}
@DependsOn(WorldMap.flashCategory::class)
class MapElementType_count : UniqueMapper.InMethod.Field(WorldMap.flashCategory::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@DependsOn(DefaultsGroup::class)
class DefaultsGroup_graphics : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<DefaultsGroup>() }
}
class playerMod : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 3323 }
.nextWithin(10) { it.opcode == GETSTATIC && it.fieldType == BOOLEAN_TYPE }
}
class camFollowHeight : StaticUniqueMapper.Field() {
override val predicate = predicateOf<Instruction2> { it.opcode == SIPUSH && it.intOperand == 5531 }
.nextWithin(50) { it.isLabel }
.prevWithin(15) { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
@MethodParameters("n", "positiveSign")
class intToString : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.arguments == listOf(INT_TYPE, BOOLEAN_TYPE) }
}
@DependsOn(VorbisCodebook::class)
class VorbisSample_codebooks : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<VorbisCodebook>().withDimensions(1) }
}
@DependsOn(VorbisFloor::class)
class VorbisSample_floors : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<VorbisFloor>().withDimensions(1) }
}
@DependsOn(VorbisResidue::class)
class VorbisSample_residues : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<VorbisResidue>().withDimensions(1) }
}
@DependsOn(VorbisMapping::class)
class VorbisSample_mappings : IdentityMapper.StaticField() {
override val predicate = predicateOf<Field2> { it.type == type<VorbisMapping>().withDimensions(1) }
}
@DependsOn(readVorbisSample::class)
class VorbisSample_loadSetupHeader : OrderMapper.InMethod.Method(readVorbisSample::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(VorbisSample_loadSetupHeader::class)
class VorbisSample_decodeSetupHeader : OrderMapper.InMethod.Method(VorbisSample_loadSetupHeader::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(VorbisSample_loadSetupHeader::class)
class VorbisSample_setupHeaderLoaded : OrderMapper.InMethod.Field(VorbisSample_loadSetupHeader::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC }
}
@DependsOn(VorbisSample_decodeSetupHeader::class)
class VorbisSample_setStream : OrderMapper.InMethod.Method(VorbisSample_decodeSetupHeader::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(VorbisSample_setStream::class)
class VorbisSample_stream : OrderMapper.InMethod.Field(VorbisSample_setStream::class, 0, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(VorbisSample_setStream::class)
class VorbisSample_bytePos : OrderMapper.InMethod.Field(VorbisSample_setStream::class, 1, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(VorbisSample_setStream::class)
class VorbisSample_bitPos : OrderMapper.InMethod.Field(VorbisSample_setStream::class, 2, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(VorbisSample_decodeSetupHeader::class)
class VorbisSample_blocksize0 : OrderMapper.InMethod.Field(VorbisSample_decodeSetupHeader::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(VorbisSample_decodeSetupHeader::class)
class VorbisSample_blocksize1 : OrderMapper.InMethod.Field(VorbisSample_decodeSetupHeader::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTSTATIC }
}
@DependsOn(VorbisSample.decodeAudio::class)
class VorbisSample_readBit : OrderMapper.InMethod.Method(VorbisSample.decodeAudio::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(VorbisSample.decodeAudio::class)
class VorbisSample_readBits : OrderMapper.InMethod.Method(VorbisSample.decodeAudio::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == INVOKESTATIC }
}
@DependsOn(LocType.loadModelType::class, AbstractArchive::class)
class LocType_modelArchive : UniqueMapper.InMethod.Field(LocType.loadModelType::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<AbstractArchive>() }
}
@DependsOn(EvictingDualNodeHashTable::class, LocType.getUnlitModel::class)
class LocType_cachedUnlitModels : UniqueMapper.InMethod.Field(LocType.getUnlitModel::class) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETSTATIC && it.fieldType == type<EvictingDualNodeHashTable>() }
}
@MethodParameters("b", "packetBit")
@DependsOn(PacketBit::class, npcIndices::class)
class updateNpcs : IdentityMapper.StaticMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments == listOf(BOOLEAN_TYPE, type<PacketBit>()) }
.and { it.instructions.first().opcode == ICONST_0 }
}
@DependsOn(GameShell.render::class)
class renderCount : OrderMapper.InMethod.Field(GameShell.render::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == BIPUSH && it.intOperand == 50 }
.prev { it.opcode == GETSTATIC && it.fieldType == INT_TYPE }
}
} | mit | 752ab65a60cd886485b4f8704134db2d | 51.011631 | 180 | 0.665364 | 4.118716 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeChooseTypeAction.kt | 3 | 2621 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.popup.PopupState
internal class NodeChooseTypeAction : DumbAwareAction(BookmarkBundle.messagePointer("mnemonic.chooser.mnemonic.change.action.text")) {
private val popupState = PopupState.forPopup()
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = false
if (popupState.isShowing) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarkNodes?.singleOrNull()?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
if (type == BookmarkType.DEFAULT) event.presentation.text = BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.action.text")
event.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(event: AnActionEvent) {
if (popupState.isRecentlyHidden) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarkNodes?.singleOrNull()?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
val chooser = BookmarkTypeChooser(type, manager.assignedTypes, bookmark.firstGroupWithDescription?.getDescription(bookmark)) { chosenType, description ->
popupState.hidePopup()
manager.setType(bookmark, chosenType)
if (description != "") {
manager.getGroups(bookmark).firstOrNull()?.setDescription(bookmark, description)
}
}
val title = when (type) {
BookmarkType.DEFAULT -> BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.popup.title")
else -> BookmarkBundle.message("mnemonic.chooser.mnemonic.change.popup.title")
}
JBPopupFactory.getInstance().createComponentPopupBuilder(chooser, chooser.firstButton)
.setFocusable(true).setRequestFocus(true)
.setMovable(false).setResizable(false)
.setTitle(title).createPopup()
.also { popupState.prepareToShow(it) }
.showInBestPositionFor(event.dataContext)
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | 9e42e4e1775f845e0ca4a1d2201c9f9a | 46.654545 | 158 | 0.766501 | 4.800366 | false | false | false | false |
apollographql/apollo-android | tests/http-cache/src/test/kotlin/HttpCacheTest.kt | 1 | 5327 | import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.cache.http.HttpFetchPolicy
import com.apollographql.apollo3.cache.http.httpCache
import com.apollographql.apollo3.cache.http.httpExpireTimeout
import com.apollographql.apollo3.cache.http.httpFetchPolicy
import com.apollographql.apollo3.cache.http.isFromHttpCache
import com.apollographql.apollo3.exception.HttpCacheMissException
import com.apollographql.apollo3.mockserver.MockResponse
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.mockserver.enqueue
import com.apollographql.apollo3.network.okHttpClient
import com.apollographql.apollo3.testing.runTest
import httpcache.GetRandom2Query
import httpcache.GetRandomQuery
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFailsWith
class HttpCacheTest {
lateinit var mockServer: MockServer
lateinit var apolloClient: ApolloClient
private val response = """
{
"data": {
"random": 42
}
}
""".trimIndent()
private val response2 = """
{
"data": {
"random2": 42
}
}
""".trimIndent()
private suspend fun before() {
mockServer = MockServer()
val dir = File("build/httpCache")
dir.deleteRecursively()
apolloClient = ApolloClient.Builder()
.serverUrl(mockServer.url())
.httpCache(dir, Long.MAX_VALUE)
.build()
}
private suspend fun tearDown() {
apolloClient.dispose()
mockServer.stop()
}
@Test
fun CacheFirst() = runTest(before = { before() }, after = { tearDown() }) {
mockServer.enqueue(response)
runBlocking {
var response = apolloClient.query(GetRandomQuery()).execute()
assertEquals(42, response.data?.random)
assertEquals(false, response.isFromHttpCache)
response = apolloClient.query(GetRandomQuery()).execute()
assertEquals(42, response.data?.random)
assertEquals(true, response.isFromHttpCache)
}
}
@Test
fun NetworkOnly() = runTest(before = { before() }, after = { tearDown() }) {
mockServer.enqueue(response)
mockServer.enqueue(MockResponse(statusCode = 500))
runBlocking {
val response = apolloClient.query(GetRandomQuery()).execute()
assertEquals(42, response.data?.random)
assertEquals(false, response.isFromHttpCache)
assertFails {
apolloClient.query(GetRandomQuery())
.httpFetchPolicy(HttpFetchPolicy.NetworkOnly)
.execute()
}
}
}
@Test
fun NetworkFirst() = runTest(before = { before() }, after = { tearDown() }) {
mockServer.enqueue(response)
mockServer.enqueue(MockResponse(statusCode = 500))
runBlocking {
var response = apolloClient.query(GetRandomQuery())
.execute()
assertEquals(42, response.data?.random)
assertEquals(false, response.isFromHttpCache)
response = apolloClient.query(GetRandomQuery())
.httpFetchPolicy(HttpFetchPolicy.NetworkFirst)
.execute()
assertEquals(42, response.data?.random)
assertEquals(true, response.isFromHttpCache)
}
}
@Test
fun Timeout() = runTest(before = { before() }, after = { tearDown() }) {
mockServer.enqueue(response)
runBlocking {
var response = apolloClient.query(GetRandomQuery()).execute()
assertEquals(42, response.data?.random)
assertEquals(false, response.isFromHttpCache)
response = apolloClient.query(GetRandomQuery()).httpExpireTimeout(500).execute()
assertEquals(42, response.data?.random)
assertEquals(true, response.isFromHttpCache)
delay(1000)
assertFailsWith(HttpCacheMissException::class) {
apolloClient.query(GetRandomQuery())
.httpExpireTimeout(500)
.httpFetchPolicy(HttpFetchPolicy.CacheOnly)
.execute()
}
}
}
@Test
fun DifferentQueriesDoNotOverlap() = runTest(before = { before() }, after = { tearDown() }) {
mockServer.enqueue(response)
mockServer.enqueue(response2)
runBlocking {
val response = apolloClient.query(GetRandomQuery()).execute()
assertEquals(42, response.data?.random)
assertEquals(false, response.isFromHttpCache)
val response2 = apolloClient.query(GetRandom2Query()).execute()
assertEquals(42, response2.data?.random2)
assertEquals(false, response2.isFromHttpCache)
}
}
@Test
fun HttpCacheDoesNotOverrideOkHttpClient() = runTest {
val interceptor = Interceptor {
it.proceed(it.request().newBuilder().header("Test-Header", "Test-Value").build())
}
val okHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
val mockServer = MockServer()
val apolloClient = ApolloClient.Builder()
.serverUrl(mockServer.url())
.okHttpClient(okHttpClient)
.httpCache(File("build/httpCache"), Long.MAX_VALUE)
.build()
kotlin.runCatching {
apolloClient.query(GetRandomQuery())
.httpFetchPolicy(HttpFetchPolicy.NetworkOnly)
.execute()
}
assertEquals("Test-Value", mockServer.takeRequest().headers["Test-Header"])
}
}
| mit | 7b79716d186f68b27527a6adba5f26c9 | 29.44 | 95 | 0.697954 | 4.495359 | false | true | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/CustomizeTabFactory.kt | 1 | 12256 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.welcomeScreen
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.actions.ShowSettingsUtilImpl
import com.intellij.ide.ui.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.PlatformEditorBundle
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.impl.KeymapManagerImpl
import com.intellij.openapi.keymap.impl.keymapComparator
import com.intellij.openapi.keymap.impl.ui.KeymapSchemeManager
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.wm.WelcomeTabFactory
import com.intellij.openapi.wm.impl.welcomeScreen.TabbedWelcomeScreen.DefaultWelcomeScreenTab
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.AnActionLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Font
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.plaf.FontUIResource
import javax.swing.plaf.LabelUI
private val settings get() = UISettings.getInstance()
private val defaultProject get() = ProjectManager.getInstance().defaultProject
private val laf get() = LafManager.getInstance()
private val keymapManager get() = KeymapManager.getInstance() as KeymapManagerImpl
private val editorColorsManager get() = EditorColorsManager.getInstance() as EditorColorsManagerImpl
class CustomizeTabFactory : WelcomeTabFactory {
override fun createWelcomeTab(parentDisposable: Disposable) = CustomizeTab(parentDisposable)
}
private fun getIdeFont() = if (settings.overrideLafFonts) settings.fontSize2D else JBFont.label().size2D
class CustomizeTab(parentDisposable: Disposable) : DefaultWelcomeScreenTab(IdeBundle.message("welcome.screen.customize.title"),
WelcomeScreenEventCollector.TabType.TabNavCustomize) {
private val supportedColorBlindness = getColorBlindness()
private val propertyGraph = PropertyGraph()
private val lafProperty = propertyGraph.graphProperty { laf.lookAndFeelReference }
private val syncThemeProperty = propertyGraph.graphProperty { laf.autodetect }
private val ideFontProperty = propertyGraph.graphProperty { getIdeFont() }
private val keymapProperty = propertyGraph.graphProperty { keymapManager.activeKeymap }
private val colorBlindnessProperty = propertyGraph.graphProperty { settings.colorBlindness ?: supportedColorBlindness.firstOrNull() }
private val adjustColorsProperty = propertyGraph.graphProperty { settings.colorBlindness != null }
private var keymapComboBox: ComboBox<Keymap>? = null
private var colorThemeComboBox: ComboBox<LafManager.LafReference>? = null
init {
lafProperty.afterChange(parentDisposable) {
val newLaf = laf.findLaf(it)
if (laf.currentLookAndFeel == newLaf) return@afterChange
ApplicationManager.getApplication().invokeLater {
QuickChangeLookAndFeel.switchLafAndUpdateUI(laf, newLaf, true)
WelcomeScreenEventCollector.logLafChanged(newLaf, laf.autodetect)
}
}
syncThemeProperty.afterChange {
if (laf.autodetect == it) return@afterChange
laf.autodetect = it
WelcomeScreenEventCollector.logLafChanged(laf.currentLookAndFeel, laf.autodetect)
}
ideFontProperty.afterChange(parentDisposable) {
if (settings.fontSize2D == it) return@afterChange
settings.overrideLafFonts = true
WelcomeScreenEventCollector.logIdeFontChanged(settings.fontSize2D, it)
settings.fontSize2D = it
updateFontSettingsLater()
}
keymapProperty.afterChange(parentDisposable) {
if (keymapManager.activeKeymap == it) return@afterChange
WelcomeScreenEventCollector.logKeymapChanged(it)
keymapManager.activeKeymap = it
}
adjustColorsProperty.afterChange(parentDisposable) {
if (adjustColorsProperty.get() == (settings.colorBlindness != null)) return@afterChange
WelcomeScreenEventCollector.logColorBlindnessChanged(adjustColorsProperty.get())
updateColorBlindness()
}
colorBlindnessProperty.afterChange(parentDisposable) {
updateColorBlindness()
}
val busConnection = ApplicationManager.getApplication().messageBus.connect(parentDisposable)
busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { updateProperty(ideFontProperty) { getIdeFont() } })
busConnection.subscribe(EditorColorsManager.TOPIC, EditorColorsListener { updateAccessibilityProperties() })
busConnection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
updateProperty(lafProperty) { laf.lookAndFeelReference }
updateLafs()
})
busConnection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
updateProperty(keymapProperty) { keymapManager.activeKeymap }
updateKeymaps()
}
override fun keymapAdded(keymap: Keymap) {
updateKeymaps()
}
override fun keymapRemoved(keymap: Keymap) {
updateKeymaps()
}
})
}
private fun updateColorBlindness() {
settings.colorBlindness = if (adjustColorsProperty.get()) colorBlindnessProperty.get() else null
ApplicationManager.getApplication().invokeLater(Runnable {
DefaultColorSchemesManager.getInstance().reload()
editorColorsManager.schemeChangedOrSwitched(null)
})
}
private fun updateFontSettingsLater() {
ApplicationManager.getApplication().invokeLater {
laf.updateUI()
settings.fireUISettingsChanged()
}
}
private fun <T> updateProperty(property: GraphProperty<T>, settingGetter: () -> T) {
val value = settingGetter()
if (property.get() != value) {
property.set(value)
}
}
private fun updateAccessibilityProperties() {
val adjustColorSetting = settings.colorBlindness != null
updateProperty(adjustColorsProperty) { adjustColorSetting }
if (adjustColorSetting) {
updateProperty(colorBlindnessProperty) { settings.colorBlindness }
}
}
override fun buildComponent(): JComponent {
return panel {
header(IdeBundle.message("welcome.screen.color.theme.header"), true)
row {
val themeBuilder = comboBox(laf.lafComboBoxModel, laf.lookAndFeelCellRenderer)
.bindItem(lafProperty)
.accessibleName(IdeBundle.message("welcome.screen.color.theme.header"))
colorThemeComboBox = themeBuilder.component
val syncCheckBox = checkBox(IdeBundle.message("preferred.theme.autodetect.selector"))
.bindSelected(syncThemeProperty)
.applyToComponent {
isOpaque = false
isVisible = laf.autodetectSupported
}
themeBuilder.enabledIf(syncCheckBox.selected.not())
cell(laf.settingsToolbar).visibleIf(syncCheckBox.selected)
}
header(IdeBundle.message("title.accessibility"))
row(IdeBundle.message("welcome.screen.ide.font.size.label")) {
fontComboBox(ideFontProperty)
}.bottomGap(BottomGap.SMALL)
createColorBlindnessSettingBlock()
header(KeyMapBundle.message("keymap.display.name"))
row {
keymapComboBox = comboBox(DefaultComboBoxModel(getKeymaps().toTypedArray()))
.bindItem(keymapProperty)
.accessibleName(KeyMapBundle.message("keymap.display.name"))
.component
link(KeyMapBundle.message("welcome.screen.keymap.configure.link")) {
ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject, KeyMapBundle.message("keymap.display.name"))
}
}
row {
cell(AnActionLink("WelcomeScreen.Configure.Import", ActionPlaces.WELCOME_SCREEN))
}.topGap(TopGap.MEDIUM)
row {
link(IdeBundle.message("welcome.screen.all.settings.link")) {
ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject,
*ShowSettingsUtilImpl.getConfigurableGroups(defaultProject, true))
}
}
}.withBorder(JBUI.Borders.empty(23, 30, 20, 20))
.withBackground(WelcomeScreenUIManager.getMainAssociatedComponentBackground())
}
private fun updateKeymaps() {
(keymapComboBox?.model as DefaultComboBoxModel?)?.apply {
removeAllElements()
addAll(getKeymaps())
selectedItem = keymapProperty.get()
}
}
private fun updateLafs() {
colorThemeComboBox?.apply {
model = laf.lafComboBoxModel
selectedItem = lafProperty.get()
}
}
private fun Panel.createColorBlindnessSettingBlock() {
if (supportedColorBlindness.isNotEmpty()) {
row {
if (supportedColorBlindness.size == 1) {
checkBox(UIBundle.message("color.blindness.checkbox.text"))
.bindSelected(adjustColorsProperty)
.comment(UIBundle.message("color.blindness.checkbox.comment"))
}
else {
val checkBox = checkBox(UIBundle.message("welcome.screen.color.blindness.combobox.text"))
.bindSelected(adjustColorsProperty)
.applyToComponent { isOpaque = false }.component
comboBox(DefaultComboBoxModel(supportedColorBlindness.toTypedArray()), SimpleListCellRenderer.create("") {
PlatformEditorBundle.message(it?.key ?: "")
})
.bindItem(colorBlindnessProperty)
.comment(UIBundle.message("color.blindness.combobox.comment"))
.enabledIf(checkBox.selected)
}
link(UIBundle.message("color.blindness.link.to.help"))
{ HelpManager.getInstance().invokeHelp("Colorblind_Settings") }
}
}
}
private fun Panel.header(@Nls title: String, firstHeader: Boolean = false) {
val row = row {
cell(HeaderLabel(title))
}.bottomGap(BottomGap.SMALL)
if (!firstHeader) {
row.topGap(TopGap.MEDIUM)
}
}
private class HeaderLabel(@Nls title: String) : JBLabel(title) {
override fun setUI(ui: LabelUI?) {
super.setUI(ui)
if (font != null) {
font = FontUIResource(font.deriveFont(font.size2D + JBUIScale.scale(3)).deriveFont(Font.BOLD))
}
}
}
private fun Row.fontComboBox(fontProperty: GraphProperty<Float>): Cell<ComboBox<Float>> {
val fontSizes = UIUtil.getStandardFontSizes().map { it.toFloat() }.toSortedSet()
fontSizes.add(fontProperty.get())
val model = DefaultComboBoxModel(fontSizes.toTypedArray())
return comboBox(model)
.bindItem(fontProperty)
.applyToComponent {
isEditable = true
}
}
private fun getColorBlindness(): List<ColorBlindness> {
return ColorBlindness.values().asList().filter { ColorBlindnessSupport.get(it) != null }
}
private fun getKeymaps(): List<Keymap> {
return keymapManager.getKeymaps(KeymapSchemeManager.FILTER).sortedWith(keymapComparator)
}
} | apache-2.0 | 2ff0be4be518ee12259c68ca4cfd3fa8 | 40.690476 | 135 | 0.739067 | 4.865423 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/plugin/test/org/jetbrains/kotlin/idea/artifacts/KotlinNativeVersion.kt | 1 | 2108 | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.artifacts
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.exists
import org.jetbrains.kotlin.konan.file.unzipTo
import java.io.File
import java.io.FileInputStream
import java.nio.file.Paths
import java.util.*
object KotlinNativeVersion {
/** This field is automatically setup from project-module-updater.
* See [org.jetbrains.tools.model.updater.updateKGPVersionForKotlinNativeTests]
*/
private const val kotlinGradlePluginVersion: String = "1.8.20-dev-2036"
/** Return bootstrap version or version from properties file of specified Kotlin Gradle Plugin.
* Make sure localMaven has kotlin-gradle-plugin with required version for cooperative development environment.
*/
val resolvedKotlinNativeVersion: String by lazy { getKotlinNativeVersionFromKotlinGradlePluginPropertiesFile() }
private fun getKotlinNativeVersionFromKotlinGradlePluginPropertiesFile(): String {
val outputPath = Paths.get(PathManager.getCommunityHomePath()).resolve("out")
.resolve("kotlin-gradle-plugin")
.resolve(kotlinGradlePluginVersion)
if (!outputPath.exists()) {
File(outputPath.toString()).mkdirs()
}
val propertiesPath = outputPath.resolve("project.properties")
if (!propertiesPath.exists()) {
val localRepository = File(FileUtil.getTempDirectory()).toPath()
val kotlinGradlePluginPath = KotlinGradlePluginDownloader.downloadKotlinGradlePlugin(kotlinGradlePluginVersion, localRepository)
kotlinGradlePluginPath.unzipTo(outputPath)
}
val propertiesFromKGP = Properties()
FileInputStream(propertiesPath.toFile()).use { propertiesFromKGP.load(it) }
return propertiesFromKGP.getProperty("kotlin.native.version")
}
} | apache-2.0 | 7f167a329f84a1e4c3640f17a4907b66 | 42.9375 | 140 | 0.744307 | 4.758465 | false | false | false | false |
JetBrains/intellij-community | plugins/full-line/local/src/org/jetbrains/completion/full/line/local/generation/search/BaseSearch.kt | 1 | 1075 | package org.jetbrains.completion.full.line.local.generation.search
import org.jetbrains.completion.full.line.local.generation.slice
import org.jetbrains.completion.full.line.local.generation.sliceArray
abstract class BaseSearch(
val vocabSize: Int,
val searchSize: Int,
) : Search {
override var hypothesesTokens: List<MutableList<Int>> = listOf(mutableListOf())
protected set
override var hypothesesScores: MutableList<Double> = mutableListOf(0.0)
protected set
lateinit var sortMask: IntArray
protected set
protected fun updateState(samples: IntArray, sampleScores: DoubleArray, sortMask: IntArray) {
applySliceToState(sortMask)
hypothesesScores = sampleScores.toMutableList()
for (i in hypothesesTokens.indices) {
hypothesesTokens[i].add(samples[i])
}
}
protected fun applySliceToState(tensorSlice: IntArray) {
hypothesesScores = hypothesesScores.slice(tensorSlice).toMutableList()
hypothesesTokens = tensorSlice.map { ArrayList(hypothesesTokens[it]) }
sortMask = sortMask.sliceArray(tensorSlice)
}
}
| apache-2.0 | 77ab98574b1dd236affd6f9fc24fcbdd | 31.575758 | 95 | 0.766512 | 4.118774 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirDeclarationFromUnresolvedNameContributor.kt | 1 | 7070 | // 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.completion.contributors
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.idea.completion.ItemPriority
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirRawPositionCompletionContext
import org.jetbrains.kotlin.idea.completion.priority
import org.jetbrains.kotlin.idea.completion.referenceScope
import org.jetbrains.kotlin.idea.completion.suppressAutoInsertion
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
/**
* Complete names of a completion by name of unresolved references in the code. For example
* ```
* val unr<caret>
* println(unresolvedVar)
* ```
* This contributor would contribute `unresolvedVar` at caret position above.
*/
internal class FirDeclarationFromUnresolvedNameContributor(
basicContext: FirBasicCompletionContext,
priority: Int,
) : FirCompletionContributorBase<FirRawPositionCompletionContext>(basicContext, priority) {
override fun KtAnalysisSession.complete(positionContext: FirRawPositionCompletionContext) {
val declaration = positionContext.position.getCurrentDeclarationAtCaret() ?: return
val referenceScope = referenceScope(declaration) ?: return
referenceScope.forEachDescendantOfType<KtNameReferenceExpression> { refExpr ->
ProgressManager.checkCanceled()
processReference(referenceScope, declaration, refExpr)
}
}
private fun KtAnalysisSession.processReference(
referenceScope: KtElement,
currentDeclarationInFakeFile: KtNamedDeclaration,
unresolvedRef: KtNameReferenceExpression
) {
// In a block, references must be after the declaration. Therefore, we only offer completion for unresolved names that appear after
// the current cursor position.
if (referenceScope is KtBlockExpression && unresolvedRef.startOffset < parameters.offset) {
return
}
val name = unresolvedRef.getReferencedName()
if (!prefixMatcher.prefixMatches(name)) return
if (!shouldOfferCompletion(unresolvedRef, currentDeclarationInFakeFile)) return
if (unresolvedRef.reference?.resolve() == null) {
val lookupElement = LookupElementBuilder.create(name).suppressAutoInsertion()
.also { it.priority = ItemPriority.FROM_UNRESOLVED_NAME_SUGGESTION }
sink.addElement(lookupElement)
}
}
private fun KtAnalysisSession.shouldOfferCompletion(
unresolvedRef: KtNameReferenceExpression,
currentDeclarationInFakeFile: KtNamedDeclaration
): Boolean {
val refExprParent = unresolvedRef.parent
val receiver = if (refExprParent is KtCallExpression) {
refExprParent.getReceiverForSelector()
} else {
unresolvedRef.getReceiverForSelector()
}
return when (val symbol = currentDeclarationInFakeFile.getSymbol()) {
is KtCallableSymbol -> when {
refExprParent is KtUserType -> false
// If current declaration is a function, we only offer names of unresolved function calls. For property declarations, we
// always offer an unresolved usage because a property may be called if the object has an `invoke` method.
refExprParent !is KtCallableReferenceExpression && refExprParent !is KtCallExpression && symbol is KtFunctionLikeSymbol -> false
receiver != null -> {
val actualReceiverType = receiver.getKtType() ?: return false
val expectedReceiverType = getReceiverType(symbol) ?: return false
// FIXME: this check does not work with generic types (i.e. List<String> and List<T>)
actualReceiverType isSubTypeOf expectedReceiverType
}
else -> {
// If there is no explicit receiver at call-site, we check if any implicit receiver at call-site matches the extension
// receiver type for the current declared symbol
val extensionReceiverType = symbol.receiverType ?: return true
getImplicitReceiverTypesAtPosition(unresolvedRef).any { it isSubTypeOf extensionReceiverType }
}
}
is KtClassOrObjectSymbol -> when {
receiver != null -> false
refExprParent is KtUserType -> true
refExprParent is KtCallExpression -> symbol.classKind == KtClassKind.CLASS
else -> symbol.classKind == KtClassKind.OBJECT
}
else -> false
}
}
private fun PsiElement.getReceiverForSelector(): KtExpression? {
val qualifiedExpression = (parent as? KtDotQualifiedExpression)?.takeIf { it.selectorExpression == this } ?: return null
return qualifiedExpression.receiverExpression
}
private fun KtAnalysisSession.getReceiverType(symbol: KtCallableSymbol): KtType? {
return symbol.receiverType ?: (symbol as? KtCallableSymbol)?.getDispatchReceiverType()
}
private fun PsiElement.getCurrentDeclarationAtCaret(): KtNamedDeclaration? {
return when (val parent = parent) {
is KtNamedDeclaration -> parent
is KtNameReferenceExpression -> {
// In a fake completion file, a property or function under construction is appended with placeholder text "X.f$", which is
// parsed as a type reference. For example, if the original file has the following content,
//
// ```
// val myProp<caret>
// ```
//
// the fake file would then contain
//
// ```
// val myPropX.f$
// ```
//
// In this case, the Kotlin PSI parser treats `myPropX` as the receiver type reference for an extension property.
// See org.jetbrains.kotlin.idea.completion.CompletionDummyIdentifierProviderService#specialExtensionReceiverDummyIdentifier
// for more details.
val userType = parent.parent as? KtUserType ?: return null
val typeRef = userType.parent as? KtTypeReference ?: return null
val callable = (typeRef.parent as? KtCallableDeclaration)?.takeIf { it.receiverTypeReference == typeRef } ?: return null
callable
}
else -> null
}
}
} | apache-2.0 | 0f465b1c9035f3cc6ac3ae7c25719d48 | 48.795775 | 144 | 0.673975 | 5.633466 | false | false | false | false |
spacecowboy/Feeder | jsonfeed-parser/src/test/kotlin/com/nononsenseapps/jsonfeed/JsonFeedParserTest.kt | 1 | 3577 | package com.nononsenseapps.jsonfeed
import kotlin.test.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class JsonFeedParserTest {
@Rule
@JvmField
val expected: ExpectedException = ExpectedException.none()
@Test
fun basic() {
val parser = JsonFeedParser()
val feed = parser.parseJson(
"""
{
"version": "https://jsonfeed.org/version/1",
"title": "My Example Feed",
"home_page_url": "https://example.org/",
"feed_url": "https://example.org/feed.json",
"items": [
{
"id": "2",
"content_text": "This is a second item.",
"url": "https://example.org/second-item"
},
{
"id": "1",
"content_html": "<p>Hello, world!</p>",
"url": "https://example.org/initial-post"
}
]
}
"""
)
assertEquals("https://jsonfeed.org/version/1", feed.version)
assertEquals("My Example Feed", feed.title)
assertEquals("https://example.org/", feed.home_page_url)
assertEquals("https://example.org/feed.json", feed.feed_url)
assertEquals(2, feed.items?.size)
assertEquals("2", feed.items!![0].id)
assertEquals("This is a second item.", feed.items!![0].content_text)
assertEquals("https://example.org/second-item", feed.items!![0].url)
assertEquals("1", feed.items!![1].id)
assertEquals("<p>Hello, world!</p>", feed.items!![1].content_html)
assertEquals("https://example.org/initial-post", feed.items!![1].url)
}
@Test
fun dateParsing() {
val parser = JsonFeedParser()
val feed = parser.parseJson(
"""
{
"version": "https://jsonfeed.org/version/1",
"title": "My Example Feed",
"home_page_url": "https://example.org/",
"feed_url": "https://example.org/feed.json",
"items": [
{
"id": "1",
"content_html": "<p>Hello, world!</p>",
"url": "https://example.org/initial-post",
"date_published": "2010-02-07T14:04:00-05:00",
"date_modified": "2012-03-08T15:05:01+09:00"
}
]
}
"""
)
assertEquals("https://jsonfeed.org/version/1", feed.version)
assertEquals("My Example Feed", feed.title)
assertEquals("https://example.org/", feed.home_page_url)
assertEquals("https://example.org/feed.json", feed.feed_url)
assertEquals(1, feed.items?.size)
assertEquals("1", feed.items!![0].id)
assertEquals("<p>Hello, world!</p>", feed.items!![0].content_html)
assertEquals("https://example.org/initial-post", feed.items!![0].url)
assertEquals("2010-02-07T14:04:00-05:00", feed.items!![0].date_published)
assertEquals("2012-03-08T15:05:01+09:00", feed.items!![0].date_modified)
}
@Test
fun cowboyOnline() {
val parser = JsonFeedParser()
val feed = parser.parseUrl("https://cowboyprogrammer.org/feed.json")
assertEquals("https://jsonfeed.org/version/1", feed.version)
assertEquals("Cowboy Programmer", feed.title)
assertEquals("Space Cowboy", feed.author?.name)
assertEquals("https://cowboyprogrammer.org/css/images/logo.png", feed.icon)
}
@Test
fun badUrl() {
expected.expectMessage("Bad URL. Perhaps it is missing an http:// prefix?")
expected.expect(IllegalArgumentException::class.java)
JsonFeedParser().parseUrl("cowboyprogrammer.org/feed.json")
}
}
| gpl-3.0 | ca72431efc0230f5ebd33b060d83f40a | 30.377193 | 83 | 0.585407 | 3.683831 | false | true | false | false |
exercism/xkotlin | exercises/practice/pascals-triangle/.meta/src/reference/kotlin/PascalsTriangle.kt | 1 | 450 | object PascalsTriangle {
fun computeTriangle(rows: Int): List<List<Int>> {
require(rows >= 0) { "Rows can't be negative!" }
if (rows == 0) return emptyList()
return (1..rows).map { buildTriangleRow(it) }
}
private fun buildTriangleRow(row: Int): List<Int> {
var m = 1
return listOf(1) + (1 until row).map { col ->
m = m * (row - col) / col
return@map m
}
}
}
| mit | 9dda9a311aba53d1858999d3842ab450 | 25.470588 | 56 | 0.52 | 3.543307 | false | false | false | false |
allotria/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/events/EventId.kt | 3 | 4967 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog.events
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
abstract class BaseEventId(val eventId: String) {
abstract fun getFields(): List<EventField<*>>
}
class EventId(private val group: EventLogGroup, eventId: String) : BaseEventId(eventId) {
fun log() {
FeatureUsageLogger.log(group, eventId)
}
fun log(project: Project?) {
FeatureUsageLogger.log(group, eventId, FeatureUsageData().addProject(project).build())
}
fun metric(): MetricEvent {
return MetricEvent(eventId, null)
}
override fun getFields(): List<EventField<*>> = emptyList()
}
class EventId1<T>(private val group: EventLogGroup, eventId: String, private val field1: EventField<T>) : BaseEventId(eventId) {
fun log(value1: T) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1).build())
}
fun log(project: Project?, value1: T) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1).addProject(project).build())
}
fun metric(value1: T): MetricEvent {
return MetricEvent(eventId, buildUsageData(value1))
}
private fun buildUsageData(value1: T): FeatureUsageData {
val data = FeatureUsageData()
field1.addData(data, value1)
return data
}
override fun getFields(): List<EventField<*>> = listOf(field1)
}
class EventId2<T1, T2>(private val group: EventLogGroup, eventId: String, private val field1: EventField<T1>, private val field2: EventField<T2>) : BaseEventId(eventId) {
fun log(value1: T1, value2: T2) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1, value2).build())
}
fun log(project: Project?, value1: T1, value2: T2) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1, value2).addProject(project).build())
}
fun metric(value1: T1, value2: T2): MetricEvent {
return MetricEvent(eventId, buildUsageData(value1, value2))
}
private fun buildUsageData(value1: T1, value2: T2): FeatureUsageData {
val data = FeatureUsageData()
field1.addData(data, value1)
field2.addData(data, value2)
return data
}
override fun getFields(): List<EventField<*>> = listOf(field1, field2)
}
class EventId3<T1, T2, T3>(private val group: EventLogGroup, eventId: String, private val field1: EventField<T1>, private val field2: EventField<T2>, private val field3: EventField<T3>) : BaseEventId(eventId) {
fun log(value1: T1, value2: T2, value3: T3) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1, value2, value3).build())
}
fun log(project: Project?, value1: T1, value2: T2, value3: T3) {
FeatureUsageLogger.log(group, eventId, buildUsageData(value1, value2, value3).addProject(project).build())
}
fun metric(value1: T1, value2: T2, value3: T3): MetricEvent {
return MetricEvent(eventId, buildUsageData(value1, value2, value3))
}
private fun buildUsageData(value1: T1, value2: T2, value3: T3): FeatureUsageData {
val data = FeatureUsageData()
field1.addData(data, value1)
field2.addData(data, value2)
field3.addData(data, value3)
return data
}
override fun getFields(): List<EventField<*>> = listOf(field1, field2, field3)
}
class VarargEventId internal constructor(private val group: EventLogGroup, eventId: String, vararg fields: EventField<*>) : BaseEventId(eventId) {
private val fields = fields.toMutableList()
fun log(vararg pairs: EventPair<*>) {
log(listOf(*pairs))
}
fun log(pairs: List<EventPair<*>>) {
FeatureUsageLogger.log(group, eventId, buildUsageData(pairs).build())
}
fun log(project: Project?, vararg pairs: EventPair<*>) {
log(project, listOf(*pairs))
}
fun log(project: Project?, pairs: List<EventPair<*>>) {
FeatureUsageLogger.log(group, eventId, buildUsageData(pairs).addProject(project).build())
}
fun metric(vararg pairs: EventPair<*>): MetricEvent {
return metric(listOf(*pairs))
}
fun metric(pairs: List<EventPair<*>>): MetricEvent {
return MetricEvent(eventId, buildUsageData(pairs))
}
private fun buildUsageData(pairs: List<EventPair<*>>): FeatureUsageData {
val data = FeatureUsageData()
for (pair in pairs) {
if (pair.field !in fields) throw IllegalArgumentException("Field not in fields for this event ID")
@Suppress("UNCHECKED_CAST")
(pair.field as EventField<Any?>).addData(data, pair.data)
}
return data
}
override fun getFields(): List<EventField<*>> = fields.toList()
companion object {
val LOG = Logger.getInstance(VarargEventId::class.java)
}
} | apache-2.0 | f9364d11c0950d81cdacfd69bcf0344c | 33.985915 | 210 | 0.722569 | 3.823711 | false | false | false | false |
allotria/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigCharClassLetterRedundancyInspection.kt | 6 | 2344 | // 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.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.TextRange
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigSanitizeCharClassQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigCharClass
import org.editorconfig.language.psi.EditorConfigCharClassLetter
import org.editorconfig.language.psi.EditorConfigVisitor
class EditorConfigCharClassLetterRedundancyInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitCharClass(charClass: EditorConfigCharClass) {
val letters = charClass.charClassLetterList
val message = EditorConfigBundle["inspection.charclass.duplicate.message"]
// Ranges are collected this way
// in order to avoid overwhelming user
// with a bunch of one-character warnings
var state = State.INITIAL
var firstDuplicateStart = Int.MAX_VALUE
letters.forEach {
val unique = isUnique(it, letters)
if (unique && state == State.COLLECTING_DUPLICATES) {
val range = TextRange.create(firstDuplicateStart, it.startOffsetInParent)
holder.registerProblem(charClass, range, message, EditorConfigSanitizeCharClassQuickFix())
state = State.INITIAL
}
else if (!unique && state == State.INITIAL) {
firstDuplicateStart = it.startOffsetInParent
state = State.COLLECTING_DUPLICATES
}
}
if (state == State.COLLECTING_DUPLICATES) {
val last = letters.last()
val range = TextRange.create(firstDuplicateStart, last.startOffsetInParent + last.textLength)
holder.registerProblem(charClass, range, message, EditorConfigSanitizeCharClassQuickFix())
}
}
}
private fun isUnique(letter: EditorConfigCharClassLetter, letters: List<EditorConfigCharClassLetter>) =
letters.count(letter::textMatches) <= 1
private enum class State {
INITIAL,
COLLECTING_DUPLICATES
}
}
| apache-2.0 | 43e3870eace782641879833741f77e79 | 42.407407 | 140 | 0.750853 | 5.030043 | false | true | false | false |
allotria/intellij-community | plugins/changeReminder/src/com/jetbrains/changeReminder/stats/ChangeReminderStatsCollector.kt | 3 | 2698 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.stats
import com.intellij.internal.statistic.eventLog.EventLogConfiguration.anonymize
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.changeReminder.predict.PredictionData
import java.util.*
internal data class ChangeReminderAnonymousPath(val value: String)
internal enum class ChangeReminderEventType {
CHANGELIST_CHANGED,
CHANGES_COMMITTED,
NODE_EXPANDED;
override fun toString() = name.toLowerCase(Locale.ENGLISH)
}
internal enum class ChangeReminderEventDataKey {
COMMITTED_FILES,
DISPLAYED_PREDICTION,
CUR_MODIFIED_FILES,
PREV_MODIFIED_FILES,
PREDICTION_FOR_FILES,
EMPTY_REASON;
override fun toString() = name.toLowerCase(Locale.ENGLISH)
}
internal fun VirtualFile.anonymize(): ChangeReminderAnonymousPath = ChangeReminderAnonymousPath(anonymize(path))
internal fun FilePath.anonymize(): ChangeReminderAnonymousPath = ChangeReminderAnonymousPath(anonymize(path))
internal fun Collection<VirtualFile>.anonymizeVirtualFileCollection(): Collection<ChangeReminderAnonymousPath> = this.map { it.anonymize() }
internal fun Collection<FilePath>.anonymizeFilePathCollection(): Collection<ChangeReminderAnonymousPath> = this.map { it.anonymize() }
internal fun FeatureUsageData.addPredictionData(predictionData: PredictionData) {
when (predictionData) {
is PredictionData.Prediction -> {
addChangeReminderLogData(
ChangeReminderEventDataKey.DISPLAYED_PREDICTION,
predictionData.predictionToDisplay.anonymizeVirtualFileCollection()
)
addChangeReminderLogData(
ChangeReminderEventDataKey.PREDICTION_FOR_FILES,
predictionData.requestedFiles.anonymizeFilePathCollection()
)
}
is PredictionData.EmptyPrediction -> {
addData(ChangeReminderEventDataKey.EMPTY_REASON.toString(), predictionData.reason.toString())
}
}
}
internal fun FeatureUsageData.addChangeReminderLogData(key: ChangeReminderEventDataKey, value: Collection<ChangeReminderAnonymousPath>) {
addData(key.toString(), value.map { it.value })
}
internal fun logEvent(project: Project, event: ChangeReminderUserEvent) {
val logData = FeatureUsageData()
event.addToLogData(logData)
FUCounterUsageLogger.getInstance().logEvent(project, "vcs.change.reminder", event.eventType.toString(), logData)
} | apache-2.0 | b4e4514e4a778b36fe788cbaf2327d1c | 38.115942 | 140 | 0.802076 | 4.604096 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserIgnoredFilesNode.kt | 2 | 3110 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui
import com.intellij.ide.DataManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.ChangeListOwner
import com.intellij.openapi.vcs.changes.IgnoredViewDialog
import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl
import com.intellij.openapi.vcs.changes.ignore.actions.IgnoreFileActionGroup
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.treeStructure.Tree
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.Nls
import javax.swing.tree.TreePath
class ChangesBrowserIgnoredFilesNode(val project: Project,
files: List<FilePath>,
private val myUpdatingMode: Boolean)
: ChangesBrowserSpecificFilePathsNode<ChangesBrowserNode.Tag>(ChangesBrowserNode.IGNORED_FILES_TAG, files,
{ if (!project.isDisposed) IgnoredViewDialog(project).show() }) {
override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) {
super.render(renderer, selected, expanded, hasFocus)
if (myUpdatingMode) {
appendUpdatingState(renderer)
}
}
override fun canAcceptDrop(dragBean: ChangeListDragBean) = dragBean.unversionedFiles.isNotEmpty()
override fun acceptDrop(dragOwner: ChangeListOwner, dragBean: ChangeListDragBean) {
val tree = dragBean.sourceComponent as? Tree ?: return
val vcs = dragBean.unversionedFiles.getVcs() ?: return
val ignoreFileType = VcsIgnoreManagerImpl.getInstanceImpl(project).findIgnoreFileType(vcs) ?: return
val ignoreGroup = IgnoreFileActionGroup(ignoreFileType)
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
null, ignoreGroup, DataManager.getInstance().getDataContext(dragBean.sourceComponent),
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false)
tree.getPathBounds(TreePath(dragBean.targetNode.path))?.let { dropBounds ->
popup.show(RelativePoint(dragBean.sourceComponent, dropBounds.location))
}
}
@Nls
override fun getTextPresentation(): String = getUserObject().toString()
override fun getSortWeight() = ChangesBrowserNode.IGNORED_SORT_WEIGHT
private fun List<FilePath>.getVcs(): AbstractVcs? = mapNotNull { file -> VcsUtil.getVcsFor(project, file) }.firstOrNull()
} | apache-2.0 | 766776d8e07c2340214ecebce2a2526f | 42.208333 | 123 | 0.758842 | 4.573529 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-debug/src/DebugProbes.kt | 1 | 5737 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("UNUSED", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package kotlinx.coroutines.debug
import kotlinx.coroutines.*
import kotlinx.coroutines.debug.internal.*
import java.io.*
import java.lang.management.*
import kotlin.coroutines.*
/**
* Debug probes support.
*
* Debug probes is a dynamic attach mechanism which installs multiple hooks into coroutines machinery.
* It slows down all coroutine-related code, but in return provides a lot of diagnostic information, including
* asynchronous stack-traces and coroutine dumps (similar to [ThreadMXBean.dumpAllThreads] and `jstack` via [DebugProbes.dumpCoroutines].
* All introspecting methods throw [IllegalStateException] if debug probes were not installed.
*
* Installed hooks:
*
* * `probeCoroutineResumed` is invoked on every [Continuation.resume].
* * `probeCoroutineSuspended` is invoked on every continuation suspension.
* * `probeCoroutineCreated` is invoked on every coroutine creation using stdlib intrinsics.
*
* Overhead:
* * Every created coroutine is stored in a concurrent hash map and hash map is looked up and
* updated on each suspension and resumption.
* * If [DebugProbes.enableCreationStackTraces] is enabled, stack trace of the current thread is captured on
* each created coroutine that is a rough equivalent of throwing an exception per each created coroutine.
*/
@ExperimentalCoroutinesApi
public object DebugProbes {
/**
* Whether coroutine creation stack traces should be sanitized.
* Sanitization removes all frames from `kotlinx.coroutines` package except
* the first one and the last one to simplify diagnostic.
*/
public var sanitizeStackTraces: Boolean
get() = DebugProbesImpl.sanitizeStackTraces
set(value) {
DebugProbesImpl.sanitizeStackTraces = value
}
/**
* Whether coroutine creation stack traces should be captured.
* When enabled, for each created coroutine a stack trace of the current
* thread is captured and attached to the coroutine.
* This option can be useful during local debug sessions, but is recommended
* to be disabled in production environments to avoid stack trace dumping overhead.
*/
public var enableCreationStackTraces: Boolean
get() = DebugProbesImpl.enableCreationStackTraces
set(value) {
DebugProbesImpl.enableCreationStackTraces = value
}
/**
* Determines whether debug probes were [installed][DebugProbes.install].
*/
public val isInstalled: Boolean get() = DebugProbesImpl.isInstalled
/**
* Installs a [DebugProbes] instead of no-op stdlib probes by redefining
* debug probes class using the same class loader as one loaded [DebugProbes] class.
*/
public fun install() {
DebugProbesImpl.install()
}
/**
* Uninstall debug probes.
*/
public fun uninstall() {
DebugProbesImpl.uninstall()
}
/**
* Invokes given block of code with installed debug probes and uninstall probes in the end.
*/
public inline fun withDebugProbes(block: () -> Unit) {
install()
try {
block()
} finally {
uninstall()
}
}
/**
* Returns string representation of the coroutines [job] hierarchy with additional debug information.
* Hierarchy is printed from the [job] as a root transitively to all children.
*/
public fun jobToString(job: Job): String = DebugProbesImpl.hierarchyToString(job)
/**
* Returns string representation of all coroutines launched within the given [scope].
* Throws [IllegalStateException] if the scope has no a job in it.
*/
public fun scopeToString(scope: CoroutineScope): String =
jobToString(scope.coroutineContext[Job] ?: error("Job is not present in the scope"))
/**
* Prints [job] hierarchy representation from [jobToString] to the given [out].
*/
public fun printJob(job: Job, out: PrintStream = System.out): Unit =
out.println(DebugProbesImpl.hierarchyToString(job))
/**
* Prints all coroutines launched within the given [scope].
* Throws [IllegalStateException] if the scope has no a job in it.
*/
public fun printScope(scope: CoroutineScope, out: PrintStream = System.out): Unit =
printJob(scope.coroutineContext[Job] ?: error("Job is not present in the scope"), out)
/**
* Returns all existing coroutines info.
* The resulting collection represents a consistent snapshot of all existing coroutines at the moment of invocation.
*/
public fun dumpCoroutinesInfo(): List<CoroutineInfo> = DebugProbesImpl.dumpCoroutinesInfo().map { CoroutineInfo(it) }
/**
* Dumps all active coroutines into the given output stream, providing a consistent snapshot of all existing coroutines at the moment of invocation.
* The output of this method is similar to `jstack` or a full thread dump. It can be used as the replacement to
* "Dump threads" action.
*
* Example of the output:
* ```
* Coroutines dump 2018/11/12 19:45:14
*
* Coroutine "coroutine#42":StandaloneCoroutine{Active}@58fdd99, state: SUSPENDED
* at MyClass$awaitData.invokeSuspend(MyClass.kt:37)
* (Coroutine creation stacktrace)
* at MyClass.createIoRequest(MyClass.kt:142)
* at MyClass.fetchData(MyClass.kt:154)
* at MyClass.showData(MyClass.kt:31)
* ...
* ```
*/
public fun dumpCoroutines(out: PrintStream = System.out): Unit = DebugProbesImpl.dumpCoroutines(out)
}
| apache-2.0 | 6378452fdd468e3d94fe5ab82767fb6a | 38.565517 | 152 | 0.697054 | 4.717928 | false | false | false | false |
zdary/intellij-community | platform/platform-api/src/com/intellij/ui/tabs/impl/themes/TabTheme.kt | 2 | 5272 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.impl.themes
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.util.ui.JBUI
import java.awt.Color
interface TabTheme {
val background: Color?
val borderColor: Color
val underlineColor: Color
val inactiveUnderlineColor: Color
val hoverBackground: Color
val underlinedTabBackground: Color?
val underlinedTabForeground: Color
val underlineHeight: Int
val hoverInactiveBackground: Color?
val underlinedTabInactiveBackground: Color?
val underlinedTabInactiveForeground: Color?
val inactiveColoredTabBackground: Color?
}
open class DefaultTabTheme : TabTheme {
override val background: Color? get() = JBUI.CurrentTheme.DefaultTabs.background()
override val borderColor: Color get() = JBUI.CurrentTheme.DefaultTabs.borderColor()
override val underlineColor: Color get() = JBUI.CurrentTheme.DefaultTabs.underlineColor()
override val inactiveUnderlineColor: Color get() = JBUI.CurrentTheme.DefaultTabs.inactiveUnderlineColor()
override val hoverBackground: Color get() = JBUI.CurrentTheme.DefaultTabs.hoverBackground()
override val underlinedTabBackground: Color? get() = JBUI.CurrentTheme.DefaultTabs.underlinedTabBackground()
override val underlinedTabForeground: Color get() = JBUI.CurrentTheme.DefaultTabs.underlinedTabForeground()
override val underlineHeight: Int get()= JBUI.CurrentTheme.DefaultTabs.underlineHeight()
override val hoverInactiveBackground: Color?
get() = hoverBackground
override val underlinedTabInactiveBackground: Color?
get() = underlinedTabBackground
override val underlinedTabInactiveForeground: Color
get() = underlinedTabForeground
override val inactiveColoredTabBackground: Color
get() = JBUI.CurrentTheme.DefaultTabs.inactiveColoredTabBackground()
}
class EditorTabTheme : TabTheme {
val globalScheme: EditorColorsScheme
get() = EditorColorsManager.getInstance().globalScheme
override val background: Color
get() = JBUI.CurrentTheme.EditorTabs.background()
override val borderColor: Color
get() = JBUI.CurrentTheme.EditorTabs.borderColor()
override val underlineColor: Color
get() = globalScheme.getColor(EditorColors.TAB_UNDERLINE) ?: JBUI.CurrentTheme.EditorTabs.underlineColor()
override val inactiveUnderlineColor: Color
get() = globalScheme.getColor(EditorColors.TAB_UNDERLINE_INACTIVE) ?: JBUI.CurrentTheme.EditorTabs.inactiveUnderlineColor()
override val hoverBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.hoverBackground()
override val underlinedTabBackground: Color?
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED).backgroundColor?: JBUI.CurrentTheme.EditorTabs.underlinedTabBackground()
override val underlinedTabForeground: Color
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED).foregroundColor?: JBUI.CurrentTheme.EditorTabs.underlinedTabForeground()
override val underlineHeight: Int
get() = JBUI.CurrentTheme.EditorTabs.underlineHeight()
override val hoverInactiveBackground: Color
get() = hoverBackground
override val underlinedTabInactiveBackground: Color?
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED_INACTIVE).backgroundColor?: underlinedTabBackground
override val underlinedTabInactiveForeground: Color
get() = globalScheme.getAttributes(EditorColors.TAB_SELECTED_INACTIVE).foregroundColor?: underlinedTabForeground
override val inactiveColoredTabBackground: Color
get() = JBUI.CurrentTheme.EditorTabs.inactiveColoredFileBackground()
}
internal class ToolWindowTabTheme : DefaultTabTheme() {
override val background: Color?
get() = null
override val borderColor: Color
get() = JBUI.CurrentTheme.ToolWindow.borderColor()
override val underlineColor: Color
get() = JBUI.CurrentTheme.ToolWindow.underlineColor()
override val inactiveUnderlineColor: Color
get() = JBUI.CurrentTheme.ToolWindow.inactiveUnderlineColor()
override val hoverBackground: Color
get() = JBUI.CurrentTheme.ToolWindow.hoverBackground()
override val underlinedTabBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabBackground()
override val underlinedTabForeground: Color
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabForeground()
override val underlineHeight: Int
get() = JBUI.CurrentTheme.ToolWindow.underlineHeight()
override val hoverInactiveBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.hoverInactiveBackground()
override val underlinedTabInactiveBackground: Color?
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabInactiveBackground()
override val underlinedTabInactiveForeground: Color
get() = JBUI.CurrentTheme.ToolWindow.underlinedTabInactiveForeground()
}
internal class DebuggerTabTheme : DefaultTabTheme() {
override val underlineHeight: Int
get() = JBUI.CurrentTheme.DebuggerTabs.underlineHeight()
override val underlinedTabBackground: Color?
get() = JBUI.CurrentTheme.DebuggerTabs.underlinedTabBackground()
} | apache-2.0 | d14253ff9dfbd3aa59dc083bf75e3137 | 44.852174 | 140 | 0.801024 | 5.60255 | false | false | false | false |
leafclick/intellij-community | platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt | 1 | 8468 | // 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("ProjectUtil")
package com.intellij.openapi.project
import com.intellij.ide.DataManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.openapi.wm.WindowManager
import com.intellij.util.PathUtilRt
import com.intellij.util.io.exists
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.text.trimMiddle
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.function.Consumer
import javax.swing.JComponent
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
@JvmOverloads
fun calcRelativeToProjectPath(file: VirtualFile,
project: Project?,
includeFilePath: Boolean = true,
includeUniqueFilePath: Boolean = false,
keepModuleAlwaysOnTheLeft: Boolean = false): String {
if (file is VirtualFilePathWrapper && file.enforcePresentableName()) {
return if (includeFilePath) file.presentablePath else file.name
}
val url = when {
includeFilePath -> file.presentableUrl
includeUniqueFilePath && project != null -> UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file)
else -> file.name
}
return if (project == null) url
else displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft)
}
fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file)
/**
* guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned
*/
@JvmOverloads
fun guessProjectForContentFile(file: VirtualFile,
fileType: FileType = FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence)): Project? {
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) {
return null
}
val list = ProjectManager.getInstance().openProjects.filter {
!it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file)
}
return list.firstOrNull { WindowManager.getInstance().getFrame(it)?.isActive ?: false } ?: list.firstOrNull()
}
fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean = ProjectCoreUtil.isProjectOrWorkspaceFile(file)
fun guessCurrentProject(component: JComponent?): Project {
var project: Project? = null
if (component != null) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component))
}
@Suppress("DEPRECATION")
return project
?: ProjectManager.getInstance().openProjects.firstOrNull()
?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext)
?: ProjectManager.getInstance().defaultProject
}
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
return try {
Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists()
}
catch (e: InvalidPathException) {
false
}
}
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*/
fun Project.guessProjectDir() : VirtualFile? {
if (isDefault) {
return null
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.firstOrNull { it.name == this.name }
module?.guessModuleDir()?.let { return it }
return LocalFileSystem.getInstance().findFileByPath(basePath!!)
}
/**
* Tries to guess the main module directory
*
* Please use this method only in case if no any additional information about module location
* eg. some contained files or etc.
*/
fun Module.guessModuleDir(): VirtualFile? {
val contentRoots = rootManager.contentRoots.filter { it.isDirectory }
return contentRoots.find { it.name == name } ?: contentRoots.firstOrNull()
}
@JvmOverloads
fun Project.getProjectCacheFileName(isForceNameUse: Boolean = false, hashSeparator: String = ".", extensionWithDot: String = ""): String {
val presentableUrl = presentableUrl
var name = when {
isForceNameUse || presentableUrl == null -> name
else -> {
// lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests
PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
}
name = sanitizeFileName(name, isTruncate = false)
// do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended)
val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode())
// trim to avoid "File name too long"
name = name.trimMiddle(name.length.coerceAtMost(255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false)
return "$name$hashSeparator${locationHash}$extensionWithDot"
}
@JvmOverloads
fun Project.getProjectCachePath(cacheDirName: String, isForceNameUse: Boolean = false, extensionWithDot: String = ""): Path {
return appSystemDir.resolve(cacheDirName).resolve(getProjectCacheFileName(isForceNameUse, extensionWithDot = extensionWithDot))
}
fun Project.getExternalConfigurationDir(): Path {
return getProjectCachePath("external_build_system")
}
/**
* Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed
*/
@JvmOverloads
fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path {
return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator))
}
/**
* Add one-time projectOpened listener.
*/
fun runWhenProjectOpened(project : Project, handler: Runnable) {
runWhenProjectOpened(project) {
handler.run()
}
}
/**
* Add one-time first projectOpened listener.
*/
@JvmOverloads
fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) {
runWhenProjectOpened(project) {
handler.accept(it)
}
}
/**
* Add one-time projectOpened listener.
*/
inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) {
val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(eventProject: Project) {
if (project == null || project === eventProject) {
connection.disconnect()
handler(eventProject)
}
}
})
}
inline fun processOpenedProjects(processor: (Project) -> Unit) {
for (project in (ProjectManager.getInstanceIfCreated()?.openProjects ?: return)) {
if (project.isDisposed || !project.isInitialized) {
continue
}
processor(project)
}
} | apache-2.0 | 2f159a804d68182a3dc8d5e6698fd28f | 37.671233 | 161 | 0.753543 | 4.602174 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/CollectionTest/sortedNullableBy.kt | 2 | 876 | import kotlin.test.*
import kotlin.comparisons.*
fun <T> assertSorted(list: List<T>, cmp: Comparator<in T>, message: String = "") {
if (list.isEmpty() || list.size == 1) {
return
}
val it = list.iterator()
var prev = it.next()
while(it.hasNext()) {
val cur = it.next()
assert(cmp.compare(prev, cur) <= 0)
prev = cur
}
}
fun box() {
fun String.nullIfEmpty() = if (isEmpty()) null else this
listOf(null, "", "a").let {
assertSorted(it.sortedWith(nullsFirst(compareBy { it })), nullsFirst(compareBy { it }))
assertSorted(it.sortedWith(nullsLast(compareByDescending { it })), compareByDescending { it })
assertSorted(
it.sortedWith(nullsFirst(compareByDescending { it.nullIfEmpty() })),
nullsFirst(compareByDescending { it.nullIfEmpty() })
)
}
}
| apache-2.0 | da38c7a451fb6bf59f6fc4cde7645e8c | 31.444444 | 102 | 0.591324 | 3.859031 | false | false | false | false |
mpcjanssen/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/FilterSortFragment.kt | 1 | 6745 | package nl.mpcjanssen.simpletask
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.mobeta.android.dslv.DragSortListView
import nl.mpcjanssen.simpletask.util.Config
import java.util.*
import kotlin.collections.ArrayList
class FilterSortFragment : Fragment() {
private var originalItems: ArrayList<String>? = null
private var lv: DragSortListView? = null
internal var adapter: SortItemAdapter? = null
internal var directions = ArrayList<String>()
internal var adapterList = ArrayList<String>()
internal var sortUpId: Int = 0
internal var sortDownId: Int = 0
internal lateinit var m_app: TodoApplication
private val onDrop = DragSortListView.DropListener { from, to ->
adapter?.let {
if (from != to) {
val item = it.getItem(from)
it.remove(item)
it.insert(item, to)
val sortItem = directions[from]
directions.removeAt(from)
directions.add(to, sortItem)
}
}
}
private val onRemove = DragSortListView.RemoveListener { which -> adapter?.remove(adapter?.getItem(which)) }
private // this DSLV xml declaration does not call for the use
// of the default DragSortController; therefore,
// DSLVFragment has a buildController() method.
val layout: Int
get() = R.layout.simple_list_item_single_choice
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val arguments = arguments
if (originalItems == null) {
if (savedInstanceState != null) {
originalItems = savedInstanceState.getStringArrayList(STATE_SELECTED)
} else {
originalItems = arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS)?: ArrayList()
}
}
Log.d(TAG, "Created view with: " + originalItems)
m_app = TodoApplication.app
// Set the proper theme
if (TodoApplication.config.isDarkTheme || TodoApplication.config.isBlackTheme) {
sortDownId = R.drawable.ic_action_sort_down_dark
sortUpId = R.drawable.ic_action_sort_up_dark
} else {
sortDownId = R.drawable.ic_action_sort_down
sortUpId = R.drawable.ic_action_sort_up
}
adapterList.clear()
val layout: LinearLayout
layout = inflater.inflate(R.layout.single_filter,
container, false) as LinearLayout
val keys = resources.getStringArray(R.array.sortKeys)
for (item in originalItems!!) {
val parts = item.split("!".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val sortType: String
var sortDirection: String
if (parts.size == 1) {
sortType = parts[0]
sortDirection = Query.NORMAL_SORT
} else {
sortDirection = parts[0]
sortType = parts[1]
if (sortDirection.isEmpty() || sortDirection != Query.REVERSED_SORT) {
sortDirection = Query.NORMAL_SORT
}
}
val index = Arrays.asList(*keys).indexOf(sortType)
if (index != -1) {
adapterList.add(sortType)
directions.add(sortDirection)
keys[index] = null
}
}
// Add sorts not already in the sortlist
for (item in keys) {
if (item != null) {
adapterList.add(item)
directions.add(Query.NORMAL_SORT)
}
}
lv = layout.findViewById(R.id.dslistview) as DragSortListView
lv!!.setDropListener(onDrop)
lv!!.setRemoveListener(onRemove)
adapter = activity?.let { SortItemAdapter(it, R.layout.sort_list_item, R.id.text, adapterList) }
lv!!.adapter = adapter
lv!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
var direction = directions[position]
if (direction == Query.REVERSED_SORT) {
direction = Query.NORMAL_SORT
} else {
direction = Query.REVERSED_SORT
}
directions.removeAt(position)
directions.add(position, direction)
adapter?.notifyDataSetChanged()
}
return layout
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putStringArrayList(STATE_SELECTED, selectedItem)
}
override fun onDestroyView() {
originalItems = selectedItem
super.onDestroyView()
}
val selectedItem: ArrayList<String>
get() {
val multiSort = ArrayList<String>()
when {
lv != null -> for (i in 0 until (adapter?.count?:1)) {
multiSort.add(directions[i] + Query.SORT_SEPARATOR + adapter?.getSortType(i))
}
originalItems != null -> multiSort.addAll(originalItems as ArrayList<String>)
else -> multiSort.addAll(arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS) ?: java.util.ArrayList())
}
return multiSort
}
inner class SortItemAdapter(context: Context, resource: Int, textViewResourceId: Int, objects: List<String>) : ArrayAdapter<String>(context, resource, textViewResourceId, objects) {
private val names: Array<String>
init {
names = resources.getStringArray(R.array.sort)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val row = super.getView(position, convertView, parent)
val reverseButton = row.findViewById(R.id.reverse_button) as ImageButton
val label = row.findViewById(R.id.text) as TextView
label.text = TodoApplication.config.getSortString(adapterList[position])
if (directions[position] == Query.REVERSED_SORT) {
reverseButton.setBackgroundResource(sortUpId)
} else {
reverseButton.setBackgroundResource(sortDownId)
}
return row
}
fun getSortType(position: Int): String {
return adapterList[position]
}
}
companion object {
private val STATE_SELECTED = "selectedItem"
internal val TAG = FilterActivity::class.java.simpleName
}
}
| gpl-3.0 | d9ef6dbcc86183f51ed19c4f58a9303c | 35.459459 | 185 | 0.602372 | 4.923358 | false | false | false | false |
rizafu/CoachMark | coachmark/src/main/java/com/rizafu/coachmark/CoachMarkSequence.kt | 1 | 1922 | package com.rizafu.coachmark
import java.util.Collections
import java.util.LinkedList
import java.util.NoSuchElementException
import java.util.Queue
/**
* Created by RizaFu on 11/14/16.
*/
class CoachMarkSequence {
private val coachMarks: Queue<CoachMark.Builder> = LinkedList<CoachMark.Builder>()
private var coachMark: CoachMark? = null
private var started: Boolean = false
private var onSequenceFinish: (() -> Unit)? = null
private var onSequenceShowNext: ((CoachMarkSequence, CoachMark?) -> Unit)? = null
fun setCoachMarks(vararg coachMarks: CoachMark.Builder): CoachMarkSequence {
Collections.addAll<CoachMark.Builder>(this.coachMarks, *coachMarks)
return this
}
fun setCoachMarks(coachMarks: List<CoachMark.Builder>): CoachMarkSequence {
this.coachMarks.addAll(coachMarks)
return this
}
fun addCoachMark(coachMarks: CoachMark.Builder): CoachMarkSequence {
this.coachMarks.add(coachMarks)
return this
}
fun setOnSequenceFinish(onSequenceFinish: () -> Unit): CoachMarkSequence {
this.onSequenceFinish = onSequenceFinish
return this
}
fun setOnSequenceShowNext(onSequenceShowNext: (CoachMarkSequence, CoachMark?) -> Unit): CoachMarkSequence {
this.onSequenceShowNext = onSequenceShowNext
return this
}
fun start() {
if (coachMarks.isEmpty() || started) return
started = true
next()
}
fun showNext() {
coachMark?.dismiss()
}
private operator fun next() {
try {
coachMark = coachMarks.remove()
.setOnClickTarget{ it.dismiss() }
.setOnAfterDismissListener { next() }
.show()
onSequenceShowNext?.invoke(this, coachMark)
} catch (e: NoSuchElementException) {
onSequenceFinish?.invoke()
}
}
} | apache-2.0 | 19b5661a45567d944e07cbaadbf08030 | 26.869565 | 111 | 0.649844 | 4.012526 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/strings/kt894.kt | 4 | 197 | fun stringConcat(n : Int) : String? {
var string : String? = ""
for (i in 0..(n - 1))
string += "LOL "
return string
}
fun box() = if(stringConcat(3) == "LOL LOL LOL ") "OK" else "fail"
| apache-2.0 | 2069f27faa26f3db37de6a4b67ede9db | 23.625 | 66 | 0.558376 | 2.774648 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/navigation/gotoClass/typealias.kt | 12 | 412 | typealias TestGlobal = Any
fun some() {
typealias TestInFun = Any
}
interface SomeTrait {
typealias TestInTrait = Any
}
class Some() {
typealias TestInClass = Any
companion object {
typealias TestInClassObject = Any
}
}
// SEARCH_TEXT: Test
// REF: (<root>).TestGlobal
// REF: (in Some).TestInClass
// REF: (in Some.Companion).TestInClassObject
// REF: (in SomeTrait).TestInTrait | apache-2.0 | 19ee9e57593638280c7db44b44f0d877 | 16.956522 | 45 | 0.674757 | 3.646018 | false | true | false | false |
android/compose-samples | Owl/app/src/main/java/com/example/owl/ui/theme/Color.kt | 1 | 1572 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.owl.ui.theme
import androidx.compose.material.Colors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
val yellow200 = Color(0xffffeb46)
val yellow400 = Color(0xffffc000)
val yellow500 = Color(0xffffde03)
val yellowDarkPrimary = Color(0xff242316)
val blue200 = Color(0xff91a4fc)
val blue700 = Color(0xff0336ff)
val blue800 = Color(0xff0035c9)
val blueDarkPrimary = Color(0xff1c1d24)
val pink200 = Color(0xffff7597)
val pink500 = Color(0xffff0266)
val pink600 = Color(0xffd8004d)
val pinkDarkPrimary = Color(0xff24191c)
/**
* Return the fully opaque color that results from compositing [onSurface] atop [surface] with the
* given [alpha]. Useful for situations where semi-transparent colors are undesirable.
*/
@Composable
fun Colors.compositedOnSurface(alpha: Float): Color {
return onSurface.copy(alpha = alpha).compositeOver(surface)
}
| apache-2.0 | ec36dab81735077edd344000898e16db | 33.173913 | 98 | 0.774809 | 3.613793 | false | false | false | false |
smmribeiro/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/url/VirtualFileUrlManagerImpl.kt | 2 | 10792 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.url
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.storage.impl.IntIdGenerator
import com.intellij.workspaceModel.storage.impl.VirtualFileNameStore
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.Hash.Strategy
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import it.unimi.dsi.fastutil.ints.IntArrayList
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet
import org.jetbrains.annotations.ApiStatus
open class VirtualFileUrlManagerImpl : VirtualFileUrlManager {
private val idGenerator = IntIdGenerator()
private var emptyUrl: VirtualFileUrl? = null
private val fileNameStore = VirtualFileNameStore()
private val id2NodeMapping = Int2ObjectOpenHashMap<FilePathNode>()
private val rootNode = FilePathNode(0, 0)
@Synchronized
override fun fromUrl(url: String): VirtualFileUrl {
if (url.isEmpty()) return getEmptyUrl()
return add(url)
}
override fun fromPath(path: String): VirtualFileUrl {
return fromUrl("file://${FileUtil.toSystemIndependentName(path)}")
}
@Synchronized
override fun getParentVirtualUrl(vfu: VirtualFileUrl): VirtualFileUrl? {
vfu as VirtualFileUrlImpl
return id2NodeMapping.get(vfu.id)?.parent?.getVirtualFileUrl(this)
}
@Synchronized
override fun getSubtreeVirtualUrlsById(vfu: VirtualFileUrl): List<VirtualFileUrl> {
vfu as VirtualFileUrlImpl
return id2NodeMapping.get(vfu.id).getSubtreeNodes().map { it.getVirtualFileUrl(this) }
}
@Synchronized
fun getUrlById(id: Int): String {
if (id <= 0) return ""
var node = id2NodeMapping[id]
val contentIds = IntArrayList()
while (node != null) {
contentIds.add(node.contentId)
node = node.parent
}
if (contentIds.size == 1) {
return fileNameStore.getNameForId(contentIds.getInt(0))?.let {
return@let if (it.isEmpty()) "/" else it
} ?: ""
}
val builder = StringBuilder()
for (index in contentIds.size - 1 downTo 0) {
builder.append(fileNameStore.getNameForId(contentIds.getInt(index)))
if (index != 0) builder.append("/")
}
return builder.toString()
}
@Synchronized
internal fun append(parentVfu: VirtualFileUrl, relativePath: String): VirtualFileUrl {
parentVfu as VirtualFileUrlImpl
return add(relativePath, id2NodeMapping.get(parentVfu.id))
}
protected open fun createVirtualFileUrl(id: Int, manager: VirtualFileUrlManagerImpl): VirtualFileUrl {
return VirtualFileUrlImpl(id, manager)
}
@ApiStatus.Internal
fun getCachedVirtualFileUrls(): List<VirtualFileUrl> = id2NodeMapping.values.mapNotNull { it.getCachedVirtualFileUrl() }
internal fun add(path: String, parentNode: FilePathNode? = null): VirtualFileUrl {
val segments = splitNames(path)
var latestNode: FilePathNode? = parentNode ?: findRootNode(segments.first())
val latestElement = segments.size - 1
for (index in segments.indices) {
val nameId = fileNameStore.generateIdForName(segments[index])
// Latest node can be NULL only if it's root node
if (latestNode == null) {
val nodeId = idGenerator.generateId()
val newNode = FilePathNode(nodeId, nameId)
id2NodeMapping[nodeId] = newNode
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) {
rootNode.addChild(newNode)
return newNode.getVirtualFileUrl(this)
}
latestNode = newNode
rootNode.addChild(newNode)
continue
}
if (latestNode === findRootNode(latestNode.contentId)) {
if (latestNode.contentId == nameId) {
if (index == latestElement) return latestNode.getVirtualFileUrl(this)
continue
}
}
val node = latestNode.findChild(nameId)
if (node == null) {
val nodeId = idGenerator.generateId()
val newNode = FilePathNode(nodeId, nameId, latestNode)
id2NodeMapping[nodeId] = newNode
latestNode.addChild(newNode)
latestNode = newNode
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) return newNode.getVirtualFileUrl(this)
}
else {
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) return node.getVirtualFileUrl(this)
latestNode = node
}
}
return getEmptyUrl()
}
internal fun remove(path: String) {
val node = findLatestFilePathNode(path)
if (node == null) {
println("File not found")
return
}
if (!node.isEmpty()) return
var currentNode: FilePathNode = node
do {
val parent = currentNode.parent
if (parent == null) {
if (currentNode === findRootNode(currentNode.contentId) && currentNode.isEmpty()) {
removeNameUsage(currentNode.contentId)
id2NodeMapping.remove(currentNode.nodeId)
rootNode.removeChild(currentNode)
}
return
}
parent.removeChild(currentNode)
removeNameUsage(currentNode.contentId)
id2NodeMapping.remove(currentNode.nodeId)
currentNode = parent
}
while (currentNode.isEmpty())
}
internal fun update(oldPath: String, newPath: String) {
val latestPathNode = findLatestFilePathNode(oldPath)
if (latestPathNode == null) return
remove(oldPath)
add(newPath)
}
private fun getEmptyUrl(): VirtualFileUrl {
if (emptyUrl == null) {
emptyUrl = createVirtualFileUrl(0, this)
}
return emptyUrl!!
}
private fun removeNameUsage(contentId: Int) {
val name = fileNameStore.getNameForId(contentId)
assert(name != null)
fileNameStore.removeName(name!!)
}
private fun findLatestFilePathNode(path: String): FilePathNode? {
val segments = splitNames(path)
var latestNode: FilePathNode? = findRootNode(segments.first())
val latestElement = segments.size - 1
for (index in segments.indices) {
val nameId = fileNameStore.getIdForName(segments[index]) ?: return null
// Latest node can be NULL only if it's root node
if (latestNode == null) return null
if (latestNode === findRootNode(latestNode.contentId)) {
if (latestNode.contentId == nameId) {
if (index == latestElement) return latestNode else continue
}
}
latestNode.findChild(nameId)?.let {
if (index == latestElement) return it
latestNode = it
} ?: return null
}
return null
}
private fun findRootNode(segment: String): FilePathNode? {
val segmentId = fileNameStore.getIdForName(segment) ?: return null
return rootNode.findChild(segmentId)
}
private fun findRootNode(contentId: Int): FilePathNode? = rootNode.findChild(contentId)
private fun splitNames(path: String): List<String> = path.split('/', '\\')
fun print() = rootNode.print()
fun isEqualOrParentOf(parentNodeId: Int, childNodeId: Int): Boolean {
if (parentNodeId == 0 && childNodeId == 0) return true
var current = childNodeId
while (current > 0) {
if (parentNodeId == current) return true
current = id2NodeMapping[current]?.parent?.nodeId ?: return false
}
/*
TODO It may look like this + caching + invalidating
val segmentName = getSegmentName(id).toString()
val parent = id2parent.getValue(id)
val parentParent = id2parent.getValue(parent)
return if (parentParent <= 0) {
val fileSystem = VirtualFileManager.getInstance().getFileSystem(getSegmentName(parent).toString())
fileSystem?.findFileByPath(segmentName)
} else {
getVirtualFileById(parent)?.findChild(segmentName)
}
}
*/
return false
}
internal inner class FilePathNode(val nodeId: Int, val contentId: Int, val parent: FilePathNode? = null) {
private var virtualFileUrl: VirtualFileUrl? = null
private var children: ObjectOpenCustomHashSet<FilePathNode>? = null
fun findChild(nameId: Int): FilePathNode? {
return children?.get(FilePathNode(0, nameId))
}
fun getSubtreeNodes(): List<FilePathNode> {
return getSubtreeNodes(mutableListOf())
}
private fun getSubtreeNodes(subtreeNodes: MutableList<FilePathNode>): List<FilePathNode> {
children?.forEach {
subtreeNodes.add(it)
it.getSubtreeNodes(subtreeNodes)
}
return subtreeNodes
}
fun addChild(newNode: FilePathNode) {
createChildrenList()
children!!.add(newNode)
}
fun removeChild(node: FilePathNode) {
children?.remove(node)
}
fun getVirtualFileUrl(virtualFileUrlManager: VirtualFileUrlManagerImpl): VirtualFileUrl {
val cachedValue = virtualFileUrl
if (cachedValue != null) return cachedValue
val url = virtualFileUrlManager.createVirtualFileUrl(nodeId, virtualFileUrlManager)
virtualFileUrl = url
return url
}
fun getCachedVirtualFileUrl(): VirtualFileUrl? = virtualFileUrl
fun isEmpty() = children == null || children!!.isEmpty()
private fun createChildrenList() {
if (children == null) children = ObjectOpenCustomHashSet(HASHING_STRATEGY)
}
fun print(): String {
val buffer = StringBuilder()
print(buffer, "", "")
return buffer.toString()
}
private fun print(buffer: StringBuilder, prefix: String, childrenPrefix: String) {
val name = [email protected](contentId)
if (name != null) buffer.append("$prefix $name\n")
val iterator = children?.iterator() ?: return
while (iterator.hasNext()) {
val next = iterator.next()
if (name == null) {
next.print(buffer, childrenPrefix, childrenPrefix)
continue
}
if (iterator.hasNext()) {
next.print(buffer, "$childrenPrefix |- ", "$childrenPrefix | ")
}
else {
next.print(buffer, "$childrenPrefix '- ", "$childrenPrefix ")
}
}
}
}
private companion object {
val HASHING_STRATEGY: Strategy<FilePathNode> = object : Strategy<FilePathNode> {
override fun equals(node1: FilePathNode?, node2: FilePathNode?): Boolean {
if (node1 === node2) {
return true
}
if (node1 == null || node2 == null) {
return false
}
return node1.contentId == node2.contentId
}
override fun hashCode(node: FilePathNode?): Int = node?.contentId ?: 0
}
}
} | apache-2.0 | d45af78105ee16246f4f95bfd98db910 | 32.623053 | 140 | 0.677724 | 4.643718 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/getSourceModuleDependencies.kt | 2 | 4766 | // 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.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.getBuildSystemType
import org.jetbrains.kotlin.idea.project.isHMPPEnabled
import org.jetbrains.kotlin.platform.TargetPlatform
internal fun Module.getSourceModuleDependencies(
forProduction: Boolean,
platform: TargetPlatform
): List<IdeaModuleInfo> {
// Use StringBuilder so that all lines are written into the log atomically (otherwise
// logs of call to getIdeaModelDependencies for several different modules interleave, leading
// to unreadable mess)
val debugString: StringBuilder? = if (LOG.isDebugEnabled) StringBuilder() else null
debugString?.appendLine("Building idea model dependencies for module ${this}, platform=${platform}, forProduction=$forProduction")
val allIdeaModuleInfoDependencies = resolveDependenciesFromOrderEntries(debugString, forProduction)
val supportedModuleInfoDependencies = filterSourceModuleDependencies(debugString, platform, allIdeaModuleInfoDependencies)
LOG.debug(debugString?.toString())
return supportedModuleInfoDependencies.toList()
}
private fun Module.resolveDependenciesFromOrderEntries(
debugString: StringBuilder?,
forProduction: Boolean,
): Set<IdeaModuleInfo> {
//NOTE: lib dependencies can be processed several times during recursive traversal
val result = LinkedHashSet<IdeaModuleInfo>()
val dependencyEnumerator = ModuleRootManager.getInstance(this).orderEntries().compileOnly().recursively().exportedOnly()
if (forProduction && getBuildSystemType() == BuildSystemType.JPS) {
dependencyEnumerator.productionOnly()
}
debugString?.append(" IDEA dependencies: [")
dependencyEnumerator.forEach { orderEntry ->
debugString?.append("${orderEntry.presentableName} ")
if (orderEntry.acceptAsDependency(forProduction)) {
result.addAll(orderEntryToModuleInfo(project, orderEntry, forProduction))
debugString?.append("OK; ")
} else {
debugString?.append("SKIP; ")
}
true
}
debugString?.appendLine("]")
return result.toSet()
}
private fun Module.filterSourceModuleDependencies(
debugString: StringBuilder?,
platform: TargetPlatform,
dependencies: Set<IdeaModuleInfo>
): Set<IdeaModuleInfo> {
val dependencyFilter = if (isHMPPEnabled) HmppSourceModuleDependencyFilter(platform) else NonHmppSourceModuleDependenciesFilter(platform)
val supportedDependencies = dependencies.filter { dependency -> dependencyFilter.isSupportedDependency(dependency) }.toSet()
debugString?.appendLine(
" Corrected result (Supported dependencies): ${
supportedDependencies.joinToString(
prefix = "[",
postfix = "]",
separator = ";"
) { it.displayedName }
}"
)
return supportedDependencies
}
private fun OrderEntry.acceptAsDependency(forProduction: Boolean): Boolean {
return this !is ExportableOrderEntry
|| !forProduction
// this is needed for Maven/Gradle projects with "production-on-test" dependency
|| this is ModuleOrderEntry && isProductionOnTestDependency
|| scope.isForProductionCompile
}
private fun orderEntryToModuleInfo(project: Project, orderEntry: OrderEntry, forProduction: Boolean): List<IdeaModuleInfo> {
fun Module.toInfos() = correspondingModuleInfos().filter { !forProduction || it is ModuleProductionSourceInfo }
if (!orderEntry.isValid) return emptyList()
return when (orderEntry) {
is ModuleSourceOrderEntry -> {
orderEntry.getOwnerModule().toInfos()
}
is ModuleOrderEntry -> {
val module = orderEntry.module ?: return emptyList()
if (forProduction && orderEntry.isProductionOnTestDependency) {
listOfNotNull(module.testSourceInfo())
} else {
module.toInfos()
}
}
is LibraryOrderEntry -> {
val library = orderEntry.library ?: return listOf()
createLibraryInfo(project, library)
}
is JdkOrderEntry -> {
val sdk = orderEntry.jdk ?: return listOf()
listOfNotNull(SdkInfo(project, sdk))
}
else -> {
throw IllegalStateException("Unexpected order entry $orderEntry")
}
}
}
| apache-2.0 | 0563c0e279f924448d429b0a4190c2fc | 39.735043 | 158 | 0.704154 | 5.471871 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/customization/AvatarEquipmentFragment.kt | 1 | 5593 | package com.habitrpg.android.habitica.ui.fragments.inventory.customization
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.responses.UnlockResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.adapter.CustomizationEquipmentRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.MarginDecoration
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import io.reactivex.Flowable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_recyclerview.*
import javax.inject.Inject
class AvatarEquipmentFragment : BaseMainFragment() {
@Inject
lateinit var inventoryRepository: InventoryRepository
var type: String? = null
var category: String? = null
private var activeEquipment: String? = null
internal var adapter: CustomizationEquipmentRecyclerViewAdapter = CustomizationEquipmentRecyclerViewAdapter()
internal var layoutManager: GridLayoutManager = GridLayoutManager(activity, 2)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.fragment_recyclerview, container, false)
compositeSubscription.add(adapter.getSelectCustomizationEvents()
.flatMap { equipment ->
inventoryRepository.equip(user, if (user?.preferences?.costume == true) "costume" else "equipped", equipment.key ?: "")
}
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getUnlockCustomizationEvents()
.flatMap<UnlockResponse> {
Flowable.empty()
}
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getUnlockSetEvents()
.flatMap<UnlockResponse> { set ->
val user = this.user
if (user != null) {
userRepository.unlockPath(user, set)
} else {
Flowable.empty()
}
}
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = AvatarEquipmentFragmentArgs.fromBundle(it)
type = args.type
if (args.category.isNotEmpty()) {
category = args.category
}
}
setGridSpanCount(view.width)
val layoutManager = GridLayoutManager(activity, 4)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (adapter.getItemViewType(position) == 0) {
layoutManager.spanCount
} else {
1
}
}
}
recyclerView.layoutManager = layoutManager
recyclerView.addItemDecoration(MarginDecoration(context))
recyclerView.adapter = adapter
recyclerView.itemAnimator = SafeDefaultItemAnimator()
this.loadEquipment()
compositeSubscription.add(userRepository.getUser().subscribeWithErrorHandler(Consumer {
updateUser(it)
}))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun loadEquipment() {
val type = this.type ?: return
inventoryRepository.getEquipmentType(type, category ?: "").subscribe(Consumer {
adapter.setEquipment(it)
}, RxErrorHandler.handleEmptyError())
}
private fun setGridSpanCount(width: Int) {
val itemWidth = context?.resources?.getDimension(R.dimen.customization_width) ?: 0F
var spanCount = (width / itemWidth).toInt()
if (spanCount == 0) {
spanCount = 1
}
layoutManager.spanCount = spanCount
}
fun updateUser(user: User) {
this.updateActiveCustomization(user)
this.adapter.gemBalance = user.gemCount
adapter.notifyDataSetChanged()
}
private fun updateActiveCustomization(user: User) {
if (this.type == null || user.preferences == null) {
return
}
val outfit = if (user.preferences?.costume == true) this.user?.items?.gear?.costume else this.user?.items?.gear?.equipped
val activeEquipment = when (this.type) {
"headAccessory" -> outfit?.headAccessory
"back" -> outfit?.back
"eyewear" -> outfit?.eyeWear
else -> ""
}
if (activeEquipment != null) {
this.activeEquipment = activeEquipment
this.adapter.activeEquipment = activeEquipment
}
}
} | gpl-3.0 | c3f7f105828931827145f6d93447694e | 39.244604 | 139 | 0.658323 | 5.31654 | false | false | false | false |
FuturemanGaming/FutureBot-Discord | src/main/kotlin/com/futuremangaming/futurebot/external/DisconnectListener.kt | 1 | 1714 | /*
* Copyright 2014-2017 FuturemanGaming
*
* 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.futuremangaming.futurebot.external
import com.futuremangaming.futurebot.getLogger
import net.dv8tion.jda.core.events.DisconnectEvent
import net.dv8tion.jda.core.events.Event
import net.dv8tion.jda.core.events.ExceptionEvent
import net.dv8tion.jda.core.hooks.EventListener
object DisconnectListener : EventListener {
val LOG = getLogger("Connection")
override fun onEvent(event: Event): Unit = when (event) {
is DisconnectEvent -> {
val client = event.clientCloseFrame
val code = event.closeCode
if (code !== null)
LOG.warn("Disconnected [Server] ${code.code}: ${code.meaning}")
else if (client !== null)
LOG.warn("Disconnected [Client] ${client.closeCode}: ${client.closeReason}")
else LOG.error("Disconnected for unknown reason! ${event.serviceCloseFrame.closeReason}")
Unit
}
is ExceptionEvent -> {
if (!event.isLogged)
LOG.warn("Unhandled JDA Exception", event.cause)
Unit
}
else -> { }
}
} | apache-2.0 | ac91f349d1a8eaec95bd525765712c41 | 35.489362 | 101 | 0.668611 | 4.232099 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/ext/DateTimeExt.kt | 1 | 5751 | package slatekit.common.ext
import org.threeten.bp.*
import org.threeten.bp.format.DateTimeFormatter
import slatekit.common.DateTimes
import slatekit.common.utils.Random
// ********************************************
// Conversions
// ********************************************
fun Month.daysInMonth(year:Int): Int = this.length(Year.isLeap(year.toLong()))
fun LocalDate.format(pattern: String): String = this.format(DateTimeFormatter.ofPattern(pattern))
fun LocalDate.toDateDisplay(): String = this.format("MMM dd, yyyy")
fun LocalDate.toNumeric(): Int = format("yyyyMMdd").toInt()
fun LocalTime.format(pattern: String): String = this.format(DateTimeFormatter.ofPattern(pattern))
fun LocalTime.toNumeric(): Int = format("HHmmss").toInt()
fun LocalTime.tohhmm():String = this.format("hh:mm a")
fun LocalTime.tohmm():String = this.format("h:mm a")
fun LocalDateTime.zoned(): ZonedDateTime = this.atZone(ZoneId.systemDefault())
fun ZonedDateTime.local(): LocalDateTime = this.toLocalDateTime()
fun ZonedDateTime.date(): LocalDate = this.toLocalDate()
fun ZonedDateTime.time(): LocalTime = this.toLocalTime()
fun ZonedDateTime.toDateKey() : String = this.format("YYYYMMdd")
fun ZonedDateTime.toNumeric(): Long = format("yyyyMMddHHmmss").toLong()
fun ZonedDateTime.toNumericYearMonth(): Long = format("YYYYMM").toLong()
fun ZonedDateTime.atStartOfMonth():ZonedDateTime = DateTimes.of(this.year, this.monthValue, 0, this.hour, this.minute, this.second, 0, this.zone)
fun ZonedDateTime.daysInMonth(): Int = this.month.length(Year.isLeap(this.year.toLong()))
fun ZonedDateTime.midnight(): ZonedDateTime = DateTimes.Companion.of(this.year, this.monthValue, this.dayOfMonth, 0, 0, 0, 0, this.zone)
fun ZonedDateTime.plus(time:LocalTime):ZonedDateTime = this.plusHours(time.hour.toLong()).plusMinutes(time.minute.toLong()).plusSeconds(time.second.toLong())
// ********************************************
// Duration
// ********************************************
fun ZonedDateTime.durationFrom(dt:ZonedDateTime): Duration = Duration.between(this.toInstant(), dt.toInstant())
fun ZonedDateTime.periodFrom(dt:ZonedDateTime): Period = Period.between(this.toLocalDate(), dt.toLocalDate())
fun ZonedDateTime.yearsFrom(dt: ZonedDateTime): Int = this.periodFrom(dt).years
fun ZonedDateTime.monthsFrom(dt: ZonedDateTime): Int = this.periodFrom(dt).months
fun ZonedDateTime.daysFrom(dt: ZonedDateTime): Int = this.periodFrom(dt).days
fun ZonedDateTime.hoursFrom(dt: ZonedDateTime): Long = this.durationFrom(dt).toHours()
// ********************************************
// Comparisons
// ********************************************
operator fun ZonedDateTime.compareTo(dt: ZonedDateTime): Int = this.compareTo(dt)
operator fun ZonedDateTime.plus(duration: Duration): ZonedDateTime = this.plus(duration)
operator fun ZonedDateTime.plus(period: Period): ZonedDateTime = this.plus(period)
operator fun ZonedDateTime.minus(duration: Duration): ZonedDateTime = this.minus(duration)
operator fun ZonedDateTime.minus(period: Period): ZonedDateTime = this.minus(period)
// ********************************************
// To String
// ********************************************
fun LocalDateTime.format(pattern: String): String = this.format(DateTimeFormatter.ofPattern(pattern))
fun LocalDateTime.toStringMySql(): String = format("yyyy-MM-dd HH:mm:ss")
fun LocalDateTime.toNumeric(): Long = format("yyyyMMddHHmmss").toLong()
fun LocalDateTime.toStringNumeric(sep: String = "-"): String = format("yyyy${sep}MM${sep}dd${sep}HH${sep}mm${sep}ss")
fun ZonedDateTime.format(pattern: String): String = this.format(DateTimeFormatter.ofPattern(pattern))
fun ZonedDateTime.toIdWithRandom(digits:Int = 5): String = format("yyMMddHHmmss").toLong().toString() + Random.digitsN(digits)
fun ZonedDateTime.toStringNumeric(sep: String = "-"): String = format("yyyy${sep}MM${sep}dd${sep}HH${sep}mm${sep}ss")
fun ZonedDateTime.toStringYYYYMMDD(sep: String = "-"): String = format("yyyy${sep}MM${sep}dd")
fun ZonedDateTime.toStringMMMDD(): String = this.format("MMM dd")
fun ZonedDateTime.toStringMMDDYYYY(sep: String = "-"): String = format("MM${sep}dd${sep}yyyy")
fun ZonedDateTime.toStringMySql(): String = format("yyyy-MM-dd HH:mm:ss")
fun ZonedDateTime.toStringUtc(): String = format("yyyy-MM-dd'T'HH:mm:ss'Z'")
fun ZonedDateTime.toStringTime(sep: String = "-"): String = format("HH${sep}mm${sep}ss")
fun ZonedDateTime.toDateDisplay(): String = this.format("MMM dd, yyyy")
fun ZonedDateTime.toDateTimeDisplay(): String = this.format("MMM dd, yyyy hh:mm a")
fun ZonedDateTime.toShortDateTimeDisplay(): String = this.format("MMM dd, YY h:mm a")
/**
* Gets the current ZonedDateTime at UTC at the same "instant"
* This essential converts the time from e.g. New York to UTC ( +4hr )
*/
fun ZonedDateTime.atUtc(): ZonedDateTime = this.withZoneSameInstant(DateTimes.UTC)
/**
* Gets the current ZonedDateTime at UTC at the same "local" time
* This essential converts the time from e.g. New York to UTC
*/
fun ZonedDateTime.atUtcLocal(): ZonedDateTime = this.withZoneSameLocal(DateTimes.UTC)
/**
* Gets the current ZonedDateTime at the local timezone
*/
fun ZonedDateTime.atLocal(): ZonedDateTime = this.withZoneSameInstant(ZoneId.systemDefault())
/**
* Gets the current ZonedDateTime at the same "instant" of timezone supplied.
* This essential converts the time from e.g. New York to Europe/Athens ( +7hr )
*/
fun ZonedDateTime.atZone(zone: String): ZonedDateTime = this.withZoneSameInstant(ZoneId.of(zone))
/**
* Gets the current ZonedDateTime at the same "instant" of timezone supplied.
* This essential converts the time from e.g. New York to Europe/Athens ( +7hr )
*/
fun ZonedDateTime.atZone(zone: ZoneId): ZonedDateTime = this.withZoneSameInstant(zone)
| apache-2.0 | 8abd0426bb85825695d065776d41095b | 53.254717 | 157 | 0.713093 | 4.055712 | false | false | false | false |
ReplayMod/ReplayMod | src/main/kotlin/com/replaymod/simplepathing/gui/panels/UIPositionKeyframePanel.kt | 1 | 9472 | package com.replaymod.simplepathing.gui.panels
import com.replaymod.core.gui.common.input.*
import com.replaymod.core.gui.utils.Axis
import com.replaymod.core.gui.utils.Resources
import com.replaymod.core.gui.utils.hiddenChildOf
import com.replaymod.core.gui.utils.onSetValueAndNow
import com.replaymod.core.utils.i18n
import com.replaymod.core.utils.toVector3f
import com.replaymod.core.utils.transpose
import com.replaymod.replay.gui.overlay.panels.UIToggleablePanel
import com.replaymod.replaystudio.pathing.change.Change
import com.replaymod.replaystudio.pathing.change.CombinedChange
import com.replaymod.simplepathing.SPTimeline
import com.replaymod.simplepathing.gui.KeyframeState
import com.replaymod.simplepathing.gui.moveKeyframes
import com.replaymod.simplepathing.gui.movePosKeyframes
import de.johni0702.minecraft.gui.utils.lwjgl.vector.Vector3f
import gg.essential.elementa.UIComponent
import gg.essential.elementa.components.UIContainer
import gg.essential.elementa.components.UIText
import gg.essential.elementa.components.Window
import gg.essential.elementa.constraints.*
import gg.essential.elementa.dsl.*
import java.util.*
import kotlin.math.*
import kotlin.time.Duration
class UIPositionKeyframePanel(
val state: KeyframeState,
) : UIToggleablePanel() {
init {
toggleButton.texture(Resources.icon("pos_keyframe_panel"))
constrain {
width = 230.pixels
height = 114.pixels
}
}
val translateContainer by UIContainer().constrain {
width = 128.pixels
height = ChildBasedSizeConstraint()
} childOf this
val translateLabel by UIContainer().constrain {
width = 100.percent
height = 20.pixels
}.addChild(UIText("Translate".i18n()).constrain {
x = CenterConstraint()
y = CenterConstraint()
}) childOf translateContainer
val translateXYZ by UIContainer().constrain {
y = SiblingConstraint()
width = 100.percent
height = ChildBasedSizeConstraint()
} childOf translateContainer
val translateX by FieldComponent(Axis.X) childOf translateXYZ
val translateY by FieldComponent(Axis.Y) childOf translateXYZ
val translateZ by FieldComponent(Axis.Z) childOf translateXYZ
val rotateContainer by UIContainer().constrain {
x = SiblingConstraint()
width = 102.pixels
height = ChildBasedSizeConstraint()
} childOf this
val rotateLabel by UIContainer().constrain {
width = 100.percent
height = 20.pixels
}.addChild(UIText("Rotate".i18n()).constrain {
x = CenterConstraint()
y = CenterConstraint()
}) childOf rotateContainer
val rotateXYZ by UIContainer().constrain {
y = SiblingConstraint()
width = 100.percent
height = ChildBasedSizeConstraint()
} childOf rotateContainer
val rotateX by FieldComponent(Axis.X) childOf rotateXYZ
val rotateY by FieldComponent(Axis.Y) childOf rotateXYZ
val rotateZ by FieldComponent(Axis.Z) childOf rotateXYZ
val timeField by UIInputOrExpressionField.forTimeInput().constrain {
x = 0.pixels boundTo rotateZ.input.integer
y = SiblingConstraint(4f)
width = 60.pixels
height = 20.pixels
}.apply {
input.onActivate { apply() }
} childOf this
val timeLabel by UIContainer().constrain {
x = 5.pixels(alignOutside = true) boundTo timeField
y = 0.pixels boundTo timeField
width = ChildBasedSizeConstraint()
height = CopyConstraintFloat() boundTo timeField
}.addChild(UIText("Video Time (min:sec:ms)".i18n()).constrain {
y = CenterConstraint()
}) childOf this
init {
state.selectedPositionKeyframes.map { it.entries.firstOrNull() }.onSetValueAndNow { selection ->
val (time, keyframe) = selection?.toPair().transpose()
timeField.input.value = time ?: Duration.ZERO
(keyframe?.position ?: Triple(0.0, 0.0, 0.0)).let { (x, y, z) ->
translateX.value = x
translateY.value = y
translateZ.value = z
}
(keyframe?.rotation ?: Triple(0.0, 0.0, 0.0)).let { (x, y, z) ->
rotateX.value = x
rotateY.value = y
rotateZ.value = z
}
}
}
private fun apply() {
val selection = state.selection.get()
val (time, keyframe) = state.selectedPositionKeyframes.get().entries.firstOrNull() ?: return
val (pos, rot) = keyframe
val timeline = state.mod.currentTimeline
val newPos = Triple(translateX.value, translateY.value, translateZ.value)
val newRot = Triple(rotateX.value, rotateY.value, rotateZ.value)
var change = state.movePosKeyframes(selection,
Vector3f.sub(newPos.toVector3f(), pos.toVector3f(), null),
Vector3f.sub(newRot.toVector3f(), rot.toVector3f(), null),
)
val newTime = timeField.input.value
if (newTime != time) {
change = CombinedChange.createFromApplied(
change,
state.moveKeyframes(selection, newTime - time)
)
}
timeline.timeline.pushChange(change)
}
inner class FieldComponent(axis: Axis) : UIContainer() {
init {
constrain {
y = SiblingConstraint(4f)
width = 100.percent
height = 20.pixels
}
}
val label by UIContainer().constrain {
width = 16.pixels
height = 100.percent
}.addChild(UIText(axis.toString()).constrain {
x = CenterConstraint()
y = CenterConstraint()
color = axis.color.toConstraint()
}) childOf this
val input by DecimalInputField().constrain {
x = SiblingConstraint()
width = FillConstraint() - 6.pixels
} childOf this
init {
input.onActivate { apply() }
}
var value by input::value
}
class DecimalInputField(
fractionalDigits: Int = 5,
) : UIContainer() {
private val fractionMultiplier = (10.0).pow(fractionalDigits)
init {
constrain {
width = 100.percent
height = 100.percent
}
}
val expression by UIInputField(UIExpressionInput()).constrain {
width = 100.percent
height = 100.percent
} hiddenChildOf this
val decimal by UIContainer().constrain {
width = 100.percent
height = 100.percent
} childOf this
val integer by UIInputField(UIIntegerInput()).constrain {
width = FillConstraint()
} childOf decimal
val dot by UIContainer().constrain {
x = SiblingConstraint()
width = 5.pixels
height = 100.percent
}.addChild(UIText(".", shadow = false).constrain {
x = CenterConstraint()
y = CenterConstraint()
}) childOf decimal
val fraction by UIInputField(UIIntegerInput(fixedDigits = fractionalDigits)).constrain {
x = SiblingConstraint()
width = 37.pixels
} childOf decimal
init {
val maybeSwitchToExpression: UIComponent.(typedChar: Char, keyCode: Int) -> Unit = { typedChar, keyCode ->
this as UIIntegerInput
if (typedChar in UIExpressionInput.expressionChars && (typedChar != '-' || !isCursorAtAbsoluteStart)) {
decimal.hide(instantly = true)
expression.unhide()
with(expression.input) {
setText(integer.input.getText() + "." + fraction.input.getText())
grabWindowFocus()
setActive(true)
keyTypedListeners.forEach { it(typedChar, keyCode) }
}
}
}
integer.input.keyTypedListeners.add(0, maybeSwitchToExpression)
fraction.input.keyTypedListeners.add(0, maybeSwitchToExpression)
expression.input.onActivate {
// Re-assigning the value will switch back to integer+fraction fields
value = expression.input.value ?: return@onActivate
// Forward the activation
integer.input.activateAction("")
}
expression.input.onFocusLost {
// Re-assigning the value will switch back to integer+fraction fields
value = value
}
}
var value: Double
get() {
val int = integer.input.value
return int + (int.sign * fraction.input.value / fractionMultiplier)
}
set(value) {
integer.input.value = value.toInt()
fraction.input.value = (abs(value - value.toInt()) * fractionMultiplier).roundToInt()
expression.hide(instantly = true)
decimal.unhide()
if (Window.ofOrNull(expression) != null && expression.input.hasFocus()) {
integer.input.grabWindowFocus()
}
}
fun onActivate(listener: () -> Unit) {
integer.input.onActivate { listener() }
fraction.input.onActivate { listener() }
}
}
} | gpl-3.0 | 7dcf91cba483a451c3c6fbaad82cac18 | 34.085185 | 119 | 0.607052 | 4.618235 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt | 2 | 8868 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import java.util.*
open class ChangeVariableTypeFix(element: KtCallableDeclaration, type: KotlinType) : KotlinQuickFixAction<KtCallableDeclaration>(element) {
private val typeContainsError = ErrorUtils.containsErrorType(type)
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type)
open fun variablePresentation(): String? {
val element = element!!
val name = element.name
return if (name != null) {
val container = element.unsafeResolveToDescriptor().containingDeclaration as? ClassDescriptor
val containerName = container?.name?.takeUnless { it.isSpecial }?.asString()
if (containerName != null) "'$containerName.$name'" else "'$name'"
} else {
null
}
}
override fun getText(): String {
if (element == null) return ""
val variablePresentation = variablePresentation()
return if (variablePresentation != null) {
KotlinBundle.message("change.type.of.0.to.1", variablePresentation, typePresentation)
} else {
KotlinBundle.message("change.type.to.0", typePresentation)
}
}
class OnType(element: KtCallableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type), HighPriorityAction {
override fun variablePresentation() = null
}
class ForOverridden(element: KtVariableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type) {
override fun variablePresentation(): String? {
val presentation = super.variablePresentation() ?: return null
return KotlinBundle.message("base.property.0", presentation)
}
}
override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = !typeContainsError
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(file)
assert(element.nameIdentifier != null) { "ChangeVariableTypeFix applied to variable without name" }
val replacingTypeReference = psiFactory.createType(typeSourceCode)
val toShorten = ArrayList<KtTypeReference>()
toShorten.add(element.setTypeReference(replacingTypeReference)!!)
if (element is KtProperty) {
val getterReturnTypeRef = element.getter?.returnTypeReference
if (getterReturnTypeRef != null) {
toShorten.add(getterReturnTypeRef.replace(replacingTypeReference) as KtTypeReference)
}
val setterParameterTypeRef = element.setter?.parameter?.typeReference
if (setterParameterTypeRef != null) {
toShorten.add(setterParameterTypeRef.replace(replacingTypeReference) as KtTypeReference)
}
}
ShortenReferences.DEFAULT.process(toShorten)
}
object ComponentFunctionReturnTypeMismatchFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val entry = ChangeCallableReturnTypeFix.getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic)
val context = entry.analyze()
val resolvedCall = context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry) ?: return null
if (DescriptorToSourceUtils.descriptorToDeclaration(resolvedCall.candidateDescriptor) == null) return null
val expectedType = resolvedCall.candidateDescriptor.returnType ?: return null
return ChangeVariableTypeFix(entry, expectedType)
}
}
object PropertyOrReturnTypeMismatchOnOverrideFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val actions = LinkedList<IntentionAction>()
val element = diagnostic.psiElement as? KtCallableDeclaration
if (element !is KtProperty && element !is KtParameter) return actions
val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor ?: return actions
var lowerBoundOfOverriddenPropertiesTypes = QuickFixUtil.findLowerBoundOfOverriddenCallablesReturnTypes(descriptor)
val propertyType = descriptor.returnType ?: error("Property type cannot be null if it mismatches something")
val overriddenMismatchingProperties = LinkedList<PropertyDescriptor>()
var canChangeOverriddenPropertyType = true
for (overriddenProperty in descriptor.overriddenDescriptors) {
val overriddenPropertyType = overriddenProperty.returnType
if (overriddenPropertyType != null) {
if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(propertyType, overriddenPropertyType)) {
overriddenMismatchingProperties.add(overriddenProperty)
} else if (overriddenProperty.isVar && !KotlinTypeChecker.DEFAULT.equalTypes(
overriddenPropertyType,
propertyType
)
) {
canChangeOverriddenPropertyType = false
}
if (overriddenProperty.isVar && lowerBoundOfOverriddenPropertiesTypes != null &&
!KotlinTypeChecker.DEFAULT.equalTypes(lowerBoundOfOverriddenPropertiesTypes, overriddenPropertyType)
) {
lowerBoundOfOverriddenPropertiesTypes = null
}
}
}
if (lowerBoundOfOverriddenPropertiesTypes != null) {
actions.add(OnType(element, lowerBoundOfOverriddenPropertiesTypes))
}
if (overriddenMismatchingProperties.size == 1 && canChangeOverriddenPropertyType) {
val overriddenProperty = DescriptorToSourceUtils.descriptorToDeclaration(overriddenMismatchingProperties.single())
if (overriddenProperty is KtProperty) {
actions.add(ForOverridden(overriddenProperty, propertyType))
}
}
return actions
}
}
object VariableInitializedWithNullFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val binaryExpression = diagnostic.psiElement.getStrictParentOfType<KtBinaryExpression>() ?: return null
val left = binaryExpression.left ?: return null
if (binaryExpression.operationToken != KtTokens.EQ) return null
val property = left.mainReference?.resolve() as? KtProperty ?: return null
if (!property.isVar || property.typeReference != null || !property.initializer.isNullExpression()) return null
return ChangeVariableTypeFix(property, Errors.TYPE_MISMATCH.cast(diagnostic).b.makeNullable())
}
}
}
| apache-2.0 | dbbc3ea82d44431681d4d350bc110403 | 50.55814 | 158 | 0.71166 | 5.838051 | false | false | false | false |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/gc/GarbageCollector.kt | 1 | 13718 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.gc
import jetbrains.exodus.ExodusException
import jetbrains.exodus.core.dataStructures.LongArrayList
import jetbrains.exodus.core.dataStructures.Priority
import jetbrains.exodus.core.dataStructures.hash.IntHashMap
import jetbrains.exodus.core.dataStructures.hash.PackedLongHashSet
import jetbrains.exodus.core.execution.Job
import jetbrains.exodus.core.execution.JobProcessorAdapter
import jetbrains.exodus.core.execution.LatchJob
import jetbrains.exodus.core.execution.SharedTimer
import jetbrains.exodus.env.*
import jetbrains.exodus.io.Block
import jetbrains.exodus.io.DataReader
import jetbrains.exodus.io.DataWriter
import jetbrains.exodus.io.RemoveBlockType
import jetbrains.exodus.log.AbstractBlockListener
import jetbrains.exodus.log.Log
import jetbrains.exodus.log.LogUtil
import jetbrains.exodus.log.Loggable
import jetbrains.exodus.runtime.OOMGuard
import jetbrains.exodus.tree.ExpiredLoggableCollection
import jetbrains.exodus.util.DeferredIO
import mu.KLogging
import java.io.File
import java.util.concurrent.ConcurrentLinkedQueue
class GarbageCollector(internal val environment: EnvironmentImpl) {
// the last time when background cleaning job was invoked
var lastInvocationTime = 0L
private val ec: EnvironmentConfig = environment.environmentConfig
val utilizationProfile = UtilizationProfile(environment, this)
private val pendingFilesToDelete = PackedLongHashSet()
private val deletionQueue = ConcurrentLinkedQueue<Long>()
internal val cleaner = BackgroundCleaner(this)
private val openStoresCache = IntHashMap<StoreImpl>()
init {
environment.log.addBlockListener(object : AbstractBlockListener() {
override fun blockCreated(block: Block, reader: DataReader, writer: DataWriter) {
utilizationProfile.estimateTotalBytes()
if (!cleaner.isCleaning && isTooMuchFreeSpace) {
wake()
}
}
})
SharedTimer.registerPeriodicTask(PeriodicGc(this))
}
internal val maximumFreeSpacePercent: Int
get() = 100 - ec.gcMinUtilization
internal val isTooMuchFreeSpace: Boolean
get() = utilizationProfile.totalFreeSpacePercent() > maximumFreeSpacePercent
internal val minFileAge: Int
get() = ec.gcFileMinAge
internal val log: Log
get() = environment.log
internal val startTime: Long
get() = environment.created + ec.gcStartIn
val isSuspended: Boolean
get() = cleaner.isSuspended
fun clear() {
utilizationProfile.clear()
pendingFilesToDelete.clear()
deletionQueue.clear()
openStoresCache.clear()
}
fun getCleanerJobProcessor() = cleaner.getJobProcessor()
@Suppress("unused")
fun setCleanerJobProcessor(processor: JobProcessorAdapter) {
getCleanerJobProcessor().queue(object : Job() {
override fun execute() {
cleaner.setJobProcessor(processor)
wake(true)
}
}, Priority.highest)
}
fun addBeforeGcAction(action: Runnable) = cleaner.addBeforeGcAction(action)
fun wake(estimateTotalUtilization: Boolean = false) {
if (ec.isGcEnabled) {
environment.executeTransactionSafeTask {
if (estimateTotalUtilization) {
utilizationProfile.estimateTotalBytes()
}
cleaner.queueCleaningJob()
}
}
}
internal fun wakeAt(millis: Long) {
if (ec.isGcEnabled) {
cleaner.queueCleaningJobAt(millis)
}
}
fun fetchExpiredLoggables(loggables: ExpiredLoggableCollection) {
if (loggables.fromScratch) {
utilizationProfile.computeUtilizationFromScratch()
} else {
utilizationProfile.fetchExpiredLoggables(loggables)
}
}
fun getFileFreeBytes(fileAddress: Long) = utilizationProfile.getFileFreeBytes(fileAddress)
fun suspend() = cleaner.suspend()
fun resume() = cleaner.resume()
fun finish() = cleaner.finish()
/* public access is necessary to invoke the method from the Reflect class */
fun doCleanFile(fileAddress: Long) = doCleanFiles(setOf(fileAddress).iterator())
/**
* Cleans fragmented files. It is expected that the files are sorted by utilization, i.e.
* the first files are more fragmented. In order to avoid race conditions and synchronization issues,
* this method should be called from the thread of background cleaner.
*
* @param fragmentedFiles fragmented files
* @return `false` if there was unsuccessful attempt to clean a file (GC txn wasn't acquired or flushed)
*/
internal fun cleanFiles(fragmentedFiles: Iterator<Long>): Boolean {
cleaner.checkThread()
return doCleanFiles(fragmentedFiles)
}
internal fun isFileCleaned(file: Long) = pendingFilesToDelete.contains(file)
/**
* For tests only!!!
*/
fun waitForPendingGC() {
getCleanerJobProcessor().waitForLatchJob(object : LatchJob() {
override fun execute() {
release()
}
}, 100, Priority.lowest)
}
/**
* For tests only!!!
*/
fun cleanEntireLog() {
cleaner.cleanEntireLog()
}
/**
* For tests only!!!
*/
fun testDeletePendingFiles() {
val files = pendingFilesToDelete.toLongArray()
var aFileWasDeleted = false
val currentFile = LongArray(1)
for (file in files) {
utilizationProfile.removeFile(file)
currentFile[0] = file
environment.removeFiles(currentFile, if (ec.gcRenameFiles) RemoveBlockType.Rename else RemoveBlockType.Delete)
aFileWasDeleted = true
}
if (aFileWasDeleted) {
pendingFilesToDelete.clear()
utilizationProfile.estimateTotalBytes()
}
}
internal fun deletePendingFiles() {
if (!cleaner.isCurrentThread) {
getCleanerJobProcessor().queue(GcJob(this) {
deletePendingFiles()
})
} else {
val filesToDelete = LongArrayList()
while (true) {
(deletionQueue.poll() ?: break).apply {
if (pendingFilesToDelete.remove(this)) {
filesToDelete.add(this)
}
}
}
if (!filesToDelete.isEmpty) {
// force flush and fsync in order to fix XD-249
// in order to avoid data loss, it's necessary to make sure that any GC transaction is flushed
// to underlying storage device before any file is deleted
environment.flushAndSync()
val filesArray = filesToDelete.toArray()
environment.removeFiles(filesArray, if (ec.gcRenameFiles) RemoveBlockType.Rename else RemoveBlockType.Delete)
filesArray.forEach { utilizationProfile.removeFile(it) }
utilizationProfile.estimateTotalBytesAndWakeGcIfNecessary()
}
}
}
private fun doCleanFiles(fragmentedFiles: Iterator<Long>): Boolean {
// if there are no more files then even don't start a txn
if (!fragmentedFiles.hasNext()) {
return true
}
val guard = OOMGuard(softRef = false)
val txn: ReadWriteTransaction = try {
environment.beginGCTransaction()
} catch (_: ReadonlyTransactionException) {
return false
} catch (_: TransactionAcquireTimeoutException) {
return false
}
val cleanedFiles = PackedLongHashSet()
val isTxnExclusive = txn.isExclusive
try {
val started = System.currentTimeMillis()
while (fragmentedFiles.hasNext()) {
fragmentedFiles.next().let { file ->
cleanSingleFile(file, txn)
cleanedFiles.add(file)
}
if (!isTxnExclusive) {
break // do not process more than one file in a non-exclusive txn
}
if (started + ec.gcTransactionTimeout <= System.currentTimeMillis()) {
break // break by timeout
}
if (guard.isItCloseToOOM()) {
break // break because of the risk of OutOfMemoryError
}
}
if (!txn.forceFlush()) {
// paranoiac check
if (isTxnExclusive) {
throw ExodusException("Can't be: exclusive txn should be successfully flushed")
}
return false
}
} catch (_: ReadonlyTransactionException) {
return false
} catch (e: Throwable) {
throw ExodusException.toExodusException(e)
} finally {
txn.abort()
}
if (cleanedFiles.isNotEmpty()) {
for (file in cleanedFiles) {
if (isTxnExclusive) {
log.clearFileFromLogCache(file)
}
pendingFilesToDelete.add(file)
utilizationProfile.resetFile(file)
}
utilizationProfile.estimateTotalBytes()
environment.executeTransactionSafeTask {
val filesDeletionDelay = ec.gcFilesDeletionDelay
if (filesDeletionDelay == 0) {
queueDeletionOfFiles(cleanedFiles)
} else {
DeferredIO.getJobProcessor().queueIn(object : Job() {
override fun execute() {
queueDeletionOfFiles(cleanedFiles)
}
}, filesDeletionDelay.toLong())
}
}
}
return true
}
private fun queueDeletionOfFiles(cleanedFiles: PackedLongHashSet) {
for (file in cleanedFiles) {
deletionQueue.offer(file)
}
deletePendingFiles()
}
/**
* @param fileAddress address of the file to clean
* @param txn transaction
*/
private fun cleanSingleFile(fileAddress: Long, txn: ReadWriteTransaction) {
// the file can be already cleaned
if (isFileCleaned(fileAddress)) {
throw ExodusException("Attempt to clean already cleaned file")
}
loggingInfo {
"start cleanFile(${environment.location}${File.separatorChar}${LogUtil.getLogFilename(fileAddress)})" +
", free bytes = ${formatBytes(getFileFreeBytes(fileAddress))}"
}
val log = log
if (logger.isDebugEnabled) {
val high = log.highAddress
val highFile = log.highFileAddress
logger.debug(String.format(
"Cleaner acquired txn when log high address was: %d (%s@%d) when cleaning file %s",
high, LogUtil.getLogFilename(highFile), high - highFile, LogUtil.getLogFilename(fileAddress)
))
}
try {
val nextFileAddress = fileAddress + log.fileLengthBound
val loggables = log.getLoggableIterator(fileAddress)
while (loggables.hasNext()) {
val loggable = loggables.next()
if (loggable == null || loggable.address >= nextFileAddress) {
break
}
val structureId = loggable.structureId
if (structureId != Loggable.NO_STRUCTURE_ID && structureId != EnvironmentImpl.META_TREE_ID) {
var store = openStoresCache.get(structureId)
if (store == null) {
// TODO: remove openStoresCache when txn.openStoreByStructureId() is fast enough (XD-381)
store = txn.openStoreByStructureId(structureId)
openStoresCache[structureId] = store
}
store.reclaim(txn, loggable, loggables)
}
}
} catch (e: Throwable) {
logger.error("cleanFile(" + LogUtil.getLogFilename(fileAddress) + ')'.toString(), e)
throw e
}
}
companion object : KLogging() {
const val UTILIZATION_PROFILE_STORE_NAME = "exodus.gc.up"
@JvmStatic
fun isUtilizationProfile(storeName: String): Boolean {
return UTILIZATION_PROFILE_STORE_NAME == storeName
}
internal fun loggingInfo(message: () -> String) {
logger.info { message() }
}
internal fun loggingError(t: Throwable?, message: () -> String) {
if (t == null) {
logger.error { message() }
} else {
logger.error(t) { message() }
}
}
internal fun loggingDebug(message: () -> String) {
logger.debug { message() }
}
internal fun formatBytes(bytes: Long) = if (bytes == Long.MAX_VALUE) "Unknown" else "${bytes / 1000}Kb"
}
} | apache-2.0 | 6f04ddb98e8ef222ac8184d0144d5d16 | 35.486702 | 125 | 0.605992 | 4.892297 | false | false | false | false |
siosio/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/bridgeModelModifiableEntities.kt | 1 | 24400 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.impl.EntityDataDelegation
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.ModuleDependencyEntityDataDelegation
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlLibraryRootProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlListProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlNullableProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlProperty
import com.intellij.workspaceModel.storage.impl.references.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
private val LOG = logger<WorkspaceEntityStorage>()
class ModifiableModuleEntity : ModifiableWorkspaceEntityBase<ModuleEntity>() {
internal var dependencyChanged = false
var name: String by EntityDataDelegation()
var type: String? by EntityDataDelegation()
var dependencies: List<ModuleDependencyItem> by ModuleDependencyEntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleEntity(name: String, dependencies: List<ModuleDependencyItem>, source: EntitySource,
type: String? = null): ModuleEntity {
LOG.debug { "Add moduleEntity: $name" }
return addEntity(ModifiableModuleEntity::class.java, source) {
this.name = name
this.type = type
this.dependencies = dependencies
}
}
class ModifiableJavaModuleSettingsEntity : ModifiableWorkspaceEntityBase<JavaModuleSettingsEntity>() {
var inheritedCompilerOutput: Boolean by EntityDataDelegation()
var excludeOutput: Boolean by EntityDataDelegation()
var compilerOutput: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var compilerOutputForTests: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var languageLevelId: String? by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(JavaModuleSettingsEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addJavaModuleSettingsEntity(inheritedCompilerOutput: Boolean,
excludeOutput: Boolean,
compilerOutput: VirtualFileUrl?,
compilerOutputForTests: VirtualFileUrl?,
languageLevelId: String?,
module: ModuleEntity,
source: EntitySource) = addEntity(
ModifiableJavaModuleSettingsEntity::class.java, source) {
this.inheritedCompilerOutput = inheritedCompilerOutput
this.excludeOutput = excludeOutput
this.compilerOutput = compilerOutput
this.compilerOutputForTests = compilerOutputForTests
this.languageLevelId = languageLevelId
this.module = module
}
class ModifiableModuleCustomImlDataEntity : ModifiableWorkspaceEntityBase<ModuleCustomImlDataEntity>() {
var rootManagerTagCustomData: String? by EntityDataDelegation()
var customModuleOptions: MutableMap<String, String> by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(ModuleCustomImlDataEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addModuleCustomImlDataEntity(rootManagerTagCustomData: String?,
customModuleOptions: Map<String, String>,
module: ModuleEntity,
source: EntitySource) = addEntity(
ModifiableModuleCustomImlDataEntity::class.java, source) {
this.rootManagerTagCustomData = rootManagerTagCustomData
this.customModuleOptions = HashMap(customModuleOptions)
this.module = module
}
class ModifiableModuleGroupPathEntity : ModifiableWorkspaceEntityBase<ModuleGroupPathEntity>() {
var path: List<String> by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(ModuleGroupPathEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addModuleGroupPathEntity(path: List<String>,
module: ModuleEntity, source: EntitySource) = addEntity(
ModifiableModuleGroupPathEntity::class.java, source) {
this.path = path
this.module = module
}
class ModifiableSourceRootEntity : ModifiableWorkspaceEntityBase<SourceRootEntity>() {
var contentRoot: ContentRootEntity by MutableManyToOne.NotNull(SourceRootEntity::class.java, ContentRootEntity::class.java)
var url: VirtualFileUrl by VirtualFileUrlProperty()
var rootType: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addSourceRootEntity(contentRoot: ContentRootEntity,
url: VirtualFileUrl,
rootType: String, source: EntitySource) = addEntity(
ModifiableSourceRootEntity::class.java, source) {
this.contentRoot = contentRoot
this.url = url
this.rootType = rootType
}
class ModifiableJavaSourceRootEntity : ModifiableWorkspaceEntityBase<JavaSourceRootEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(JavaSourceRootEntity::class.java, SourceRootEntity::class.java)
var generated: Boolean by EntityDataDelegation()
var packagePrefix: String by EntityDataDelegation()
}
/**
* [JavaSourceRootEntity] has the same entity source as [SourceRootEntity].
* [JavaSourceRootEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun WorkspaceEntityStorageDiffBuilder.addJavaSourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
packagePrefix: String) = addEntity(
ModifiableJavaSourceRootEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.generated = generated
this.packagePrefix = packagePrefix
}
class ModifiableJavaResourceRootEntity : ModifiableWorkspaceEntityBase<JavaResourceRootEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(JavaResourceRootEntity::class.java, SourceRootEntity::class.java)
var generated: Boolean by EntityDataDelegation()
var relativeOutputPath: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addJavaResourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
relativeOutputPath: String) = addEntity(
ModifiableJavaResourceRootEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.generated = generated
this.relativeOutputPath = relativeOutputPath
}
class ModifiableCustomSourceRootPropertiesEntity : ModifiableWorkspaceEntityBase<CustomSourceRootPropertiesEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(CustomSourceRootPropertiesEntity::class.java, SourceRootEntity::class.java)
var propertiesXmlTag: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addCustomSourceRootPropertiesEntity(sourceRoot: SourceRootEntity, propertiesXmlTag: String) = addEntity(
ModifiableCustomSourceRootPropertiesEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.propertiesXmlTag = propertiesXmlTag
}
class ModifiableContentRootEntity : ModifiableWorkspaceEntityBase<ContentRootEntity>() {
var url: VirtualFileUrl by VirtualFileUrlProperty()
var excludedUrls: List<VirtualFileUrl> by VirtualFileUrlListProperty()
var excludedPatterns: List<String> by EntityDataDelegation()
var module: ModuleEntity by MutableManyToOne.NotNull(ContentRootEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addContentRootEntity(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity): ContentRootEntity {
return addContentRootEntityWithCustomEntitySource(url, excludedUrls, excludedPatterns, module, module.entitySource)
}
/**
* Entity source of content root is *almost* the same as the entity source of the corresponding module.
* Please update assertConsistency in [ContentRootEntityData] if you're using this method.
*/
fun WorkspaceEntityStorageDiffBuilder.addContentRootEntityWithCustomEntitySource(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity, source: EntitySource) = addEntity(
ModifiableContentRootEntity::class.java, source) {
this.url = url
this.excludedUrls = excludedUrls
this.excludedPatterns = excludedPatterns
this.module = module
}
class ModifiableLibraryEntity : ModifiableWorkspaceEntityBase<LibraryEntity>() {
var tableId: LibraryTableId by EntityDataDelegation()
var name: String by EntityDataDelegation()
var roots: List<LibraryRoot> by VirtualFileUrlLibraryRootProperty()
var excludedRoots: List<VirtualFileUrl> by VirtualFileUrlListProperty()
}
fun WorkspaceEntityStorageDiffBuilder.addLibraryEntity(name: String, tableId: LibraryTableId, roots: List<LibraryRoot>,
excludedRoots: List<VirtualFileUrl>, source: EntitySource) = addEntity(
ModifiableLibraryEntity::class.java, source) {
this.tableId = tableId
this.name = name
this.roots = roots
this.excludedRoots = excludedRoots
}
class ModifiableLibraryPropertiesEntity : ModifiableWorkspaceEntityBase<LibraryPropertiesEntity>() {
var library: LibraryEntity by MutableOneToOneChild.NotNull(LibraryPropertiesEntity::class.java, LibraryEntity::class.java)
var libraryType: String by EntityDataDelegation()
var propertiesXmlTag: String? by EntityDataDelegation()
}
/**
* [LibraryPropertiesEntity] has the same entity source as [LibraryEntity].
* [LibraryPropertiesEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun WorkspaceEntityStorageDiffBuilder.addLibraryPropertiesEntity(library: LibraryEntity,
libraryType: String,
propertiesXmlTag: String?) = addEntity(
ModifiableLibraryPropertiesEntity::class.java, library.entitySource) {
this.library = library
this.libraryType = libraryType
this.propertiesXmlTag = propertiesXmlTag
}
class ModifiableSdkEntity : ModifiableWorkspaceEntityBase<SdkEntity>() {
var library: LibraryEntity by MutableOneToOneChild.NotNull(SdkEntity::class.java, LibraryEntity::class.java)
var homeUrl: VirtualFileUrl by VirtualFileUrlProperty()
}
fun WorkspaceEntityStorageDiffBuilder.addSdkEntity(library: LibraryEntity,
homeUrl: VirtualFileUrl, source: EntitySource) = addEntity(ModifiableSdkEntity::class.java,
source) {
this.library = library
this.homeUrl = homeUrl
}
class ModifiableExternalSystemModuleOptionsEntity : ModifiableWorkspaceEntityBase<ExternalSystemModuleOptionsEntity>() {
var module: ModuleEntity by MutableOneToOneChild.NotNull(ExternalSystemModuleOptionsEntity::class.java, ModuleEntity::class.java)
var externalSystem: String? by EntityDataDelegation()
var externalSystemModuleVersion: String? by EntityDataDelegation()
var linkedProjectPath: String? by EntityDataDelegation()
var linkedProjectId: String? by EntityDataDelegation()
var rootProjectPath: String? by EntityDataDelegation()
var externalSystemModuleGroup: String? by EntityDataDelegation()
var externalSystemModuleType: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.getOrCreateExternalSystemModuleOptions(module: ModuleEntity,
source: EntitySource): ExternalSystemModuleOptionsEntity =
module.externalSystemOptions ?: addEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, source) {
this.module = module
}
class ModifiableFacetEntity : ModifiableWorkspaceEntityBase<FacetEntity>() {
var name: String by EntityDataDelegation()
var facetType: String by EntityDataDelegation()
var configurationXmlTag: String? by EntityDataDelegation()
var moduleId: ModuleId by EntityDataDelegation()
var module: ModuleEntity by MutableManyToOne.NotNull(FacetEntity::class.java, ModuleEntity::class.java)
var underlyingFacet: FacetEntity? by MutableManyToOne.Nullable(FacetEntity::class.java, FacetEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addFacetEntity(name: String, facetType: String, configurationXmlTag: String?, module: ModuleEntity,
underlyingFacet: FacetEntity?, source: EntitySource) =
addEntity(ModifiableFacetEntity::class.java, source) {
this.name = name
this.facetType = facetType
this.configurationXmlTag = configurationXmlTag
this.module = module
this.underlyingFacet = underlyingFacet
this.moduleId = module.persistentId()
}
class ModifiableArtifactEntity : ModifiableWorkspaceEntityBase<ArtifactEntity>() {
var name: String by EntityDataDelegation()
var artifactType: String by EntityDataDelegation()
var includeInProjectBuild: Boolean by EntityDataDelegation()
var outputUrl: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var rootElement: CompositePackagingElementEntity? by MutableOneToAbstractOneParent(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java)
var customProperties: Sequence<ArtifactPropertiesEntity> by customPropertiesDelegate
companion object {
val customPropertiesDelegate = MutableOneToMany<ArtifactEntity, ArtifactPropertiesEntity, ModifiableArtifactEntity>(ArtifactEntity::class.java, ArtifactPropertiesEntity::class.java, false)
}
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactEntity(name: String,
artifactType: String,
includeInProjectBuild: Boolean,
outputUrl: VirtualFileUrl?,
rootElement: CompositePackagingElementEntity,
source: EntitySource): ArtifactEntity {
return addEntity(ModifiableArtifactEntity::class.java, source) {
this.name = name
this.artifactType = artifactType
this.includeInProjectBuild = includeInProjectBuild
this.outputUrl = outputUrl
this.rootElement = rootElement
}
}
class ModifiableArtifactPropertiesEntity : ModifiableWorkspaceEntityBase<ArtifactPropertiesEntity>() {
var artifact: ArtifactEntity by MutableManyToOne.NotNull(ArtifactPropertiesEntity::class.java, ArtifactEntity::class.java)
var providerType: String by EntityDataDelegation()
var propertiesXmlTag: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactPropertiesEntity(artifact: ArtifactEntity,
providerType: String,
propertiesXmlTag: String?, source: EntitySource) = addEntity(
ModifiableArtifactPropertiesEntity::class.java, source) {
this.artifact = artifact
this.providerType = providerType
this.propertiesXmlTag = propertiesXmlTag
}
abstract class ModifiableCompositePackagingElementEntity<T: CompositePackagingElementEntity>(clazz: Class<T>) : ModifiableWorkspaceEntityBase<T>() {
var children: Sequence<PackagingElementEntity> by MutableOneToAbstractMany(clazz, PackagingElementEntity::class.java)
}
class ModifiableArtifactRootElementEntity : ModifiableCompositePackagingElementEntity<ArtifactRootElementEntity>(
ArtifactRootElementEntity::class.java
)
fun WorkspaceEntityStorageDiffBuilder.addArtifactRootElementEntity(children: List<PackagingElementEntity>,
source: EntitySource): ArtifactRootElementEntity {
return addEntity(ModifiableArtifactRootElementEntity::class.java, source) {
this.children = children.asSequence()
}
}
class ModifiableDirectoryPackagingElementEntity : ModifiableCompositePackagingElementEntity<DirectoryPackagingElementEntity>(
DirectoryPackagingElementEntity::class.java) {
var directoryName: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addDirectoryPackagingElementEntity(directoryName: String,
children: List<PackagingElementEntity>,
source: EntitySource): DirectoryPackagingElementEntity {
return addEntity(ModifiableDirectoryPackagingElementEntity::class.java, source) {
this.directoryName = directoryName
this.children = children.asSequence()
}
}
class ModifiableArchivePackagingElementEntity : ModifiableCompositePackagingElementEntity<ArchivePackagingElementEntity>(
ArchivePackagingElementEntity::class.java) {
var fileName: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArchivePackagingElementEntity(fileName: String,
children: List<PackagingElementEntity>,
source: EntitySource): ArchivePackagingElementEntity {
return addEntity(ModifiableArchivePackagingElementEntity::class.java, source) {
this.fileName = fileName
this.children = children.asSequence()
}
}
class ModifiableArtifactOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ArtifactOutputPackagingElementEntity>() {
var artifact: ArtifactId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactOutputPackagingElementEntity(artifact: ArtifactId?, source: EntitySource): ArtifactOutputPackagingElementEntity {
return addEntity(ModifiableArtifactOutputPackagingElementEntity::class.java, source) {
this.artifact = artifact
}
}
class ModifiableModuleOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleOutputPackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleOutputPackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleOutputPackagingElementEntity {
return addEntity(ModifiableModuleOutputPackagingElementEntity::class.java, source) {
this.module = module
}
}
class ModifiableLibraryFilesPackagingElementEntity : ModifiableWorkspaceEntityBase<LibraryFilesPackagingElementEntity>() {
var library: LibraryId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addLibraryFilesPackagingElementEntity(library: LibraryId?, source: EntitySource): LibraryFilesPackagingElementEntity {
return addEntity(ModifiableLibraryFilesPackagingElementEntity::class.java, source) {
this.library = library
}
}
class ModifiableModuleSourcePackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleSourcePackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleSourcePackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleSourcePackagingElementEntity {
return addEntity(ModifiableModuleSourcePackagingElementEntity::class.java, source) {
this.module = module
}
}
class ModifiableModuleTestOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleTestOutputPackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleTestOutputPackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleTestOutputPackagingElementEntity {
return addEntity(ModifiableModuleTestOutputPackagingElementEntity::class.java, source) {
this.module = module
}
}
abstract class ModifiableFileOrDirectoryPackagingElement<T : FileOrDirectoryPackagingElementEntity> : ModifiableWorkspaceEntityBase<T>() {
var filePath: VirtualFileUrl by VirtualFileUrlProperty()
}
class ModifiableDirectoryCopyPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<DirectoryCopyPackagingElementEntity>()
fun WorkspaceEntityStorageDiffBuilder.addDirectoryCopyPackagingElementEntity(filePath: VirtualFileUrl, source: EntitySource): DirectoryCopyPackagingElementEntity {
return addEntity(ModifiableDirectoryCopyPackagingElementEntity::class.java, source) {
this.filePath = filePath
}
}
class ModifiableExtractedDirectoryPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<ExtractedDirectoryPackagingElementEntity>() {
var pathInArchive: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addExtractedDirectoryPackagingElementEntity(filePath: VirtualFileUrl,
pathInArchive: String,
source: EntitySource): ExtractedDirectoryPackagingElementEntity {
return addEntity(ModifiableExtractedDirectoryPackagingElementEntity::class.java, source) {
this.filePath = filePath
this.pathInArchive = pathInArchive
}
}
class ModifiableFileCopyPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<FileCopyPackagingElementEntity>() {
var renamedOutputFileName: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addFileCopyPackagingElementEntity(filePath: VirtualFileUrl,
renamedOutputFileName: String?,
source: EntitySource): FileCopyPackagingElementEntity {
return addEntity(ModifiableFileCopyPackagingElementEntity::class.java, source) {
this.filePath = filePath
this.renamedOutputFileName = renamedOutputFileName
}
}
class ModifiableCustomPackagingElementEntity : ModifiableCompositePackagingElementEntity<CustomPackagingElementEntity>(CustomPackagingElementEntity::class.java) {
var typeId: String by EntityDataDelegation()
var propertiesXmlTag: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addCustomPackagingElementEntity(typeId: String,
propertiesXmlTag: String,
children: List<PackagingElementEntity>,
source: EntitySource): CustomPackagingElementEntity {
return addEntity(ModifiableCustomPackagingElementEntity::class.java, source) {
this.typeId = typeId
this.propertiesXmlTag = propertiesXmlTag
this.children = children.asSequence()
}
}
| apache-2.0 | a6af7951bc9cefc505218c4decf08577 | 52.159041 | 192 | 0.720451 | 6.989401 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/NotificationHeaderViewHolder.kt | 1 | 1947 | package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders
import android.graphics.drawable.Drawable
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.NotificationHeader
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.hashtag_notification_header_list_item.view.*
class NotificationHeaderViewHolder(
override val containerView: View,
val navigatorApi: NewNavigatorApi,
var collapseListener: (Boolean, String) -> Unit
) : androidx.recyclerview.widget.RecyclerView.ViewHolder(containerView), LayoutContainer {
val collapseDrawable: Drawable? by lazy {
val typedArray = containerView.context.obtainStyledAttributes(
arrayOf(
R.attr.collapseDrawable
).toIntArray()
)
val drawable = typedArray.getDrawable(0)
typedArray.recycle()
drawable
}
val expandDrawable: Drawable? by lazy {
val typedArray = containerView.context.obtainStyledAttributes(
arrayOf(
R.attr.expandDrawable
).toIntArray()
)
val drawable = typedArray.getDrawable(0)
typedArray.recycle()
drawable
}
fun bindView(tag: NotificationHeader) {
containerView.notificationTag.text = "#" + tag.tag
containerView.notificationCount.text = tag.notificationsCount.toString()
val drawable = if (tag.visible) collapseDrawable else expandDrawable
containerView.collapseButtonImageView.setImageDrawable(drawable)
containerView.collapseButtonImageView.setOnClickListener {
collapseListener(!tag.visible, tag.tag)
}
containerView.setOnClickListener {
navigatorApi.openTagActivity(tag.tag.removePrefix("#"))
}
}
} | mit | 52b256a99f3b60d77a2e77e6cad09bb8 | 36.461538 | 90 | 0.712892 | 5.178191 | false | false | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/sdk/PySdkToInstall.kt | 1 | 18084 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.google.common.hash.HashFunction
import com.google.common.hash.Hashing
import com.google.common.io.Files
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.util.ExecUtil.execAndGetOutput
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk.*
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.io.HttpRequests
import com.intellij.webcore.packaging.PackageManagementService
import com.intellij.webcore.packaging.PackagesNotificationPanel
import com.jetbrains.python.PyBundle
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.DownloadResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.InstallationResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.LookupResult
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkDownloadOnWindows
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkInstallationOnMac
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkInstallationOnWindows
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkLookupOnMac
import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkLookupOnWindows
import com.jetbrains.python.sdk.flavors.MacPythonSdkFlavor
import org.jetbrains.annotations.CalledInAny
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
private val LOGGER = Logger.getInstance(PySdkToInstall::class.java)
@CalledInAny
internal fun getSdksToInstall(): List<PySdkToInstall> {
return if (SystemInfo.isWindows) listOf(getPy39ToInstallOnWindows(), getPy310ToInstallOnWindows())
else if (SystemInfo.isMac) listOf(PySdkToInstallViaXCodeSelect())
else emptyList()
}
@RequiresEdt
fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>): Sdk? {
return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks) } else it }
}
@RequiresEdt
fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): Sdk? {
return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks, context) } else it }
}
private fun getPy39ToInstallOnWindows(): PySdkToInstallOnWindows {
val version = "3.9"
val name = "Python $version"
@Suppress("DEPRECATION") val hashFunction = Hashing.md5()
return PySdkToInstallOnWindows(
name,
version,
"https://www.python.org/ftp/python/3.9.10/python-3.9.10-amd64.exe",
28909456,
"747ac35ae667f4ec1ee3b001e9b7dbc6",
hashFunction,
"python-3.9.10-amd64.exe"
)
}
private fun getPy310ToInstallOnWindows(): PySdkToInstallOnWindows {
val version = "3.10"
val name = "Python $version"
@Suppress("DEPRECATION") val hashFunction = Hashing.md5()
return PySdkToInstallOnWindows(
name,
version,
"https://www.python.org/ftp/python/3.10.2/python-3.10.2-amd64.exe",
28239176,
"2b4fd1ed6e736f0e65572da64c17e020",
hashFunction,
"python-3.10.2-amd64.exe"
)
}
abstract class PySdkToInstall internal constructor(name: String, version: String)
: ProjectJdkImpl(name, PythonSdkType.getInstance(), null, version) {
/**
* Customize [renderer], which is typically either [com.intellij.ui.ColoredListCellRenderer] or [com.intellij.ui.ColoredTreeCellRenderer].
*/
@CalledInAny
abstract fun renderInList(renderer: SimpleColoredComponent)
@CalledInAny
@NlsContexts.DialogMessage
abstract fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String
@RequiresEdt
abstract fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk?
}
private class PySdkToInstallOnWindows(name: String,
private val version: String,
private val url: String,
private val size: Long,
private val hash: String,
private val hashFunction: HashFunction,
private val targetFileName: String) : PySdkToInstall(name, version) {
override fun renderInList(renderer: SimpleColoredComponent) {
renderer.append(name)
renderer.append(" $url", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) // NON-NLS
renderer.icon = AllIcons.Actions.Download
}
@NlsContexts.DialogMessage
override fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String {
val fileSize = StringUtil.formatFileSize(size)
return HtmlBuilder()
.append(PyBundle.message("python.sdk.executable.not.found.header"))
.append(tag("ul").children(
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.specify.path", text("...").bold(), "python.exe"))),
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.download.and.install",
text(defaultButtonName).bold(), fileSize)))
)).toString()
}
override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
try {
val project = module?.project
return ProgressManager.getInstance().run(
object : Task.WithResult<PyDetectedSdk?, Exception>(project, PyBundle.message("python.sdk.installing", name), true) {
override fun compute(indicator: ProgressIndicator): PyDetectedSdk? = install(project, systemWideSdksDetector, indicator)
}
)
}
catch (e: IOException) {
handleIOException(e)
}
catch (e: PyInstallationExecutionException) {
handleExecutionException(e)
}
catch (e: PyInstallationException) {
handleInstallationException(e)
}
return null
}
private fun install(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>, indicator: ProgressIndicator): PyDetectedSdk? {
val targetFile = File(PathManager.getTempPath(), targetFileName)
try {
indicator.text = PyBundle.message("python.sdk.downloading", targetFileName)
if (indicator.isCanceled) {
logSdkDownloadOnWindows(project, version, DownloadResult.CANCELLED)
return null
}
downloadInstaller(project, targetFile, indicator)
if (indicator.isCanceled) {
logSdkDownloadOnWindows(project, version, DownloadResult.CANCELLED)
return null
}
checkInstallerConsistency(project, targetFile)
logSdkDownloadOnWindows(project, version, DownloadResult.OK)
indicator.text = PyBundle.message("python.sdk.running", targetFileName)
indicator.text2 = PyBundle.message("python.sdk.installing.windows.warning")
indicator.isIndeterminate = true
if (indicator.isCanceled) {
logSdkInstallationOnWindows(project, version, InstallationResult.CANCELLED)
return null
}
runInstaller(project, targetFile, indicator)
logSdkInstallationOnWindows(project, version, InstallationResult.OK)
return findInstalledSdk(project, systemWideSdksDetector)
}
finally {
FileUtil.delete(targetFile)
}
}
private fun downloadInstaller(project: Project?, targetFile: File, indicator: ProgressIndicator) {
LOGGER.info("Downloading $url to $targetFile")
return try {
HttpRequests.request(url).saveToFile(targetFile, indicator)
}
catch (e: IOException) {
logSdkDownloadOnWindows(project, version, DownloadResult.EXCEPTION)
throw IOException("Failed to download $url to $targetFile.", e)
}
catch (e: ProcessCanceledException) {
logSdkDownloadOnWindows(project, version, DownloadResult.CANCELLED)
throw e
}
}
private fun checkInstallerConsistency(project: Project?, installer: File) {
LOGGER.debug("Checking installer size")
val sizeDiff = installer.length() - size
if (sizeDiff != 0L) {
logSdkDownloadOnWindows(project, version, DownloadResult.SIZE)
throw IOException("Downloaded $installer has incorrect size, difference is ${sizeDiff.absoluteValue} bytes.")
}
LOGGER.debug("Checking installer checksum")
val actualHashCode = Files.asByteSource(installer).hash(hashFunction).toString()
if (!actualHashCode.equals(hash, ignoreCase = true)) {
logSdkDownloadOnWindows(project, version, DownloadResult.CHECKSUM)
throw IOException("Checksums for $installer does not match. Actual value is $actualHashCode, expected $hash.")
}
}
private fun handleIOException(e: IOException) {
LOGGER.info(e)
e.message?.let {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
it,
null,
e.cause?.message,
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun runInstaller(project: Project?, installer: File, indicator: ProgressIndicator) {
val commandLine = GeneralCommandLine(installer.absolutePath, "/quiet")
LOGGER.info("Running ${commandLine.commandLineString}")
val output = runInstaller(project, commandLine, indicator)
if (output.isCancelled) logSdkInstallationOnWindows(project, version, InstallationResult.CANCELLED)
if (output.exitCode != 0) logSdkInstallationOnWindows(project, version, InstallationResult.EXIT_CODE)
if (output.isTimeout) logSdkInstallationOnWindows(project, version, InstallationResult.TIMEOUT)
if (output.exitCode != 0 || output.isTimeout) throw PyInstallationException(commandLine, output)
}
private fun handleInstallationException(e: PyInstallationException) {
val processOutput = e.output
processOutput.checkSuccess(LOGGER)
if (processOutput.isCancelled) {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.installation.has.been.cancelled.title", name),
PackageManagementService.ErrorDescription(
PyBundle.message("python.sdk.some.installed.python.components.might.get.inconsistent.after.cancellation"),
e.commandLine.commandLineString,
listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() },
PyBundle.message("python.sdk.consider.installing.python.manually")
)
)
}
else {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
if (processOutput.isTimeout) PyBundle.message("python.sdk.failed.to.install.timed.out")
else PyBundle.message("python.sdk.failed.to.install.exit.code", processOutput.exitCode),
e.commandLine.commandLineString,
listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() },
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun runInstaller(project: Project?, commandLine: GeneralCommandLine, indicator: ProgressIndicator): ProcessOutput {
try {
return CapturingProcessHandler(commandLine).runProcessWithProgressIndicator(indicator)
}
catch (e: ExecutionException) {
logSdkInstallationOnWindows(project, version, InstallationResult.EXCEPTION)
throw PyInstallationExecutionException(commandLine, e)
}
}
private fun handleExecutionException(e: PyInstallationExecutionException) {
LOGGER.info(e)
e.cause.message?.let {
PackagesNotificationPanel.showError(
PyBundle.message("python.sdk.failed.to.install.title", name),
PackageManagementService.ErrorDescription(
it,
e.commandLine.commandLineString,
null,
PyBundle.message("python.sdk.try.to.install.python.manually")
)
)
}
}
private fun findInstalledSdk(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
LOGGER.debug("Resetting system-wide sdks detectors")
resetSystemWideSdksDetectors()
return systemWideSdksDetector()
.also { sdks ->
LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } }
}
.also {
logSdkLookupOnWindows(
project,
version,
if (it.isEmpty()) LookupResult.NOT_FOUND else LookupResult.FOUND
)
}
.singleOrNull()
}
private class PyInstallationException(val commandLine: GeneralCommandLine, val output: ProcessOutput) : Exception()
private class PyInstallationExecutionException(val commandLine: GeneralCommandLine, override val cause: ExecutionException) : Exception()
}
private class PySdkToInstallViaXCodeSelect : PySdkToInstall("Python", "") {
override fun renderInList(renderer: SimpleColoredComponent) {
renderer.append(name)
renderer.append(" ")
renderer.append(PyBundle.message("python.cldt.installing.suggestion"), SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
@NlsContexts.DialogMessage
override fun getInstallationWarning(defaultButtonName: String): String {
val commandChunk = text(MacPythonSdkFlavor.getXCodeSelectInstallCommand().commandLineString)
return HtmlBuilder()
.append(PyBundle.message("python.sdk.executable.not.found.header"))
.append(tag("ul").children(
tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.specify.path", text("...").bold(), "python"))),
tag("li").children(raw(
PyBundle.message("python.sdk.executable.not.found.option.install.with.cldt", text(defaultButtonName).bold(), commandChunk.code())
)),
tag("li").children(text(PyBundle.message("python.sdk.executable.not.found.option.install.or.brew")))
)).toString()
}
override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? {
val project = module?.project
return ProgressManager.getInstance().run(
object : Task.WithResult<PyDetectedSdk?, Exception>(project, PyBundle.message("python.cldt.installing.title"), true) {
override fun compute(indicator: ProgressIndicator): PyDetectedSdk? {
@Suppress("DialogTitleCapitalization")
indicator.text = PyBundle.message("python.cldt.installing.indicator")
indicator.text2 = PyBundle.message("python.cldt.installing.skip")
runXCodeSelectInstall(project)
while (!MacPythonSdkFlavor.areCommandLineDeveloperToolsAvailable() && isInstallCommandLineDeveloperToolsAppRunning()) {
if (indicator.isCanceled) {
logSdkInstallationOnMac(project, InstallationResult.CANCELLED)
return null
}
Thread.sleep(TimeUnit.SECONDS.toMillis(5))
}
logSdkInstallationOnMac(
project,
if (MacPythonSdkFlavor.areCommandLineDeveloperToolsAvailable()) InstallationResult.OK else InstallationResult.EXIT_CODE
)
LOGGER.debug("Resetting system-wide sdks detectors")
resetSystemWideSdksDetectors()
return systemWideSdksDetector()
.also { sdks ->
LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } }
}
.also {
logSdkLookupOnMac(
project,
if (it.isEmpty()) LookupResult.NOT_FOUND else LookupResult.FOUND
)
}
.singleOrNull()
}
}
.also {
it.cancelText = IdeBundle.message("button.skip")
it.cancelTooltipText = IdeBundle.message("button.skip")
}
)
}
private fun runXCodeSelectInstall(project: Project?) {
val commandLine = MacPythonSdkFlavor.getXCodeSelectInstallCommand()
try {
execAndGetOutput(commandLine)
.also {
if (LOGGER.isDebugEnabled) {
LOGGER.debug("Result of '${commandLine.commandLineString}':\n$it")
}
}
}
catch (e: ExecutionException) {
logSdkInstallationOnMac(project, InstallationResult.EXCEPTION)
LOGGER.warn("Exception during '${commandLine.commandLineString}'", e)
}
}
private fun isInstallCommandLineDeveloperToolsAppRunning(): Boolean {
val appName = "Install Command Line Developer Tools.app"
return OSProcessUtil
.getProcessList()
.any { it.commandLine.contains(appName) }
.also {
if (LOGGER.isDebugEnabled) {
LOGGER.debug("'$appName' is${if (it) "" else " not"} running")
}
}
}
}
| apache-2.0 | b70919372ea6d935ee29c946ee3dda2b | 39.456376 | 140 | 0.718868 | 4.498507 | false | false | false | false |
NineWorlds/serenity-android | serenity-android-common/src/main/kotlin/us/nineworlds/serenity/common/android/mediacodec/MediaCodecInfoUtil.kt | 2 | 2995 | package us.nineworlds.serenity.common.android.mediacodec
import android.media.MediaCodecList
import android.util.Log
class MediaCodecInfoUtil {
val supportedContainers = hashMapOf(
"video/mkv" to true,
"video/mp4" to true,
"video/avi" to false,
"video/webm" to true,
"video/ogg" to true,
"video/mv4" to true
)
/**
* Logs to the logcat the available audio and video codecs that the device reports it supports.
* The log will contain the codec name, whether is supports encoding or decoding, and the mime type it matches too.
*
*/
fun logAvailableCodecs() {
val mediaCodecList = MediaCodecList(MediaCodecList.ALL_CODECS)
for (codec in mediaCodecList.codecInfos) {
val codeInfo = "Codec Name: ${codec.name}\nIs Encoder: ${codec.isEncoder}\n"
Log.d(MediaCodecInfoUtil::class.java.simpleName, codeInfo)
for (type in codec.supportedTypes) {
Log.d(MediaCodecInfoUtil::class.java.simpleName, " Type: ${type}")
}
}
}
/**
* Looks up a codec by mime type and returns whether the device supports
* the codec natively or not.
*
* @param mimeType The video or audio mimeType string for the codec
*/
fun isCodecSupported(mimeType: String): Boolean {
val mediaCodecList = MediaCodecList(MediaCodecList.ALL_CODECS)
for (codecInfo in mediaCodecList.codecInfos) {
Log.d(MediaCodecInfoUtil::class.java.simpleName, "Codec: ${codecInfo.name}" )
if (!codecInfo.isEncoder) {
val types: Array<String> = codecInfo.supportedTypes
for (type in types) {
Log.d(MediaCodecInfoUtil::class.java.simpleName, " Type: $type" )
if (type == mimeType) {
Log.d(MediaCodecInfoUtil::class.java.simpleName, "MimeType Found for $mimeType!")
return true
}
}
}
}
Log.d(MediaCodecInfoUtil::class.java.simpleName, "MimeType $mimeType not supported.")
return false
}
/**
* Checks to see if ExoPlayer supports the container type. This is different than the types that the device itself
* may support.
*/
fun isExoPlayerContainerSupported(mimeType: String) = if (supportedContainers.contains(mimeType)) {
supportedContainers.get(mimeType)
} else {
false
}
/**
* Find the correct video mimetype based off information that was returned to us by the server.
*
*/
fun findCorrectVideoMimeType(mimeType: String): String {
val videoMimeType = when (mimeType.substringAfter("video/").toLowerCase()) {
"mpeg-4" -> "video/mp4"
"mpeg4" -> "video/mp4v-es"
"h264" -> "video/avc"
"h263" -> "video/3gpp"
"mpeg2" -> "video/mpeg2"
else -> mimeType
}
return videoMimeType
}
fun findCorrectAudioMimeType(mimeType: String): String {
val audioMimType = when (mimeType.substringAfter("audio/").toLowerCase()) {
"mp3" -> "audio/mpeg"
"aac" -> "audio/mp4a-latm"
else -> mimeType
}
return audioMimType
}
} | mit | 595f07c7987b0de7d76660e161859453 | 30.536842 | 117 | 0.661102 | 3.884565 | false | false | false | false |
jwren/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenTreeStructureProvider.kt | 1 | 4668 | // 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.idea.maven.utils
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.ProjectRootsUtil
import com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode
import com.intellij.ide.projectView.impl.nodes.PsiFileNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager.Companion.getInstance
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiFile
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.SmartList
import com.intellij.util.ui.UIUtil
import org.jetbrains.idea.maven.importing.MavenProjectImporter.Companion.isImportToTreeStructureEnabled
import org.jetbrains.idea.maven.project.MavenProjectsManager
class MavenTreeStructureProvider : TreeStructureProvider, DumbAware {
override fun modify(parent: AbstractTreeNode<*>,
children: Collection<AbstractTreeNode<*>>,
settings: ViewSettings): Collection<AbstractTreeNode<*>> {
val project = parent.project ?: return children
val manager = MavenProjectsManager.getInstance(project)
if (!manager.isMavenizedProject) {
return children
}
if (parent is ProjectViewProjectNode || parent is PsiDirectoryNode) {
val modifiedChildren: MutableCollection<AbstractTreeNode<*>> = SmartList()
for (child in children) {
var childToAdd = child
if (child is PsiFileNode) {
if (child.virtualFile != null && MavenUtil.isPotentialPomFile(child.virtualFile!!.name)) {
val mavenProject = manager.findProject(child.virtualFile!!)
if (mavenProject != null) {
childToAdd = MavenPomFileNode(project, child.value, settings, manager.isIgnored(mavenProject))
}
}
}
if (isImportToTreeStructureEnabled(project) && child is PsiDirectoryNode && parent is PsiDirectoryNode) {
childToAdd = getMavenModuleNode(project, child, settings) ?: child
}
modifiedChildren.add(childToAdd)
}
return modifiedChildren
}
return children
}
private fun getMavenModuleNode(project: Project,
directoryNode: PsiDirectoryNode,
settings: ViewSettings): MavenModuleDirectoryNode? {
val psiDirectory = directoryNode.value ?: return null
val virtualFile = psiDirectory.virtualFile
if (!ProjectRootsUtil.isModuleContentRoot(virtualFile, project)) return null
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
val module = fileIndex.getModuleForFile(virtualFile)
if (!isMavenModule(module)) return null
val moduleShortName: String = getModuleShortName(module) ?: return null
return MavenModuleDirectoryNode(project, psiDirectory, settings, moduleShortName, directoryNode.filter)
}
private fun isMavenModule(module: Module?): Boolean {
return if (module != null && !module.isDisposed) getInstance(module).isMavenized() else false
}
private fun getModuleShortName(module: Module?): String? {
if (module != null) {
if (module.name.endsWith(".test")) {
return "test";
}
if (module.name.endsWith(".main")) {
return "main";
}
}
return null;
}
private inner class MavenPomFileNode(project: Project?,
value: PsiFile,
viewSettings: ViewSettings?,
val myIgnored: Boolean) : PsiFileNode(project, value, viewSettings) {
val strikeAttributes = SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, UIUtil.getInactiveTextColor())
override fun updateImpl(data: PresentationData) {
if (myIgnored) {
data.addText(value.name, strikeAttributes)
}
super.updateImpl(data)
}
@Suppress("DEPRECATION")
override fun getTestPresentation(): String? {
if (myIgnored) {
return "-MavenPomFileNode:" + super.getTestPresentation() + " (ignored)"
} else {
return "-MavenPomFileNode:" + super.getTestPresentation()
}
}
}
} | apache-2.0 | 56849bc1fa5047a260e48ac094dd4b90 | 43.04717 | 158 | 0.70587 | 4.944915 | false | false | false | false |
jwren/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarSlotManager.kt | 1 | 17459 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.CommonBundle
import com.intellij.execution.IS_RUN_MANAGER_INITIALIZED
import com.intellij.execution.RunManager
import com.intellij.execution.RunManagerListener
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.compound.CompoundRunConfiguration
import com.intellij.execution.impl.ExecutionManagerImpl
import com.intellij.execution.runToolbar.data.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.ide.ActivityTracker
import com.intellij.lang.LangBundle
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.CheckedDisposable
import com.intellij.openapi.util.Disposer
import com.intellij.ui.AppUIUtil
import com.intellij.util.messages.Topic
import java.util.*
import javax.swing.SwingUtilities
class RunToolbarSlotManager(val project: Project) {
companion object {
private val LOG = Logger.getInstance(RunToolbarSlotManager::class.java)
fun getInstance(project: Project): RunToolbarSlotManager = project.service()
@JvmField
@Topic.ProjectLevel
val RUN_TOOLBAR_SLOT_CONFIGURATION_MAP_TOPIC = Topic("RunToolbarWidgetSlotConfigurationMapChanged",
RWSlotsConfigurationListener::class.java)
}
private val runToolbarSettings = RunToolbarSettings.getInstance(project)
internal val slotListeners = RWSlotController()
internal val activeListener = RWAddedController()
internal val stateListeners = RWStateController()
internal var mainSlotData = SlotDate(UUID.randomUUID().toString())
val activeProcesses = RWActiveProcesses()
private val dataIds = mutableListOf<String>()
private val slotsData = mutableMapOf<String, SlotDate>()
private var activeDisposable: CheckedDisposable? = null
private val processController = RWProcessController(project)
internal var active: Boolean = false
set(value) {
if (field == value) return
field = value
if (value) {
if (RunToolbarProcess.logNeeded) LOG.info(
"ACTIVE SM settings: new on top ${runToolbarSettings.getMoveNewOnTop()}; update by selected ${getUpdateMainBySelected()} RunToolbar")
clear()
val disp = Disposer.newCheckedDisposable()
Disposer.register(project, disp)
activeDisposable = disp
val settingsData = runToolbarSettings.getConfigurations()
val slotOrder = settingsData.first
val configurations = settingsData.second
slotOrder.filter { configurations[it] != null }.forEachIndexed { index, s ->
if (index == 0) {
mainSlotData.updateId(s)
mainSlotData.configuration = configurations[s]
slotsData[mainSlotData.id] = mainSlotData
}
else {
addSlot(configurations[s], s)
}
}
if (RunToolbarProcess.logNeeded) LOG.info("SM restoreRunConfigurations: ${configurations.values} RunToolbar")
val con = project.messageBus.connect(disp)
con.subscribe(RunManagerListener.TOPIC, object : RunManagerListener {
override fun runConfigurationSelected(settings: RunnerAndConfigurationSettings?) {
if (!getUpdateMainBySelected() || mainSlotData.configuration == settings) return
mainSlotData.environment?.let {
val slot = addSlot(settings)
if (RunToolbarProcess.logNeeded) LOG.info("SM runConfigurationSelected: $settings first slot added RunToolbar")
moveToTop(slot.id)
} ?: kotlin.run {
mainSlotData.configuration = settings
if (RunToolbarProcess.logNeeded) LOG.info("SM runConfigurationSelected: $settings change main configuration RunToolbar")
update()
}
}
override fun runConfigurationRemoved(settings: RunnerAndConfigurationSettings) {
var changed = false
slotsData.filter { it.value == settings && it.value.environment == null }.forEach {
changed = true
it.value.configuration = RunManager.getInstance(project).selectedConfiguration
}
if (changed) {
update()
}
}
})
val executions = processController.getActiveExecutions()
executions.filter { it.isRunning() == true }.forEach { addNewProcess(it) }
activeListener.enabled()
update()
SwingUtilities.invokeLater {
ActivityTracker.getInstance().inc()
}
}
else {
activeDisposable?.let {
if (!it.isDisposed)
Disposer.dispose(it)
activeDisposable = null
}
activeListener.disabled()
clear()
if (RunToolbarProcess.logNeeded) LOG.info(
"INACTIVE SM RunToolbar")
}
slotListeners.rebuildPopup()
publishConfigurations(getConfigurationMap())
}
private fun getUpdateMainBySelected(): Boolean {
return runToolbarSettings.getUpdateMainBySelected()
}
private fun getMoveNewOnTop(executionEnvironment: ExecutionEnvironment): Boolean {
if (!runToolbarSettings.getMoveNewOnTop()) return false
val suppressValue = executionEnvironment.getUserData(RunToolbarData.RUN_TOOLBAR_SUPPRESS_MAIN_SLOT_USER_DATA_KEY) ?: false
return !suppressValue
}
private fun clear() {
dataIds.clear()
slotsData.clear()
slotsData[mainSlotData.id] = mainSlotData
activeProcesses.clear()
state = RWSlotManagerState.INACTIVE
}
private fun traceState() {
if (!RunToolbarProcess.logNeeded) return
val separator = " "
val ids = dataIds.indices.mapNotNull { "${it + 1}: ${slotsData[dataIds[it]]}" }.joinToString(", ")
LOG.info("SM state: $state" +
"${separator}== slots: 0: ${mainSlotData}, $ids" +
"${separator}== slotsData: ${slotsData.values} RunToolbar")
}
init {
SwingUtilities.invokeLater {
if (project.isDisposed) return@invokeLater
slotsData[mainSlotData.id] = mainSlotData
activeListener.addListener(RunToolbarShortcutHelper(project))
Disposer.register(project) {
activeListener.clear()
stateListeners.clear()
slotListeners.clear()
}
}
}
private fun update() {
saveSlotsConfiguration()
updateState()
if (!RunToolbarProcess.logNeeded) return
LOG.trace("!!!!!UPDATE RunToolbar")
}
internal fun startWaitingForAProcess(slotDate: RunToolbarData, settings: RunnerAndConfigurationSettings, executorId: String) {
slotsData.values.forEach {
val waitingForAProcesses = it.waitingForAProcesses
if (slotDate == it) {
waitingForAProcesses.start(project, settings, executorId)
}
else {
if (waitingForAProcesses.isWaitingForASubProcess(settings, executorId)) {
waitingForAProcesses.clear()
}
}
}
}
internal fun getMainOrFirstActiveProcess(): RunToolbarProcess? {
return mainSlotData.environment?.getRunToolbarProcess() ?: activeProcesses.processes.keys.firstOrNull()
}
internal fun slotsCount(): Int {
return dataIds.size
}
private var state: RWSlotManagerState = RWSlotManagerState.INACTIVE
set(value) {
if (value == field) return
field = value
traceState()
stateListeners.stateChanged(value)
}
private fun updateState() {
state = when (activeProcesses.getActiveCount()) {
0 -> RWSlotManagerState.INACTIVE
1 -> {
mainSlotData.environment?.let {
RWSlotManagerState.SINGLE_MAIN
} ?: RWSlotManagerState.SINGLE_PLAIN
}
else -> {
mainSlotData.environment?.let {
RWSlotManagerState.MULTIPLE_WITH_MAIN
} ?: RWSlotManagerState.MULTIPLE
}
}
}
internal fun getState(): RWSlotManagerState {
return state
}
private fun getAppropriateSettings(env: ExecutionEnvironment): Iterable<SlotDate> {
val sortedSlots = mutableListOf<SlotDate>()
sortedSlots.add(mainSlotData)
sortedSlots.addAll(dataIds.mapNotNull { slotsData[it] }.toList())
return sortedSlots.filter { it.configuration == env.runnerAndConfigurationSettings }
}
internal fun processNotStarted(env: ExecutionEnvironment) {
val config = env.runnerAndConfigurationSettings ?: return
val appropriateSettings = getAppropriateSettings(env)
val emptySlotsWithConfiguration = appropriateSettings.filter { it.environment == null }
emptySlotsWithConfiguration.map { it.waitingForAProcesses }.firstOrNull {
it.isWaitingForASingleProcess(config, env.executor.id)
}?.clear() ?: run {
slotsData.values.filter { it.configuration?.configuration is CompoundRunConfiguration }.firstOrNull { slotsData ->
slotsData.waitingForAProcesses.isWaitingForASubProcess(config, env.executor.id)
}?.clear()
}
}
internal fun processStarted(env: ExecutionEnvironment) {
addNewProcess(env)
update()
SwingUtilities.invokeLater {
ActivityTracker.getInstance().inc()
}
}
private fun addNewProcess(env: ExecutionEnvironment) {
val appropriateSettings = getAppropriateSettings(env)
val emptySlotsWithConfiguration = appropriateSettings.filter { it.environment == null }
var newSlot = false
val slot = appropriateSettings.firstOrNull { it.environment?.executionId == env.executionId }
?: emptySlotsWithConfiguration.firstOrNull { slotData ->
env.runnerAndConfigurationSettings?.let {
slotData.waitingForAProcesses.isWaitingForASingleProcess(it, env.executor.id)
} ?: false
}
?: emptySlotsWithConfiguration.firstOrNull()
?: kotlin.run {
newSlot = true
addSlot(env.runnerAndConfigurationSettings)
}
slot.environment = env
activeProcesses.updateActiveProcesses(slotsData)
if (newSlot) {
val isCompoundProcess = slotsData.values.filter { it.configuration?.configuration is CompoundRunConfiguration }.firstOrNull { slotsData ->
env.runnerAndConfigurationSettings?.let {
slotsData.waitingForAProcesses.checkAndUpdate(it, env.executor.id)
} ?: false
} != null
if (!isCompoundProcess) {
if (getMoveNewOnTop(env)) {
moveToTop(slot.id)
}
}
}
}
fun processTerminating(env: ExecutionEnvironment) {
slotsData.values.firstOrNull { it.environment?.executionId == env.executionId }?.let {
it.environment = env
}
activeProcesses.updateActiveProcesses(slotsData)
updateState()
SwingUtilities.invokeLater {
ActivityTracker.getInstance().inc()
}
}
fun processTerminated(executionId: Long) {
slotsData.values.firstOrNull { it.environment?.executionId == executionId }?.let { slotDate ->
val removable = slotDate.environment?.runnerAndConfigurationSettings?.let {
!RunManager.getInstance(project).hasSettings(it)
} ?: true
if (removable) {
if (slotDate == mainSlotData && slotsData.size == 1) {
slotDate.clear()
slotDate.configuration = RunManager.getInstance(project).selectedConfiguration
}
else {
removeSlot(slotDate.id)
}
}
else {
slotDate.environment = null
}
}
if (RunToolbarProcess.logNeeded) LOG.info("SM process stopped: $executionId RunToolbar")
activeProcesses.updateActiveProcesses(slotsData)
updateState()
SwingUtilities.invokeLater {
ActivityTracker.getInstance().inc()
}
}
internal fun addAndSaveSlot(): SlotDate {
val slot = addSlot()
saveSlotsConfiguration()
return slot
}
private fun addSlot(configuration: RunnerAndConfigurationSettings? = null, id: String = UUID.randomUUID().toString()): SlotDate {
val slot = SlotDate(id)
slot.configuration = configuration
dataIds.add(slot.id)
slotsData[slot.id] = slot
slotListeners.slotAdded()
return slot
}
internal fun getData(index: Int): SlotDate? {
return if (index >= 0 && index < dataIds.size) {
dataIds[index].let {
slotsData[it]
}
}
else null
}
internal fun moveToTop(id: String) {
if (mainSlotData.id == id) return
slotsData[id]?.let { newMain ->
val oldMain = mainSlotData
mainSlotData = newMain
dataIds.remove(id)
dataIds.add(0, oldMain.id)
}
update()
}
internal fun removeSlot(id: String) {
val index = dataIds.indexOf(id)
fun remove() {
if (id == mainSlotData.id) {
if (dataIds.isNotEmpty()) {
val firstSlotId = dataIds[0]
slotsData[firstSlotId]?.let {
mainSlotData = it
slotsData.remove(id)
dataIds.remove(it.id)
}
}
}
else {
slotsData.remove(id)
dataIds.remove(id)
}
SwingUtilities.invokeLater {
slotListeners.slotRemoved(index)
ActivityTracker.getInstance().inc()
}
}
(if (index >= 0) getData(index) else if (mainSlotData.id == id) mainSlotData else null)?.let { slotDate ->
slotDate.environment?.let {
if (it.isRunning() != true) {
remove()
}
else if (Messages.showOkCancelDialog(
project,
LangBundle.message("run.toolbar.remove.active.process.slot.message"),
LangBundle.message("run.toolbar.remove.active.process.slot.title", it.runnerAndConfigurationSettings?.name ?: ""),
LangBundle.message("run.toolbar.remove.active.process.slot.ok"),
CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon()/*, object : DialogWrapper.DoNotAskOption.Adapter() {
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
}
}*/) == Messages.OK) {
it.contentToReuse?.let {
ExecutionManagerImpl.stopProcess(it)
}
remove()
}
} ?: run {
remove()
}
} ?: slotListeners.rebuildPopup()
update()
}
internal fun configurationChanged(slotId: String, configuration: RunnerAndConfigurationSettings?) {
AppUIUtil.invokeLaterIfProjectAlive(project) {
project.messageBus.syncPublisher(RUN_TOOLBAR_SLOT_CONFIGURATION_MAP_TOPIC).configurationChanged(slotId, configuration)
}
saveSlotsConfiguration()
}
private fun saveSlotsConfiguration() {
if (IS_RUN_MANAGER_INITIALIZED.get(project) == true) {
val runManager = RunManager.getInstance(project)
mainSlotData.configuration?.let {
if (runManager.hasSettings(it) &&
it != runManager.selectedConfiguration &&
mainSlotData.environment?.getRunToolbarProcess()?.isTemporaryProcess() != true) {
runManager.selectedConfiguration = mainSlotData.configuration
if (RunToolbarProcess.logNeeded) LOG.info(
"MANAGER saveSlotsConfiguration. change selected configuration by main: ${mainSlotData.configuration} RunToolbar")
}
}
}
val slotOrder = getSlotOrder()
val configurations = getConfigurationMap(slotOrder)
if (RunToolbarProcess.logNeeded) LOG.info("MANAGER saveSlotsConfiguration: ${configurations} RunToolbar")
runToolbarSettings.setConfigurations(configurations, slotOrder)
publishConfigurations(configurations)
}
private fun getSlotOrder(): List<String> {
val list = mutableListOf<String>()
list.add(mainSlotData.id)
list.addAll(dataIds)
return list
}
private fun getConfigurationMap(slotOrder: List<String>): Map<String, RunnerAndConfigurationSettings?> {
return slotOrder.associateWith { slotsData[it]?.configuration }
}
fun getConfigurationMap(): Map<String, RunnerAndConfigurationSettings?> {
return getConfigurationMap(getSlotOrder())
}
private fun publishConfigurations(slotConfigurations: Map<String, RunnerAndConfigurationSettings?>) {
AppUIUtil.invokeLaterIfProjectAlive(project) {
project.messageBus.syncPublisher(RUN_TOOLBAR_SLOT_CONFIGURATION_MAP_TOPIC).slotsConfigurationChanged(slotConfigurations)
}
}
}
internal open class SlotDate(override var id: String) : RunToolbarData {
companion object {
var index = 0
}
fun updateId(value: String) {
id = value
}
override var configuration: RunnerAndConfigurationSettings? = null
get() = environment?.runnerAndConfigurationSettings ?: field
override var environment: ExecutionEnvironment? = null
set(value) {
if (field != value)
field = value
value?.let {
configuration = it.runnerAndConfigurationSettings
} ?: run {
waitingForAProcesses.clear()
}
}
override val waitingForAProcesses = RWWaitingForAProcesses()
override fun clear() {
environment = null
waitingForAProcesses.clear()
}
override fun toString(): String {
return "$id-${environment?.let { "$it [${it.executor.actionName} ${it.executionId}]" } ?: configuration?.configuration?.name ?: "configuration null"}"
}
}
| apache-2.0 | dc30935db4a978f68a7f785f4e99435e | 31.694757 | 158 | 0.675125 | 5.063515 | false | true | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/util/api/Datamuse.kt | 1 | 2865 | package totoro.yui.util.api
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import totoro.yui.util.api.data.Definition
import totoro.yui.util.api.data.Phonetics
import java.net.URL
import java.net.URLEncoder
object Datamuse {
private const val charset = "UTF-8"
fun definition(word: String, partOfSpeech: List<String>, exclude: List<String>): Definition? {
val raw = URL("https://api.datamuse.com/words?sp=${URLEncoder.encode(word, charset)}&md=d").readText()
@Suppress("UNCHECKED_CAST")
val array = Parser().parse(StringBuilder(raw)) as JsonArray<JsonObject>
return if (array.isNotEmpty()) {
val json = array.first()
val subj = json.string("word")
val defs = json.array<String>("defs")
if (defs != null && defs.isNotEmpty()) {
val filteredDefs = (
if (partOfSpeech.isEmpty()) defs
else defs.filter { def -> partOfSpeech.any { part -> def.startsWith(part) } }
).filterNot { exclude.any { def -> it.endsWith(def) } }
if (filteredDefs.isNotEmpty()) {
val def = filteredDefs[Math.round(Math.random() * (filteredDefs.size - 1)).toInt()]
.split("\t")
Definition(subj.orEmpty(), def[0], def[1])
} else null
} else null
} else null
}
private fun searchfor(option: String, value: String): List<String> {
val raw = URL("https://api.datamuse.com/words?$option=${URLEncoder.encode(value, charset)}").readText()
@Suppress("UNCHECKED_CAST")
val array = Parser().parse(StringBuilder(raw)) as JsonArray<JsonObject>
return array.mapNotNull { it.string("word") }
}
fun thesaurus(word: String): List<String> = searchfor("rel_syn", word)
fun antonyms(word: String): List<String> = searchfor("rel_ant", word)
fun word(definition: String): List<String> = searchfor("ml", definition)
fun rhyme(word: String): List<String> = searchfor("rel_rhy", word)
fun describe(word: String): List<String> = searchfor("rel_jjb", word)
fun phonetics(word: String): Phonetics? {
val raw = URL("https://api.datamuse.com/words?sp=${URLEncoder.encode(word, charset)}&md=r&ipa=1").readText()
@Suppress("UNCHECKED_CAST")
val array = Parser().parse(StringBuilder(raw)) as JsonArray<JsonObject>
return if (array.isNotEmpty()) {
val json = array.first()
val subj = json.string("word")
val tags = json.array<String>("tags")
if (tags != null && tags.size >= 2) {
val phonetics = tags[1].drop(9)
return Phonetics(subj.orEmpty(), phonetics)
} else null
} else null
}
}
| mit | be1d7a5074ea2061fcf7a3c60993626d | 41.761194 | 116 | 0.598255 | 3.892663 | false | false | false | false |
androidx/androidx | compose/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/integration/macrobenchmark/target/LazyColumnActivity.kt | 3 | 3347 | /*
* Copyright 2020 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.integration.macrobenchmark.target
import android.os.Bundle
import android.view.Choreographer
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.Checkbox
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Recomposer
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
class LazyColumnActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val itemCount = intent.getIntExtra(EXTRA_ITEM_COUNT, 3000)
val entries = List(itemCount) { Entry("Item $it") }
setContent {
LazyColumn(
modifier = Modifier.fillMaxWidth().semantics { contentDescription = "IamLazy" }
) {
items(entries) {
ListRow(it)
}
}
}
launchIdlenessTracking()
}
companion object {
const val EXTRA_ITEM_COUNT = "ITEM_COUNT"
}
}
internal fun ComponentActivity.launchIdlenessTracking() {
val contentView: View = findViewById(android.R.id.content)
val callback: Choreographer.FrameCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (Recomposer.runningRecomposers.value.any { it.hasPendingWork }) {
contentView.contentDescription = "COMPOSE-BUSY"
} else {
contentView.contentDescription = "COMPOSE-IDLE"
}
Choreographer.getInstance().postFrameCallback(this)
}
}
Choreographer.getInstance().postFrameCallback(callback)
}
@Composable
private fun ListRow(entry: Entry) {
Card(modifier = Modifier.padding(8.dp)) {
Row {
Text(
text = entry.contents,
modifier = Modifier.padding(16.dp)
)
Spacer(modifier = Modifier.weight(1f, fill = true))
Checkbox(
checked = false,
onCheckedChange = {},
modifier = Modifier.padding(16.dp)
)
}
}
}
data class Entry(val contents: String)
| apache-2.0 | 14a7db878ac5e8b25618797dc871db75 | 33.153061 | 95 | 0.686884 | 4.66156 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsGroupsActionGroup.kt | 6 | 995 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vcs.ProjectLevelVcsManager
class VcsGroupsActionGroup : DefaultActionGroup(), DumbAware {
override fun update(e: AnActionEvent) {
val presentation = e.presentation
val project = e.project
if (project != null) {
presentation.text = ProjectLevelVcsManager.getInstance(project).consolidatedVcsName
}
presentation.isEnabledAndVisible = project != null && project.isTrusted()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
} | apache-2.0 | 1fa114fbe888e2aeaa5021df9325ed4d | 38.84 | 158 | 0.792965 | 4.806763 | false | false | false | false |
jwren/intellij-community | platform/testFramework/src/com/intellij/testFramework/FixtureRule.kt | 1 | 19074 | // 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.testFramework
import com.intellij.configurationStore.LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.DocumentReferenceManager
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.roots.impl.libraries.LibraryTableTracker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker
import com.intellij.project.TestProjectManager
import com.intellij.project.stateStore
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.isDirectory
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.throwIfNotEmpty
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.rules.ExternalResource
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.lang.annotation.Inherited
import java.nio.file.Path
private var sharedModule: Module? = null
open class ApplicationRule : TestRule {
companion object {
init {
Logger.setFactory(TestLoggerFactory::class.java)
}
}
final override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
before(description)
try {
base.evaluate()
}
finally {
after()
}
}
}
}
protected open fun before(description: Description) {
TestApplicationManager.getInstance()
}
protected open fun after() {
}
}
open class ApplicationExtension : BeforeAllCallback, AfterAllCallback {
companion object {
init {
Logger.setFactory(TestLoggerFactory::class.java)
}
}
override fun beforeAll(context: ExtensionContext) {
TestApplicationManager.getInstance()
}
override fun afterAll(context: ExtensionContext) {}
}
/**
* Rule should be used only and only if you open projects in a custom way in test cases and cannot use [ProjectRule].
*/
class ProjectTrackingRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
(ProjectManager.getInstance() as TestProjectManager).startTracking().use {
base.evaluate()
}
}
}
}
}
class ProjectObject(private val runPostStartUpActivities: Boolean = false,
private val preloadServices: Boolean = false,
private val projectDescriptor: LightProjectDescriptor? = null) {
internal var sharedProject: ProjectEx? = null
internal var testClassName: String? = null
var virtualFilePointerTracker: VirtualFilePointerTracker? = null
var libraryTracker: LibraryTableTracker? = null
var projectTracker: AccessToken? = null
internal fun createProject(): ProjectEx {
val projectFile = TemporaryDirectory.generateTemporaryPath("project_${testClassName}${ProjectFileType.DOT_DEFAULT_EXTENSION}")
val options = createTestOpenProjectOptions(runPostStartUpActivities = runPostStartUpActivities).copy(preloadServices = preloadServices)
val project = (ProjectManager.getInstance() as TestProjectManager).openProject(projectFile, options) as ProjectEx
virtualFilePointerTracker = VirtualFilePointerTracker()
libraryTracker = LibraryTableTracker()
return project
}
internal fun catchAndRethrow(l: MutableList<Throwable>) {
l.catchAndStoreExceptions { sharedProject?.let { PlatformTestUtil.forceCloseProjectWithoutSaving(it) } }
l.catchAndStoreExceptions { projectTracker?.finish() }
l.catchAndStoreExceptions { virtualFilePointerTracker?.assertPointersAreDisposed() }
l.catchAndStoreExceptions { libraryTracker?.assertDisposed() }
l.catchAndStoreExceptions {
sharedProject = null
sharedModule = null
}
throwIfNotEmpty(l)
}
val projectIfOpened: ProjectEx?
get() = sharedProject
val project: ProjectEx
get() {
var result = sharedProject
if (result == null) {
synchronized(this) {
result = sharedProject
if (result == null) {
result = createProject()
sharedProject = result
}
}
}
return result!!
}
val module: Module
get() {
var result = sharedModule
if (result == null) {
runInEdtAndWait {
(projectDescriptor ?: LightProjectDescriptor()).setUpProject(project, object : LightProjectDescriptor.SetupHandler {
override fun moduleCreated(module: Module) {
result = module
sharedModule = module
}
})
}
}
return result!!
}
}
class ProjectRule(private val runPostStartUpActivities: Boolean = false,
preloadServices: Boolean = false,
projectDescriptor: LightProjectDescriptor? = null) : ApplicationRule() {
companion object {
@JvmStatic
fun withoutRunningStartUpActivities() = ProjectRule(runPostStartUpActivities = false)
@JvmStatic
fun withRunningStartUpActivities() = ProjectRule(runPostStartUpActivities = true)
/**
* Think twice before use. And then do not use. To support old code.
*/
@ApiStatus.Internal
fun createStandalone(): ProjectRule {
val result = ProjectRule()
result.before(Description.EMPTY)
return result
}
}
private val projectObject = ProjectObject(runPostStartUpActivities, preloadServices, projectDescriptor)
override fun before(description: Description) {
super.before(description)
projectObject.testClassName = sanitizeFileName(description.className.substringAfterLast('.'))
projectObject.projectTracker = (ProjectManager.getInstance() as TestProjectManager).startTracking()
}
override fun after() {
val l = mutableListOf<Throwable>()
l.catchAndStoreExceptions { super.after() }
projectObject.catchAndRethrow(l)
}
/**
* Think twice before use. And then do not use. To support old code.
*/
@ApiStatus.Internal
fun close() {
after()
}
val projectIfOpened: ProjectEx?
get() = projectObject.projectIfOpened
val project: ProjectEx
get() = projectObject.project
val module: Module
get() = projectObject.module
}
/**
* Encouraged using on static fields to avoid project creating for each test.
* Project created on request, so, could be used as a bare (only application).
*/
class ProjectExtension(runPostStartUpActivities: Boolean = false,
preloadServices: Boolean = false,
projectDescriptor: LightProjectDescriptor? = null) : ApplicationExtension() {
private val projectObject = ProjectObject(runPostStartUpActivities, preloadServices, projectDescriptor)
override fun beforeAll(context: ExtensionContext) {
super.beforeAll(context)
projectObject.testClassName = sanitizeFileName(context.testClass.map { it.simpleName }.orElse(context.displayName).substringAfterLast('.'))
projectObject.projectTracker = (ProjectManager.getInstance() as TestProjectManager).startTracking()
}
override fun afterAll(context: ExtensionContext) {
val l = mutableListOf<Throwable>()
l.catchAndStoreExceptions { super.afterAll(context) }
projectObject.catchAndRethrow(l)
}
val projectIfOpened: ProjectEx?
get() = projectObject.sharedProject
val project: ProjectEx
get() = projectObject.project
val module: Module
get() = projectObject.module
}
/**
* rules: outer, middle, inner
* out:
* starting outer rule
* starting middle rule
* starting inner rule
* finished inner rule
* finished middle rule
* finished outer rule
*/
class RuleChain(vararg val rules: TestRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
var statement = base
for (i in (rules.size - 1) downTo 0) {
statement = rules[i].apply(statement, description)
}
return statement
}
}
private fun <T : Annotation> Description.getOwnOrClassAnnotation(annotationClass: Class<T>) = getAnnotation(annotationClass) ?: testClass?.getAnnotation(annotationClass)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
@Inherited
annotation class RunsInEdt
class EdtRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInEdt::class.java) == null) {
base
}
else {
statement { runInEdtAndWait { base.evaluate() } }
}
}
}
class InitInspectionRule : TestRule {
override fun apply(base: Statement, description: Description): Statement = statement { runInInitMode { base.evaluate() } }
}
inline fun statement(crossinline runnable: () -> Unit): Statement = object : Statement() {
override fun evaluate() {
runnable()
}
}
/**
* Do not optimise test load speed.
* @see IProjectStore.setOptimiseTestLoadSpeed
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInActiveStoreMode
class ActiveStoreRule(private val projectRule: ProjectRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
if (description.getOwnOrClassAnnotation(RunsInActiveStoreMode::class.java) == null) {
return base
}
else {
return statement {
projectRule.project.runInLoadComponentStateMode { base.evaluate() }
}
}
}
}
/**
* In test mode component state is not loaded. Project or module store will load component state if project/module file exists.
* So must be a strong reason to explicitly use this method.
*/
inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T {
val store = stateStore
val isModeDisabled = store.isOptimiseTestLoadSpeed
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = false
}
try {
return task()
}
finally {
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = true
}
}
}
inline fun <T> Project.use(task: (Project) -> T): T =
try {
task(this)
}
finally {
PlatformTestUtil.forceCloseProjectWithoutSaving(this)
}
class DisposeNonLightProjectsRule : ExternalResource() {
override fun after() {
val projectManager = ProjectManagerEx.getInstanceExIfCreated() ?: return
projectManager.openProjects.forEachGuaranteed {
if (!ProjectManagerImpl.isLight(it)) {
ApplicationManager.getApplication().invokeAndWait {
projectManager.forceCloseProject(it)
}
}
}
}
}
class DisposeModulesRule(private val projectRule: ProjectRule) : ExternalResource() {
override fun after() {
val project = projectRule.projectIfOpened ?: return
val moduleManager = ModuleManager.getInstance(project)
ApplicationManager.getApplication().invokeAndWait {
moduleManager.modules.forEachGuaranteed {
if (!it.isDisposed && it !== sharedModule) {
moduleManager.disposeModule(it)
}
}
}
}
}
/**
* Only and only if "before" logic in case of exception doesn't require "after" logic - must be no side effects if "before" finished abnormally.
* So, should be one task per rule.
*/
class WrapRule(private val before: () -> () -> Unit) : TestRule {
override fun apply(base: Statement, description: Description): Statement = statement {
val after = before()
try {
base.evaluate()
}
finally {
after()
}
}
}
fun createProjectAndUseInLoadComponentStateMode(tempDirManager: TemporaryDirectory,
directoryBased: Boolean = false,
useDefaultProjectSettings: Boolean = true,
task: (Project) -> Unit) {
val file = tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}", refreshVfs = true)
val project = ProjectManagerEx.getInstanceEx().openProject(file, createTestOpenProjectOptions().copy(
isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectSettings,
beforeInit = { it.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true) }
))!!
project.use {
project.runInLoadComponentStateMode {
task(project)
}
}
}
suspend fun loadAndUseProjectInLoadComponentStateMode(tempDirManager: TemporaryDirectory,
projectCreator: (suspend (VirtualFile) -> Path)? = null,
task: suspend (Project) -> Unit) {
createOrLoadProject(tempDirManager, projectCreator, task = task, directoryBased = false, loadComponentState = true)
}
fun refreshProjectConfigDir(project: Project) {
LocalFileSystem.getInstance().findFileByNioFile(project.stateStore.directoryStorePath!!)!!.refresh(false, true)
}
suspend fun <T> runNonUndoableWriteAction(file: VirtualFile, runnable: suspend () -> T): T {
return runUndoTransparentWriteAction {
val result = runBlocking { runnable() }
val documentReference = DocumentReferenceManager.getInstance().create(file)
val undoManager = UndoManager.getGlobalInstance() as UndoManagerImpl
undoManager.nonundoableActionPerformed(documentReference, false)
result
}
}
suspend fun createOrLoadProject(tempDirManager: TemporaryDirectory,
projectCreator: (suspend (VirtualFile) -> Path)? = null,
directoryBased: Boolean = true,
loadComponentState: Boolean = false,
useDefaultProjectSettings: Boolean = true,
task: suspend (Project) -> Unit) {
val file = if (projectCreator == null) {
tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}", refreshVfs = false)
}
else {
val dir = tempDirManager.createVirtualDir()
withContext(AppUIExecutor.onWriteThread().coroutineDispatchingContext()) {
runNonUndoableWriteAction(dir) {
projectCreator(dir)
}
}
}
createOrLoadProject(file, useDefaultProjectSettings, projectCreator == null, loadComponentState, task)
}
private suspend fun createOrLoadProject(projectPath: Path,
useDefaultProjectSettings: Boolean,
isNewProject: Boolean,
loadComponentState: Boolean,
task: suspend (Project) -> Unit) {
var options = createTestOpenProjectOptions().copy(
useDefaultProjectAsTemplate = useDefaultProjectSettings,
isNewProject = isNewProject
)
if (loadComponentState) {
options = options.copy(beforeInit = { it.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true) })
}
val project = ProjectManagerEx.getInstanceEx().openProject(projectPath, options)!!
project.use {
if (loadComponentState) {
project.runInLoadComponentStateMode {
task(project)
}
}
else {
task(project)
}
}
}
suspend fun loadProject(projectPath: Path, task: suspend (Project) -> Unit) {
createOrLoadProject(projectPath, false, false, true, task)
}
/**
* Copy files from [projectPaths] directories to a temp directory, load project from it and pass it to [checkProject].
*/
fun loadProjectAndCheckResults(projectPaths: List<Path>, tempDirectory: TemporaryDirectory, checkProject: suspend (Project) -> Unit) {
@Suppress("RedundantSuspendModifier", "BlockingMethodInNonBlockingContext")
suspend fun copyProjectFiles(targetDir: VirtualFile): Path {
val projectDir = VfsUtil.virtualToIoFile(targetDir)
var projectFileName: String? = null
for (projectPath in projectPaths) {
val dir = if (projectPath.isDirectory()) projectPath
else {
projectFileName = projectPath.fileName.toString()
projectPath.parent
}
FileUtil.copyDir(dir.toFile(), projectDir)
}
VfsUtil.markDirtyAndRefresh(false, true, true, targetDir)
return if (projectFileName != null) projectDir.toPath().resolve(projectFileName) else projectDir.toPath()
}
runBlocking {
createOrLoadProject(tempDirectory, ::copyProjectFiles, directoryBased = projectPaths.all { it.isDirectory() },
loadComponentState = true, useDefaultProjectSettings = false) {
checkProject(it)
}
}
}
open class DisposableRule : ExternalResource() {
private var _disposable = lazy { Disposer.newDisposable() }
val disposable: Disposable
get() = _disposable.value
@Suppress("ObjectLiteralToLambda")
inline fun register(crossinline disposable: () -> Unit) {
Disposer.register(this.disposable, object : Disposable {
override fun dispose() {
disposable()
}
})
}
public override fun after() {
if (_disposable.isInitialized()) {
Disposer.dispose(_disposable.value)
_disposable = lazy { Disposer.newDisposable() }
}
}
}
class DisposableExtension : DisposableRule(), AfterEachCallback {
override fun afterEach(context: ExtensionContext?) {
after()
}
}
class SystemPropertyRule(private val name: String, private val value: String) : ExternalResource() {
override fun apply(base: Statement, description: Description): Statement {
return object: Statement() {
override fun evaluate() {
before()
try {
PlatformTestUtil.withSystemProperty<RuntimeException>(name, value) { base.evaluate() }
}
finally {
after()
}
}
}
}
}
| apache-2.0 | 50e1e8c1113089ef952ff9b7a830a1a0 | 33.491863 | 169 | 0.704991 | 4.971071 | false | true | false | false |
PaleoCrafter/VanillaImmersion | src/main/kotlin/de/mineformers/vanillaimmersion/client/renderer/FurnaceRenderer.kt | 1 | 3228 | package de.mineformers.vanillaimmersion.client.renderer
import de.mineformers.vanillaimmersion.block.Furnace
import de.mineformers.vanillaimmersion.tileentity.FurnaceLogic
import de.mineformers.vanillaimmersion.tileentity.FurnaceLogic.Companion.Slot.FUEL
import de.mineformers.vanillaimmersion.tileentity.FurnaceLogic.Companion.Slot.INPUT
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.GlStateManager.color
import net.minecraft.client.renderer.GlStateManager.enableRescaleNormal
import net.minecraft.client.renderer.GlStateManager.popMatrix
import net.minecraft.client.renderer.GlStateManager.pushMatrix
import net.minecraft.client.renderer.GlStateManager.rotate
import net.minecraft.client.renderer.GlStateManager.scale
import net.minecraft.client.renderer.GlStateManager.translate
import net.minecraft.client.renderer.OpenGlHelper
import net.minecraft.client.renderer.RenderHelper
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType.NONE
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer
/**
* Renders the items inside a furnace
*/
open class FurnaceRenderer : TileEntitySpecialRenderer<FurnaceLogic>() {
override fun render(te: FurnaceLogic, x: Double, y: Double, z: Double,
partialTicks: Float, destroyStage: Int, partialAlpha: Float) {
if (te.blockState.block !is Furnace)
return
pushMatrix()
color(1f, 1f, 1f, 1f)
// Use the lighting of the furnace
val light = te.world.getCombinedLight(te.pos, 0)
val bX = light % 65536
val bY = light / 65536
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, bX.toFloat(), bY.toFloat())
// Translate to the furnace's center and rotate according to its orientation
translate(x + 0.5, y, z + 0.5)
rotate(180f - te.facing.horizontalAngle, 0f, 1f, 0f)
rotate(180f, 0f, 1f, 0f)
Minecraft.getMinecraft().textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
enableRescaleNormal()
RenderHelper.enableStandardItemLighting()
// Render the fuel item
pushMatrix()
translate(0.0, 0.2, 0.0)
scale(0.25, 0.25, 0.25)
// Use the "embers" shader to gradually turn the item into ashes
// TODO: Make this actually look nice
Shaders.EMBERS.activate()
Shaders.EMBERS.setUniformFloat("tint", 0.1f, 0.1f, 0.1f, 0f)
var t = te.getField(1).toFloat()
if (t == 0f) {
t = 200f
}
t = te.getField(0) / t
if (!te.isBurning)
t = 1f
Shaders.EMBERS.setUniformFloat("progress", 1f - t)
Minecraft.getMinecraft().renderItem.renderItem(te[FUEL], NONE)
Shaders.EMBERS.deactivate()
popMatrix()
// Render the input item
// TODO: Move this to an IBakedModel
pushMatrix()
translate(0.0, 0.675, 0.0)
scale(0.25, 0.25, 0.25)
Minecraft.getMinecraft().renderItem.renderItem(te[INPUT], NONE)
popMatrix()
RenderHelper.disableStandardItemLighting()
popMatrix()
}
} | mit | 072c333d4847c7a49aeefde2b89f80bd | 40.397436 | 103 | 0.702602 | 4.024938 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/vfu.kt | 1 | 8060 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
interface VFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : VFUEntity, WorkspaceEntity.Builder<VFUEntity>, ObjBuilder<VFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl
}
companion object : Type<VFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): VFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUEntity, modification: VFUEntity.Builder.() -> Unit) = modifyEntity(
VFUEntity.Builder::class.java, entity, modification)
//endregion
interface VFUWithTwoPropertiesEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
val secondFileProperty: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : VFUWithTwoPropertiesEntity, WorkspaceEntity.Builder<VFUWithTwoPropertiesEntity>, ObjBuilder<VFUWithTwoPropertiesEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl
override var secondFileProperty: VirtualFileUrl
}
companion object : Type<VFUWithTwoPropertiesEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: VirtualFileUrl,
secondFileProperty: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): VFUWithTwoPropertiesEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty
builder.secondFileProperty = secondFileProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUWithTwoPropertiesEntity,
modification: VFUWithTwoPropertiesEntity.Builder.() -> Unit) = modifyEntity(
VFUWithTwoPropertiesEntity.Builder::class.java, entity, modification)
//endregion
interface NullableVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NullableVFUEntity, WorkspaceEntity.Builder<NullableVFUEntity>, ObjBuilder<NullableVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl?
}
companion object : Type<NullableVFUEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NullableVFUEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NullableVFUEntity, modification: NullableVFUEntity.Builder.() -> Unit) = modifyEntity(
NullableVFUEntity.Builder::class.java, entity, modification)
//endregion
interface ListVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: List<VirtualFileUrl>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ListVFUEntity, WorkspaceEntity.Builder<ListVFUEntity>, ObjBuilder<ListVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: MutableList<VirtualFileUrl>
}
companion object : Type<ListVFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: List<VirtualFileUrl>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ListVFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ListVFUEntity, modification: ListVFUEntity.Builder.() -> Unit) = modifyEntity(
ListVFUEntity.Builder::class.java, entity, modification)
//endregion
interface SetVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: Set<VirtualFileUrl>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SetVFUEntity, WorkspaceEntity.Builder<SetVFUEntity>, ObjBuilder<SetVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: MutableSet<VirtualFileUrl>
}
companion object : Type<SetVFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: Set<VirtualFileUrl>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): SetVFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty.toMutableWorkspaceSet()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SetVFUEntity, modification: SetVFUEntity.Builder.() -> Unit) = modifyEntity(
SetVFUEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addVFUEntity(
data: String,
fileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUEntity {
val vfuEntity = VFUEntity(data, virtualFileManager.fromUrl(fileUrl), source)
this.addEntity(vfuEntity)
return vfuEntity
}
fun MutableEntityStorage.addVFU2Entity(
data: String,
fileUrl: String,
secondFileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUWithTwoPropertiesEntity {
val vfuWithTwoPropertiesEntity = VFUWithTwoPropertiesEntity(data, virtualFileManager.fromUrl(fileUrl), virtualFileManager.fromUrl(secondFileUrl), source)
this.addEntity(vfuWithTwoPropertiesEntity)
return vfuWithTwoPropertiesEntity
}
fun MutableEntityStorage.addNullableVFUEntity(
data: String,
fileUrl: String?,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): NullableVFUEntity {
val nullableVFUEntity = NullableVFUEntity(data, source) {
this.fileProperty = fileUrl?.let { virtualFileManager.fromUrl(it) }
}
this.addEntity(nullableVFUEntity)
return nullableVFUEntity
}
fun MutableEntityStorage.addListVFUEntity(
data: String,
fileUrl: List<String>,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): ListVFUEntity {
val listVFUEntity = ListVFUEntity(data, fileUrl.map { virtualFileManager.fromUrl(it) }, source)
this.addEntity(listVFUEntity)
return listVFUEntity
}
| apache-2.0 | 1d9813f313fc109413371f2b60642509 | 33.592275 | 155 | 0.737841 | 5.460705 | false | false | false | false |
GunoH/intellij-community | platform/util/testSrc/com/intellij/util/containers/GenerateRecursiveSequenceTest.kt | 12 | 1540 | // 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.util.containers
import com.intellij.testFramework.UsefulTestCase
class GenerateRecursiveSequenceTest : UsefulTestCase() {
fun testEmpty() {
assertTrue(generateRecursiveSequence<String>(emptySequence()) { s -> s.lineSequence() }.toList().isEmpty())
generateRecursiveSequence<String>(emptySequence()) {
fail("No children. So this should not be called")
emptySequence()
}.firstOrNull()
}
fun testGraph() {
class Node(val name: String) {
val children = mutableListOf<Node>()
}
val n1 = Node("n1")
val n2 = Node("n2")
val n3 = Node("n3")
val n4 = Node("n4")
val n5 = Node("n5")
n1.children += n2
n1.children += n3
n2.children += n1
n2.children += n3
n3.children += n4
n3.children += n2
n3.children += n5
val names = generateRecursiveSequence(sequenceOf(n1)) { n -> n.children.asSequence() }.map { it.name }.toList()
assertOrderedEquals(names, "n1", "n2", "n3", "n4", "n5")
generateRecursiveSequence(sequenceOf(n1)) { n ->
assertTrue(n != n3)
n.children.asSequence()
}.map { it.name }.find { it == "n2" }
val visitedNodes = mutableListOf<Node>()
generateRecursiveSequence(sequenceOf(n1)) { n ->
visitedNodes += n
n.children.asSequence()
}.last()
assertTrue(visitedNodes.size == 5 && visitedNodes.distinct().size == 5)
}
} | apache-2.0 | 11cf14f8b24402fd9c1c5a46101d8885 | 27.537037 | 140 | 0.642857 | 3.719807 | false | true | false | false |
LouisCAD/Splitties | modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/CollapsingToolbarLayout.kt | 1 | 1766 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.views.dsl.material
import androidx.appcompat.R
import com.google.android.material.appbar.CollapsingToolbarLayout
import splitties.resources.styledDimenPxSize
import splitties.views.dsl.core.matchParent
import splitties.views.dsl.core.wrapContent
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import com.google.android.material.appbar.CollapsingToolbarLayout.LayoutParams as LP
@Suppress("unused")
val CollapsingToolbarLayout.PIN
get() = LP.COLLAPSE_MODE_PIN
@Suppress("unused")
val CollapsingToolbarLayout.PARALLAX
get() = LP.COLLAPSE_MODE_PARALLAX
inline fun CollapsingToolbarLayout.defaultLParams(
width: Int = matchParent,
height: Int = wrapContent,
initParams: LP.() -> Unit = {}
): LP = LP(width, height).apply(initParams)
inline fun CollapsingToolbarLayout.defaultLParams(
width: Int = matchParent,
height: Int = wrapContent,
collapseMode: Int = LP.COLLAPSE_MODE_OFF,
parallaxMultiplier: Float = 0.5f, // Default value as of 27.1.1
initParams: LP.() -> Unit = {}
): LP {
contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) }
return LP(width, height).also {
it.collapseMode = collapseMode
it.parallaxMultiplier = parallaxMultiplier
}.apply(initParams)
}
inline fun CollapsingToolbarLayout.actionBarLParams(
collapseMode: Int = LP.COLLAPSE_MODE_OFF,
parallaxMultiplier: Float = 0.5f // Default value as of 27.1.1
): LP = LP(matchParent, styledDimenPxSize(R.attr.actionBarSize)).also {
it.collapseMode = collapseMode
it.parallaxMultiplier = parallaxMultiplier
}
| apache-2.0 | 5167ab860e8922095c8de772c883333e | 33.627451 | 109 | 0.754813 | 3.941964 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/PackageBasedCallChecker.kt | 5 | 1756 | // 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.sequence.psi.impl
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
class PackageBasedCallChecker(private val supportedPackage: String) : StreamCallChecker {
override fun isIntermediateCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, true)
}
override fun isTerminationCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, false)
}
private fun checkResultSupported(
expression: KtCallExpression,
shouldSupportResult: Boolean
): Boolean {
val resultType = expression.resolveType()
return resultType != null && shouldSupportResult == isSupportedType(resultType)
}
private fun checkReceiverSupported(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType()
return receiverType != null && isSupportedType(receiverType)
}
private fun isSupportedType(type: KotlinType): Boolean {
val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type)
return StringUtil.getPackageName(typeName).startsWith(supportedPackage)
}
} | apache-2.0 | daf5616c1621f24332b8c7b99131579e | 44.051282 | 158 | 0.773918 | 4.891365 | false | false | false | false |
appmattus/layercache | layercache-android/src/test/kotlin/com/appmattus/layercache/EncryptedSharedPreferencesCacheIntegrationShould.kt | 1 | 4862 | /*
* Copyright 2021 Appmattus Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("IllegalIdentifier")
package com.appmattus.layercache
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.appmattus.layercache.keystore.RobolectricKeyStore
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.MockedStatic
import org.mockito.Mockito.mockStatic
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(manifest = Config.NONE, sdk = [22, 28])
class EncryptedSharedPreferencesCacheIntegrationShould {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val masterKey by lazy { MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build() }
private val sharedPreferences by lazy {
EncryptedSharedPreferences.create(
context,
"test",
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
private val stringCache: Cache<String, String> by lazy {
sharedPreferences.asStringCache().also {
runBlocking {
it.evictAll()
}
}
}
private val intCache: Cache<String, Int> by lazy {
sharedPreferences.asIntCache().also {
runBlocking {
it.evictAll()
}
}
}
private lateinit var jce: MockedStatic<out Any>
@Before
fun setup() {
// Disable
jce = mockStatic(Class.forName("javax.crypto.JceSecurity")) {
if (it.method.name == "getVerificationResult") null else it.callRealMethod()
}
}
@After
fun tearDown() {
jce.close()
}
@Test
fun return_value_when_cache_has_value_2() {
runBlocking {
// given we have a cache with a value
stringCache.set("key", "value")
// when we retrieve a value
val result = stringCache.get("key")
// then it is returned
assertEquals("value", result)
}
}
@Test(expected = NullPointerException::class)
fun return_value_when_cache_has_value_3() {
runBlocking {
// given we have a cache with a value
stringCache.set("key", TestUtils.uninitialized())
// then exception is thrown
}
}
@Test
fun return_value_when_cache_has_value_4() {
runBlocking {
// given we have a cache with a value
intCache.set("key", 5)
// when we retrieve a value
val result = intCache.get("key")
// then it is returned
assertEquals(5, result)
}
}
@Test
fun return_null_when_the_cache_is_empty() {
runBlocking {
// given we have an empty cache, integratedCache
// when we retrieve a value
val result = stringCache.get("key")
// then it is null
assertNull(result)
}
}
@Test
fun return_value_when_cache_has_value() {
runBlocking {
// given we have a cache with a value
stringCache.set("key", "value")
// when we retrieve a value
val result = stringCache.get("key")
// then it is returned
assertEquals("value", result)
}
}
@Test
fun return_null_when_the_key_has_been_evicted() {
runBlocking {
// given we have a cache with a value
stringCache.set("key", "value")
// when we evict the value
stringCache.evict("key")
// then the value is null
assertNull(stringCache.get("key"))
}
}
companion object {
@JvmStatic
@BeforeClass
public fun beforeClass() {
RobolectricKeyStore.setup
}
}
}
| apache-2.0 | bc97478289b138b5ec4c94c00488953f | 26.942529 | 117 | 0.623612 | 4.560976 | false | true | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/tail/Tailer.kt | 1 | 6901 | package com.cognifide.gradle.aem.common.instance.tail
import com.cognifide.gradle.aem.AemVersion
import com.cognifide.gradle.aem.common.instance.Instance
import com.cognifide.gradle.aem.common.instance.InstanceManager
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.aem.common.instance.tail.io.ConsolePrinter
import com.cognifide.gradle.aem.common.instance.tail.io.FileDestination
import com.cognifide.gradle.aem.common.instance.tail.io.LogFiles
import com.cognifide.gradle.aem.common.instance.tail.io.UrlSource
import com.cognifide.gradle.common.utils.using
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.nio.file.Paths
import kotlin.math.max
class Tailer(val manager: InstanceManager) {
internal val aem = manager.aem
private val common = aem.common
/**
* Directory where log files will be stored.
*/
val logStorageDir = aem.obj.dir {
convention(manager.buildDir.dir("tail/logs"))
aem.prop.file("instance.tail.logStorageDir")?.let { set(it) }
}
/**
* Determines log file being tracked on AEM instance.
*/
var logFilePath = aem.obj.string {
convention("/logs/error.log")
aem.prop.string("instance.tail.logFilePath")?.let { set(it) }
}
/**
* Path to file holding wildcard rules that will effectively deactivate notifications for desired exception.
*
* Changes in that file are automatically considered (tailer restart is not required).
*/
val incidentFilter = aem.obj.file {
convention(manager.configDir.file("tail/incidentFilter.txt"))
aem.prop.file("instance.tail.incidentFilter")?.let { set(it) }
}
/**
* Indicates if tailer will print all logs to console.
*/
val console = aem.obj.boolean {
convention(true)
aem.prop.boolean("instance.tail.console")?.let { set(it) }
}
/**
* Time window in which exceptions will be aggregated and reported as single incident.
*/
val incidentDelay = aem.obj.long {
convention(5000L)
aem.prop.long("instance.tail.incidentDelay")?.let { set(it) }
}
/**
* Determines how often logs will be polled from AEM instance.
*/
val fetchInterval = aem.obj.long {
convention(500L)
aem.prop.long("instance.tail.fetchInterval")?.let { set(it) }
}
val lockInterval = aem.obj.long {
convention(fetchInterval.map { max(1000L + it, 2000L) })
aem.prop.long("instance.tail.lockInterval")?.let { set(it) }
}
val linesChunkSize = aem.obj.long {
convention(400L)
aem.prop.long("instance.tail.linesChunkSize")?.let { set(it) }
}
/**
* Hook for tracking all log entries on each AEM instance.
*
* Useful for integrating external services like chats etc.
*/
fun logListener(callback: Log.(Instance) -> Unit) {
this.logListener = callback
}
internal var logListener: Log.(Instance) -> Unit = {}
/**
* Log filter responsible for filtering incidents.
*/
val logFilter = LogFilter(aem.project).apply {
excludeFile(incidentFilter)
}
fun logFilter(options: LogFilter.() -> Unit) = logFilter.using(options)
/**
* Determines which log entries are considered as incidents.
*/
fun incidentChecker(predicate: Log.(Instance) -> Boolean) {
this.incidentChecker = predicate
}
fun tail(instance: Instance) = tail(listOf(instance))
/**
* Run tailer daemons (tracking instance logs).
*/
fun tail(instances: Collection<Instance>) {
checkStartLock()
initIncidentFilter()
runBlocking {
startAll(instances).forEach { tailer ->
launch {
while (isActive) {
logFiles.lock()
tailer.tail()
delay(fetchInterval.get())
}
}
}
}
}
internal var incidentChecker: Log.(Instance) -> Boolean = { instance ->
val levels = Formats.toList(instance.property("instance.tail.incidentLevels"))
?: aem.prop.list("instance.tail.incidentLevels")
?: INCIDENT_LEVELS_DEFAULT
val oldMillis = instance.property("instance.tail.incidentOld")?.toLong()
?: aem.prop.long("instance.tail.incidentOld")
?: INCIDENT_OLD_DEFAULT
isLevel(levels) && !isOlderThan(oldMillis) && !logFilter.isExcluded(this)
}
// https://sridharmandra.blogspot.com/2016/08/tail-aem-logs-in-browser.html
fun errorLogEndpoint(instance: Instance): String {
val fileName = logFilePath.get()
val path = when {
instance.version.atLeast(AemVersion.VERSION_6_2_0) -> ENDPOINT_PATH
else -> ENDPOINT_PATH_OLD
}
return "$path?tail=${linesChunkSize.get()}&name=$fileName"
}
val logFile: String get() = Paths.get(logFilePath.get()).fileName.toString()
private val logFiles = LogFiles(this)
private fun checkStartLock() {
if (logFiles.isLocked()) {
throw TailerException("Another instance of log tailer is running for this project.")
}
logFiles.lock()
}
private fun initIncidentFilter() = incidentFilter.get().asFile.run {
parentFile.mkdirs()
createNewFile()
}
private fun startAll(instances: Collection<Instance>): List<LogTailer> {
val notificationChannel = Channel<LogChunk>(Channel.UNLIMITED)
val logNotifier = LogNotifier(notificationChannel, common.notifier, logFiles)
logNotifier.listenTailed()
return instances.map { start(it, notificationChannel) }
}
private fun start(instance: Instance, notificationChannel: Channel<LogChunk>): LogTailer {
val source = UrlSource(this, instance)
val destination = FileDestination(instance.name, logFiles)
val logAnalyzerChannel = Channel<Log>(Channel.UNLIMITED)
val logAnalyzer = InstanceAnalyzer(this, instance, logAnalyzerChannel, notificationChannel)
logAnalyzer.listenTailed()
val logFile = logFiles.main(instance.name)
aem.logger.lifecycle("Tailing logs to file: $logFile")
return LogTailer(source, destination, InstanceLogInfo(instance), logAnalyzerChannel, consolePrinter(instance))
}
private fun consolePrinter(instance: Instance) = when {
console.get() -> ConsolePrinter(InstanceLogInfo(instance), { aem.logger.lifecycle(it) })
else -> ConsolePrinter.none()
}
companion object {
const val ENDPOINT_PATH = "/system/console/slinglog/tailer.txt"
const val ENDPOINT_PATH_OLD = "/bin/crxde/logs"
val INCIDENT_LEVELS_DEFAULT = listOf("ERROR")
const val INCIDENT_OLD_DEFAULT = 1000L * 10
}
}
| apache-2.0 | e4515e6834f30640cd495c4c751ef6dc | 32.338164 | 118 | 0.647008 | 4.177361 | false | false | false | false |
kmikusek/light-sensor | app/src/main/java/pl/pw/mgr/lightsensor/points/PointsAdapter.kt | 1 | 2868 | package pl.pw.mgr.lightsensor.points
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.item_point.view.*
import pl.pw.mgr.lightsensor.R
import pl.pw.mgr.lightsensor.common.C
import pl.pw.mgr.lightsensor.data.model.Point
internal class PointsAdapter(
private val context: Context
) : RecyclerView.Adapter<PointsAdapter.ViewHolder>() {
//TODO to powinno byc sortowane po wart punktu?
private val items = mutableListOf<Point>()
private var selectedPosition = C.INVALID_INT
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.before.text = item.before.toString()
holder.after.text = item.after.toString()
holder.checkbox.isChecked = position == selectedPosition
holder.root.setOnClickListener {
if (holder.checkbox.isChecked) {
holder.checkbox.isChecked = false
selectedPosition = C.INVALID_INT
} else {
holder.checkbox.isChecked = true
val lastPosition = selectedPosition
selectedPosition = position
if (lastPosition != C.INVALID_INT) {
notifyItemChanged(lastPosition)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup?, position: Int) =
ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_point, parent, false))
override fun getItemCount() = items.size
fun setItems(items: List<Point>) {
this.items.clear()
this.items.addAll(items)
notifyDataSetChanged()
}
fun addItem(item: Point){
items.add(item)
notifyItemInserted(itemCount - 1)
}
fun removeItem(item: Point) {
val position = items.indexOf(item)
items.remove(item)
if (position != C.INVALID_INT) {
selectedPosition = C.INVALID_INT
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
}
}
fun updateItem(id: String){
items.forEachIndexed { index, point -> if(point.id == id) notifyItemChanged(index)}
}
fun getSelectedPoint() = items.getOrNull(selectedPosition)
internal class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val root: RelativeLayout = view.item_point_root
val checkbox: AppCompatCheckBox = view.checkbox
val before: AppCompatTextView = view.before
val after: AppCompatTextView = view.after
}
} | mit | 6165e640ad1d42e08dc2850cb2c72e90 | 32.752941 | 96 | 0.670153 | 4.625806 | false | false | false | false |
Phakx/AdventOfCode | 2016/kotlin/src/advent/9.kt | 1 | 1759 | package advent
import java.io.File
/**
* Created by bkeucher on 12/27/16.
*/
fun main(args: Array<String>) {
val resource = 9.javaClass.getResource("advent/inputs/input_9")
val input = File(resource.toURI()).readText()
val result = calcPart1(input)
println("Part1: " + result)
println("Part2: " + result)
}
private fun calcPart1(input: String): Long {
var index = 0
var loop = true
val chars = input.toCharArray()
val marker_start_char = '('
val marker_end_char = ')'
var result = 0L
var marker_start = 0
var marker_end = 0
while (loop) {
try {
if (marker_start < marker_end && marker_end == index - 1) {
val string = input.substring(marker_start + 1, marker_end)
val split = string.split("x")
(0..split[1].toInt() - 1).forEach {
//Part 1
// result += (input.substring(marker_end + 1, split[0].toInt() + marker_end + 1)).length
//Part 2
result += (calcPart1(input.substring(marker_end + 1, split[0].toInt() + marker_end + 1)))
}
//Part 1
index = marker_end + split[0].toInt() + 1
}
if (chars[index] != marker_start_char && chars[index] != marker_end_char && chars[index].isLetter() && chars[index].isUpperCase()) {
result += 1
}
if (chars[index] == marker_start_char) {
marker_start = index
}
if (chars[index] == marker_end_char) {
marker_end = index
}
index++
} catch(e: Exception) {
loop = false
}
}
return result
} | mit | e431aac457e18a33024009331cc1a4cb | 28.333333 | 144 | 0.499716 | 3.874449 | false | false | false | false |
sargunster/CakeParse | src/main/kotlin/me/sargunvohra/lib/cakeparse/api/Convenience.kt | 1 | 1304 | package me.sargunvohra.lib.cakeparse.api
import me.sargunvohra.lib.cakeparse.parser.Parser
import me.sargunvohra.lib.cakeparse.parser.BaseParser
import me.sargunvohra.lib.cakeparse.parser.Result
/**
* Convenience function to create a reference to a parser for a recursive dependency.
*
* @param parser a function that just returns the target parser.
*
* @return a new parser that acts just like the provided parser.
*/
fun <A> ref(parser: () -> Parser<A>) = BaseParser { input -> parser().eat(input) }
/**
* Create a parser that is always satisfied, so it is satisfied by consuming no input.
*
* @return a new parser that is always satisfied and consumes no input.
*/
fun <A> empty(): BaseParser<A?> = BaseParser { input -> Result<A?>(null, input) }
/**
* Create a parser that tries to satisfy the provided parser, but still succeeds if the provided parser fails.
*
* @param target the target parser to try.
*
* @return a new parser that is always satisfied, but tries to parse the [target].
*/
fun <A> optional(target: Parser<A>) = target or empty<A>()
/**
* Equivalent to [atLeast(0, target)][atLeast].
*/
fun <A> zeroOrMore(target: Parser<A>) = atLeast(0, target)
/**
* Equivalent to [atLeast(1, target)][atLeast].
*/
fun <A> oneOrMore(target: Parser<A>) = atLeast(1, target) | apache-2.0 | 21ae51efd59ad2ab297eb6e64ceaf3d4 | 31.625 | 110 | 0.708589 | 3.632312 | false | false | false | false |
jbmlaird/DiscogsBrowser | app/src/testShared/bj/vinylbrowser/search/SearchFactory.kt | 1 | 1161 | package bj.vinylbrowser.search
import bj.vinylbrowser.greendao.SearchTerm
import bj.vinylbrowser.model.search.SearchResult
/**
* Created by Josh Laird on 21/05/2017.
*/
object SearchFactory {
// Java seems to interpret all of these SearchTerms as the same when using .indexOf() so this
// must be incremented to be recognised as different
var index: Int = 0
@JvmStatic fun buildThreeSearchResults(): List<SearchResult> {
return listOf(buildSearchResult("release"), buildSearchResult("release"),
buildSearchResult("release"))
}
@JvmStatic fun buildArtistAndReleaseSearchResult(): List<SearchResult> {
return listOf(buildSearchResult("artist"), buildSearchResult("release"))
}
@JvmStatic fun buildPastSearch(): SearchTerm {
val searchTerm = SearchTerm()
searchTerm.searchTerm = "yeson"
return searchTerm
}
private fun buildSearchResult(type: String): SearchResult {
val result = SearchResult()
result.id = index++.toString()
result.title = "title"
result.type = type
result.thumb = "thumb"
return result
}
} | mit | a87ce43731a66b3b3bcf5d44ee2daabb | 30.405405 | 97 | 0.677003 | 4.797521 | false | false | false | false |
team4186/season-2017 | src/main/kotlin/org/usfirst/frc/team4186/di/modules/services.kt | 1 | 2056 | package org.usfirst.frc.team4186.di.modules
import com.github.salomonbrys.kodein.*
import edu.wpi.first.wpilibj.DriverStation
import edu.wpi.first.wpilibj.Timer
import edu.wpi.first.wpilibj.command.Scheduler
import edu.wpi.first.wpilibj.hal.HAL
import edu.wpi.first.wpilibj.networktables.NetworkTable
import org.usfirst.frc.team4186.drive.TankDrive
import org.usfirst.frc.team4186.drive.TwinMotorArcadeDrive
import org.usfirst.frc.team4186.extensions.MotorSafetyAdapterImpl
import org.usfirst.frc.team4186.hardware.SaitekX52Adapter
typealias HalReporter = (resource: Int, instanceNumber: Int, context: Int, feature: String) -> Unit
val services_module = Kodein.Module {
bind<DriverStation>() with singleton { DriverStation.getInstance() }
bind<NetworkTable>() with factory { table: String -> NetworkTable.getTable(table) }
bind<HalReporter>() with instance({ r, i, c, f -> HAL.report(r, i, c, f) })
bind<Double>(tag = Hardware.TIMESTAMP) with provider { Timer.getFPGATimestamp() }
bind<Scheduler>() with singleton { Scheduler.getInstance() }
bind<SaitekX52Adapter>() with singleton {
SaitekX52Adapter(
driverStation = instance(),
port = 0,
halReporter = instance()
)
}
bind<TwinMotorArcadeDrive>() with singleton {
TwinMotorArcadeDrive(
leftMotor = instance(Hardware.Motor.LEFT),
rightMotor = instance(Hardware.Motor.RIGHT),
safety = MotorSafetyAdapterImpl(
description = "Drive",
enabled = true,
expiration = 0.2,
timestampProvider = provider(Hardware.TIMESTAMP)
),
halReporter = instance()
)
}
bind<TankDrive>() with singleton {
TankDrive(
leftMotor = instance(Hardware.Motor.LEFT),
rightMotor = instance(Hardware.Motor.RIGHT),
safety = MotorSafetyAdapterImpl(
description = "Drive",
enabled = false,
expiration = 0.2,
timestampProvider = provider(Hardware.TIMESTAMP)
),
halReporter = instance()
)
}
} | mit | 5da727f41c1e539e29911770b1d1cbb9 | 33.864407 | 99 | 0.687743 | 3.765568 | false | false | false | false |
atok/smartcard-encrypt | src/main/java/com/github/atok/smartcard/iso/APDU.kt | 1 | 1483 | package com.github.atok.smartcard.iso
import javax.smartcardio.CommandAPDU
object APDU {
// CLA INS PI P2 LC CDATA
val OPEN_PGP_AID = bytes(0xD2, 0x76, 0x00, 0x01, 0x24, 0x01)
enum class Pin { Pin1, Pin2 }
//TODO 0x81
fun verify(pin: String, p2: Int = 0x82): CommandAPDU {
return CommandAPDU(bytes(0x00, 0x20, 0x00, p2, pin.length) + pin.toByteArray(Charsets.UTF_8))
}
fun sign(data: ByteArray): CommandAPDU {
return CommandAPDU(bytes(0x00, 0x2a, 0x9e, 0x9a, data.size) + data + bytes(0x00))
}
fun decipher(data: ByteArray, chain: Boolean = false): CommandAPDU {
val length = data.size
// val lenBytes = bytes(0x00, (length shr 8) and 0xFF, length and 0xFF)
// turns out openPGP in yubikey does not support extended APDU
val lenBytes = bytes(length)
val cla = if(chain) 0x10 else 0x00
val bytes = bytes(cla, 0x2a, 0x80, 0x86) + lenBytes + data + bytes(0x00)
return CommandAPDU(bytes)
}
fun selectApplet(aid: ByteArray = OPEN_PGP_AID): CommandAPDU {
return CommandAPDU(0x00, 0xA4, 0x04, 0x00, aid)
}
fun getPublicKey(): CommandAPDU {
return CommandAPDU(bytes(0x00, 0x47, 0x00, 0x00, 0x01, 0xB8))
}
private fun bytes(vararg byte: Int): ByteArray {
byte.forEach {
if(it > 255) throw IllegalArgumentException("Value to big: $it")
}
return byte.map { it.toByte() }.toByteArray()
}
} | gpl-2.0 | 94c93a82b93eacafa318dc6dff9eb37e | 31.26087 | 101 | 0.628456 | 3.128692 | false | false | false | false |
blademainer/intellij-community | plugins/settings-repository/src/settings/IcsSettings.kt | 4 | 3487 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectWriter
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.Time
import java.io.File
private val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = DefaultPrettyPrinter.NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: File) {
val serialized = ObjectMapper().writer<ObjectWriter>(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size() <= 2) {
FileUtil.delete(settingsFile)
}
else {
FileUtil.writeToFile(settingsFile, serialized)
}
}
fun loadSettings(settingsFile: File): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile, IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
class IcsSettings {
var shareProjectWorkspace = false
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
@JsonIgnore
val path: String?
get() {
if (url == null) {
return null
}
else {
var fileName = PathUtilRt.getFileName(url!!)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length() - suffix.length())
}
// the convention is that the .git extension should be used for bare repositories
return "${FileUtil.sanitizeFileName(fileName, false)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
} | apache-2.0 | eafae1ee3dff1e37e9552d2ec147dfe2 | 29.867257 | 107 | 0.724405 | 4.22155 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/substring/KMP.kt | 1 | 1074 | package io.uuddlrlrba.ktalgs.substring
class KMP(val pat: String) {
private val R: Int = 256 // the radix
private val dfa: Array<IntArray> // the KMP automoton
init {
// build DFA from pattern
val m = pat.length
dfa = Array(R) { IntArray(m) }
dfa[pat[0].toInt()][0] = 1
var x = 0
var j = 1
while (j < m) {
for (c in 0 until R) {
dfa[c][j] = dfa[c][x] // Copy mismatch cases.
}
dfa[pat[j].toInt()][j] = j + 1 // Set match case.
x = dfa[pat[j].toInt()][x] // Update restart state.
j++
}
}
fun search(txt: String): Int {
// simulate operation of DFA on text
val m = pat.length
val n = txt.length
var i: Int = 0
var j: Int
j = 0
while (i < n && j < m) {
j = dfa[txt[i].toInt()][j]
i++
}
if (j == m) return i - m // found
return n // not found
}
} | mit | 4084e5387e2728833acc73728e0dbc9f | 27.289474 | 69 | 0.421788 | 3.703448 | false | false | false | false |
ognev-zair/Kotlin-AgendaCalendarView | kotlin-agendacalendarview/src/main/java/com/ognev/kotlin/agendacalendarview/calendar/weekslist/WeekListView.kt | 1 | 4200 | package com.ognev.kotlin.agendacalendarview.calendar.weekslist
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import com.ognev.kotlin.agendacalendarview.utils.BusProvider
import com.ognev.kotlin.agendacalendarview.utils.Events
class WeekListView : RecyclerView {
private var mUserScrolling = false
private var mScrolling = false
// region Constructors
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
// endregion
// region Public methods
/**
* Enable snapping behaviour for this recyclerView
* @param enabled enable or disable the snapping behaviour
*/
fun setSnapEnabled(enabled: Boolean) {
if (enabled) {
addOnScrollListener(mScrollListener)
} else {
removeOnScrollListener(mScrollListener)
}
}
// endregion
// region Private methods
private val mScrollListener = object : OnScrollListener() {
override
fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
}
override
fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val weeksAdapter = getAdapter() as WeeksAdapter
when (newState) {
SCROLL_STATE_IDLE -> {
if (mUserScrolling) {
scrollToView(centerView)
postDelayed({ weeksAdapter.isDragging = false }, 700) // Wait for recyclerView to settle
}
mUserScrolling = false
mScrolling = false
}
// If scroll is caused by a touch (scroll touch, not any touch)
SCROLL_STATE_DRAGGING -> {
BusProvider.instance.send(Events.CalendarScrolledEvent() as Any)
// If scroll was initiated already, this is not a user scrolling, but probably a tap, else set userScrolling
if (!mScrolling) {
mUserScrolling = true
}
weeksAdapter.isDragging = (true)
}
SCROLL_STATE_SETTLING -> {
// The user's finger is not touching the list anymore, no need
// for any alpha animation then
weeksAdapter.isAlphaSet = (true)
mScrolling = true
}
}
}
}
private fun getChildClosestToPosition(y: Int): View? {
if (getChildCount() <= 0) {
return null
}
val itemHeight = getChildAt(0).getMeasuredHeight()
var closestY = 9999
var closestChild: View? = null
for (i in 0..getChildCount() - 1) {
val child = getChildAt(i)
val childCenterY = child.getY() + itemHeight / 2
val yDistance = childCenterY - y
// If child center is closer than previous closest, set it as closest
if (Math.abs(yDistance) < Math.abs(closestY)) {
closestY = yDistance.toInt()
closestChild = child
}
}
return closestChild
}
private val centerView: View
get() = getChildClosestToPosition(measuredHeight / 2)!!
private fun scrollToView(child: View?) {
if (child == null) {
return
}
stopScroll()
val scrollDistance = getScrollDistance(child)
if (scrollDistance != 0) {
smoothScrollBy(0, scrollDistance)
}
}
private fun getScrollDistance(child: View): Int {
val itemHeight = getChildAt(0).getMeasuredHeight()
val centerY = getMeasuredHeight() / 2
val childCenterY = child.getY() + itemHeight / 2
return childCenterY.toInt() - centerY
}
// endregion
}
| apache-2.0 | 859f703b3e926e13eaec400ed41b986e | 29.882353 | 128 | 0.582143 | 5.109489 | false | false | false | false |
square/sqldelight | runtime/src/commonMain/kotlin/com/squareup/sqldelight/Transacter.kt | 1 | 9414 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.sqldelight
import com.squareup.sqldelight.Transacter.Transaction
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.internal.currentThreadId
interface TransactionCallbacks {
fun afterCommit(function: () -> Unit)
fun afterRollback(function: () -> Unit)
}
interface TransactionWithReturn<R> : TransactionCallbacks {
/**
* Rolls back this transaction.
*/
fun rollback(returnValue: R): Nothing
/**
* Begin an inner transaction.
*/
fun <R> transaction(body: TransactionWithReturn<R>.() -> R): R
}
interface TransactionWithoutReturn : TransactionCallbacks {
/**
* Rolls back this transaction.
*/
fun rollback(): Nothing
/**
* Begin an inner transaction.
*/
fun transaction(body: TransactionWithoutReturn.() -> Unit)
}
/**
* A transaction-aware [SqlDriver] wrapper which can begin a [Transaction] on the current connection.
*/
interface Transacter {
/**
* Starts a [Transaction] and runs [body] in that transaction.
*
* @throws IllegalStateException if [noEnclosing] is true and there is already an active
* [Transaction] on this thread.
*/
fun <R> transactionWithResult(
noEnclosing: Boolean = false,
bodyWithReturn: TransactionWithReturn<R>.() -> R
): R
/**
* Starts a [Transaction] and runs [body] in that transaction.
*
* @throws IllegalStateException if [noEnclosing] is true and there is already an active
* [Transaction] on this thread.
*/
fun transaction(
noEnclosing: Boolean = false,
body: TransactionWithoutReturn.() -> Unit
)
/**
* A SQL transaction. Can be created through the driver via [SqlDriver.newTransaction] or
* through an implementation of [Transacter] by calling [Transacter.transaction].
*
* A transaction is expected never to escape the thread it is created on, or more specifically,
* never to escape the lambda scope of [Transacter.transaction] and [Transacter.transactionWithResult].
*/
abstract class Transaction : TransactionCallbacks {
private val ownerThreadId = currentThreadId()
internal val postCommitHooks = mutableListOf<() -> Unit>()
internal val postRollbackHooks = mutableListOf<() -> Unit>()
internal val queriesFuncs = mutableMapOf<Int, () -> List<Query<*>>>()
internal var successful: Boolean = false
internal var childrenSuccessful: Boolean = true
internal var transacter: Transacter? = null
/**
* The parent transaction, if there is any.
*/
protected abstract val enclosingTransaction: Transaction?
internal fun enclosingTransaction() = enclosingTransaction
/**
* Signal to the underlying SQL driver that this transaction should be finished.
*
* @param successful Whether the transaction completed successfully or not.
*/
protected abstract fun endTransaction(successful: Boolean)
internal fun endTransaction() {
checkThreadConfinement()
endTransaction(successful && childrenSuccessful)
}
/**
* Queues [function] to be run after this transaction successfully commits.
*/
override fun afterCommit(function: () -> Unit) {
checkThreadConfinement()
postCommitHooks.add(function)
}
/**
* Queues [function] to be run after this transaction rolls back.
*/
override fun afterRollback(function: () -> Unit) {
checkThreadConfinement()
postRollbackHooks.add(function)
}
internal fun checkThreadConfinement() = check(ownerThreadId == currentThreadId()) {
"""
Transaction objects (`TransactionWithReturn` and `TransactionWithoutReturn`) must be used
only within the transaction lambda scope.
""".trimIndent()
}
}
}
private class RollbackException(val value: Any? = null) : Throwable()
private class TransactionWrapper<R>(
val transaction: Transaction
) : TransactionWithoutReturn, TransactionWithReturn<R> {
override fun rollback(): Nothing {
transaction.checkThreadConfinement()
throw RollbackException()
}
override fun rollback(returnValue: R): Nothing {
transaction.checkThreadConfinement()
throw RollbackException(returnValue)
}
/**
* Queues [function] to be run after this transaction successfully commits.
*/
override fun afterCommit(function: () -> Unit) {
transaction.afterCommit(function)
}
/**
* Queues [function] to be run after this transaction rolls back.
*/
override fun afterRollback(function: () -> Unit) {
transaction.afterRollback(function)
}
override fun transaction(body: TransactionWithoutReturn.() -> Unit) {
transaction.transacter!!.transaction(false, body)
}
override fun <R> transaction(body: TransactionWithReturn<R>.() -> R): R {
return transaction.transacter!!.transactionWithResult(false, body)
}
}
/**
* A transaction-aware [SqlDriver] wrapper which can begin a [Transaction] on the current connection.
*/
abstract class TransacterImpl(private val driver: SqlDriver) : Transacter {
/**
* For internal use, notifies the listeners of [queryList] that their underlying result set has
* changed.
*/
protected fun notifyQueries(identifier: Int, queryList: () -> List<Query<*>>) {
val transaction = driver.currentTransaction()
if (transaction != null) {
if (!transaction.queriesFuncs.containsKey(identifier)) {
transaction.queriesFuncs[identifier] = queryList
}
} else {
queryList.invoke().forEach { it.notifyDataChanged() }
}
}
/**
* For internal use, creates a string in the format (?, ?, ?) where there are [count] offset.
*/
protected fun createArguments(count: Int): String {
if (count == 0) return "()"
return buildString(count + 2) {
append("(?")
repeat(count - 1) {
append(",?")
}
append(')')
}
}
override fun transaction(
noEnclosing: Boolean,
body: TransactionWithoutReturn.() -> Unit
) {
transactionWithWrapper<Unit?>(noEnclosing, body)
}
override fun <R> transactionWithResult(
noEnclosing: Boolean,
bodyWithReturn: TransactionWithReturn<R>.() -> R
): R {
return transactionWithWrapper(noEnclosing, bodyWithReturn)
}
private fun <R> transactionWithWrapper(noEnclosing: Boolean, wrapperBody: TransactionWrapper<R>.() -> R): R {
val transaction = driver.newTransaction()
val enclosing = transaction.enclosingTransaction()
check(enclosing == null || !noEnclosing) { "Already in a transaction" }
var thrownException: Throwable? = null
var returnValue: R? = null
try {
transaction.transacter = this
returnValue = TransactionWrapper<R>(transaction).wrapperBody()
transaction.successful = true
} catch (e: Throwable) {
thrownException = e
} finally {
transaction.endTransaction()
if (enclosing == null) {
if (!transaction.successful || !transaction.childrenSuccessful) {
// TODO: If this throws, and we threw in [body] then create a composite exception.
try {
transaction.postRollbackHooks.forEach { it.invoke() }
} catch (rollbackException: Throwable) {
thrownException?.let {
throw Throwable("Exception while rolling back from an exception.\nOriginal exception: $thrownException\nwith cause ${thrownException.cause}\n\nRollback exception: $rollbackException", rollbackException)
}
throw rollbackException
}
transaction.postRollbackHooks.clear()
} else {
transaction.queriesFuncs
.flatMap { (_, queryListSupplier) -> queryListSupplier.invoke() }
.distinct()
.forEach { it.notifyDataChanged() }
transaction.queriesFuncs.clear()
transaction.postCommitHooks.forEach { it.invoke() }
transaction.postCommitHooks.clear()
}
} else {
enclosing.childrenSuccessful = transaction.successful && transaction.childrenSuccessful
enclosing.postCommitHooks.addAll(transaction.postCommitHooks)
enclosing.postRollbackHooks.addAll(transaction.postRollbackHooks)
enclosing.queriesFuncs.putAll(transaction.queriesFuncs)
}
if (enclosing == null && thrownException is RollbackException) {
// We can safely cast to R here because the rollback exception is always created with the
// correct type.
@Suppress("UNCHECKED_CAST")
return thrownException.value as R
} else if (thrownException != null) {
throw thrownException
} else {
// We can safely cast to R here because any code path that led here will have set the
// returnValue to the result of the block
@Suppress("UNCHECKED_CAST")
return returnValue as R
}
}
}
}
| apache-2.0 | 15d36896173192703c28d197b20ddc05 | 32.031579 | 216 | 0.681963 | 4.614706 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/app/view/components/StatusComponent.kt | 1 | 2472 | /*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.app.view.components
import android.content.res.Resources
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import org.blitzortung.android.alert.AlertLabel
import org.blitzortung.android.alert.AlertLabelHandler
import org.blitzortung.android.alert.event.AlertEvent
import org.blitzortung.android.alert.event.AlertResultEvent
class StatusComponent(
private val warning: TextView,
private val status: TextView,
private val progressBar: ProgressBar,
private val errorIndicator: ImageView,
resources: Resources
) : AlertLabel {
private val alertLabelHandler: AlertLabelHandler
val alertEventConsumer: (AlertEvent) -> Unit
init {
progressBar.visibility = View.INVISIBLE
errorIndicator.visibility = View.INVISIBLE
alertLabelHandler = AlertLabelHandler(this, resources)
alertEventConsumer = { event ->
alertLabelHandler.apply(
if (event is AlertResultEvent)
event.alertResult
else
null)
}
}
fun startProgress() {
progressBar.apply {
visibility = View.VISIBLE
progress = 0
}
}
fun stopProgress() {
progressBar.apply {
visibility = View.INVISIBLE
progress = progressBar.max
}
}
fun indicateError(indicateError: Boolean) {
errorIndicator.visibility = if (indicateError) View.VISIBLE else View.INVISIBLE
}
fun setText(statusText: String) {
status.text = statusText
}
override fun setAlarmTextColor(color: Int) {
warning.setTextColor(color)
}
override fun setAlarmText(alarmText: String) {
warning.text = alarmText
}
}
| apache-2.0 | 02b429690004212a2e4cc5560a7b00c6 | 27.402299 | 87 | 0.678268 | 4.864173 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/findUsages/TaggedClassImplicitUsageProvider.kt | 1 | 1901 | package com.gmail.blueboxware.libgdxplugin.filetypes.skin.findUsages
import com.gmail.blueboxware.libgdxplugin.utils.allScope
import com.gmail.blueboxware.libgdxplugin.utils.isLibGDX199
import com.intellij.codeInsight.daemon.ImplicitUsageProvider
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
/*
* Copyright 2018 Blue Box Ware
*
* 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.
*/
class TaggedClassImplicitUsageProvider : ImplicitUsageProvider {
override fun isImplicitUsage(element: PsiElement): Boolean {
if (element !is PsiClass || !element.project.isLibGDX199()) {
return false
}
return CachedValuesManager.getCachedValue(element) {
val parameters =
ReferencesSearch.SearchParameters(element, element.allScope(), true)
var found = false
TaggedClassUsagesSearcher().execute(parameters) {
found = true
return@execute false
}
return@getCachedValue CachedValueProvider.Result.create(found, element)
}
}
override fun isImplicitRead(element: PsiElement): Boolean = false
override fun isImplicitWrite(element: PsiElement): Boolean = false
}
| apache-2.0 | a55695ed8c7a01a3343a503f708fa311 | 32.946429 | 84 | 0.729616 | 4.764411 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaGDXAssetsInspection.kt | 1 | 7446 | package com.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.inspections.checkFilename
import com.gmail.blueboxware.libgdxplugin.inspections.checkSkinFilename
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.*
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.*
/*
* Copyright 2017 Blue Box Ware
*
* 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.
*/
internal class JavaGDXAssetsInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("gdxassets.annotation.inspection.descriptor")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
object : JavaElementVisitor() {
override fun visitAnnotation(annotation: PsiAnnotation?) {
if (annotation == null || annotation.qualifiedName != ASSET_ANNOTATION_NAME) {
return
}
if ((annotation.owner as? PsiModifierList)?.context is PsiVariable) {
if (annotation.getClassNamesOfOwningVariable().none { it in TARGETS_FOR_GDXANNOTATION }) {
holder.registerProblem(
annotation,
message("gdxassets.annotation.problem.descriptor.wrong.target"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
}
}
override fun visitAnnotationParameterList(list: PsiAnnotationParameterList?) {
(list?.context as? PsiAnnotation)?.let { annotation ->
if (annotation.qualifiedName != ASSET_ANNOTATION_NAME) {
return
}
(annotation.findAttributeValue(ASSET_ANNOTATION_SKIN_PARAM_NAME) as? PsiArrayInitializerMemberValue)
?.initializers
?.forEach {
((it as? PsiLiteralExpression)?.value as? String)?.let { value ->
checkSkinFilename(it, value, holder)
}
}
(annotation.findAttributeValue(
ASSET_ANNOTATION_SKIN_PARAM_NAME
) as? PsiLiteralExpression)?.let { literal ->
(literal.value as? String)?.let { value ->
checkSkinFilename(literal, value, holder)
}
}
(annotation.findAttributeValue(
ASSET_ANNOTATION_ATLAS_PARAM_NAME
) as? PsiArrayInitializerMemberValue)?.initializers?.forEach {
((it as? PsiLiteralExpression)?.value as? String)?.let { value ->
checkFilename(it, value, holder)
}
}
(annotation.findAttributeValue(
ASSET_ANNOTATION_ATLAS_PARAM_NAME
) as? PsiLiteralExpression)?.let { literal ->
(literal.value as? String)?.let { value ->
checkFilename(literal, value, holder)
}
}
(annotation.findAttributeValue(
ASSET_ANNOTATION_PROPERTIES_PARAM_NAME
) as? PsiArrayInitializerMemberValue)?.initializers?.forEach {
((it as? PsiLiteralExpression)?.value as? String)?.let { value ->
checkFilename(it, value, holder)
}
}
(annotation.findAttributeValue(
ASSET_ANNOTATION_PROPERTIES_PARAM_NAME
) as? PsiLiteralExpression)?.let { literal ->
(literal.value as? String)?.let { value ->
checkFilename(literal, value, holder)
}
}
annotation.parameterList.attributes.forEach { psiNameValuePair ->
if (psiNameValuePair.name == ASSET_ANNOTATION_SKIN_PARAM_NAME) {
if (annotation.getClassNamesOfOwningVariable().none { it == SKIN_CLASS_NAME }) {
registerUselessParameterProblem(
holder, psiNameValuePair, ASSET_ANNOTATION_SKIN_PARAM_NAME, SKIN_CLASS_NAME
)
}
} else if (psiNameValuePair.name == ASSET_ANNOTATION_ATLAS_PARAM_NAME) {
if (annotation.getClassNamesOfOwningVariable()
.none { it == TEXTURE_ATLAS_CLASS_NAME || it == SKIN_CLASS_NAME }
) {
registerUselessParameterProblem(
holder,
psiNameValuePair,
ASSET_ANNOTATION_ATLAS_PARAM_NAME,
"$SKIN_CLASS_NAME or $TEXTURE_ATLAS_CLASS_NAME"
)
}
} else if (psiNameValuePair.name == ASSET_ANNOTATION_PROPERTIES_PARAM_NAME) {
if (annotation.getClassNamesOfOwningVariable().none { it == I18NBUNDLE_CLASS_NAME }) {
registerUselessParameterProblem(
holder,
psiNameValuePair,
ASSET_ANNOTATION_PROPERTIES_PARAM_NAME,
I18NBUNDLE_CLASS_NAME
)
}
}
}
}
}
}
private fun PsiAnnotation.getClassNamesOfOwningVariable(): List<String> {
((owner as? PsiModifierList)?.context as? PsiVariable)?.type?.let { type ->
if (type is PsiClassType) {
return type.resolve()?.supersAndThis()?.mapNotNull { it.qualifiedName } ?: listOf()
}
}
return listOf()
}
private fun registerUselessParameterProblem(
holder: ProblemsHolder,
psiNameValuePair: PsiNameValuePair,
parameterName: String,
className: String
) {
psiNameValuePair.nameIdentifier?.let { identifier ->
holder.registerProblem(
identifier,
message(
"gdxassets.annotation.problem.descriptor.useless.parameter",
parameterName,
className
)
)
}
}
}
| apache-2.0 | 3472d7510a336d08e0468cf49734ac16 | 41.793103 | 120 | 0.512624 | 6.189526 | false | false | false | false |
sujeet4github/MyLangUtils | LangKotlin/reactive-playground-master/src/main/kotlin/pl/piomin/service/Organization.kt | 1 | 750 | package pl.piomin.service
class Organization(var id: Int, var name: String) {
var employees: MutableList<Employee> = ArrayList()
var departments: MutableList<Department> = ArrayList()
constructor(id: Int, name: String, employees: MutableList<Employee>, departments: MutableList<Department>) : this(id, name){
this.employees.addAll(employees)
this.departments.addAll(departments)
}
constructor(id: Int, name: String, employees: MutableList<Employee>) : this(id, name){
this.employees.addAll(employees)
}
override fun toString(): String{
val address2Str = "Organization {id = ${id}, name = ${name}, e = ${employees.joinToString()}, d = ${departments.joinToString()} }"
return address2Str
}
} | gpl-3.0 | 3a5394d4652bf9c7a1a649386e829407 | 36.55 | 132 | 0.690667 | 3.787879 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.