repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/client/storage/gcloud/gcs/GcsStorageFactory.kt | 1 | 2529 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.client.storage.gcloud.gcs
import com.google.cloud.storage.StorageOptions
import com.google.protobuf.kotlin.toByteString
import java.security.MessageDigest
import org.wfanet.measurement.common.HexString
import org.wfanet.measurement.gcloud.gcs.GcsStorageClient
import org.wfanet.measurement.storage.StorageClient
import org.wfanet.panelmatch.client.storage.StorageDetails
import org.wfanet.panelmatch.client.storage.StorageDetails.BucketType
import org.wfanet.panelmatch.common.ExchangeDateKey
import org.wfanet.panelmatch.common.storage.StorageFactory
import org.wfanet.panelmatch.common.storage.withPrefix
class GcsStorageFactory(
private val storageDetails: StorageDetails,
private val exchangeDateKey: ExchangeDateKey
) : StorageFactory {
override fun build(): StorageClient {
val gcs = storageDetails.gcs
val bucketId: String =
when (val bucketType: BucketType = gcs.bucketType) {
BucketType.STATIC_BUCKET -> gcs.bucket
BucketType.ROTATING_BUCKET -> {
val storageDetailsFingerprint =
fingerprint("${gcs.bucket}-${gcs.projectName}-${storageDetails.visibility.name}")
val exchangeFingerprint = fingerprint(exchangeDateKey.path)
// Maximum bucket size is 63 characters. 512 bits in hex is 32 characters, so we drop one.
storageDetailsFingerprint + exchangeFingerprint.take(31)
}
BucketType.UNKNOWN_TYPE,
BucketType.UNRECOGNIZED -> error("Invalid bucket_type: $bucketType")
}
return GcsStorageClient(
StorageOptions.newBuilder().setProjectId(gcs.projectName).build().service,
bucketId
)
.withPrefix(exchangeDateKey.path)
}
}
private fun fingerprint(data: String): String {
val digest = MessageDigest.getInstance("SHA-512").digest(data.toByteArray(Charsets.UTF_8))
return HexString(digest.toByteString()).value.toLowerCase()
}
| apache-2.0 | d3d7a4115e5dcc71015dd8b1f0620c84 | 41.864407 | 100 | 0.755635 | 4.452465 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/view/activity/index/SplashActivity.kt | 1 | 3914 | package com.mxt.anitrend.view.activity.index
import android.content.Intent
import android.os.Bundle
import butterknife.BindView
import butterknife.ButterKnife
import com.mxt.anitrend.R
import com.mxt.anitrend.base.custom.activity.ActivityBase
import com.mxt.anitrend.base.custom.view.image.WideImageView
import com.mxt.anitrend.extension.getCompatTintedDrawable
import com.mxt.anitrend.model.entity.base.VersionBase
import com.mxt.anitrend.presenter.base.BasePresenter
import com.mxt.anitrend.util.CompatUtil
import com.mxt.anitrend.util.DialogUtil
import com.mxt.anitrend.util.KeyUtil
import com.mxt.anitrend.util.date.DateUtil
import com.mxt.anitrend.view.activity.base.WelcomeActivity
/**
* Created by max on 2017/10/04.
* Base splash screen
*/
class SplashActivity : ActivityBase<VersionBase, BasePresenter>() {
@BindView(R.id.preview_credits)
lateinit var giphyCitation: WideImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
ButterKnife.bind(this)
setPresenter(BasePresenter(this))
setViewModel(true)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
giphyCitation.setImageResource(if (!CompatUtil.isLightTheme(this)) R.drawable.powered_by_giphy_light else R.drawable.powered_by_giphy_dark)
onActivityReady()
}
/**
* Make decisions, check for permissions or fire background threads from this method
* N.B. Must be called after onPostCreate
*/
override fun onActivityReady() {
presenter.checkGenresAndTags(this)
presenter.checkValidAuth()
makeRequest()
}
override fun updateUI() {
if (isAlive) {
if(presenter.checkIfMigrationIsNeeded()) {
val freshInstall = presenter.settings.isFreshInstall
val intent = Intent(
this@SplashActivity,
if (freshInstall)
WelcomeActivity::class.java
else
MainActivity::class.java
)
startActivity(intent)
finish()
} else {
val drawable = getCompatTintedDrawable(R.drawable.ic_system_update_grey_600_24dp)
val dialog = DialogUtil.createDefaultDialog(this)
.autoDismiss(false)
.positiveText(R.string.Ok)
.title(R.string.title_migration_failed)
.content(R.string.text_migration_failed)
.onAny { dialog, _ ->
dialog.dismiss()
finish()
}
if (drawable != null)
dialog.icon(drawable)
dialog.show()
}
}
}
override fun makeRequest() {
val versionBase = presenter.database.remoteVersion
// How frequent the application checks for updates on startup
if (versionBase == null || DateUtil.timeDifferenceSatisfied(KeyUtil.TIME_UNIT_HOURS, versionBase.lastChecked, 2)) {
viewModel.params.putString(KeyUtil.arg_branch_name, presenter.settings.updateChannel)
viewModel.requestData(KeyUtil.UPDATE_CHECKER_REQ, applicationContext)
} else
updateUI()
}
/**
* Called when the model state is changed.
*
* @param model The new data
*/
override fun onChanged(model: VersionBase?) {
super.onChanged(model)
if (model != null)
presenter.database.remoteVersion = model
updateUI()
}
override fun showError(error: String) {
updateUI()
}
override fun showEmpty(message: String) {
updateUI()
}
}
| lgpl-3.0 | 22afbb1d035f7b247fa055349360d187 | 33.637168 | 147 | 0.622381 | 4.773171 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/widget/CameraSurfaceView.kt | 1 | 2625 | package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki t_saki@serenegiant.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.serenegiant.camera.CameraConst
import com.serenegiant.camera.CameraUtils
import java.io.IOException
/**
* カメラ映像を流し込んで表示するだけのSurfaceView実装
*/
@Suppress("DEPRECATION")
class CameraSurfaceView @JvmOverloads constructor(context: Context?,
attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: SurfaceView(context, attrs, defStyleAttr) {
private var mHasSurface = false
private var mCamera: Camera? = null
val cameraRotation = 0
/**
* コンストラクタ
*/
init {
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
mHasSurface = true
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
startPreview()
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
mHasSurface = false
stopPreview()
}
})
}
fun onResume() {
if (mHasSurface) {
startPreview()
}
}
fun onPause() {
stopPreview()
}
private fun startPreview() {
if (mCamera == null) {
try {
mCamera = CameraUtils.setupCamera(context,
CameraConst.FACING_BACK,
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
CameraUtils.setPreviewSurface(mCamera!!, this)
} catch (e: IOException) {
Log.w(TAG, e)
mCamera = null
}
if (mCamera != null) {
mCamera!!.startPreview()
}
}
}
private fun stopPreview() {
if (mCamera != null) {
mCamera!!.stopPreview()
mCamera!!.release()
mCamera = null
}
}
companion object {
private const val DEBUG = true // set false on production
private val TAG = CameraSurfaceView::class.java.simpleName
private const val CAMERA_ID = 0
}
} | apache-2.0 | 0f0d47cd4953987b93dbb1c5fe6300cc | 23.970874 | 93 | 0.714897 | 3.590782 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/guilds/GuildOverviewFragment.kt | 1 | 6059 | package com.habitrpg.android.habitica.ui.fragments.social.guilds
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding
import com.habitrpg.android.habitica.extensions.addCloseButton
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import javax.inject.Inject
class GuildOverviewFragment : BaseMainFragment<FragmentViewpagerBinding>(), SearchView.OnQueryTextListener {
@Inject
internal lateinit var socialRepository: SocialRepository
override var binding: FragmentViewpagerBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding {
return FragmentViewpagerBinding.inflate(inflater, container, false)
}
private var statePagerAdapter: FragmentStateAdapter? = null
private var userGuildsFragment: GuildListFragment? = GuildListFragment()
private var publicGuildsFragment: GuildListFragment? = GuildListFragment()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.usesTabLayout = true
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setViewPagerAdapter()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_public_guild, menu)
val searchItem = menu.findItem(R.id.action_search)
val guildSearchView = searchItem?.actionView as? SearchView
val theTextArea = guildSearchView?.findViewById<SearchView.SearchAutoComplete>(R.id.search_src_text)
context?.let { theTextArea?.setHintTextColor(ContextCompat.getColor(it, R.color.white)) }
guildSearchView?.queryHint = getString(R.string.guild_search_hint)
guildSearchView?.setOnQueryTextListener(this)
guildSearchView?.setOnCloseListener {
getActiveFragment()?.onClose() ?: true
}
}
@Suppress("ReturnCount")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_create_item -> {
showCreationDialog()
return true
}
R.id.action_reload -> {
getActiveFragment()?.fetchGuilds()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun showCreationDialog() {
val context = context ?: return
val dialog = HabiticaAlertDialog(context)
dialog.setTitle(R.string.create_guild)
dialog.setMessage(R.string.create_guild_description)
dialog.addButton(R.string.open_website, isPrimary = true, isDestructive = false) { _, _ ->
val uriUrl = "https://habitica.com/groups/myGuilds".toUri()
val launchBrowser = Intent(Intent.ACTION_VIEW, uriUrl)
val l = context.packageManager.queryIntentActivities(launchBrowser, PackageManager.MATCH_DEFAULT_ONLY)
val notHabitica = l.first { !it.activityInfo.processName.contains("habitica") }
launchBrowser.setPackage(notHabitica.activityInfo.processName)
startActivity(launchBrowser)
}
dialog.addCloseButton()
dialog.show()
}
private fun getActiveFragment(): GuildListFragment? {
return if (binding?.viewPager?.currentItem == 0) {
userGuildsFragment
} else {
publicGuildsFragment
}
}
private fun setViewPagerAdapter() {
val fragmentManager = childFragmentManager
statePagerAdapter = object : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment {
val fragment = GuildListFragment()
fragment.onlyShowUsersGuilds = position == 0
if (position == 0) {
userGuildsFragment = fragment
} else {
publicGuildsFragment = fragment
}
return fragment
}
override fun getItemCount(): Int {
return 2
}
}
binding?.viewPager?.adapter = statePagerAdapter
tabLayout?.let {
binding?.viewPager?.let { it1 ->
TabLayoutMediator(it, it1) { tab, position ->
tab.text = when (position) {
0 -> getString(R.string.my_guilds)
1 -> getString(R.string.discover)
else -> ""
}
}.attach()
}
}
statePagerAdapter?.notifyDataSetChanged()
}
override fun onQueryTextSubmit(query: String?): Boolean {
return getActiveFragment()?.onQueryTextSubmit(query) ?: false
}
override fun onQueryTextChange(newText: String?): Boolean {
return getActiveFragment()?.onQueryTextChange(newText) ?: false
}
}
| gpl-3.0 | 5644c546d2a9c7f0260e3ff1fe4920a6 | 37.106918 | 114 | 0.670738 | 5.227783 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/log/lexer/MarkLogicErrorLogTokenType.kt | 1 | 3002 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.log.lexer
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import uk.co.reecedunn.intellij.plugin.marklogic.log.lang.MarkLogicErrorLog
object MarkLogicErrorLogTokenType {
val WHITE_SPACE: IElementType = TokenType.WHITE_SPACE
val DATE: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_DATE", MarkLogicErrorLog)
val TIME: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_TIME", MarkLogicErrorLog)
val SERVER: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_SERVER", MarkLogicErrorLog)
val MESSAGE: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_MESSAGE", MarkLogicErrorLog)
val COLON: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_COLON", MarkLogicErrorLog)
val CONTINUATION: IElementType = IElementType("MARK_LOGIC_ERROR_LOG_CONTINUATION", MarkLogicErrorLog)
object LogLevel {
val UNKNOWN: ILogLevelElementType = ILogLevelElementType("Unknown", MarkLogicErrorLog)
val FINEST: ILogLevelElementType = ILogLevelElementType("Finest", MarkLogicErrorLog)
val FINER: ILogLevelElementType = ILogLevelElementType("Finer", MarkLogicErrorLog)
val FINE: ILogLevelElementType = ILogLevelElementType("Fine", MarkLogicErrorLog)
val DEBUG: ILogLevelElementType = ILogLevelElementType("Debug", MarkLogicErrorLog)
val CONFIG: ILogLevelElementType = ILogLevelElementType("Config", MarkLogicErrorLog)
val INFO: ILogLevelElementType = ILogLevelElementType("Info", MarkLogicErrorLog)
val NOTICE: ILogLevelElementType = ILogLevelElementType("Notice", MarkLogicErrorLog)
val WARNING: ILogLevelElementType = ILogLevelElementType("Warning", MarkLogicErrorLog)
val ERROR: ILogLevelElementType = ILogLevelElementType("Error", MarkLogicErrorLog)
val CRITICAL: ILogLevelElementType = ILogLevelElementType("Critical", MarkLogicErrorLog)
val ALERT: ILogLevelElementType = ILogLevelElementType("Alert", MarkLogicErrorLog)
val EMERGENCY: ILogLevelElementType = ILogLevelElementType("Emergency", MarkLogicErrorLog)
private val VALUES: Array<ILogLevelElementType> = arrayOf(
FINEST, FINER, FINE, DEBUG, CONFIG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY
)
fun token(name: CharSequence): ILogLevelElementType = VALUES.find { it.name == name } ?: UNKNOWN
}
}
| apache-2.0 | 38a80214289e1bb94e15e5dbcfa3dbe8 | 54.592593 | 105 | 0.758494 | 4.534743 | false | true | false | false |
elect86/jAssimp | src/main/kotlin/assimp/fast_atof.kt | 2 | 2598 | package assimp
import glm_.*
import java.nio.ByteBuffer
/** signed variant of strtoul10 */
fun ByteBuffer.strtol10(begin: Int, end: Int): Int {
val bytes = ByteArray(end - begin) { get(begin + it) }
return String(bytes).i
}
/** Convert a string in decimal format to a number */
fun ByteBuffer.strtoul10(beginOut: IntArray): Int {
var value = 0
var begin = beginOut[0]
while (true) {
val c = get(begin).c
if (c < '0' || c > '9') break
value = value * 10 + (get(begin).c - '0')
++begin
}
if (beginOut[1] != 0) beginOut[1] = begin
return value
}
/** Special version of the function, providing higher accuracy and safety
* It is mainly used by fast_atof to prevent ugly and unwanted integer overflows. */
fun ByteBuffer.strtoul10_64(beginOutMax: IntArray): Long {
var cur = 0
var value = 0L
var begin = beginOutMax[0]
var c = get(begin).c
if (c < '0' || c > '9') throw Exception("The string starting with \"$c\" cannot be converted into a value.")
while (true) {
if (c < '0' || c > '9') break
val newValue = value * 10 + (c - '0')
// numeric overflow, we rely on you
if (newValue < value) logger.warn { "Converting the string starting with \"$c\" into a value resulted in overflow." }
//throw std::overflow_error();
value = newValue
c = get(++begin).c
++cur
if (beginOutMax[2] != 0 && beginOutMax[2] == cur) {
if (beginOutMax[1] != 0) { /* skip to end */
while (c in '0'..'9')
c = get(++begin).c
beginOutMax[1] = begin
}
return value
}
}
if (beginOutMax[1] != 0) beginOutMax[1] = begin
if (beginOutMax[2] != 0) beginOutMax[2] = cur
return value
}
/** signed variant of strtoul10_64 */
fun ByteBuffer.strtol10_64(begin: Int, end: Int): Long {
val bytes = ByteArray(end - begin) { get(begin + it) }
return String(bytes).L
}
fun ByteBuffer.fast_atof(begin: Int, end: Int): Float {
val bytes = ByteArray(end - begin) { get(begin + it) }
return String(bytes).f
}
fun ByteBuffer.strncmp(string: String, ptr: Int = pos, length: Int = string.length): Boolean {
for (i in 0 until length)
if (get(ptr + i).c != string[i])
return false
return true
}
fun strtoul10(input: String, ptr: Int): uint {
var value = 0
var i = ptr
while (true) {
if (input[i] < '0' || input[i] > '9') break
value = value * 10 + (input[i] - '0')
++i
}
return value
} | mit | 211e0df6103424c272d469a8e7803c4d | 28.873563 | 125 | 0.56659 | 3.378414 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/widget/TaskListFactory.kt | 1 | 3970 | package com.habitrpg.android.habitica.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.text.SpannableStringBuilder
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.common.habitica.helpers.MarkdownParser
import com.habitrpg.shared.habitica.models.tasks.TaskType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject
abstract class TaskListFactory internal constructor(
val context: Context,
intent: Intent,
private val taskType: TaskType,
private val listItemResId: Int,
private val listItemTextResId: Int
) : RemoteViewsService.RemoteViewsFactory {
private val job = SupervisorJob()
private val widgetId: Int = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0)
@Inject
lateinit var taskRepository: TaskRepository
@Inject
lateinit var userRepository: UserRepository
private var taskList: List<Task> = ArrayList()
private var reloadData: Boolean = false
init {
this.reloadData = false
}
private fun loadData() {
if (!this::taskRepository.isInitialized) {
return
}
CoroutineScope(Dispatchers.Main + job).launch(ExceptionHandler.coroutine()) {
val tasks = taskRepository.getTasks(taskType, null, emptyArray()).firstOrNull()?.filter { task ->
task.type == TaskType.TODO && !task.completed || task.isDisplayedActive
} ?: return@launch
taskList = taskRepository.getTaskCopies(tasks)
reloadData = false
AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(widgetId, R.id.list_view)
}
}
override fun onCreate() {
HabiticaBaseApplication.userComponent?.inject(this)
this.loadData()
}
override fun onDestroy() { /* no-op */ }
override fun onDataSetChanged() {
if (this.reloadData) {
this.loadData()
}
this.reloadData = true
}
override fun getCount(): Int {
return taskList.size
}
override fun getViewAt(position: Int): RemoteViews {
val remoteView = RemoteViews(context.packageName, listItemResId)
if (taskList.size > position) {
val task = taskList[position]
val parsedText = MarkdownParser.parseMarkdown(task.text)
val builder = SpannableStringBuilder(parsedText)
remoteView.setTextViewText(listItemTextResId, builder)
remoteView.setInt(R.id.checkbox_background, "setBackgroundResource", task.lightTaskColor)
val fillInIntent = Intent()
fillInIntent.putExtra(TaskListWidgetProvider.TASK_ID_ITEM, task.id)
remoteView.setOnClickFillInIntent(R.id.checkbox_background, fillInIntent)
}
return remoteView
}
override fun getLoadingView(): RemoteViews {
return RemoteViews(context.packageName, listItemResId)
}
override fun getViewTypeCount(): Int {
return 1
}
override fun getItemId(position: Int): Long {
if (taskList.size > position) {
val task = taskList[position]
return task.id.hashCode().toLong()
}
return position.toLong()
}
override fun hasStableIds(): Boolean {
return true
}
}
| gpl-3.0 | 476c45caecc67ae7289871d61c4ef47b | 33.132743 | 109 | 0.682872 | 5.012626 | false | false | false | false |
MarkNKamau/JustJava-Android | core/src/test/java/com/marknjunge/core/SampleData.kt | 1 | 933 | package com.marknjunge.core
import com.marknjunge.core.data.model.Address
import com.marknjunge.core.data.model.Session
import com.marknjunge.core.data.model.User
import com.marknjunge.core.data.model.Product
import com.marknjunge.core.data.model.ProductChoice
import com.marknjunge.core.data.model.ProductChoiceOption
internal object SampleData {
val address = Address(0, "Street", "instructions", "-1,1")
val user = User(1, "fName", "lName", 0L, "254712345678", "contact@mail.com", "token", "PASSWORD", listOf(address))
val session = Session("", 0L, 0)
val productChoiceOption = ProductChoiceOption(0, 0.0, "name", "desc")
val productChoice = ProductChoice(0, "choice", 0, 0, 0, listOf(productChoiceOption))
val product = Product(
0,
"prod",
"prod",
"image",
0L,
0.0,
"desc",
"type",
listOf(productChoice),
"status"
)
}
| apache-2.0 | 355aaddda3da5b80cf9da4f0ea2dd2ad | 31.172414 | 118 | 0.659164 | 3.574713 | false | false | false | false |
jriley/HackerNews | mobile/src/main/kotlin/dev/jriley/hackernews/data/Story.kt | 1 | 1668 | package dev.jriley.hackernews.data
import androidx.room.Entity
import androidx.room.PrimaryKey
/*
* id : The item's unique id.
* isDeleted : true if the item is deleted.
* type : The type of item. One of "job", "story", "comment", "poll", or "pollopt".
* by : The username of the item's author.
* time : Creation date of the item, in Unix Time.
* text : The comment, story or poll text. HTML.
* isDead : true if the item is dead.
* parent : The item's parent. For comments, either another comment or the relevant story. For pollopts, the relevant poll.
* kids : The ids of the item's comments, in ranked display order.
* url : The URL of the story.
* score : The story's score, or the votes for a pollopt.
* title : The title of the story, poll or job.
* parts : A list of related pollopts, in display order.
* descendants : In the case of stories or polls, the total comment count.
**/
@Entity(tableName = story)
data class Story(@PrimaryKey(autoGenerate = false)
val id: Long = -1L,
val by: String = "",
val time: Long? = -1L,
val url: String = "",
val score: Long? = -1L,
val title: String = "",
val isBookmarked: Boolean = false,
val storyTypes: Int = StoryTypes.NEW.ordinal) {
constructor(story: Story, storyTypes: StoryTypes) : this(story.id, story.by, story.time, story.url, story.score, story.title, story.isBookmarked, storyTypes.ordinal)
constructor(story: Story, bookmark: Boolean) : this(story.id, story.by, story.time, story.url, story.score, story.title, bookmark, story.storyTypes)
companion object
} | mpl-2.0 | 95a89950fc214b7bed667119397d6ba9 | 45.361111 | 169 | 0.654676 | 3.674009 | false | false | false | false |
KeenenCharles/AndroidUnplash | androidunsplash/src/main/java/com/keenencharles/unsplash/models/Collection.kt | 1 | 809 | package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class Collection(
var id: String? = null,
var title: String? = null,
var description: String? = null,
var curated: Boolean? = null,
var private: Boolean? = null,
var user: User? = null,
var links: Links? = null,
@SerializedName("cover_photo") var coverPhoto: CoverPhoto? = null,
@SerializedName("share_key") var shareKey: String? = null,
@SerializedName("total_photos") var totalPhotos: Int? = null,
@SerializedName("published_at") var publishedAt: String? = null,
@SerializedName("updated_at") var updatedAt: String? = null
) : Parcelable | mit | 268613f8d8cfec207b1c11e00c11d124 | 37.571429 | 74 | 0.667491 | 4.170103 | false | false | false | false |
Faless/godot | platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt | 16 | 7115 | /*************************************************************************/
/* VkThread.kt */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
@file:JvmName("VkThread")
package org.godotengine.godot.vulkan
import android.util.Log
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Thread implementation for the [VkSurfaceView] onto which the vulkan logic is ran.
*
* The implementation is modeled after [android.opengl.GLSurfaceView]'s GLThread.
*/
internal class VkThread(private val vkSurfaceView: VkSurfaceView, private val vkRenderer: VkRenderer) : Thread(TAG) {
companion object {
private val TAG = VkThread::class.java.simpleName
}
/**
* Used to run events scheduled on the thread.
*/
private val eventQueue = ArrayList<Runnable>()
/**
* Used to synchronize interaction with other threads (e.g: main thread).
*/
private val lock = ReentrantLock()
private val lockCondition = lock.newCondition()
private var shouldExit = false
private var exited = false
private var rendererInitialized = false
private var rendererResumed = false
private var resumed = false
private var surfaceChanged = false
private var hasSurface = false
private var width = 0
private var height = 0
/**
* Determine when drawing can occur on the thread. This usually occurs after the
* [android.view.Surface] is available, the app is in a resumed state.
*/
private val readyToDraw
get() = hasSurface && resumed
private fun threadExiting() {
lock.withLock {
exited = true
lockCondition.signalAll()
}
}
/**
* Queue an event on the [VkThread].
*/
fun queueEvent(event: Runnable) {
lock.withLock {
eventQueue.add(event)
lockCondition.signalAll()
}
}
/**
* Request the thread to exit and block until it's done.
*/
fun blockingExit() {
lock.withLock {
shouldExit = true
lockCondition.signalAll()
while (!exited) {
try {
Log.i(TAG, "Waiting on exit for $name")
lockCondition.await()
} catch (ex: InterruptedException) {
currentThread().interrupt()
}
}
}
}
/**
* Invoked when the app resumes.
*/
fun onResume() {
lock.withLock {
resumed = true
lockCondition.signalAll()
}
}
/**
* Invoked when the app pauses.
*/
fun onPause() {
lock.withLock {
resumed = false
lockCondition.signalAll()
}
}
/**
* Invoked when the [android.view.Surface] has been created.
*/
fun onSurfaceCreated() {
// This is a no op because surface creation will always be followed by surfaceChanged()
// which provide all the needed information.
}
/**
* Invoked following structural updates to [android.view.Surface].
*/
fun onSurfaceChanged(width: Int, height: Int) {
lock.withLock {
hasSurface = true
surfaceChanged = true;
this.width = width
this.height = height
lockCondition.signalAll()
}
}
/**
* Invoked when the [android.view.Surface] is no longer available.
*/
fun onSurfaceDestroyed() {
lock.withLock {
hasSurface = false
lockCondition.signalAll()
}
}
/**
* Thread loop modeled after [android.opengl.GLSurfaceView]'s GLThread.
*/
override fun run() {
try {
while (true) {
var event: Runnable? = null
lock.withLock {
while (true) {
// Code path for exiting the thread loop.
if (shouldExit) {
vkRenderer.onVkDestroy()
return
}
// Check for events and execute them outside of the loop if found to avoid
// blocking the thread lifecycle by holding onto the lock.
if (eventQueue.isNotEmpty()) {
event = eventQueue.removeAt(0)
break;
}
if (readyToDraw) {
if (!rendererResumed) {
rendererResumed = true
vkRenderer.onVkResume()
if (!rendererInitialized) {
rendererInitialized = true
vkRenderer.onVkSurfaceCreated(vkSurfaceView.holder.surface)
}
}
if (surfaceChanged) {
vkRenderer.onVkSurfaceChanged(vkSurfaceView.holder.surface, width, height)
surfaceChanged = false
}
// Break out of the loop so drawing can occur without holding onto the lock.
break;
} else if (rendererResumed) {
// If we aren't ready to draw but are resumed, that means we either lost a surface
// or the app was paused.
rendererResumed = false
vkRenderer.onVkPause()
}
// We only reach this state if we are not ready to draw and have no queued events, so
// we wait.
// On state change, the thread will be awoken using the [lock] and [lockCondition], and
// we will resume execution.
lockCondition.await()
}
}
// Run queued event.
if (event != null) {
event?.run()
continue
}
// Draw only when there no more queued events.
vkRenderer.onVkDrawFrame()
}
} catch (ex: InterruptedException) {
Log.i(TAG, "InterruptedException", ex)
} catch (ex: IllegalStateException) {
Log.i(TAG, "IllegalStateException", ex)
} finally {
threadExiting()
}
}
}
| mit | 9a7f49d323bdf395c1c8060f957071f4 | 29.405983 | 117 | 0.592551 | 4.309509 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/RuntimeDebugInfo.kt | 1 | 2120 | package com.bajdcc.LALR1.grammar.runtime
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeArray
import java.io.Serializable
/**
* 【扩展】调试与开发
*
* @author bajdcc
*/
class RuntimeDebugInfo : IRuntimeDebugInfo, Serializable {
override val dataMap = mutableMapOf<String, Any>()
private val exports = mutableMapOf<String, Int>()
private val func = mutableMapOf<Int, String>()
private val externalValue = mutableMapOf<String, RuntimeDebugValue>()
private val externalExec = mutableMapOf<String, RuntimeDebugExec>()
override val externFuncList: List<RuntimeArray>
get() {
val array = mutableListOf<RuntimeArray>()
externalExec.entries.sortedBy { it.key }.forEach { a ->
val arr = RuntimeArray()
arr.add(RuntimeObject(a.key))
arr.add(RuntimeObject(exports.getOrDefault(a.key, -1).toLong()))
arr.add(RuntimeObject(a.value.paramsDoc))
arr.add(RuntimeObject(a.value.doc))
array.add(arr)
}
return array
}
fun addExports(name: String, addr: Int) {
exports[name] = addr
}
fun addFunc(name: String, addr: Int) {
func[addr] = name
}
override fun getFuncNameByAddress(addr: Int): String {
return func.getOrDefault(addr, "unknown")
}
override fun getAddressOfExportFunc(name: String): Int {
return exports.getOrDefault(name, -1)
}
override fun getValueCallByName(name: String): RuntimeDebugValue? {
return externalValue.getOrDefault(name, null)
}
override fun getExecCallByName(name: String): RuntimeDebugExec? {
return externalExec.getOrDefault(name, null)
}
override fun addExternalValue(name: String, func: RuntimeDebugValue): Boolean {
return externalValue.put(name, func) != null
}
override fun addExternalFunc(name: String, func: RuntimeDebugExec): Boolean {
return externalExec.put(name, func) != null
}
companion object {
private const val serialVersionUID = 1L
}
}
| mit | 985e1d6bb8475d60544949703773868d | 29.911765 | 83 | 0.647954 | 4.342975 | false | false | false | false |
android/architecture-components-samples | GithubBrowserSample/app/src/androidTest/java/com/android/example/github/util/RecyclerViewMatcher.kt | 1 | 2801 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.github.util
import android.content.res.Resources
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
/**
* taken from https://gist.github.com/baconpat/8405a88d04bd1942eb5e430d33e4faa2
* license MIT
*/
class RecyclerViewMatcher(private val recyclerViewId: Int) {
fun atPosition(position: Int): Matcher<View> {
return atPositionOnView(position, -1)
}
private fun atPositionOnView(position: Int, targetViewId: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
var resources: Resources? = null
var childView: View? = null
override fun describeTo(description: Description) {
var idDescription = recyclerViewId.toString()
if (this.resources != null) {
idDescription = try {
this.resources!!.getResourceName(recyclerViewId)
} catch (var4: Resources.NotFoundException) {
"$recyclerViewId (resource name not found)"
}
}
description.appendText("RecyclerView with id: $idDescription at position: $position")
}
public override fun matchesSafely(view: View): Boolean {
this.resources = view.resources
if (childView == null) {
val recyclerView = view.rootView.findViewById<RecyclerView>(recyclerViewId)
if (recyclerView?.id == recyclerViewId) {
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
childView = viewHolder?.itemView
} else {
return false
}
}
return if (targetViewId == -1) {
view === childView
} else {
val targetView = childView?.findViewById<View>(targetViewId)
view === targetView
}
}
}
}
} | apache-2.0 | 27fa9c6d3c829ee1f9c8549c2d020b7c | 34.923077 | 101 | 0.60407 | 5.046847 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadServiceFacade.kt | 1 | 2107 | package org.wordpress.android.ui.uploads
import android.content.Context
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.PostImmutableModel
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import java.util.ArrayList
import javax.inject.Inject
/**
* An injectable class built on top of [UploadService].
*
* The main purpose of this is to provide testability for classes that use [UploadService]. This should never
* contain any static methods.
*/
class UploadServiceFacade @Inject constructor(private val appContext: Context) {
fun uploadPost(context: Context, post: PostModel, trackAnalytics: Boolean) {
val intent = UploadService.getRetryUploadServiceIntent(context, post, trackAnalytics)
context.startService(intent)
}
fun uploadPost(context: Context, postId: Int, isFirstTimePublish: Boolean) =
UploadService.uploadPost(context, postId, isFirstTimePublish)
fun isPostUploadingOrQueued(post: PostImmutableModel) =
UploadService.isPostUploadingOrQueued(post)
fun cancelFinalNotification(post: PostImmutableModel) =
UploadService.cancelFinalNotification(appContext, post)
fun cancelFinalNotificationForMedia(site: SiteModel) =
UploadService.cancelFinalNotificationForMedia(appContext, site)
fun uploadMedia(mediaList: ArrayList<MediaModel>) =
UploadService.uploadMedia(appContext, mediaList)
fun getPendingOrInProgressFeaturedImageUploadForPost(post: PostImmutableModel): MediaModel? =
UploadService.getPendingOrInProgressFeaturedImageUploadForPost(post)
fun uploadMediaFromEditor(mediaList: ArrayList<MediaModel>) {
UploadService.uploadMediaFromEditor(appContext, mediaList)
}
fun isPendingOrInProgressMediaUpload(mediaModel: MediaModel): Boolean =
UploadService.isPendingOrInProgressMediaUpload(mediaModel)
fun getUploadProgressForMedia(mediaModel: MediaModel): Float =
UploadService.getUploadProgressForMedia(mediaModel)
}
| gpl-2.0 | 1e1805dd5095aa4a80a23747eb7f0c73 | 41.14 | 109 | 0.776459 | 5.052758 | false | false | false | false |
edwardharks/Aircraft-Recognition | androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/aircraftupdater/Injector.kt | 1 | 709 | package com.edwardharker.aircraftrecognition.aircraftupdater
import com.edwardharker.aircraftrecognition.repository.aircraftRepository
import com.edwardharker.aircraftrecognition.repository.remoteAircraftRepository
import com.edwardharker.aircraftrecognition.repository.staticAircraftRepository
import rx.android.schedulers.AndroidSchedulers.mainThread
import rx.schedulers.Schedulers.io
fun aircraftUpdater(): AircraftUpdater {
return AircraftUpdater(
ioScheduler = io(),
mainScheduler = mainThread(),
staticAircraftRepository = staticAircraftRepository(),
remoteAircraftRepository = remoteAircraftRepository(),
aircraftRepository = aircraftRepository()
)
}
| gpl-3.0 | 90bf1f82d6ec1838defb10115bd0e58b | 40.705882 | 79 | 0.812412 | 5.717742 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/textFieldWithBrowseButton.kt | 1 | 2926 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder
import com.intellij.openapi.Disposable
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.ObservableMutableProperty
import com.intellij.openapi.observable.util.bind
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.validation.DialogValidation
import com.intellij.openapi.ui.validation.forTextFieldWithBrowseButton
import com.intellij.openapi.ui.validation.trimParameter
import com.intellij.ui.dsl.builder.impl.CellImpl.Companion.installValidationRequestor
import com.intellij.util.containers.map2Array
import org.jetbrains.annotations.ApiStatus
import kotlin.reflect.KMutableProperty0
import com.intellij.openapi.observable.util.whenTextChangedFromUi as whenTextChangedFromUiImpl
/**
* Minimal width of text field in chars
*
* @see COLUMNS_TINY
* @see COLUMNS_SHORT
* @see COLUMNS_MEDIUM
* @see COLUMNS_LARGE
*/
fun <T : TextFieldWithBrowseButton> Cell<T>.columns(columns: Int): Cell<T> {
component.textField.columns = columns
return this
}
@Deprecated("Please, recompile code", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval
fun <T : TextFieldWithBrowseButton> Cell<T>.bindText(property: GraphProperty<String>) = bindText(property)
fun <T : TextFieldWithBrowseButton> Cell<T>.bindText(property: ObservableMutableProperty<String>): Cell<T> {
installValidationRequestor(property)
return applyToComponent { bind(property) }
}
fun <T : TextFieldWithBrowseButton> Cell<T>.bindText(prop: KMutableProperty0<String>): Cell<T> {
return bindText(prop.toMutableProperty())
}
fun <T : TextFieldWithBrowseButton> Cell<T>.bindText(getter: () -> String, setter: (String) -> Unit): Cell<T> {
return bindText(MutableProperty(getter, setter))
}
fun <T : TextFieldWithBrowseButton> Cell<T>.bindText(prop: MutableProperty<String>): Cell<T> {
return bind(TextFieldWithBrowseButton::getText, TextFieldWithBrowseButton::setText, prop)
}
fun <T : TextFieldWithBrowseButton> Cell<T>.text(text: String): Cell<T> {
component.text = text
return this
}
fun <T : TextFieldWithBrowseButton> Cell<T>.trimmedTextValidation(vararg validations: DialogValidation.WithParameter<() -> String>) =
textValidation(*validations.map2Array { it.trimParameter() })
fun <T : TextFieldWithBrowseButton> Cell<T>.textValidation(vararg validations: DialogValidation.WithParameter<() -> String>) =
validation(*validations.map2Array { it.forTextFieldWithBrowseButton() })
@ApiStatus.Experimental
fun <T : TextFieldWithBrowseButton> Cell<T>.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit): Cell<T> {
return applyToComponent { whenTextChangedFromUiImpl(parentDisposable, listener) }
} | apache-2.0 | f772cacc207086b71f369fb246da1e3f | 43.348485 | 158 | 0.795967 | 4.259098 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithLambdaFix.kt | 1 | 4297 | // 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.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class SurroundWithLambdaFix(
expression: KtExpression
) : KotlinQuickFixAction<KtExpression>(expression), HighPriorityAction {
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("surround.with.lambda")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val nameReference = element ?: return
val newExpression = KtPsiFactory(project).buildExpression {
appendFixedText("{ ")
appendExpression(nameReference)
appendFixedText(" }")
}
nameReference.replace(newExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
private val LOG = Logger.getInstance(SurroundWithLambdaFix::class.java)
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? {
val diagnosticFactory = diagnostic.factory
val expectedType: KotlinType
val expressionType: KotlinType
when (diagnosticFactory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.TYPE_MISMATCH_WARNING -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.CONSTANT_EXPECTED_TYPE_MISMATCH -> {
val context = (diagnostic.psiFile as KtFile).analyzeWithContent()
val diagnosticWithParameters = Errors.CONSTANT_EXPECTED_TYPE_MISMATCH.cast(diagnostic)
val diagnosticElement = diagnostic.psiElement
if (!(diagnosticElement is KtExpression)) {
LOG.error("Unexpected element: " + diagnosticElement.text)
return null
}
expectedType = diagnosticWithParameters.b
expressionType = context.getType(diagnosticElement) ?: return null
}
else -> {
LOG.error("Unexpected diagnostic: " + DefaultErrorMessages.render(diagnostic))
return null
}
}
if (!expectedType.isFunctionOrSuspendFunctionType) return null
if (expectedType.arguments.size != 1) return null
val lambdaReturnType = expectedType.arguments[0].type
if (!expressionType.makeNotNullable().isSubtypeOf(lambdaReturnType) &&
!(expressionType.isPrimitiveNumberType() && lambdaReturnType.isPrimitiveNumberType())
) return null
val diagnosticElement = diagnostic.psiElement as KtExpression
return SurroundWithLambdaFix(diagnosticElement)
}
}
} | apache-2.0 | f5b832ba59fd223876b2157debd42e24 | 46.755556 | 158 | 0.686293 | 5.767785 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/LibraryInfoCache.kt | 1 | 5706 | // 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.base.projectStructure
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.serviceContainer.AlreadyDisposedException
import com.intellij.util.PathUtil
import com.intellij.util.messages.Topic
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.findLibraryBridge
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.base.util.caching.WorkspaceEntityChangeListener
import org.jetbrains.kotlin.idea.base.platforms.LibraryEffectiveKindProvider
import org.jetbrains.kotlin.idea.base.platforms.isKlibLibraryRootForPlatform
import org.jetbrains.kotlin.idea.base.platforms.platform
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
class LibraryInfoCache(project: Project): SynchronizedFineGrainedEntityCache<Library, List<LibraryInfo>>(project, cleanOnLowMemory = true) {
override fun subscribe() {
val busConnection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeImmediately(busConnection, ModelChangeListener(project))
}
override fun checkKeyValidity(key: Library) {
if (key is LibraryEx && key.isDisposed) {
throw AlreadyDisposedException("Library ${key.name} is already disposed")
}
}
override fun calculate(key: Library): List<LibraryInfo> {
return when (val platformKind = getPlatform(key).idePlatformKind) {
is JvmIdePlatformKind -> listOf(JvmLibraryInfo(project, key))
is CommonIdePlatformKind -> createLibraryInfos(key, platformKind, ::CommonKlibLibraryInfo, ::CommonMetadataLibraryInfo)
is JsIdePlatformKind -> createLibraryInfos(key, platformKind, ::JsKlibLibraryInfo, ::JsMetadataLibraryInfo)
is NativeIdePlatformKind -> createLibraryInfos(key, platformKind, ::NativeKlibLibraryInfo, null)
else -> error("Unexpected platform kind: $platformKind")
}
}
private fun createLibraryInfos(
library: Library,
platformKind: IdePlatformKind,
klibLibraryInfoFactory: (Project, Library, String) -> LibraryInfo,
metadataLibraryInfoFactory: ((Project, Library) -> LibraryInfo)?
): List<LibraryInfo> {
val defaultPlatform = platformKind.defaultPlatform
val klibFiles = library.getFiles(OrderRootType.CLASSES).filter { it.isKlibLibraryRootForPlatform(defaultPlatform) }
if (klibFiles.isNotEmpty()) {
return ArrayList<LibraryInfo>(klibFiles.size).apply {
for (file in klibFiles) {
val path = PathUtil.getLocalPath(file) ?: continue
add(klibLibraryInfoFactory(project, library, path))
}
}
} else if (metadataLibraryInfoFactory != null) {
return listOfNotNull(metadataLibraryInfoFactory(project, library))
} else {
return emptyList()
}
}
private fun getPlatform(library: Library): TargetPlatform {
if (library is LibraryEx && !library.isDisposed) {
return LibraryEffectiveKindProvider.getInstance(project).getEffectiveKind(library).platform
}
return JvmPlatforms.defaultJvmPlatform
}
internal class ModelChangeListener(project: Project) : WorkspaceEntityChangeListener<LibraryEntity, Library>(project, afterChangeApplied = false) {
override val entityClass: Class<LibraryEntity>
get() = LibraryEntity::class.java
override fun map(storage: EntityStorage, entity: LibraryEntity): Library? =
entity.findLibraryBridge(storage) ?:
// TODO: workaround to bypass bug with new modules not present in storageAfter
entity.findLibraryBridge(WorkspaceModel.getInstance(project).entityStorage.current)
override fun entitiesChanged(outdated: List<Library>) {
val libraryInfoCache = getInstance(project)
val droppedLibraryInfos = libraryInfoCache.invalidateKeysAndGetOutdatedValues(outdated).flatten()
if (droppedLibraryInfos.isNotEmpty()) {
project.messageBus.syncPublisher(OutdatedLibraryInfoListener.TOPIC).libraryInfosRemoved(droppedLibraryInfos)
}
}
}
companion object {
fun getInstance(project: Project): LibraryInfoCache = project.service()
}
}
interface OutdatedLibraryInfoListener {
fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>)
companion object {
@JvmStatic
@Topic.ProjectLevel
val TOPIC = Topic.create("library info listener", OutdatedLibraryInfoListener::class.java)
}
}
| apache-2.0 | fbdc4d6a15bedb844b6242cae51c6a53 | 47.355932 | 151 | 0.746232 | 5.149819 | false | false | false | false |
datarank/tempest | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/Randomizers.kt | 1 | 2945 | /*
* The MIT License (MIT)
* Copyright (c) 2018 DataRank, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.simplymeasured.elasticsearch.plugins.tempest.balancer
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.ListIterable
import org.eclipse.collections.api.ordered.OrderedIterable
import org.eclipse.collections.impl.list.mutable.FastList
import org.eclipse.collections.impl.list.mutable.primitive.DoubleArrayList
import java.util.*
fun <T> ListIterable<T>.selectRandomWeightedElement(random: Random, weight: (T) -> Double): T? {
if (this.isEmpty) { return null }
val weights = DoubleArrayList.newWithNValues(this.size(), 0.0)
this.forEachWithIndex { it, index ->
val accumulator = if (index == 0) 0.0 else weights[index - 1]
weights[index] = weight.invoke(it) + accumulator
}
val weightedSelection = random.nextDouble() * weights.last
val selectedIndex = weights.binarySearch(weightedSelection).let { if (it < 0) -(it + 1) else it }
return this[selectedIndex]
}
fun <T> ListIterable<T>.selectRandomNormalizedWeightedElement(random: Random, weight: (T) -> Double): T? {
if (this.isEmpty) { return null }
val accumulatedWeights = DoubleArrayList.newWithNValues(this.size(), 0.0)
val maxWeight = this.asLazy().collect(weight).max()
this.forEachWithIndex { it, index ->
val accumulator = if (index == 0) 0.0 else accumulatedWeights[index - 1]
accumulatedWeights[index] = maxWeight + 1.0 - weight.invoke(it) + accumulator
}
val weightedSelection = random.nextDouble() * accumulatedWeights.last
val selectedIndex = accumulatedWeights.binarySearch(weightedSelection).let { if (it < 0) -(it + 1) else it }
return this[selectedIndex]
}
fun <T> ListIterable<T>.selectRandomElement(random: Random): T {
return this[random.nextInt(this.size())]
} | mit | f726c2a5848547350494b4e1556947e6 | 45.03125 | 112 | 0.734126 | 4.001359 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-14-part-2/app/src/androidTest/java/dev/mfazio/pennydrop/LiveDataTestExtensions.kt | 2 | 873 | package dev.mfazio.pennydrop
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
// Adapted from here: https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 2,
timeUnit: TimeUnit = TimeUnit.SECONDS
): T? {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(newValue: T?) {
data = newValue
latch.countDown()
this@getOrAwaitValue.removeObserver(this)
}
}
this.observeForever(observer)
if(!latch.await(time, timeUnit)) {
this@getOrAwaitValue.removeObserver(observer)
return null
}
return data
} | apache-2.0 | 8a4d3423d5a91c267cbafa587da8722e | 24.705882 | 133 | 0.689576 | 4.098592 | false | false | false | false |
spinnaker/orca | keiko-core/src/main/kotlin/com/netflix/spinnaker/q/QueueProcessor.kt | 3 | 4617 | /*
* Copyright 2017 Netflix, 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.netflix.spinnaker.q
import com.netflix.spinnaker.KotlinOpen
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.HandlerThrewError
import com.netflix.spinnaker.q.metrics.MessageDead
import com.netflix.spinnaker.q.metrics.NoHandlerCapacity
import java.time.Duration
import java.util.Random
import java.util.concurrent.RejectedExecutionException
import javax.annotation.PostConstruct
import org.slf4j.Logger
import org.slf4j.LoggerFactory.getLogger
import org.springframework.scheduling.annotation.Scheduled
/**
* The processor that fetches messages from the [Queue] and hands them off to
* the appropriate [MessageHandler].
*/
@KotlinOpen
class QueueProcessor(
private val queue: Queue,
private val executor: QueueExecutor<*>,
private val handlers: Collection<MessageHandler<*>>,
private val activators: List<Activator>,
private val publisher: EventPublisher,
private val deadMessageHandler: DeadMessageCallback,
private val fillExecutorEachCycle: Boolean = true,
private val requeueDelay: Duration = Duration.ofSeconds(0),
private val requeueMaxJitter: Duration = Duration.ofSeconds(0)
) {
private val log: Logger = getLogger(javaClass)
private val random: Random = Random()
/**
* Polls the [Queue] once (or more if [fillExecutorEachCycle] is true) so
* long as [executor] has capacity.
*/
@Scheduled(fixedDelayString = "\${queue.poll.frequency.ms:50}")
fun poll() =
ifEnabled {
if (executor.hasCapacity()) {
if (fillExecutorEachCycle) {
if (queue.canPollMany) {
queue.poll(executor.availableCapacity(), callback)
} else {
executor.availableCapacity().downTo(1).forEach {
pollOnce()
}
}
} else {
pollOnce()
}
} else {
publisher.publishEvent(NoHandlerCapacity)
}
}
/**
* Polls the [Queue] once to attempt to read a single message.
*/
private fun pollOnce() {
queue.poll(callback)
}
val callback: QueueCallback = { message, ack ->
log.info("Received message $message")
val handler = handlerFor(message)
if (handler != null) {
try {
executor.execute {
try {
QueueContextHolder.set(message)
handler.invoke(message)
ack.invoke()
} catch (e: Throwable) {
// Something very bad is happening
log.error("Unhandled throwable from $message", e)
publisher.publishEvent(HandlerThrewError(message))
} finally {
QueueContextHolder.clear()
}
}
} catch (e: RejectedExecutionException) {
var requeueDelaySeconds = requeueDelay.seconds
if (requeueMaxJitter.seconds > 0) {
requeueDelaySeconds += random.nextInt(requeueMaxJitter.seconds.toInt())
}
val requeueDelay = Duration.ofSeconds(requeueDelaySeconds)
val numberOfAttempts = message.getAttribute<AttemptsAttribute>()
log.warn(
"Executor at capacity, re-queuing message {} (delay: {}, attempts: {})",
message,
requeueDelay,
numberOfAttempts,
e
)
queue.push(message, requeueDelay)
}
} else {
log.error("Unsupported message type ${message.javaClass.simpleName}: $message")
deadMessageHandler.invoke(queue, message)
publisher.publishEvent(MessageDead)
}
}
private fun ifEnabled(fn: () -> Unit) {
if (activators.all { it.enabled }) {
fn.invoke()
}
}
private val handlerCache = mutableMapOf<Class<out Message>, MessageHandler<*>>()
private fun handlerFor(message: Message) =
handlerCache[message.javaClass]
.let { handler ->
handler ?: handlers
.find { it.messageType.isAssignableFrom(message.javaClass) }
?.also { handlerCache[message.javaClass] = it }
}
@PostConstruct
fun confirmQueueType() =
log.info("Using queue $queue")
}
| apache-2.0 | 5e33d4565dfda2fda120486627154db7 | 31.0625 | 85 | 0.668616 | 4.426654 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRReviewThreadsPanel.kt | 8 | 2638 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.SingleComponentCenteringLayout
import com.intellij.util.ui.UIUtil
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadModel
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
object GHPRReviewThreadsPanel {
fun create(model: GHPRReviewThreadsModel, threadComponentFactory: (GHPRReviewThreadModel) -> JComponent): JComponent {
val panel = JPanel(VerticalLayout(12)).apply {
isOpaque = false
}
val loadingPanel = JPanel(SingleComponentCenteringLayout()).apply {
isOpaque = false
add(JLabel(ApplicationBundle.message("label.loading.page.please.wait")).apply {
foreground = UIUtil.getContextHelpForeground()
})
}
Controller(model, panel, loadingPanel, threadComponentFactory)
return panel
}
private class Controller(private val model: GHPRReviewThreadsModel,
private val panel: JPanel,
private val loadingPanel: JPanel,
private val threadComponentFactory: (GHPRReviewThreadModel) -> JComponent) {
init {
model.addListDataListener(object : ListDataListener {
override fun intervalRemoved(e: ListDataEvent) {
for (i in e.index1 downTo e.index0) {
panel.remove(i)
}
updateVisibility()
panel.revalidate()
panel.repaint()
}
override fun intervalAdded(e: ListDataEvent) {
for (i in e.index0..e.index1) {
panel.add(threadComponentFactory(model.getElementAt(i)), i)
}
updateVisibility()
panel.revalidate()
panel.repaint()
}
override fun contentsChanged(e: ListDataEvent) {
if (model.loaded) panel.remove(loadingPanel)
updateVisibility()
panel.validate()
panel.repaint()
}
})
if (!model.loaded) {
panel.add(loadingPanel)
}
else for (i in 0 until model.size) {
panel.add(threadComponentFactory(model.getElementAt(i)), i)
}
updateVisibility()
}
private fun updateVisibility() {
panel.isVisible = panel.componentCount > 0
}
}
} | apache-2.0 | 3ba239cad7a3ce58f1a5b543b4da4b74 | 32.405063 | 140 | 0.66793 | 4.8051 | false | false | false | false |
GunoH/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncBridge.kt | 1 | 15568 | package com.intellij.settingsSync
import com.intellij.configurationStore.saveSettings
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.runBlockingMaybeCancellable
import com.intellij.settingsSync.SettingsSyncBridge.PushRequestMode.*
import com.intellij.util.Alarm
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.nio.file.Path
import java.time.Instant
import java.util.concurrent.TimeUnit
/**
* Handles events about settings change both from the current IDE, and from the server, merges the settings, logs them,
* and provides the combined data to clients: both to the IDE and to the server.
*/
@ApiStatus.Internal
class SettingsSyncBridge(parentDisposable: Disposable,
private val appConfigPath: Path,
private val settingsLog: SettingsLog,
private val ideMediator: SettingsSyncIdeMediator,
private val remoteCommunicator: SettingsSyncRemoteCommunicator,
private val updateChecker: SettingsSyncUpdateChecker) {
private val pendingEvents = ContainerUtil.createConcurrentList<SyncSettingsEvent>()
private val queue = MergingUpdateQueue("SettingsSyncBridge", 1000, false, null, parentDisposable, null,
Alarm.ThreadToUse.POOLED_THREAD).apply {
setRestartTimerOnAdd(true)
}
private val updateObject = object : Update(1) { // all requests are always merged
override fun run() {
processPendingEvents()
// todo what if here a new event is added; probably synchronization is needed between pPE and adding to the queue
}
}
private val settingsChangeListener = SettingsChangeListener { event ->
LOG.debug("Adding settings changed event $event to the queue")
pendingEvents.add(event)
queue.queue(updateObject)
}
@RequiresBackgroundThread
internal fun initialize(initMode: InitMode) {
saveIdeSettings()
settingsLog.initialize()
if (initMode.shouldEnableSync()) { // the queue is not activated initially => events will be collected but not processed until we perform all initialization tasks
SettingsSyncEvents.getInstance().addSettingsChangedListener(settingsChangeListener)
ideMediator.activateStreamProvider()
}
applyInitialChanges(initMode)
if (initMode.shouldEnableSync()) {
queue.activate()
}
}
private fun saveIdeSettings() {
runBlockingMaybeCancellable {
saveSettings(ApplicationManager.getApplication(), forceSavingAllSettings = true)
}
}
private fun applyInitialChanges(initMode: InitMode) {
val previousState = collectCurrentState()
settingsLog.logExistingSettings()
try {
when (initMode) {
is InitMode.TakeFromServer -> applySnapshotFromServer(initMode.cloudEvent)
InitMode.PushToServer -> mergeAndPush(previousState.idePosition, previousState.cloudPosition, FORCE_PUSH)
InitMode.JustInit -> mergeAndPush(previousState.idePosition, previousState.cloudPosition, PUSH_IF_NEEDED)
is InitMode.MigrateFromOldStorage -> migrateFromOldStorage(initMode.migration)
}
}
catch (e: Throwable) {
stopSyncingAndRollback(previousState, e)
}
}
private fun applySnapshotFromServer(cloudEvent: SyncSettingsEvent.CloudChange) {
settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings
val masterPosition = settingsLog.forceWriteToMaster(cloudEvent.snapshot, "Remote changes to initialize settings by data from cloud")
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
// normally we set cloud position only after successful push to cloud, but in this case we already take all settings from the cloud,
// so no push is needed, and we know the cloud settings state.
settingsLog.setCloudPosition(masterPosition)
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = cloudEvent.serverVersionId
}
private fun migrateFromOldStorage(migration: SettingsSyncMigration) {
val migrationSnapshot = migration.getLocalDataIfAvailable(appConfigPath)
if (migrationSnapshot != null) {
settingsLog.applyIdeState(migrationSnapshot, "Migrate from old settings sync")
LOG.info("Migration from old storage applied.")
var masterPosition = settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings & by migration
// if there is already a version on the server, then it should be preferred over migration
val updateResult = remoteCommunicator.receiveUpdates()
if (updateResult is UpdateResult.Success) {
val snapshot = updateResult.settingsSnapshot
masterPosition = settingsLog.forceWriteToMaster(snapshot, "Remote changes to overwrite migration data by settings from cloud")
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = updateResult.serverVersionId
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
}
else {
if (migration.shouldEnableNewSync()) {
forcePushToCloud(masterPosition) // otherwise we place our migrated data to the cloud
}
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
migration.migrateCategoriesSyncStatus(appConfigPath, SettingsSyncSettings.getInstance())
saveIdeSettings()
migration.executeAfterApplying()
}
settingsLog.setCloudPosition(masterPosition)
}
else {
LOG.warn("Migration from old storage didn't happen, although it was identified as possible: no data to migrate")
settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings
}
}
private fun forcePushToCloud(masterPosition: SettingsLog.Position) {
pushAndHandleResult(true, masterPosition, onRejectedPush = {
LOG.error("Reject shouldn't happen when force push is used")
SettingsSyncStatusTracker.getInstance().updateOnError(SettingsSyncBundle.message("notification.title.push.error"))
})
}
internal sealed class InitMode {
object JustInit : InitMode()
class TakeFromServer(val cloudEvent: SyncSettingsEvent.CloudChange) : InitMode()
object PushToServer : InitMode()
class MigrateFromOldStorage(val migration: SettingsSyncMigration) : InitMode() {
override fun shouldEnableSync(): Boolean {
return migration.shouldEnableNewSync()
}
}
open fun shouldEnableSync(): Boolean = true
}
@RequiresBackgroundThread
private fun processPendingEvents() {
val previousState = collectCurrentState()
try {
var pushRequestMode: PushRequestMode = PUSH_IF_NEEDED
var mergeAndPushAfterProcessingEvents = true
while (pendingEvents.isNotEmpty()) {
val event = pendingEvents.removeAt(0)
LOG.debug("Processing event $event")
when (event) {
is SyncSettingsEvent.IdeChange -> {
settingsLog.applyIdeState(event.snapshot, "Local changes made in the IDE")
}
is SyncSettingsEvent.CloudChange -> {
settingsLog.applyCloudState(event.snapshot, "Remote changes")
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = event.serverVersionId
}
is SyncSettingsEvent.LogCurrentSettings -> {
settingsLog.logExistingSettings()
}
is SyncSettingsEvent.MustPushRequest -> {
pushRequestMode = MUST_PUSH
}
is SyncSettingsEvent.DeleteServerData -> {
mergeAndPushAfterProcessingEvents = false
stopSyncingAndRollback(previousState)
deleteServerData(event.afterDeleting)
}
SyncSettingsEvent.DeletedOnCloud -> {
mergeAndPushAfterProcessingEvents = false
stopSyncingAndRollback(previousState)
}
SyncSettingsEvent.PingRequest -> {}
}
}
if (mergeAndPushAfterProcessingEvents) {
mergeAndPush(previousState.idePosition, previousState.cloudPosition, pushRequestMode)
}
}
catch (exception: Throwable) {
stopSyncingAndRollback(previousState, exception)
}
}
private fun deleteServerData(afterDeleting: (DeleteServerDataResult) -> Unit) {
val deletionSnapshot = SettingsSnapshot(SettingsSnapshot.MetaInfo(Instant.now(), getLocalApplicationInfo(), isDeleted = true),
emptySet(), null)
val pushResult = pushToCloud(deletionSnapshot, force = true)
LOG.info("Deleting server data. Result: $pushResult")
when (pushResult) {
is SettingsSyncPushResult.Success -> {
afterDeleting(DeleteServerDataResult.Success)
}
is SettingsSyncPushResult.Error -> {
afterDeleting(DeleteServerDataResult.Error(pushResult.message))
}
SettingsSyncPushResult.Rejected -> {
afterDeleting(DeleteServerDataResult.Error("Deletion rejected by server"))
}
}
}
private class CurrentState(
val masterPosition: SettingsLog.Position,
val idePosition: SettingsLog.Position,
val cloudPosition: SettingsLog.Position,
val knownServerId: String?
)
private fun collectCurrentState(): CurrentState = CurrentState(settingsLog.getMasterPosition(),
settingsLog.getIdePosition(),
settingsLog.getCloudPosition(),
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId)
private fun stopSyncingAndRollback(previousState: CurrentState, exception: Throwable? = null) {
if (exception != null) {
LOG.error("Couldn't apply settings. Disabling sync and rolling back.", exception)
}
else {
LOG.info("Settings Sync is switched off. Rolling back.")
}
SettingsSyncSettings.getInstance().syncEnabled = false
if (exception != null) {
SettingsSyncStatusTracker.getInstance().updateOnError(exception.localizedMessage)
}
ideMediator.removeStreamProvider()
SettingsSyncEvents.getInstance().removeSettingsChangedListener(settingsChangeListener)
pendingEvents.clear()
rollback(previousState)
queue.deactivate() // for tests it is important to have it the last statement, otherwise waitForAllExecuted can finish before rollback
}
private fun rollback(previousState: CurrentState) {
try {
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = previousState.knownServerId
settingsLog.setIdePosition(previousState.idePosition)
settingsLog.setCloudPosition(previousState.cloudPosition)
settingsLog.setMasterPosition(previousState.masterPosition)
// we don't need to roll back the state of the IDE here, because it is the latest stage of mergeAndPush which can fail
// (pushing can fail also, but it is a normal failure which doesn't need to roll everything back and turn the sync off
}
catch (e: Throwable) {
LOG.error("Couldn't rollback to the previous successful state", e)
}
}
private fun mergeAndPush(previousIdePosition: SettingsLog.Position,
previousCloudPosition: SettingsLog.Position,
pushRequestMode: PushRequestMode) {
val newIdePosition = settingsLog.getIdePosition()
val newCloudPosition = settingsLog.getCloudPosition()
val masterPosition: SettingsLog.Position
if (newIdePosition != previousIdePosition || newCloudPosition != previousCloudPosition) {
// move master to the actual position. It can be a fast-forward to either ide, or cloud changes, or it can be a merge
masterPosition = settingsLog.advanceMaster()
}
else {
// there were only fake events without actual changes to the repository => master doesn't need to be changed either
masterPosition = settingsLog.getMasterPosition()
}
if (newIdePosition != masterPosition) { // master has advanced further that ide => the ide needs to be updated
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
}
if (newCloudPosition != masterPosition || pushRequestMode == MUST_PUSH || pushRequestMode == FORCE_PUSH) {
pushAndHandleResult(pushRequestMode == FORCE_PUSH, masterPosition, onRejectedPush = {
// todo add protection against potential infinite reject-update-reject cycle
// (it would indicate some problem, but still shouldn't cycle forever)
// In the case of reject we'll just "wait" for the next update event:
// it will be processed in the next session anyway
if (pendingEvents.none { it is SyncSettingsEvent.CloudChange }) {
// not to wait for too long, schedule an update right away unless it has already been scheduled
updateChecker.scheduleUpdateFromServer()
}
})
}
else {
LOG.debug("Nothing to push")
}
}
private fun pushAndHandleResult(force: Boolean, positionToSetCloudBranch: SettingsLog.Position, onRejectedPush: () -> Unit) {
val pushResult: SettingsSyncPushResult = pushToCloud(settingsLog.collectCurrentSnapshot(), force)
LOG.info("Result of pushing settings to the cloud: $pushResult")
when (pushResult) {
is SettingsSyncPushResult.Success -> {
settingsLog.setCloudPosition(positionToSetCloudBranch)
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = pushResult.serverVersionId
SettingsSyncStatusTracker.getInstance().updateOnSuccess()
}
is SettingsSyncPushResult.Error -> {
SettingsSyncStatusTracker.getInstance().updateOnError(
SettingsSyncBundle.message("notification.title.push.error") + ": " + pushResult.message)
}
SettingsSyncPushResult.Rejected -> {
onRejectedPush()
}
}
}
private enum class PushRequestMode {
PUSH_IF_NEEDED,
MUST_PUSH,
FORCE_PUSH
}
private fun pushToCloud(settingsSnapshot: SettingsSnapshot, force: Boolean): SettingsSyncPushResult {
val versionId = SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId
if (force) {
return remoteCommunicator.push(settingsSnapshot, force = true, versionId)
}
else if (remoteCommunicator.checkServerState() is ServerState.UpdateNeeded) {
return SettingsSyncPushResult.Rejected
}
else {
return remoteCommunicator.push(settingsSnapshot, force = false, versionId)
}
}
private fun pushToIde(settingsSnapshot: SettingsSnapshot, targetPosition: SettingsLog.Position) {
ideMediator.applyToIde(settingsSnapshot)
settingsLog.setIdePosition(targetPosition)
LOG.info("Applied settings to the IDE.")
}
@TestOnly
fun waitForAllExecuted(timeout: Long, timeUnit: TimeUnit) {
queue.waitForAllExecuted(timeout, timeUnit)
}
@VisibleForTesting
internal fun suspendEventProcessing() {
queue.suspend()
}
@VisibleForTesting
internal fun resumeEventProcessing() {
queue.resume()
}
companion object {
private val LOG = logger<SettingsSyncBridge>()
}
} | apache-2.0 | f1f6620e2afdceb86552c29ef12ade3d | 41.192412 | 166 | 0.716084 | 5.217158 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialogWrapper.kt | 3 | 3960 | // 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.progress.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.DialogWrapper.IdeModalityType
import com.intellij.openapi.ui.DialogWrapperPeer
import com.intellij.openapi.ui.DialogWrapperPeerFactory
import com.intellij.openapi.ui.impl.DialogWrapperPeerImpl
import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer
import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer.GlasspanePeerUnavailableException
import com.intellij.ui.PopupBorder
import java.awt.Component
import java.awt.Window
import java.util.function.Function
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JRootPane
import javax.swing.border.Border
internal class ProgressDialogWrapper(
private val panel: JPanel,
private val cancelAction: () -> Unit,
peerFactory: Function<DialogWrapper, DialogWrapperPeer>,
) : DialogWrapper(peerFactory) {
init {
init()
}
override fun doCancelAction() {
cancelAction()
}
override fun init() {
super.init()
setUndecorated(true)
rootPane.windowDecorationStyle = JRootPane.NONE
panel.border = PopupBorder.Factory.create(true, true)
}
fun superInitResizeListener() {
super.initResizeListener()
}
override fun isProgressDialog(): Boolean {
return true
}
override fun createCenterPanel(): JComponent {
return panel
}
override fun createContentPaneBorder(): Border? {
return null
}
override fun createPeer(parent: Component, canBeParent: Boolean): DialogWrapperPeer {
error("must not be called")
}
override fun createPeer(owner: Window?, canBeParent: Boolean, applicationModalIfPossible: Boolean): DialogWrapperPeer {
error("must not be called")
}
override fun createPeer(project: Project?, canBeParent: Boolean): DialogWrapperPeer {
error("must not be called")
}
override fun createPeer(owner: Window?, canBeParent: Boolean, ideModalityType: IdeModalityType?): DialogWrapperPeer {
error("must not be called")
}
override fun createPeer(project: Project?, canBeParent: Boolean, ideModalityType: IdeModalityType): DialogWrapperPeer {
error("must not be called")
}
}
internal fun createDialogWrapper(
panel: JPanel,
cancelAction: () -> Unit,
window: Window,
writeAction: Boolean,
project: Project?,
): DialogWrapper {
val dialog = if (window.isShowing) {
ProgressDialogWrapper(panel, cancelAction, peerFactory(window, !writeAction))
}
else {
ProgressDialogWrapper(panel, cancelAction, peerFactory(project)).also {
it.superInitResizeListener()
}
}
setupProgressDialog(dialog, writeAction)
return dialog
}
private fun peerFactory(window: Window, lightPopup: Boolean): Function<DialogWrapper, DialogWrapperPeer> {
return java.util.function.Function { dialogWrapper ->
if (lightPopup) {
try {
GlassPaneDialogWrapperPeer(dialogWrapper, window)
}
catch (e: GlasspanePeerUnavailableException) {
DialogWrapperPeerFactory.getInstance().createPeer(dialogWrapper, window, false)
}
}
else {
DialogWrapperPeerFactory.getInstance().createPeer(dialogWrapper, window, false)
}
}
}
private fun peerFactory(project: Project?): Function<DialogWrapper, DialogWrapperPeer> {
return Function { dialogWrapper ->
DialogWrapperPeerFactory.getInstance().createPeer(dialogWrapper, project, false, IdeModalityType.IDE)
}
}
internal fun setupProgressDialog(dialog: DialogWrapper, writeAction: Boolean) {
dialog.setUndecorated(true)
val peer = dialog.peer
if (peer is DialogWrapperPeerImpl) {
peer.setAutoRequestFocus(false)
if (writeAction) {
dialog.isModal = false // display the dialog and continue with EDT execution, don't block it forever
}
}
dialog.pack()
}
| apache-2.0 | c1ebf6d017cf15f8122afe3b1d53aee0 | 29.461538 | 121 | 0.75202 | 4.43449 | false | false | false | false |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/tracker/BatteryInfoTracker.kt | 1 | 3992 | package me.ycdev.android.lib.common.tracker
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import me.ycdev.android.lib.common.pattern.SingletonHolderP1
import me.ycdev.android.lib.common.utils.LibLogger
import me.ycdev.android.lib.common.wrapper.BroadcastHelper
import me.ycdev.android.lib.common.wrapper.IntentHelper
@Suppress("unused")
class BatteryInfoTracker private constructor(cxt: Context) :
WeakTracker<BatteryInfoTracker.BatteryInfoListener>() {
private val context: Context = cxt.applicationContext
private var batteryInfo: BatteryInfo? = null
private var batteryScale = 100
private val batteryInfoReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
LibLogger.i(TAG, "Received: ${intent.action}")
updateBatteryInfo(intent)
}
}
data class BatteryInfo(
var level: Int = 0,
var scale: Int = 0,
var percent: Int = 0, // percent corrected by us
var status: Int = BatteryManager.BATTERY_STATUS_UNKNOWN,
var plugged: Int = 0,
var voltage: Int = 0,
var temperature: Double = 0.0
)
interface BatteryInfoListener {
/**
* @param newData Read-only, cannot be modified.
*/
fun onBatteryInfoUpdated(newData: BatteryInfo)
}
override fun startTracker() {
LibLogger.i(TAG, "BatteryInfo tracker is running")
val filter = IntentFilter()
filter.addAction(Intent.ACTION_BATTERY_CHANGED)
val intent = BroadcastHelper.registerForExternal(context, batteryInfoReceiver, filter)
if (intent != null) {
updateBatteryInfo(intent)
}
}
override fun stopTracker() {
LibLogger.i(TAG, "BatteryInfo tracker is stopped")
context.unregisterReceiver(batteryInfoReceiver)
}
override fun onListenerAdded(listener: BatteryInfoListener) {
batteryInfo?.let { listener.onBatteryInfoUpdated(it) }
}
private fun updateBatteryInfo(intent: Intent) {
val data = BatteryInfo()
data.level = IntentHelper.getIntExtra(intent, BatteryManager.EXTRA_LEVEL, 0)
data.scale = IntentHelper.getIntExtra(intent, BatteryManager.EXTRA_SCALE, 100)
data.status = IntentHelper.getIntExtra(
intent,
BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_UNKNOWN
)
data.plugged = IntentHelper.getIntExtra(intent, BatteryManager.EXTRA_PLUGGED, 0)
data.voltage = IntentHelper.getIntExtra(intent, BatteryManager.EXTRA_VOLTAGE, 0)
data.temperature = IntentHelper.getIntExtra(
intent, BatteryManager.EXTRA_TEMPERATURE, 0
) * 0.1
fixData(data)
val reportedPercent = if (data.scale < 1) data.level else data.level * 100 / data.scale
data.percent = when {
reportedPercent < 0 -> 0
reportedPercent > 100 -> 100
else -> reportedPercent
}
LibLogger.d(TAG, "battery info updated: $data")
batteryInfo = data
notifyListeners { it.onBatteryInfoUpdated(data) }
}
private fun fixData(data: BatteryInfo) {
// We may need to update 'batteryScale'
if (data.level > data.scale) {
LibLogger.e(
TAG, "Bad battery data! level: %d, scale: %d, batteryScale: %d",
data.level, data.scale, batteryScale
)
if (data.level % 100 == 0) {
batteryScale = data.level
}
}
// We may need to correct the 'data.scale'
if (data.scale < batteryScale) {
data.scale = batteryScale
}
}
companion object : SingletonHolderP1<BatteryInfoTracker, Context>(::BatteryInfoTracker) {
private const val TAG = "BatteryInfoTracker"
}
}
| apache-2.0 | f389801ad75f960ede8f76c17dad1c59 | 34.017544 | 95 | 0.648547 | 4.372399 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/jobs/CheckServiceReachabilityJob.kt | 1 | 4296 | package org.thoughtcrime.securesms.jobs
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.BuildConfig
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobmanager.Data
import org.thoughtcrime.securesms.jobmanager.Job
import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState
import org.whispersystems.signalservice.internal.util.StaticCredentialsProvider
import org.whispersystems.signalservice.internal.websocket.WebSocketConnection
import java.util.Optional
import java.util.concurrent.TimeUnit
/**
* Checks to see if a censored user can establish a websocket connection with an uncensored network configuration.
*/
class CheckServiceReachabilityJob private constructor(params: Parameters) : BaseJob(params) {
constructor() : this(
Parameters.Builder()
.addConstraint(NetworkConstraint.KEY)
.setLifespan(TimeUnit.HOURS.toMillis(12))
.setMaxAttempts(1)
.build()
)
companion object {
private val TAG = Log.tag(CheckServiceReachabilityJob::class.java)
const val KEY = "CheckServiceReachabilityJob"
@JvmStatic
fun enqueueIfNecessary() {
val isCensored = ApplicationDependencies.getSignalServiceNetworkAccess().isCensored()
val timeSinceLastCheck = System.currentTimeMillis() - SignalStore.misc().lastCensorshipServiceReachabilityCheckTime
if (SignalStore.account().isRegistered && isCensored && timeSinceLastCheck > TimeUnit.DAYS.toMillis(1)) {
ApplicationDependencies.getJobManager().add(CheckServiceReachabilityJob())
}
}
}
override fun serialize(): Data {
return Data.EMPTY
}
override fun getFactoryKey(): String {
return KEY
}
override fun onRun() {
if (!SignalStore.account().isRegistered) {
Log.w(TAG, "Not registered, skipping.")
SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis()
return
}
if (!ApplicationDependencies.getSignalServiceNetworkAccess().isCensored()) {
Log.w(TAG, "Not currently censored, skipping.")
SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis()
return
}
SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis()
val uncensoredWebsocket = WebSocketConnection(
"uncensored-test",
ApplicationDependencies.getSignalServiceNetworkAccess().uncensoredConfiguration,
Optional.of(
StaticCredentialsProvider(
SignalStore.account().aci,
SignalStore.account().pni,
SignalStore.account().e164,
SignalStore.account().deviceId,
SignalStore.account().servicePassword
)
),
BuildConfig.SIGNAL_AGENT,
null,
""
)
try {
val startTime = System.currentTimeMillis()
val state: WebSocketConnectionState = uncensoredWebsocket.connect()
.filter { it == WebSocketConnectionState.CONNECTED || it == WebSocketConnectionState.FAILED }
.timeout(30, TimeUnit.SECONDS)
.blockingFirst(WebSocketConnectionState.FAILED)
if (state == WebSocketConnectionState.CONNECTED) {
Log.i(TAG, "Established connection in ${System.currentTimeMillis() - startTime} ms! Service is reachable!")
SignalStore.misc().isServiceReachableWithoutCircumvention = true
} else {
Log.w(TAG, "Failed to establish a connection in ${System.currentTimeMillis() - startTime} ms.")
SignalStore.misc().isServiceReachableWithoutCircumvention = false
}
} catch (exception: Exception) {
Log.w(TAG, "Failed to connect to the websocket.", exception)
SignalStore.misc().isServiceReachableWithoutCircumvention = false
} finally {
uncensoredWebsocket.disconnect()
}
}
override fun onShouldRetry(e: Exception): Boolean {
return false
}
override fun onFailure() {
}
class Factory : Job.Factory<CheckServiceReachabilityJob> {
override fun create(parameters: Parameters, data: Data): CheckServiceReachabilityJob {
return CheckServiceReachabilityJob(parameters)
}
}
}
| gpl-3.0 | cc57510b9dbfc62bd8a46c6b63a38411 | 35.10084 | 121 | 0.735568 | 4.768036 | false | false | false | false |
CzBiX/v2ex-android | app/src/main/kotlin/com/czbix/v2ex/ui/fragment/TopicListFragment.kt | 1 | 11075 | package com.czbix.v2ex.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.collection.ArraySet
import androidx.loader.app.LoaderManager.LoaderCallbacks
import androidx.loader.content.Loader
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.epoxy.addGlidePreloader
import com.airbnb.epoxy.glidePreloader
import com.bumptech.glide.Glide
import com.czbix.v2ex.AppCtx
import com.czbix.v2ex.R
import com.czbix.v2ex.common.UserState
import com.czbix.v2ex.common.exception.ConnectionException
import com.czbix.v2ex.common.exception.FatalException
import com.czbix.v2ex.common.exception.RemoteException
import com.czbix.v2ex.common.exception.RequestException
import com.czbix.v2ex.dao.NodeDao
import com.czbix.v2ex.db.TopicRecordDao
import com.czbix.v2ex.event.BaseEvent
import com.czbix.v2ex.helper.RxBus
import com.czbix.v2ex.inject.Injectable
import com.czbix.v2ex.model.Node
import com.czbix.v2ex.model.Page
import com.czbix.v2ex.model.Topic
import com.czbix.v2ex.network.HttpStatus
import com.czbix.v2ex.network.V2exService
import com.czbix.v2ex.ui.MainActivity
import com.czbix.v2ex.ui.TopicActivity
import com.czbix.v2ex.ui.TopicEditActivity
import com.czbix.v2ex.ui.adapter.TopicController
import com.czbix.v2ex.ui.adapter.`TopicController$TopicModel_`
import com.czbix.v2ex.ui.loader.AsyncTaskLoader.LoaderResult
import com.czbix.v2ex.ui.loader.TopicListLoader
import com.czbix.v2ex.ui.widget.AvatarView
import com.czbix.v2ex.ui.widget.DividerItemDecoration
import com.czbix.v2ex.ui.widget.TopicView.OnTopicActionListener
import com.czbix.v2ex.util.ExceptionUtils
import com.czbix.v2ex.util.ExecutorUtils
import com.czbix.v2ex.util.LogUtils
import com.czbix.v2ex.util.dispose
import com.google.common.net.HttpHeaders
import com.google.firebase.crashlytics.FirebaseCrashlytics
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
class TopicListFragment : androidx.fragment.app.Fragment(), LoaderCallbacks<LoaderResult<TopicListLoader.TopicList>>, SwipeRefreshLayout.OnRefreshListener, OnTopicActionListener, Injectable {
private lateinit var mPage: Page
private lateinit var controller: TopicController
private lateinit var mLayout: SwipeRefreshLayout
private lateinit var mRecyclerView: EpoxyRecyclerView
private lateinit var mFavIcon: MenuItem
private val disposables: MutableList<Disposable> = mutableListOf()
private var mFavored: Boolean = false
private var mOnceToken: String? = null
@Inject
lateinit var topicDao: TopicRecordDao
@Inject
lateinit var v2exService: V2exService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val arguments = arguments
if (arguments != null) {
arguments.getParcelable<Page>(ARG_PAGE).let {
if (it == null) {
throw FatalException("node can't be null")
}
mPage = it
}
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
mLayout = inflater.inflate(R.layout.fragment_topic_list,
container, false) as SwipeRefreshLayout
mRecyclerView = mLayout.findViewById(R.id.recycle_view)
mLayout.setColorSchemeResources(R.color.material_blue_grey_500, R.color.material_blue_grey_700, R.color.material_blue_grey_900)
mLayout.setOnRefreshListener(this)
mRecyclerView.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL_LIST))
mRecyclerView.addGlidePreloader(
Glide.with(this), 5,
preloader = glidePreloader(viewMetadata = { view ->
AvatarView.Metadata(view as AvatarView)
}) { requestManager, epoxyModel: `TopicController$TopicModel_`, viewData ->
epoxyModel.getImgRequest(requestManager, viewData.metadata.avatarView)
})
controller = TopicController(this)
mRecyclerView.setController(controller)
mLayout.isRefreshing = true
return mLayout
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val activity = activity as MainActivity
val shouldSetTitle = if (mPage is Node) {
val node = mPage as Node
if (node.hasInfo()) {
true
} else {
val dbNode = NodeDao.get(node.name)
if (dbNode == null) {
false
} else {
mPage = dbNode
true
}
}
} else if (mPage === Page.PAGE_FAV_TOPIC) {
activity.setNavSelected(R.id.drawer_favorite)
true
} else {
false
}
if (shouldSetTitle) {
activity.title = mPage.title
}
}
override fun onStart() {
super.onStart()
val loaderManager = loaderManager
if (loaderManager.getLoader<Any>(0) != null) {
// already loaded
return
}
loaderManager.initLoader(0, null, this)
}
override fun onStop() {
super.onStop()
AppCtx.eventBus.unregister(this)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<LoaderResult<TopicListLoader.TopicList>> {
val log = String.format("load list: %s", mPage.title)
FirebaseCrashlytics.getInstance().log(log)
LogUtils.d(TAG, log)
return TopicListLoader(requireActivity(), mPage, topicDao)
}
override fun onLoadFinished(loader: Loader<LoaderResult<TopicListLoader.TopicList>>, result: LoaderResult<TopicListLoader.TopicList>) {
mLayout.isRefreshing = false
if (result.hasException()) {
handleLoadException(result.mException)
return
}
result.mResult.let {
mFavored = it.isFavorited
mOnceToken = it.onceToken
controller.setData(it, it.readed)
}
requireActivity().invalidateOptionsMenu()
}
private fun handleLoadException(ex: Exception) {
var handled = false
if (ex is RequestException) {
@StringRes
var strId = 0
when (ex.code) {
HttpStatus.SC_MOVED_TEMPORARILY -> {
val location = ex.response.header(HttpHeaders.LOCATION)
if (location == "/") {
// it's blocked for new user
strId = R.string.toast_node_not_found
}
}
}
if (strId != 0) {
if (userVisibleHint) {
Toast.makeText(activity, strId, Toast.LENGTH_SHORT).show()
}
handled = true
}
}
if (!handled) {
ExceptionUtils.handleExceptionNoCatch(this, ex)
}
}
override fun onLoaderReset(loader: Loader<LoaderResult<TopicListLoader.TopicList>>) {
controller.setData(emptyList(), emptySet())
}
override fun onRefresh() {
val loader = loaderManager.getLoader<Any>(0) ?: return
loader.forceLoad()
mRecyclerView.smoothScrollToPosition(0)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_topic_list, menu)
if (UserState.isLoggedIn()) {
mFavIcon = menu.findItem(R.id.action_fav)
updateFavIcon()
} else {
menu.findItem(R.id.action_new_topic).isVisible = false
menu.findItem(R.id.action_fav).isVisible = false
}
super.onCreateOptionsMenu(menu, inflater)
}
private fun updateFavIcon() {
if (mPage !is Node || mOnceToken == null) {
mFavIcon.isVisible = false
return
}
val icon = if (mFavored)
R.drawable.ic_favorite_white_24dp else R.drawable.ic_favorite_border_white_24dp
mFavIcon.setIcon(icon)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_refresh -> {
mLayout.isRefreshing = true
onRefresh()
return true
}
R.id.action_fav -> {
onFavNode()
return true
}
R.id.action_new_topic -> {
val intent = Intent(activity, TopicEditActivity::class.java)
if (mPage is Node) {
intent.putExtra(TopicEditActivity.KEY_NODE, mPage)
}
startActivity(intent)
return true
}
}
return super.onOptionsItemSelected(item)
}
fun onFavNode() {
assert(mPage is Node)
mFavored = !mFavored
updateFavIcon()
RxBus.subscribe<BaseEvent.NodeEvent> {
updateFavIcon()
}.let {
disposables += it
}
ExecutorUtils.execute {
try {
val node = mPage as Node
runBlocking {
v2exService.favor(node, mFavored, mOnceToken!!)
}
} catch (e: Exception) {
when (e) {
is ConnectionException, is RemoteException -> {
LogUtils.w(TAG, "favorite node failed", e)
mFavored = !mFavored
}
else -> throw e
}
}
RxBus.post(BaseEvent.NodeEvent())
}
}
override fun onTopicOpen(view: View, topic: Topic) {
val intent = Intent(context, TopicActivity::class.java)
intent.putExtra(TopicActivity.KEY_TOPIC, topic)
startActivity(intent)
(controller.readedSet as ArraySet).add(topic.id)
controller.setData(controller.data, controller.readedSet)
}
override fun onDestroy() {
super.onDestroy()
disposables.dispose()
}
companion object {
private val TAG = TopicListFragment::class.java.simpleName
private val ARG_PAGE = "page"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment TopicListFragment.
*/
fun newInstance(page: Page): TopicListFragment {
val fragment = TopicListFragment()
val args = Bundle()
args.putParcelable(ARG_PAGE, page)
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | fb8fbdb06e1b1a5927ec2bfc032d70c4 | 31.478006 | 192 | 0.619142 | 4.568894 | false | false | false | false |
ktorio/ktor | ktor-io/js/src/io/ktor/utils/io/js/TextDecoderFallback.kt | 1 | 2015 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.utils.io.js
import io.ktor.utils.io.core.*
import org.khronos.webgl.*
private val ENCODING_ALIASES = setOf(
"ansi_x3.4-1968",
"ascii",
"cp1252",
"cp819",
"csisolatin1",
"ibm819",
"iso-8859-1",
"iso-ir-100",
"iso8859-1",
"iso88591",
"iso_8859-1",
"iso_8859-1:1987",
"l1",
"latin1",
"us-ascii",
"windows-1252",
"x-cp1252"
)
private val REPLACEMENT = byteArrayOf(0xEF.toByte(), 0xBF.toByte(), 0xBD.toByte())
/**
* Windows-1252 decoder.
*
* According to https://encoding.spec.whatwg.org/, ISO-8859-1 should be treated as windows-1252 for http.
*/
internal class TextDecoderFallback(
encoding: String,
val fatal: Boolean
) : Decoder {
init {
val requestedEncoding = encoding.trim().lowercase()
check(ENCODING_ALIASES.contains(requestedEncoding)) { "$encoding is not supported." }
}
override fun decode(): String = ""
override fun decode(buffer: ArrayBufferView): String = buildPacket {
val bytes = buffer as Int8Array
for (index in 0 until bytes.length) {
val byte = bytes[index]
val point: Int = byte.toCodePoint()
if (point < 0) {
check(!fatal) { "Invalid character: $point" }
writeFully(REPLACEMENT)
continue
}
if (point > 0xFF) {
writeByte((point shr 8).toByte())
}
writeByte((point and 0xFF).toByte())
}
}.readBytes().decodeToString()
override fun decode(buffer: ArrayBufferView, options: dynamic): String {
return decode(buffer)
}
}
private fun Byte.toCodePoint(): Int {
val value = toInt() and 0xFF
if (value.isASCII()) {
return value
}
return WIN1252_TABLE[value - 0x80]
}
private fun Int.isASCII(): Boolean = this in 0..0x7F
| apache-2.0 | 8ad1cd492fcbc7acf7715f41ce744516 | 23.277108 | 119 | 0.594541 | 3.677007 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL15.kt | 4 | 5190 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
const val BUFFER_OBJECT_TARGETS =
"""
#ARRAY_BUFFER #ELEMENT_ARRAY_BUFFER #PIXEL_PACK_BUFFER #PIXEL_UNPACK_BUFFER #TRANSFORM_FEEDBACK_BUFFER
#UNIFORM_BUFFER #TEXTURE_BUFFER #COPY_READ_BUFFER #COPY_WRITE_BUFFER #DRAW_INDIRECT_BUFFER #ATOMIC_COUNTER_BUFFER
#DISPATCH_INDIRECT_BUFFER #SHADER_STORAGE_BUFFER #PARAMETER_BUFFER_ARB
"""
const val BUFFER_OBJECT_PARAMETERS =
"""
GL15#GL_BUFFER_SIZE #BUFFER_USAGE #BUFFER_ACCESS #BUFFER_MAPPED #BUFFER_ACCESS_FLAGS #BUFFER_MAP_LENGTH #BUFFER_MAP_OFFSET
#BUFFER_IMMUTABLE_STORAGE #BUFFER_STORAGE_FLAGS
"""
const val QUERY_TARGETS =
"""
#SAMPLES_PASSED #PRIMITIVES_GENERATED #TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN #TIME_ELAPSED #TIMESTAMP
#ANY_SAMPLES_PASSED #ANY_SAMPLES_PASSED_CONSERVATIVE
"""
val GL15 = "GL15".nativeClassGL("GL15") {
extends = GL14
documentation =
"""
The OpenGL functionality up to version 1.5. Includes the deprecated symbols of the Compatibility Profile.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "vertex_buffer_object"),
registryLinkTo("ARB", "occlusion_query"),
registryLinkTo("EXT", "shadow_funcs")
)}
"""
IntConstant(
"New token names.",
"FOG_COORD_SRC"..0x8450,
"FOG_COORD"..0x8451,
"CURRENT_FOG_COORD"..0x8453,
"FOG_COORD_ARRAY_TYPE"..0x8454,
"FOG_COORD_ARRAY_STRIDE"..0x8455,
"FOG_COORD_ARRAY_POINTER"..0x8456,
"FOG_COORD_ARRAY"..0x8457,
"FOG_COORD_ARRAY_BUFFER_BINDING"..0x889D,
"SRC0_RGB"..0x8580,
"SRC1_RGB"..0x8581,
"SRC2_RGB"..0x8582,
"SRC0_ALPHA"..0x8588,
"SRC1_ALPHA"..0x8589,
"SRC2_ALPHA"..0x858A
)
// ARB_vertex_buffer_object
IntConstant(
"""
Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData,
GetBufferParameteriv, and GetBufferPointerv.
""",
"ARRAY_BUFFER"..0x8892,
"ELEMENT_ARRAY_BUFFER"..0x8893
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"ARRAY_BUFFER_BINDING"..0x8894,
"ELEMENT_ARRAY_BUFFER_BINDING"..0x8895,
"VERTEX_ARRAY_BUFFER_BINDING"..0x8896,
"NORMAL_ARRAY_BUFFER_BINDING"..0x8897,
"COLOR_ARRAY_BUFFER_BINDING"..0x8898,
"INDEX_ARRAY_BUFFER_BINDING"..0x8899,
"TEXTURE_COORD_ARRAY_BUFFER_BINDING"..0x889A,
"EDGE_FLAG_ARRAY_BUFFER_BINDING"..0x889B,
"SECONDARY_COLOR_ARRAY_BUFFER_BINDING"..0x889C,
"FOG_COORDINATE_ARRAY_BUFFER_BINDING"..0x889D,
"WEIGHT_ARRAY_BUFFER_BINDING"..0x889E
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttribiv.",
"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING"..0x889F
)
IntConstant(
"Accepted by the {@code usage} parameter of BufferData.",
"STREAM_DRAW"..0x88E0,
"STREAM_READ"..0x88E1,
"STREAM_COPY"..0x88E2,
"STATIC_DRAW"..0x88E4,
"STATIC_READ"..0x88E5,
"STATIC_COPY"..0x88E6,
"DYNAMIC_DRAW"..0x88E8,
"DYNAMIC_READ"..0x88E9,
"DYNAMIC_COPY"..0x88EA
)
IntConstant(
"Accepted by the {@code access} parameter of MapBuffer.",
"READ_ONLY"..0x88B8,
"WRITE_ONLY"..0x88B9,
"READ_WRITE"..0x88BA
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBufferParameteriv.",
"BUFFER_SIZE"..0x8764,
"BUFFER_USAGE"..0x8765,
"BUFFER_ACCESS"..0x88BB,
"BUFFER_MAPPED"..0x88BC
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBufferPointerv.",
"BUFFER_MAP_POINTER"..0x88BD
)
reuse(GL15C, "BindBuffer")
reuse(GL15C, "DeleteBuffers")
reuse(GL15C, "GenBuffers")
reuse(GL15C, "IsBuffer")
reuse(GL15C, "BufferData")
reuse(GL15C, "BufferSubData")
reuse(GL15C, "GetBufferSubData")
reuse(GL15C, "MapBuffer")
reuse(GL15C, "UnmapBuffer")
reuse(GL15C, "GetBufferParameteriv")
reuse(GL15C, "GetBufferPointerv")
// ARB_occlusion_query
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, and GetQueryiv.",
"SAMPLES_PASSED"..0x8914
)
IntConstant(
"Accepted by the {@code pname} parameter of GetQueryiv.",
"QUERY_COUNTER_BITS"..0x8864,
"CURRENT_QUERY"..0x8865
)
IntConstant(
"Accepted by the {@code pname} parameter of GetQueryObjectiv and GetQueryObjectuiv.",
"QUERY_RESULT"..0x8866,
"QUERY_RESULT_AVAILABLE"..0x8867
)
reuse(GL15C, "GenQueries")
reuse(GL15C, "DeleteQueries")
reuse(GL15C, "IsQuery")
reuse(GL15C, "BeginQuery")
reuse(GL15C, "EndQuery")
reuse(GL15C, "GetQueryiv")
reuse(GL15C, "GetQueryObjectiv")
reuse(GL15C, "GetQueryObjectuiv")
} | bsd-3-clause | 955d43dec7c07ad376fc5ab1ee9bbfe3 | 28.662857 | 133 | 0.63025 | 3.511502 | false | false | false | false |
SakaiTakao/CallRefuser | app/src/main/kotlin/sakaitakao/android/callrefuser/adapter/RecentIncomingCallsAdapter.kt | 1 | 5775 | /*
* Copyright (c) 2011, Sakai Takao. All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package sakaitakao.android.callrefuser.adapter
import android.content.Context
import android.telephony.PhoneNumberUtils
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.TextView
import sakaitakao.android.callrefuser.R
import sakaitakao.android.callrefuser.entity.CallLogItem
import java.util.*
/**
* 着信履歴画面のリスト部分を表示するAdaptorクラス
* @author takao
*/
class RecentIncomingCallsAdapter
/**
* コンストラクタ
* @param context
* *
* @param textViewResourceId
* *
* @param items
*/
(context: Context, textViewResourceId: Int, private val items: List<CallLogItem>) : ArrayAdapter<CallLogItem>(context, textViewResourceId, items) {
private val layoutInflater: LayoutInflater
private val selected: MutableSet<CallLogItem>
private var onItemCheckChangedListener: OnItemCheckChangedListener? = null
init {
this.layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
selected = HashSet<CallLogItem>()
}
/**
* 選択された着信を返す
* @return
*/
fun getSelected(): List<CallLogItem> {
return ArrayList(selected)
}
/**
* 項目のチェック状態が変わったら呼び出すリスナを設定する。
* @param onItemCheckChangedListener
*/
fun setOnItemCheckChangedListener(onItemCheckChangedListener: OnItemCheckChangedListener) {
this.onItemCheckChangedListener = onItemCheckChangedListener
}
/*
* (非 Javadoc)
*
* @see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
// リスト項目の View を生成。
var view: View = convertView ?: layoutInflater.inflate(R.layout.recent_incoming_calls_list_item, null)
// データを取得
val callLogItem = items[position]
showCheckBox(view, callLogItem)
showTelNo(view, callLogItem)
showName(view, callLogItem)
showDate(view, callLogItem)
view.setOnClickListener { v ->
val checkBox = v.findViewById(R.id.recent_incoming_calls_list_item_check) as CheckBox
checkBox.isChecked = !checkBox.isChecked
}
return view
}
// -------------------------------------------------------------------------
// Privates
// -------------------------------------------------------------------------
private fun showCheckBox(view: View, callLogItem: CallLogItem) {
val checkBox = view.findViewById(R.id.recent_incoming_calls_list_item_check) as CheckBox
checkBox.setOnCheckedChangeListener { compoundbutton, flag -> onItemCheckedChanged(callLogItem, flag) }
}
private fun onItemCheckedChanged(callLogItem: CallLogItem, flag: Boolean) {
if (flag) {
selected.add(callLogItem)
} else {
selected.remove(callLogItem)
}
onItemCheckChangedListener?.onItemCheckChanged(callLogItem, flag)
}
private fun showTelNo(view: View, callLogItem: CallLogItem) {
val textView = view.findViewById(R.id.recent_incoming_calls_list_item_telno) as TextView
textView.text = PhoneNumberUtils.formatNumber(callLogItem.telNo, "JP")
}
private fun showName(view: View, callLogItem: CallLogItem) {
val textView = view.findViewById(R.id.recent_incoming_calls_list_item_name) as TextView
textView.text = callLogItem.name
}
private fun showDate(view: View, callLogItem: CallLogItem) {
val textView = view.findViewById(R.id.recent_incoming_calls_list_item_last_called) as TextView
val date = DateFormat.getDateFormat(context).format(callLogItem.date)
val time = DateFormat.getTimeFormat(context).format(callLogItem.date)
textView.text = date + " " + time
}
// -------------------------------------------------------------------------
// Classes
// -------------------------------------------------------------------------
public interface OnItemCheckChangedListener {
fun onItemCheckChanged(callLogItem: CallLogItem, flag: Boolean)
}
}
| bsd-2-clause | 48760fae2ecc4780d71b6181d3640ebb | 35.435065 | 147 | 0.678845 | 4.495994 | false | false | false | false |
mdanielwork/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator30.kt | 5 | 1554 | // 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.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
/**
* Check features introduced in groovy 3.0
*/
class GroovyAnnotator30(private val holder: AnnotationHolder) : GroovyElementVisitor() {
override fun visitModifierList(modifierList: GrModifierList) {
checkDefaultModifier(modifierList)
}
private fun checkDefaultModifier(modifierList: GrModifierList) {
val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return
val parentClass = PsiTreeUtil.getParentOfType(modifier, PsiClass::class.java) ?: return
if (!parentClass.isInterface || (parentClass as? GrTypeDefinition)?.isTrait == true) {
val annotation = holder.createWarningAnnotation(modifier, GroovyBundle.message("illegal.default.modifier"))
registerFix(annotation, GrRemoveModifierFix(PsiModifier.DEFAULT, GroovyBundle.message("illegal.default.modifier.fix")), modifier)
}
}
}
| apache-2.0 | e4560d6b29d0bbb49798335fc499ffb3 | 43.4 | 140 | 0.803732 | 4.570588 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/LinkMap.kt | 1 | 3646 | package org.intellij.markdown.parser
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.accept
import org.intellij.markdown.ast.getTextInNode
import org.intellij.markdown.ast.visitors.RecursiveVisitor
import org.intellij.markdown.html.entities.EntityConverter
import java.net.URLEncoder
import java.util.*
import kotlin.text.Regex
public data class LinkMap private constructor(private val map: Map<CharSequence, LinkMap.LinkInfo>) {
public fun getLinkInfo(label: CharSequence): LinkInfo? {
return map.get(normalizeLabel(label))
}
companion object Builder {
public fun buildLinkMap(root: ASTNode, text: CharSequence): LinkMap {
val map = HashMap<CharSequence, LinkInfo>()
root.accept(object : RecursiveVisitor() {
override fun visitNode(node: ASTNode) {
if (node.type == MarkdownElementTypes.LINK_DEFINITION) {
val linkLabel = normalizeLabel(
node.children.first({ it.type == MarkdownElementTypes.LINK_LABEL }).getTextInNode(text)
)
if (!map.containsKey(linkLabel)) {
map.put(linkLabel, LinkInfo.create(node, text))
}
}
else {
super.visitNode(node)
}
}
})
return LinkMap(map)
}
private fun normalizeLabel(label: CharSequence): CharSequence {
return SPACES_REGEX.replace(label, " ").toLowerCase(Locale.US)
}
public fun normalizeDestination(s: CharSequence): CharSequence {
val dest = EntityConverter.replaceEntities(clearBounding(s, "<>"), true, true)
val sb = StringBuilder()
for (c in dest) {
val code = c.toInt()
if (code == 32) {
sb.append("%20")
} else if (code < 32 || code >= 128 || "\".<>\\^_`{|}~".contains(c)) {
sb.append(URLEncoder.encode("${c}", "UTF-8"))
} else {
sb.append(c)
}
}
return sb.toString()
}
public fun normalizeTitle(s: CharSequence): CharSequence = EntityConverter.replaceEntities(clearBounding(s, "\"\"", "''", "()"), true, true)
private fun clearBounding(s: CharSequence, vararg boundQuotes: String): CharSequence {
if (s.length == 0) {
return s
}
for (quotePair in boundQuotes) {
if (s[0] == quotePair[0] && s[s.length - 1] == quotePair[1]) {
return s.subSequence(1, s.length - 1)
}
}
return s
}
val SPACES_REGEX = Regex("\\s+")
}
public data class LinkInfo private constructor(val node: ASTNode, val destination: CharSequence, val title: CharSequence?) {
companion object {
internal fun create(node: ASTNode, fileText: CharSequence): LinkInfo {
val destination: CharSequence = normalizeDestination(
node.children.first({ it.type == MarkdownElementTypes.LINK_DESTINATION }).getTextInNode(fileText))
val title: CharSequence? = node.children.firstOrNull({ it.type == MarkdownElementTypes.LINK_TITLE })
?.getTextInNode(fileText)?.let { normalizeTitle(it) }
return LinkInfo(node, destination, title)
}
}
}
}
| apache-2.0 | cb74ab0b767513c1993105864e1e7e26 | 39.065934 | 148 | 0.556226 | 4.861333 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/utils/ToolbarUtils.kt | 1 | 2586 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.utils
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import de.dreier.mytargets.R
object ToolbarUtils {
fun showUpAsX(fragment: Fragment) {
showUpAsX((fragment.activity as AppCompatActivity?)!!)
}
private fun showUpAsX(activity: AppCompatActivity) {
val supportActionBar = activity.supportActionBar!!
supportActionBar.setDisplayHomeAsUpEnabled(true)
supportActionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp)
}
fun showHomeAsUp(fragment: Fragment) {
showHomeAsUp((fragment.activity as AppCompatActivity?)!!)
}
fun showHomeAsUp(activity: AppCompatActivity) {
val supportActionBar = activity.supportActionBar!!
supportActionBar.setDisplayHomeAsUpEnabled(true)
}
fun setSupportActionBar(fragment: Fragment, toolbar: Toolbar) {
val activity = fragment.activity as AppCompatActivity?
activity!!.setSupportActionBar(toolbar)
}
fun setTitle(fragment: Fragment, @StringRes title: Int) {
setTitle((fragment.activity as AppCompatActivity?)!!, title)
}
fun setTitle(fragment: Fragment, title: String) {
setTitle((fragment.activity as AppCompatActivity?)!!, title)
}
fun setTitle(activity: AppCompatActivity, @StringRes title: Int) {
assert(activity.supportActionBar != null)
activity.supportActionBar!!.setTitle(title)
}
fun setTitle(activity: AppCompatActivity, title: String) {
assert(activity.supportActionBar != null)
activity.supportActionBar!!.title = title
}
fun setSubtitle(fragment: Fragment, subtitle: String) {
val activity = fragment.activity as AppCompatActivity?
setSubtitle(activity!!, subtitle)
}
fun setSubtitle(activity: AppCompatActivity, subtitle: String) {
assert(activity.supportActionBar != null)
activity.supportActionBar!!.subtitle = subtitle
}
}
| gpl-2.0 | c4068cf0c5f77058b353d1e9bafbe9ef | 32.584416 | 77 | 0.720804 | 4.973077 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/ClickBoxDebug.kt | 1 | 2730 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.Model
import org.runestar.client.api.game.SceneElement
import org.runestar.client.api.game.SceneElementKind
import org.runestar.client.api.game.live.Game
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.game.live.Scene
import org.runestar.client.api.game.live.Viewport
import org.runestar.client.api.game.live.SceneElements
import org.runestar.client.api.game.live.VisibilityMap
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
import java.awt.Graphics2D
class ClickBoxDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
private val objs: MutableSet<SceneElement> = LinkedHashSet()
override fun onStart() {
add(SceneElements.cleared.subscribe { objs.clear() })
add(SceneElements.removed.subscribe { objs.remove(it) })
add(SceneElements.added.filter { it.tag.interactable }.subscribe { objs.add(it) })
Scene.reload()
add(Canvas.repaints.subscribe { g ->
objs.forEach {
g.color = colorFor(it)
if (it.isLoc) {
it.models.forEach { drawObject(g, it) }
} else {
it.models.forEach { drawOther(g, it) }
}
}
})
}
override fun onStop() {
objs.clear()
}
private fun colorFor(obj: SceneElement): Color {
return when (obj.tag.kind) {
SceneElementKind.OBJ -> Color.RED
SceneElementKind.NPC -> Color.YELLOW
SceneElementKind.PLAYER -> Color.WHITE
SceneElementKind.LOC -> when (obj) {
is SceneElement.Wall -> Color.MAGENTA
is SceneElement.Scenery -> Color.BLUE
is SceneElement.FloorDecoration -> Color.CYAN
is SceneElement.WallDecoration -> Color.ORANGE
else -> throw IllegalStateException()
}
else -> error(obj)
}
}
private fun shouldDraw(model: Model): Boolean {
val pos = model.base
val tile = pos.sceneTile
if (tile.plane != Game.plane) return false
if (!tile.isLoaded || !VisibilityMap.isVisible(tile)) return false
val pt = pos.toScreen() ?: return false
if (pt !in Viewport) return false
return true
}
private fun drawObject(g: Graphics2D, model: Model) {
if (shouldDraw(model)) g.draw(model.objectClickBox())
}
private fun drawOther(g: Graphics2D, model: Model) {
if (shouldDraw(model)) g.draw(model.boundingBox())
}
} | mit | 6b80ec88fe4ea8f36244d56e074c6cc5 | 34.012821 | 90 | 0.635531 | 4.148936 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinLambdaMethodFilter.kt | 2 | 4440 | // 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.stepping.smartStepInto
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.BreakpointStepMethodFilter
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.psi.util.parentOfType
import com.intellij.util.Range
import com.sun.jdi.Location
import org.jetbrains.kotlin.codegen.coroutines.INVOKE_SUSPEND_METHOD_NAME
import org.jetbrains.kotlin.idea.base.psi.isMultiLine
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.isGeneratedIrBackendLambdaMethodName
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.trimIfMangledInBytecode
import org.jetbrains.kotlin.idea.debugger.core.isInsideInlineArgument
import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtDeclarationWithBody
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
class KotlinLambdaMethodFilter(
lambda: KtFunction,
private val callingExpressionLines: Range<Int>?,
private val lambdaInfo: KotlinLambdaInfo
) : BreakpointStepMethodFilter {
private val lambdaPtr = lambda.createSmartPointer()
private val firstStatementPosition: SourcePosition?
private val lastStatementLine: Int
init {
val (firstPosition, lastPosition) = findFirstAndLastStatementPositions(lambda)
firstStatementPosition = firstPosition
lastStatementLine = lastPosition?.line ?: -1
}
override fun getBreakpointPosition() = firstStatementPosition
override fun getLastStatementLine() = lastStatementLine
override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean {
val lambda = lambdaPtr.getElementInReadAction() ?: return true
if (lambdaInfo.isInline) {
return isInsideInlineArgument(lambda, location, process)
}
val method = location.safeMethod() ?: return true
if (method.isBridge) {
return false
}
val methodName = method.name() ?: return false
return isTargetLambdaName(methodName) &&
location.matchesExpression(process, lambda.bodyExpression)
}
private fun Location.matchesExpression(process: DebugProcessImpl, bodyExpression: KtExpression?): Boolean {
val sourcePosition = process.positionManager.getSourcePosition(this) ?: return true
val blockAt = runReadAction { sourcePosition.elementAt.parentOfType<KtBlockExpression>(true) } ?: return true
return blockAt === bodyExpression
}
override fun getCallingExpressionLines() =
if (lambdaInfo.isInline) Range(0, Int.MAX_VALUE) else callingExpressionLines
fun isTargetLambdaName(name: String): Boolean {
val actualName = name.trimIfMangledInBytecode(lambdaInfo.isNameMangledInBytecode)
if (lambdaInfo.isSuspend) {
return actualName == INVOKE_SUSPEND_METHOD_NAME
}
return actualName == lambdaInfo.methodName || actualName.isGeneratedIrBackendLambdaMethodName()
}
}
fun findFirstAndLastStatementPositions(declaration: KtDeclarationWithBody): Pair<SourcePosition?, SourcePosition?> {
val body = declaration.bodyExpression
if (body != null && declaration.isMultiLine() && body.children.isNotEmpty()) {
var firstStatementPosition: SourcePosition? = null
var lastStatementPosition: SourcePosition? = null
val statements = (body as? KtBlockExpression)?.statements ?: listOf(body)
if (statements.isNotEmpty()) {
firstStatementPosition = SourcePosition.createFromElement(statements.first())
if (firstStatementPosition != null) {
val lastStatement = statements.last()
lastStatementPosition = SourcePosition.createFromOffset(
firstStatementPosition.file,
lastStatement.textRange.endOffset
)
}
}
return Pair(firstStatementPosition, lastStatementPosition)
}
val position = SourcePosition.createFromElement(declaration)
return Pair(position, position)
}
| apache-2.0 | e0aad2f233b708a7030cca139a0b9a2c | 44.773196 | 158 | 0.744369 | 5.045455 | false | false | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/PackageManagementPanel.kt | 1 | 9327 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.actions.PkgsToDAAction
import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction
import com.jetbrains.packagesearch.intellij.plugin.actions.TogglePackageDetailsAction
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules.ModulesTree
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails.PackageDetailsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesListPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.computeModuleTreeModel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import java.awt.Dimension
import javax.swing.JScrollPane
@Suppress("MagicNumber") // Swing dimension constants
internal class PackageManagementPanel(
val project: Project,
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")) {
private val operationFactory = PackageSearchOperationFactory()
private val operationExecutor = NotifyingOperationExecutor(project)
private val modulesTree = ModulesTree(project)
private val modulesScrollPanel = JBScrollPane(
modulesTree,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
)
private val knownRepositoriesInTargetModulesFlow = combine(
modulesTree.targetModulesStateFlow,
project.packageSearchProjectService.allInstalledKnownRepositoriesStateFlow
) { targetModules, installedRepositories ->
installedRepositories.filterOnlyThoseUsedIn(targetModules)
}
private val packagesListPanel = PackagesListPanel(
project = project,
operationExecutor = operationExecutor,
operationFactory = operationFactory,
viewModelFlow = combine(
modulesTree.targetModulesStateFlow,
project.packageSearchProjectService.installedPackagesStateFlow,
project.packageSearchProjectService.packageUpgradesStateFlow,
knownRepositoriesInTargetModulesFlow
) { targetModules, installedPackages,
packageUpgrades, knownReposInModules ->
PackagesListPanel.ViewModel(targetModules, installedPackages, packageUpgrades, knownReposInModules)
},
dataProvider = project.packageSearchProjectService.dataProvider
)
private val dataModelStateFlow = packagesListPanel.selectedPackageStateFlow
.mapNotNull { it?.packageModel }
.filterIsInstance<PackageModel.Installed>()
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, null)
private val packageDetailsPanel = PackageDetailsPanel(project, operationExecutor)
private val packagesSplitter = JBSplitter(
"PackageSearch.PackageManagementPanel.DetailsSplitter",
PackageSearchGeneralConfiguration.DefaultPackageDetailsSplitterProportion
).apply {
firstComponent = packagesListPanel.content
secondComponent = packageDetailsPanel.content
orientation = false // Horizontal split
dividerWidth = 1.scaled()
divider.background = PackageSearchUI.Colors.border
}
private val mainSplitter = JBSplitter("PackageSearch.PackageManagementPanel.Splitter", 0.1f).apply {
firstComponent = modulesScrollPanel
secondComponent = packagesSplitter
orientation = false // Horizontal split
dividerWidth = 1.scaled()
divider.background = PackageSearchUI.Colors.border
}
init {
updatePackageDetailsVisible(PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible)
modulesScrollPanel.apply {
border = emptyBorder()
minimumSize = Dimension(250.scaled(), 0)
UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true)
}
packagesListPanel.content.minimumSize = Dimension(250.scaled(), 0)
project.packageSearchProjectService.moduleModelsStateFlow
.map { computeModuleTreeModel(it) }
.onEach { modulesTree.display(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
packagesListPanel.selectedPackageStateFlow
.filterNotNull()
.onEach { PackageSearchEventsLogger.logPackageSelected(it is UiPackageModel.Installed) }
.launchIn(project.lifecycleScope)
modulesTree.targetModulesStateFlow
.onEach { PackageSearchEventsLogger.logTargetModuleSelected(it) }
.launchIn(project.lifecycleScope)
combine(
knownRepositoriesInTargetModulesFlow,
packagesListPanel.selectedPackageStateFlow,
modulesTree.targetModulesStateFlow,
packagesListPanel.onlyStableStateFlow
) { knownRepositoriesInTargetModules, selectedUiPackageModel,
targetModules, onlyStable ->
PackageDetailsPanel.ViewModel(
selectedPackageModel = selectedUiPackageModel,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
targetModules = targetModules,
onlyStable = onlyStable,
invokeLaterScope = project.lifecycleScope
)
}.flowOn(project.lifecycleScope.coroutineDispatcher)
.onEach { packageDetailsPanel.display(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private fun updatePackageDetailsVisible(becomeVisible: Boolean) {
val wasVisible = packagesSplitter.secondComponent.isVisible
packagesSplitter.secondComponent.isVisible = becomeVisible
if (!wasVisible && becomeVisible) {
packagesSplitter.proportion =
PackageSearchGeneralConfiguration.getInstance(project).packageDetailsSplitterProportion
}
if (!becomeVisible) {
PackageSearchGeneralConfiguration.getInstance(project).packageDetailsSplitterProportion =
packagesSplitter.proportion
packagesSplitter.proportion = 1.0f
}
}
private val togglePackageDetailsAction = TogglePackageDetailsAction(project, ::updatePackageDetailsVisible)
override fun build() = mainSplitter
override fun buildGearActions() = DefaultActionGroup(
ShowSettingsAction(project),
togglePackageDetailsAction
)
override fun buildTitleActions(): Array<AnAction> = arrayOf(togglePackageDetailsAction)
override fun getData(dataId: String) = when {
PkgsToDAAction.PACKAGES_LIST_PANEL_DATA_KEY.`is`(dataId) -> dataModelStateFlow.value
else -> null
}
}
| apache-2.0 | 03bd95665b533c2aa4c6534b04c760d0 | 45.402985 | 117 | 0.750616 | 5.598439 | false | false | false | false |
Virtlink/aesi | aesi-lsp/src/main/kotlin/com/virtlink/editorservices/lsp/server/SocketLanguageServerLauncher.kt | 1 | 1999 | package com.virtlink.editorservices.lsp.server
import com.google.inject.Inject
import com.google.inject.assistedinject.Assisted
import org.eclipse.lsp4j.launch.LSPLauncher
import org.eclipse.lsp4j.services.LanguageClientAware
import org.eclipse.lsp4j.services.LanguageServer
import org.slf4j.LoggerFactory
import java.io.PrintWriter
import java.net.InetSocketAddress
import java.nio.channels.AsynchronousServerSocketChannel
import java.nio.channels.AsynchronousSocketChannel
import java.nio.channels.Channels
import java.util.concurrent.TimeoutException
class SocketLanguageServerLauncher @Inject constructor(
@Assisted private val port: Int,
private val server: LanguageServer)
: ILanguageServerLauncher {
val logger = LoggerFactory.getLogger(SocketLanguageServerLauncher::class.java)
override fun launch(traceWriter: PrintWriter?) {
val serverSocket = AsynchronousServerSocketChannel.open()
val socketAddress = InetSocketAddress("localhost", this.port)
serverSocket.bind(socketAddress)
logger.info("Listening to $socketAddress...")
val socketChannelFuture = serverSocket.accept()
val socketChannel: AsynchronousSocketChannel = try { socketChannelFuture.get(/* TODO: Time-out? */) }
catch (e: TimeoutException) {
logger.info("No client connected to the server before the time-out. Exiting.")
System.exit(1)
return
}
logger.info("Connection accepted")
val inputStream = Channels.newInputStream(socketChannel)
val outputStream = Channels.newOutputStream(socketChannel)
val launcher = LSPLauncher.createServerLauncher(
server,
inputStream,
outputStream,
true,
traceWriter)
if (server is LanguageClientAware) {
val client = launcher.remoteProxy
server.connect(client)
}
launcher.startListening()
}
} | apache-2.0 | 2af90a8a561d5cd5b415bdabc6a1e2d1 | 34.087719 | 109 | 0.707354 | 4.9975 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AssertConsistencyEntityImpl.kt | 1 | 6048 | 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.ModifiableWorkspaceEntity
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.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class AssertConsistencyEntityImpl(val dataSource: AssertConsistencyEntityData) : AssertConsistencyEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val passCheck: Boolean get() = dataSource.passCheck
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: AssertConsistencyEntityData?) : ModifiableWorkspaceEntityBase<AssertConsistencyEntity>(), AssertConsistencyEntity.Builder {
constructor() : this(AssertConsistencyEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity AssertConsistencyEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// 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")
}
}
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 AssertConsistencyEntity
this.entitySource = dataSource.entitySource
this.passCheck = dataSource.passCheck
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var passCheck: Boolean
get() = getEntityData().passCheck
set(value) {
checkModificationAllowed()
getEntityData().passCheck = value
changedProperty.add("passCheck")
}
override fun getEntityData(): AssertConsistencyEntityData = result ?: super.getEntityData() as AssertConsistencyEntityData
override fun getEntityClass(): Class<AssertConsistencyEntity> = AssertConsistencyEntity::class.java
}
}
class AssertConsistencyEntityData : WorkspaceEntityData<AssertConsistencyEntity>() {
var passCheck: Boolean = false
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<AssertConsistencyEntity> {
val modifiable = AssertConsistencyEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): AssertConsistencyEntity {
return getCached(snapshot) {
val entity = AssertConsistencyEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return AssertConsistencyEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return AssertConsistencyEntity(passCheck, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as AssertConsistencyEntityData
if (this.entitySource != other.entitySource) return false
if (this.passCheck != other.passCheck) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as AssertConsistencyEntityData
if (this.passCheck != other.passCheck) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + passCheck.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + passCheck.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 1149c608da5c4efe3bbf0c4ca2b62b35 | 31.342246 | 151 | 0.740079 | 5.352212 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2017/Day17.kt | 1 | 714 | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
object Day17 : Day {
val input = 363
override fun part1() :String {
val buffer = mutableListOf(0)
var current = 0
for(i in 1 .. 2017) {
current = (current + input) % buffer.size + 1
buffer.add(current, i)
}
return buffer.get(buffer.indexOf(2017) + 1).toString()
}
override fun part2() :String {
var current = 0
var result = 0
for(i in 1..50_000_000) {
current = ((input + current) % i) + 1
if(current == 1) {
result = i
}
}
return result.toString()
}
} | mit | 8a4e2ad352df139a1a6e7d6cba4dfe5f | 21.34375 | 62 | 0.508403 | 3.880435 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/model/openshift/ApplicationDeployment.kt | 1 | 3030 | package no.skatteetaten.aurora.boober.model.openshift
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import io.fabric8.kubernetes.api.model.HasMetadata
import io.fabric8.kubernetes.api.model.ObjectMeta
import no.skatteetaten.aurora.boober.model.ApplicationDeploymentRef
import no.skatteetaten.aurora.boober.service.AuroraConfigRef
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(value = ["apiVersion", "kind", "metadata", "spec"])
data class ApplicationDeployment(
val spec: ApplicationDeploymentSpec,
@JsonIgnore
var _metadata: ObjectMeta?,
@JsonIgnore
val _kind: String = "ApplicationDeployment",
@JsonIgnore
var _apiVersion: String = "skatteetaten.no/v1"
) : HasMetadata { // or just KubernetesResource?
override fun getMetadata(): ObjectMeta {
return _metadata ?: ObjectMeta()
}
override fun getKind(): String {
return _kind
}
override fun getApiVersion(): String {
return _apiVersion
}
override fun setMetadata(metadata: ObjectMeta?) {
_metadata = metadata
}
override fun setApiVersion(version: String?) {
_apiVersion = apiVersion
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ApplicationDeploymentSpec(
var applicationId: String? = null,
var updatedAt: String? = null,
// TODO: Skal vi bare fjerne selector, vi vet ikke hva den er satt til p.g.a templates uansett.
var selector: Map<String, String> = emptyMap(),
var applicationDeploymentId: String = "",
var applicationName: String? = null,
var runnableType: String = "",
var applicationDeploymentName: String = "",
var databases: List<String> = emptyList(),
var splunkIndex: String? = null,
var managementPath: String? = null,
var releaseTo: String? = null,
var deployTag: String? = null,
var command: ApplicationDeploymentCommand? = null,
var message: String? = null,
var notifications: Set<Notification>? = null,
var build: ApplicationDeploymentBuildInformation? = null,
)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ApplicationDeploymentBuildInformation(
val baseImageName: String,
val baseImageVersion: Int,
val type: String
)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ApplicationDeploymentCommand(
val overrideFiles: Map<String, String>,
val applicationDeploymentRef: ApplicationDeploymentRef,
val auroraConfig: AuroraConfigRef
)
enum class NotificationType {
Email, Mattermost
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class Notification(val notificationLocation: String, val type: NotificationType)
| apache-2.0 | fa86b159f954a31467549b407bcbbd32 | 33.044944 | 99 | 0.747525 | 4.41691 | false | false | false | false |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/TelegramClientAdapter.kt | 1 | 1649 | package io.github.ranolp.kubo.telegram.client
import com.github.badoualy.telegram.api.Kotlogram
import com.github.badoualy.telegram.api.TelegramApp
import com.github.badoualy.telegram.api.TelegramClient
import io.github.ranolp.kubo.KuboAdapter
import io.github.ranolp.kubo.general.objects.User
import io.github.ranolp.kubo.telegram.Telegram
import io.github.ranolp.kubo.telegram.client.objects.TelegramClientUser
import org.slf4j.impl.SimpleLogger
class TelegramClientAdapter(option: TelegramClientOption) : KuboAdapter<TelegramClientOption>(option,
Telegram.CLIENT_SIDE) {
private lateinit var _client: TelegramClient
private lateinit var _myself: TelegramClientUser
val client: TelegramClient
get() = _client
override val myself: User
get() = _myself
override fun login() {
System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "ERROR")
val app = TelegramApp(option.apiId,
option.apiHash,
option.deviceModel,
option.systemVersion,
option.appVersion,
option.langCode)
_client = Kotlogram.getDefaultClient(app,
ApiStorage(option.authKeyFile, option.nearestDcFile),
updateCallback = TelegramUpdateCallback)
val sentCode = _client.authSendCode(false, option.phoneNumber, true)
print("Requires sent code: ")
val auth = _client.authSignIn(option.phoneNumber, sentCode.phoneCodeHash, readLine())
_myself = TelegramClientUser(auth.user.asUser)
}
override fun logout() {
_client.close()
Kotlogram.shutdown()
}
} | mit | ceabf26ab261e9a72e50dedd1b5d03fc | 38.285714 | 101 | 0.699212 | 4.25 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/test/kotlin/com/aemtools/ide/refactoring/TemplateParametersRenameTest.kt | 1 | 3448 | package com.aemtools.ide.refactoring
import com.aemtools.common.constant.const.JCR_ROOT
import com.aemtools.test.rename.BaseRenameTest
/**
* @author Dmytro Troynikov
*/
class TemplateParametersRenameTest : BaseRenameTest() {
fun testOptionRenameFromDeclaration() = renameCase {
before {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{@ ${CARET}param}">
$DOLLAR{param @ context=param}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ param='value'}"></div>
</div>
""")
}
renameTo("renamed")
after {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{@ renamed}">
$DOLLAR{renamed @ context=renamed}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ renamed='value'}"></div>
</div>
""")
}
}
fun testOptionRenameFromLocalUsage() = renameCase {
before {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{ @ param}">
$DOLLAR{${CARET}param}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ param='value'}"></div>
</div>
""")
}
renameTo("renamed")
after {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{ @ renamed}">
$DOLLAR{renamed}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ renamed='value'}"></div>
</div>
""")
}
}
//FIXME will be fixed in separate task
/*
fun testOptionRenameFromOuterUsage() = renameCase {
before {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{ @ param}">
$DOLLAR{param}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ ${CARET}param='value'}"></div>
</div>
""")
}
renameTo("renamed")
after {
addHtml("$JCR_ROOT/myapp/component/component.html", """
<div data-sly-template.template="$DOLLAR{ @ renamed}">
$DOLLAR{renamed}
</div>
""")
addHtml("$JCR_ROOT/myapp/component/other.html", """
<div data-sly-use.template="component.html">
<div data-sly-call="$DOLLAR{template.template @ renamed='value'}"></div>
</div>
""")
}
}
*/
}
| gpl-3.0 | da5ad306a6dad54ef62d9845235d255c | 34.183673 | 96 | 0.513631 | 4.31 | false | true | false | false |
square/okio | okio-fakefilesystem/src/commonMain/kotlin/okio/fakefilesystem/time.kt | 1 | 1472 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("-Time")
package okio.fakefilesystem
import kotlinx.datetime.Instant
import okio.FileMetadata
import okio.Path
import kotlin.jvm.JvmName
import kotlin.reflect.KClass
@JvmName("newFileMetadata")
internal fun FileMetadata(
isRegularFile: Boolean = false,
isDirectory: Boolean = false,
symlinkTarget: Path? = null,
size: Long? = null,
createdAt: Instant? = null,
lastModifiedAt: Instant? = null,
lastAccessedAt: Instant? = null,
extras: Map<KClass<*>, Any> = mapOf(),
): FileMetadata {
return FileMetadata(
isRegularFile = isRegularFile,
isDirectory = isDirectory,
symlinkTarget = symlinkTarget,
size = size,
createdAtMillis = createdAt?.toEpochMilliseconds(),
lastModifiedAtMillis = lastModifiedAt?.toEpochMilliseconds(),
lastAccessedAtMillis = lastAccessedAt?.toEpochMilliseconds(),
extras = extras,
)
}
| apache-2.0 | e488112b2faa8535074bd9da6bf90723 | 31 | 75 | 0.735054 | 4.266667 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/agent/runner/CommandLinePresentationServiceTest.kt | 1 | 3190 | package jetbrains.buildServer.dotnet.test.agent.runner
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.agent.runner.StdOutText
import jetbrains.buildServer.util.OSType
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.io.File
class CommandLinePresentationServiceTest {
@MockK private lateinit var _environment: Environment
@MockK private lateinit var _argumentsService: ArgumentsService
@MockK private lateinit var _virtualContext: VirtualContext
@BeforeMethod
fun setUp() {
MockKAnnotations.init(this)
every { _environment.os } returns OSType.WINDOWS
every { _argumentsService.normalize(any()) } answers { "\"${arg<String>(0)}\"" }
every { _virtualContext.targetOSType } returns OSType.UNIX
}
@DataProvider
fun testExecutableFilePresentation(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(Path("Dotnet.exe"), listOf(StdOutText("Dotnet.exe"))),
arrayOf(Path(File("Dir", "Dotnet.exe").path), listOf(StdOutText("Dir/"), StdOutText("Dotnet.exe"))))
}
@Test(dataProvider = "testExecutableFilePresentation")
fun shouldBuildExecutableFilePresentation(executableFile: Path, expectedOutput: List<StdOutText>) {
// Given
var presentation = createInstance()
// When
val actualOutput = presentation.buildExecutablePresentation(executableFile)
// Then
Assert.assertEquals(actualOutput, expectedOutput)
}
@DataProvider
fun testArgsPresentation(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Mandatory)), listOf(StdOutText(" \"Arg1\""))),
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Target)), listOf(StdOutText(" \"Arg1\""))),
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Secondary)), listOf(StdOutText(" \"Arg1\""))),
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Custom)), listOf(StdOutText(" \"Arg1\""))),
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Infrastructural)), listOf(StdOutText(" \"Arg1\""))),
arrayOf(listOf(CommandLineArgument("Arg1", CommandLineArgumentType.Mandatory), CommandLineArgument("Arg2", CommandLineArgumentType.Custom)), listOf(StdOutText(" \"Arg1\""), StdOutText(" \"Arg2\""))))
}
@Test(dataProvider = "testArgsPresentation")
fun shouldBuildArgsPresentation(arguments: List<CommandLineArgument>, expectedOutput: List<StdOutText>) {
// Given
var presentation = createInstance()
// When
val actualOutput = presentation.buildArgsPresentation(arguments)
// Then
Assert.assertEquals(actualOutput, expectedOutput)
}
private fun createInstance() =
CommandLinePresentationServiceImpl(_environment, _argumentsService, _virtualContext)
} | apache-2.0 | 2a89216844991fecd9bd01be49b119b5 | 43.319444 | 215 | 0.706897 | 4.862805 | false | true | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/PresentationFactory.kt | 1 | 15598 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.ide.ui.AntialiasingType
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.ui.LightweightHint
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Contract
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.font.FontRenderContext
import java.util.*
import javax.swing.Icon
import kotlin.math.max
class PresentationFactory(private val editor: EditorImpl) {
/**
* Smaller text, than editor, required to be wrapped with [roundWithBackground]
*/
@Contract(pure = true)
fun smallText(text: String): InlayPresentation {
val fontData = getFontData(editor)
val plainFont = fontData.font
val width = editor.contentComponent.getFontMetrics(plainFont).stringWidth(text)
val ascent = editor.ascent
val descent = editor.descent
val height = editor.lineHeight
val textWithoutBox = InsetPresentation(
TextInlayPresentation(width, fontData.lineHeight, text, fontData.baseline, height, ascent, descent) {
plainFont
}, top = 1, down = 1)
return withInlayAttributes(textWithoutBox)
}
/**
* Text, that is not expected to be drawn with rounding, the same font size as in editor.
*/
@Contract(pure = true)
fun text(text: String): InlayPresentation {
val font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
val width = editor.contentComponent.getFontMetrics(font).stringWidth(text)
val ascent = editor.ascent
val descent = editor.descent
val height = editor.lineHeight
return withInlayAttributes(TextInlayPresentation(
width,
height,
text,
ascent,
height,
ascent,
descent
) { font })
}
/**
* Adds inlay background and rounding with insets.
* Intended to be used with [smallText]
*/
@Contract(pure = true)
fun roundWithBackground(base: InlayPresentation): InlayPresentation {
val rounding = withInlayAttributes(RoundWithBackgroundPresentation(
InsetPresentation(
base,
left = 7,
right = 7,
top = 0,
down = 0
),
8,
8
))
val offsetFromTop = getFontData(editor).offsetFromTop(editor)
return InsetPresentation(rounding, top = offsetFromTop)
}
@Contract(pure = true)
fun icon(icon: Icon): IconPresentation = IconPresentation(icon, editor.component)
@Contract(pure = true)
fun withTooltip(tooltip: String, base: InlayPresentation): InlayPresentation = when {
tooltip.isEmpty() -> base
else -> {
var hint: LightweightHint? = null
onHover(base, object : HoverListener {
override fun onHover(event: MouseEvent) {
if (hint?.isVisible != true) {
hint = showTooltip(editor, event, tooltip)
}
}
override fun onHoverFinished() {
hint?.hide()
hint = null
}
})
}
}
@Contract(pure = true)
fun folding(placeholder: InlayPresentation, unwrapAction: () -> InlayPresentation): InlayPresentation {
return ChangeOnClickPresentation(changeOnHover(placeholder, onHover = {
attributes(placeholder) {
it.with(attributesOf(EditorColors.FOLDED_TEXT_ATTRIBUTES))
}
}), onClick = unwrapAction)
}
@Contract(pure = true)
fun inset(base: InlayPresentation, left: Int = 0, right: Int = 0, top: Int = 0, down: Int = 0): InsetPresentation {
return InsetPresentation(base, left, right, top, down)
}
/**
* Creates node, that can be collapsed/expanded by clicking on prefix/suffix.
* If presentation is collapsed, clicking to content will expand it.
*/
@Contract(pure = true)
fun collapsible(
prefix: InlayPresentation,
collapsed: InlayPresentation,
expanded: () -> InlayPresentation,
suffix: InlayPresentation,
startWithPlaceholder: Boolean = true): InlayPresentation {
val (matchingPrefix, matchingSuffix) = matchingBraces(prefix, suffix)
val prefixExposed = EventExposingPresentation(matchingPrefix)
val suffixExposed = EventExposingPresentation(matchingSuffix)
var presentationToChange: BiStatePresentation? = null
val content = BiStatePresentation(first = {
onClick(collapsed, MouseButton.Left,
onClick = { _, _ ->
presentationToChange?.flipState()
})
}, second = { expanded() }, initialState = startWithPlaceholder)
presentationToChange = content
val listener = object : InputHandler {
override fun mouseClicked(event: MouseEvent, translated: Point) {
content.flipState()
}
}
prefixExposed.addInputListener(listener)
suffixExposed.addInputListener(listener)
return seq(prefixExposed, content, suffixExposed)
}
private fun flipState() {
TODO("not implemented")
}
@Contract(pure = true)
fun matchingBraces(left: InlayPresentation, right: InlayPresentation): Pair<InlayPresentation, InlayPresentation> {
val (leftMatching, rightMatching) = matching(listOf(left, right))
return leftMatching to rightMatching
}
@Contract(pure = true)
fun matching(presentations: List<InlayPresentation>): List<InlayPresentation> = synchronousOnHover(presentations) { presentation ->
attributes(presentation) { base ->
base.with(attributesOf(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES))
}
}
/**
* On hover of any of [presentations] changes all the presentations with a given decorator.
* This presentation is stateless.
*/
@Contract(pure = true)
fun synchronousOnHover(presentations: List<InlayPresentation>,
decorator: (InlayPresentation) -> InlayPresentation): List<InlayPresentation> {
val forwardings = presentations.map { DynamicDelegatePresentation(it) }
return forwardings.map {
onHover(it, object : HoverListener {
override fun onHover(event: MouseEvent) {
for ((index, forwarding) in forwardings.withIndex()) {
forwarding.delegate = decorator(presentations[index])
}
}
override fun onHoverFinished() {
for ((index, forwarding) in forwardings.withIndex()) {
forwarding.delegate = presentations[index]
}
}
})
}
}
interface HoverListener {
fun onHover(event: MouseEvent)
fun onHoverFinished()
}
/**
* @see OnHoverPresentation
*/
@Contract(pure = true)
fun onHover(base: InlayPresentation, onHoverListener: HoverListener): InlayPresentation =
OnHoverPresentation(base, onHoverListener)
/**
* @see OnClickPresentation
*/
@Contract(pure = true)
fun onClick(base: InlayPresentation, button: MouseButton, onClick: (MouseEvent, Point) -> Unit): InlayPresentation {
return OnClickPresentation(base) { e, p ->
if (button == e.mouseButton) {
onClick(e, p)
}
}
}
/**
* @see OnClickPresentation
*/
@Contract(pure = true)
fun onClick(base: InlayPresentation, buttons: EnumSet<MouseButton>, onClick: (MouseEvent, Point) -> Unit): InlayPresentation {
return OnClickPresentation(base) { e, p ->
if (e.mouseButton in buttons) {
onClick(e, p)
}
}
}
/**
* @see ChangeOnHoverPresentation
*/
@Contract(pure = true)
fun changeOnHover(
base: InlayPresentation,
onHover: () -> InlayPresentation,
onHoverPredicate: (MouseEvent) -> Boolean = { true }
): InlayPresentation = ChangeOnHoverPresentation(base, onHover, onHoverPredicate)
@Contract(pure = true)
fun reference(base: InlayPresentation, onClickAction: () -> Unit): InlayPresentation {
val noHighlightReference = onClick(base, MouseButton.Middle) { _, _ ->
onClickAction()
}
return changeOnHover(noHighlightReference, {
val withRefAttributes = attributes(noHighlightReference) {
val attributes = attributesOf(EditorColors.REFERENCE_HYPERLINK_COLOR)
attributes.effectType = null // With underlined looks weird
it.with(attributes)
}
onClick(withRefAttributes, EnumSet.of(MouseButton.Left, MouseButton.Middle)) { _, _ ->
onClickAction()
}
}, { isControlDown(it) })
}
@Contract(pure = true)
fun psiSingleReference(base: InlayPresentation, resolve: () -> PsiElement?): InlayPresentation =
reference(base) { navigateInternal(resolve) }
@Contract(pure = true)
fun seq(vararg presentations: InlayPresentation): InlayPresentation {
return when (presentations.size) {
0 -> SpacePresentation(0, 0)
1 -> presentations.first()
else -> SequencePresentation(presentations.toList())
}
}
fun join(presentations: List<InlayPresentation>, separator: () -> InlayPresentation): InlayPresentation {
val seq = mutableListOf<InlayPresentation>()
var first = true
for (presentation in presentations) {
if (!first) {
seq.add(separator())
}
seq.add(presentation)
first = false
}
return SequencePresentation(seq)
}
@Contract(pure = true)
fun rounding(arcWidth: Int, arcHeight: Int, base: InlayPresentation): InlayPresentation =
RoundPresentation(base, arcWidth, arcHeight)
private fun attributes(base: InlayPresentation, transformer: (TextAttributes) -> TextAttributes): AttributesTransformerPresentation =
AttributesTransformerPresentation(base, transformer)
private fun withInlayAttributes(base: InlayPresentation): InlayPresentation {
return AttributesTransformerPresentation(base) {
it.withDefault(attributesOf(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT))
}
}
private fun isControlDown(e: MouseEvent): Boolean = (SystemInfo.isMac && e.isMetaDown) || e.isControlDown
private fun showTooltip(editor: Editor, e: MouseEvent, text: String): LightweightHint {
val hint = run {
val label = HintUtil.createInformationLabel(text)
label.border = JBUI.Borders.empty(6, 6, 5, 6)
LightweightHint(label)
}
val constraint = HintManager.ABOVE
val point = run {
val pointOnEditor = locationAt(e, editor.contentComponent)
val p = HintManagerImpl.getHintPosition(hint, editor, editor.xyToVisualPosition(pointOnEditor), constraint)
p.x = e.xOnScreen - editor.contentComponent.topLevelAncestor.locationOnScreen.x
p
}
HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, point,
HintManager.HIDE_BY_ANY_KEY
or HintManager.HIDE_BY_TEXT_CHANGE
or HintManager.HIDE_BY_SCROLLING,
0,
false,
HintManagerImpl.createHintHint(editor, point, hint, constraint).setContentActive(false)
)
return hint
}
private fun locationAt(e: MouseEvent, component: Component): Point {
val pointOnScreen = component.locationOnScreen
return Point(e.xOnScreen - pointOnScreen.x, e.yOnScreen - pointOnScreen.y)
}
private fun attributesOf(key: TextAttributesKey) = editor.colorsScheme.getAttributes(key) ?: TextAttributes()
private fun navigateInternal(resolve: () -> PsiElement?) {
val target = resolve()
if (target is Navigatable) {
CommandProcessor.getInstance().executeCommand(target.project, { target.navigate(true) }, null, null)
}
}
private class FontData constructor(editor: Editor, familyName: String, size: Int) {
val metrics: FontMetrics
val lineHeight: Int
val baseline: Int
val font: Font
get() = metrics.font
init {
val font = UIUtil.getFontWithFallback(familyName, Font.PLAIN, size)
val context = getCurrentContext(editor)
metrics = FontInfo.getFontMetrics(font, context)
// We assume this will be a better approximation to a real line height for a given font
lineHeight = Math.ceil(font.createGlyphVector(context, "Albpq@").visualBounds.height).toInt()
baseline = Math.ceil(font.createGlyphVector(context, "Alb").visualBounds.height).toInt()
}
fun isActual(editor: Editor, familyName: String, size: Int): Boolean {
val font = metrics.font
if (familyName != font.family || size != font.size) return false
val currentContext = getCurrentContext(editor)
return currentContext.equals(metrics.fontRenderContext)
}
private fun getCurrentContext(editor: Editor): FontRenderContext {
val editorContext = FontInfo.getFontRenderContext(editor.contentComponent)
return FontRenderContext(editorContext.transform,
AntialiasingType.getKeyForCurrentScope(false),
if (editor is EditorImpl)
editor.myFractionalMetricsHintValue
else
RenderingHints.VALUE_FRACTIONALMETRICS_OFF)
}
/**
* Offset from the top edge of drawing rectangle to rectangle with text.
*/
fun offsetFromTop(editor: Editor): Int = (editor.lineHeight - lineHeight) / 2
}
private fun getFontData(editor: Editor): FontData {
val familyName = UIUtil.getLabelFont().family
val size = max(1, editor.colorsScheme.editorFontSize - 1)
var metrics = editor.getUserData(FONT_DATA)
if (metrics != null && !metrics.isActual(editor, familyName, size)) {
metrics = null
}
if (metrics == null) {
metrics = FontData(editor, familyName, size)
editor.putUserData(FONT_DATA, metrics)
}
return metrics
}
companion object {
@JvmStatic
private val FONT_DATA = Key.create<FontData>("InlayHintFontData")
}
}
private fun TextAttributes.with(other: TextAttributes): TextAttributes {
val result = this.clone()
other.foregroundColor?.let { result.foregroundColor = it }
other.backgroundColor?.let { result.backgroundColor = it }
other.fontType.let { result.fontType = it }
other.effectType?.let { result.effectType = it }
other.effectColor?.let { result.effectColor = it }
return result
}
private fun TextAttributes.withDefault(other: TextAttributes): TextAttributes {
val result = this.clone()
if (result.foregroundColor == null) {
result.foregroundColor = other.foregroundColor
}
if (result.backgroundColor == null) {
result.backgroundColor = other.backgroundColor
}
if (result.effectType == null) {
result.effectType = other.effectType
}
if (result.effectColor == null) {
result.effectColor = other.effectColor
}
return result
} | apache-2.0 | 43ef04bb2cc8d2a4f2555d73aab74156 | 34.53303 | 140 | 0.684703 | 4.588997 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/util/RightTextCellRenderer.kt | 1 | 2197 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListCellRenderer
/**
* This renderer adds grey text aligned to the right of whatever component returned by [baseRenderer]
*
* @see com.intellij.ide.util.PsiElementModuleRenderer
*/
class RightTextCellRenderer<T>(
private val baseRenderer: ListCellRenderer<in T>,
private val text: (T) -> String?
) : ListCellRenderer<T> {
private val label = JBLabel().apply {
isOpaque = true
border = JBUI.Borders.emptyRight(UIUtil.getListCellHPadding())
}
private val spacer = JPanel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val layout = BorderLayout()
private val rendererComponent = JPanel(layout).apply {
add(spacer, BorderLayout.CENTER)
add(label, BorderLayout.EAST)
}
override fun getListCellRendererComponent(list: JList<out T>?,
value: T?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
val originalComponent = baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (value == null || list == null || originalComponent == null) return originalComponent
val text = text(value) ?: return originalComponent
val bg = if (isSelected) UIUtil.getListSelectionBackground(true) else originalComponent.background
label.text = text
label.background = bg
label.foreground = if (isSelected) UIUtil.getListSelectionForeground() else UIUtil.getInactiveTextColor()
spacer.background = bg
layout.getLayoutComponent(BorderLayout.WEST)?.let(rendererComponent::remove)
rendererComponent.add(originalComponent, BorderLayout.WEST)
return rendererComponent
}
}
| apache-2.0 | d6165a5c046d756ef179d1e7b3c66fa5 | 34.435484 | 140 | 0.695494 | 4.724731 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/dataClasses/nonTrivialFinalMemberInSuperClass.kt | 5 | 428 | abstract class Base {
final override fun toString() = "OK"
final override fun hashCode() = 42
final override fun equals(other: Any?) = false
}
data class DataClass(val field: String) : Base()
fun box(): String {
val d = DataClass("x")
if (d.toString() != "OK") return "Fail toString"
if (d.hashCode() != 42) return "Fail hashCode"
if (d.equals(d) != false) return "Fail equals"
return "OK"
}
| apache-2.0 | d7078aaf1a4bec403aca097bf08720fe | 24.176471 | 52 | 0.623832 | 3.53719 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/jvmStatic/importStaticMemberFromObject.kt | 2 | 519 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
import O.p
import O.f
import C.Companion.p1
import C.Companion.f1
object O {
@JvmStatic
fun f(): Int = 3
@JvmStatic
val p: Int = 6
}
class C {
companion object {
@JvmStatic
fun f1(): Int = 3
@JvmStatic
val p1: Int = 6
}
}
fun box(): String {
if (p + f() != 9) return "fail"
if (p1 + f1() != 9) return "fail2"
return "OK"
}
| apache-2.0 | e9f6f7d224dfd11d1df3e4d52a9662ec | 13.828571 | 72 | 0.560694 | 3.126506 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/KotlinObjCClassInfoGenerator.kt | 1 | 6862 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import llvm.LLVMStoreSizeOfType
import llvm.LLVMValueRef
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.contributedMethods
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValueOrNull
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.isFinalClass
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces
internal class KotlinObjCClassInfoGenerator(override val context: Context) : ContextUtils {
fun generate(irClass: IrClass) {
val descriptor = irClass.descriptor
assert(descriptor.isFinalClass)
val objCLLvmDeclarations = context.llvmDeclarations.forClass(descriptor).objCDeclarations!!
val instanceMethods = generateInstanceMethodDescs(irClass)
val companionObjectDescriptor = descriptor.companionObjectDescriptor
val classMethods = companionObjectDescriptor?.generateOverridingMethodDescs() ?: emptyList()
val superclassName = descriptor.getSuperClassNotAny()!!.let {
context.llvm.imports.add(it.llvmSymbolOrigin)
it.name.asString()
}
val protocolNames = descriptor.getSuperInterfaces().map {
context.llvm.imports.add(it.llvmSymbolOrigin)
it.name.asString().removeSuffix("Protocol")
}
val bodySize =
LLVMStoreSizeOfType(llvmTargetData, context.llvmDeclarations.forClass(descriptor).bodyType).toInt()
val className = selectClassName(descriptor)?.let { staticData.cStringLiteral(it) } ?: NullPointer(int8Type)
val info = Struct(runtime.kotlinObjCClassInfo,
className,
staticData.cStringLiteral(superclassName),
staticData.placeGlobalConstArray("", int8TypePtr,
protocolNames.map { staticData.cStringLiteral(it) } + NullPointer(int8Type)),
staticData.placeGlobalConstArray("", runtime.objCMethodDescription, instanceMethods),
Int32(instanceMethods.size),
staticData.placeGlobalConstArray("", runtime.objCMethodDescription, classMethods),
Int32(classMethods.size),
Int32(bodySize),
objCLLvmDeclarations.bodyOffsetGlobal.pointer,
descriptor.typeInfoPtr,
companionObjectDescriptor?.typeInfoPtr ?: NullPointer(runtime.typeInfoType),
objCLLvmDeclarations.classPointerGlobal.pointer
)
objCLLvmDeclarations.classInfoGlobal.setInitializer(info)
objCLLvmDeclarations.classPointerGlobal.setInitializer(NullPointer(int8Type))
objCLLvmDeclarations.bodyOffsetGlobal.setInitializer(Int32(0))
}
private fun generateInstanceMethodDescs(
irClass: IrClass
): List<ObjCMethodDesc> = mutableListOf<ObjCMethodDesc>().apply {
val descriptor = irClass.descriptor
addAll(descriptor.generateOverridingMethodDescs())
addAll(irClass.generateImpMethodDescs())
val allImplementedSelectors = this.map { it.selector }.toSet()
assert(descriptor.getSuperClassNotAny()!!.isExternalObjCClass())
val allInitMethodsInfo = descriptor.getSuperClassNotAny()!!.constructors
.mapNotNull { it.getObjCInitMethod()?.getExternalObjCMethodInfo() }
.filter { it.selector !in allImplementedSelectors }
.distinctBy { it.selector }
allInitMethodsInfo.mapTo(this) {
ObjCMethodDesc(it.selector, it.encoding, context.llvm.missingInitImp)
}
}
private fun selectClassName(descriptor: ClassDescriptor): String? {
val exportObjCClassAnnotation =
descriptor.annotations.findAnnotation(context.interopBuiltIns.exportObjCClass.fqNameSafe)
return if (exportObjCClassAnnotation != null) {
exportObjCClassAnnotation.getStringValueOrNull("name") ?: descriptor.name.asString()
} else if (descriptor.isExported()) {
descriptor.fqNameSafe.asString()
} else {
null // Generate as anonymous.
}
}
private val impType = pointerType(functionType(int8TypePtr, true, int8TypePtr, int8TypePtr))
private inner class ObjCMethodDesc(
val selector: String, val encoding: String, val impFunction: LLVMValueRef
) : Struct(
runtime.objCMethodDescription,
constPointer(impFunction).bitcast(impType),
staticData.cStringLiteral(selector),
staticData.cStringLiteral(encoding)
)
private fun generateMethodDesc(info: ObjCMethodInfo) = ObjCMethodDesc(
info.selector,
info.encoding,
context.llvm.externalFunction(
info.imp,
functionType(voidType),
origin = info.bridge.llvmSymbolOrigin
)
)
private fun ClassDescriptor.generateOverridingMethodDescs(): List<ObjCMethodDesc> =
this.unsubstitutedMemberScope.contributedMethods.filter {
it.kind.isReal && it !is ConstructorDescriptor
}.mapNotNull { it.getObjCMethodInfo() }.map { generateMethodDesc(it) }
private fun IrClass.generateImpMethodDescs(): List<ObjCMethodDesc> = this.declarations
.filterIsInstance<IrSimpleFunction>()
.mapNotNull {
val annotation =
it.descriptor.annotations.findAnnotation(context.interopBuiltIns.objCMethodImp.fqNameSafe) ?:
return@mapNotNull null
ObjCMethodDesc(
annotation.getStringValue("selector"),
annotation.getStringValue("encoding"),
it.descriptor.llvmFunction
)
}
} | apache-2.0 | 91b002dc0d240b06c128eea9cf389773 | 42.163522 | 117 | 0.690032 | 5.348402 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/ToggleButtonTest.kt | 1 | 22433 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.testutils.assertShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.filters.SdkSuppress
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class ToggleButtonBehaviourTest {
@get:Rule
val rule = createComposeRule()
@Test
fun supports_testtag() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun has_clickaction_when_enabled() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = true,
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertHasClickAction()
}
@Test
fun has_clickaction_when_disabled() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = false,
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertHasClickAction()
}
@Test
fun is_toggleable() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNode(isToggleable()).assertExists()
}
@Test
fun is_correctly_enabled_when_enabled_equals_true() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
content = { TestImage() },
enabled = true,
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertIsEnabled()
}
@Test
fun is_correctly_disabled_when_enabled_equals_false() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
content = { TestImage() },
enabled = false,
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertIsNotEnabled()
}
@Test
fun is_on_when_checked() {
rule.setContentWithTheme {
ToggleButton(
checked = true,
onCheckedChange = {},
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertIsOn()
}
@Test
fun is_off_when_unchecked() {
rule.setContentWithTheme {
ToggleButton(
checked = false,
onCheckedChange = {},
content = { TestImage() },
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG).assertIsOff()
}
@Test
fun responds_to_toggle_on() {
rule.setContentWithTheme {
val (checked, onCheckedChange) = remember { mutableStateOf(false) }
ToggleButton(
content = { TestImage() },
checked = checked,
onCheckedChange = onCheckedChange,
enabled = true,
modifier = Modifier.testTag(TEST_TAG)
)
}
rule
.onNodeWithTag(TEST_TAG)
.assertIsOff()
.performClick()
.assertIsOn()
}
@Test
fun responds_to_toggle_off() {
rule.setContentWithTheme {
val (checked, onCheckedChange) = remember { mutableStateOf(true) }
ToggleButton(
content = { TestImage() },
checked = checked,
onCheckedChange = onCheckedChange,
enabled = true,
modifier = Modifier.testTag(TEST_TAG)
)
}
rule
.onNodeWithTag(TEST_TAG)
.assertIsOn()
.performClick()
.assertIsOff()
}
@Test
fun does_not_toggle_when_disabled() {
rule.setContentWithTheme {
val (checked, onCheckedChange) = remember { mutableStateOf(false) }
ToggleButton(
content = { TestImage() },
checked = checked,
onCheckedChange = onCheckedChange,
enabled = false,
modifier = Modifier.testTag(TEST_TAG)
)
}
rule
.onNodeWithTag(TEST_TAG)
.assertIsOff()
.performClick()
.assertIsOff()
}
@Test
fun has_role_checkbox() {
rule.setContentWithTheme {
ToggleButton(
content = { TestImage() },
checked = false,
onCheckedChange = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
rule.onNodeWithTag(TEST_TAG)
.assert(
SemanticsMatcher.expectValue(
SemanticsProperties.Role,
Role.Checkbox
)
)
}
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun is_circular_under_ltr() =
rule.isCircular(LayoutDirection.Ltr) {
ToggleButton(
content = {},
checked = true,
enabled = true,
onCheckedChange = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun is_circular_under_rtl() =
rule.isCircular(LayoutDirection.Rtl) {
ToggleButton(
content = {},
checked = true,
enabled = true,
onCheckedChange = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
@Test
fun default_toggle_button_shape_is_circle() {
rule.isShape(CircleShape) { modifier ->
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(),
modifier = modifier
) {}
}
}
@Test
fun allows_custom_toggle_button_shape_override() {
val shape = CutCornerShape(4.dp)
rule.isShape(shape) { modifier ->
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(),
shape = shape,
modifier = modifier
) {}
}
}
@Test
fun displays_text_content() {
val textContent = "abc"
rule.setContentWithTheme {
ToggleButton(
content = { Text(textContent) },
checked = true,
onCheckedChange = {},
)
}
rule.onNodeWithText(textContent).assertExists()
}
}
class ToggleButtonSizeTest {
@get:Rule
val rule = createComposeRule()
@Test
fun gives_default_correct_tapsize() {
rule.verifyTapSize(TapSize.Default) {
ToggleButton(
content = { Text("abc") },
checked = true,
onCheckedChange = {},
)
}
}
@Test
fun gives_small_correct_tapsize() {
rule.verifyTapSize(TapSize.Small) {
ToggleButton(
content = { TestImage() },
checked = true,
onCheckedChange = {},
modifier = Modifier.size(ToggleButtonDefaults.SmallToggleButtonSize)
)
}
}
}
class ToggleButtonColorTest {
@get:Rule
val rule = createComposeRule()
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_checked_primary_colors() =
verifyColors(
Status.Enabled,
checked = true,
{ MaterialTheme.colors.primary },
{ MaterialTheme.colors.onPrimary }
)
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_unchecked_secondary_colors() =
verifyColors(
Status.Enabled,
checked = false,
{ MaterialTheme.colors.surface },
{ MaterialTheme.colors.onSurface }
)
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_checked_disabled_alpha() =
verifyColors(
Status.Disabled,
checked = true,
{ MaterialTheme.colors.primary },
{ MaterialTheme.colors.onPrimary }
)
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_unchecked_disabled_alpha() =
verifyColors(
Status.Disabled,
checked = false,
{ MaterialTheme.colors.surface },
{ MaterialTheme.colors.onSurface }
)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun allows_custom_checked_background_override() {
val override = Color.Yellow
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(
checkedBackgroundColor =
override
),
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(override, 50.0f)
}
@Test
fun allows_custom_checked_content_override() {
val override = Color.Green
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(
checkedContentColor =
override
),
content = { actualContentColor = LocalContentColor.current },
modifier = Modifier.testTag(TEST_TAG)
)
}
}
assertEquals(override, actualContentColor)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun allows_custom_unchecked_background_override() {
val override = Color.Red
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = false,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(
uncheckedBackgroundColor =
override
),
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(override, 50.0f)
}
@Test
fun allows_custom_unchecked_content_override() {
val override = Color.Green
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = false,
onCheckedChange = {},
enabled = true,
colors = ToggleButtonDefaults.toggleButtonColors(
uncheckedContentColor =
override
),
content = { actualContentColor = LocalContentColor.current },
modifier = Modifier.testTag(TEST_TAG)
)
}
}
assertEquals(override, actualContentColor)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun allows_custom_checked_disabled_background_override() {
val override = Color.Yellow
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = false,
colors = ToggleButtonDefaults.toggleButtonColors
(disabledCheckedBackgroundColor = override),
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(override, 50.0f)
}
@Test
fun allows_custom_checked_disabled_content_override() {
val override = Color.Green
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = true,
onCheckedChange = {},
enabled = false,
colors = ToggleButtonDefaults.toggleButtonColors(
disabledCheckedContentColor =
override
),
content = {
actualContentColor = LocalContentColor.current
},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
assertEquals(override, actualContentColor)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun allows_custom_unchecked_disabled_background_override() {
val override = Color.Red
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = false,
onCheckedChange = {},
enabled = false,
colors = ToggleButtonDefaults.toggleButtonColors
(disabledUncheckedBackgroundColor = override),
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(override, 50.0f)
}
@Test
fun allows_custom_unchecked_disabled_content_override() {
val override = Color.Green
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize()) {
ToggleButton(
checked = false,
onCheckedChange = {},
enabled = false,
colors = ToggleButtonDefaults.toggleButtonColors
(disabledUncheckedContentColor = override),
content = { actualContentColor = LocalContentColor.current },
modifier = Modifier.testTag(TEST_TAG)
)
}
}
assertEquals(override, actualContentColor)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
private fun verifyColors(
status: Status,
checked: Boolean,
backgroundColor: @Composable () -> Color,
contentColor: @Composable () -> Color
) {
val testBackgroundColor = Color.Magenta
var expectedBackground = Color.Transparent
var expectedContent = Color.Transparent
var actualContent = Color.Transparent
var actualDisabledAlpha = 0f
rule.setContentWithTheme {
expectedBackground = backgroundColor()
expectedContent = contentColor()
Box(
modifier = Modifier
.fillMaxSize()
.background(testBackgroundColor)
) {
ToggleButton(
checked = checked,
onCheckedChange = {},
enabled = status.enabled(),
content = {
actualContent = LocalContentColor.current
actualDisabledAlpha = ContentAlpha.disabled
},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
if (status.enabled()) {
assertEquals(expectedContent, actualContent)
if (expectedBackground != Color.Transparent) {
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(expectedBackground, 50.0f)
}
} else {
assertEquals(expectedContent.copy(alpha = actualDisabledAlpha), actualContent)
if (expectedBackground != Color.Transparent) {
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(
expectedBackground.copy(alpha = actualDisabledAlpha)
.compositeOver(testBackgroundColor), 50.0f
)
}
}
}
}
private fun ComposeContentTestRule.verifyTapSize(
expected: TapSize,
content: @Composable () -> Unit
) {
setContentWithThemeForSizeAssertions {
content()
}
.assertHeightIsEqualTo(expected.size)
.assertWidthIsEqualTo(expected.size)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
private fun ComposeContentTestRule.isCircular(
layoutDirection: LayoutDirection,
padding: Dp = 0.dp,
content: @Composable () -> Unit
) {
var background = Color.Transparent
var surface = Color.Transparent
setContentWithTheme {
background = MaterialTheme.colors.primary
surface = MaterialTheme.colors.surface
CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) {
Box(
Modifier
.padding(padding)
.background(surface)
) {
content()
}
}
}
onNodeWithTag(TEST_TAG)
.captureToImage()
.assertShape(
density = density,
shape = CircleShape,
horizontalPadding = padding,
verticalPadding = padding,
backgroundColor = surface,
shapeColor = background
)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
private fun ComposeContentTestRule.isShape(
expectedShape: Shape,
content: @Composable (Modifier) -> Unit
) {
var background = Color.Transparent
var buttonColor = Color.Transparent
val padding = 0.dp
setContentWithTheme {
background = MaterialTheme.colors.surface
buttonColor = MaterialTheme.colors.primary
content(
Modifier
.testTag(TEST_TAG)
.padding(padding)
.background(background))
}
onNodeWithTag(TEST_TAG)
.captureToImage()
.assertShape(
density = density,
horizontalPadding = 0.dp,
verticalPadding = 0.dp,
shapeColor = buttonColor,
backgroundColor = background,
shape = expectedShape
)
}
| apache-2.0 | d5ed502d7e9d6c75f6f93c16a0644f78 | 29.646175 | 90 | 0.546917 | 5.562361 | false | true | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/GithubAuthenticationManager.kt | 3 | 6012 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.AuthData
import com.intellij.util.concurrency.annotations.RequiresEdt
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.Component
internal class GHAccountAuthData(val account: GithubAccount, login: String, token: String) : AuthData(login, token) {
val server: GithubServerPath get() = account.server
val token: String get() = password!!
}
/**
* Entry point for interactions with Github authentication subsystem
*/
class GithubAuthenticationManager internal constructor() {
private val accountManager: GHAccountManager get() = service()
@CalledInAny
fun hasAccounts() = accountManager.accounts.isNotEmpty()
@CalledInAny
fun getAccounts(): Set<GithubAccount> = accountManager.accounts
@CalledInAny
internal fun getTokenForAccount(account: GithubAccount): String? = accountManager.findCredentials(account)
@RequiresEdt
@JvmOverloads
internal fun requestNewToken(account: GithubAccount, project: Project?, parentComponent: Component? = null): String? =
login(
project, parentComponent,
GHLoginRequest(
text = GithubBundle.message("account.token.missing.for", account),
server = account.server, login = account.name
)
)?.updateAccount(account)
@RequiresEdt
@JvmOverloads
fun requestNewAccount(project: Project?, parentComponent: Component? = null): GithubAccount? =
login(
project, parentComponent,
GHLoginRequest(isCheckLoginUnique = true)
)?.registerAccount()
@RequiresEdt
@JvmOverloads
fun requestNewAccountForServer(server: GithubServerPath, project: Project?, parentComponent: Component? = null): GithubAccount? =
login(
project, parentComponent,
GHLoginRequest(server = server, isCheckLoginUnique = true)
)?.registerAccount()
@RequiresEdt
@JvmOverloads
fun requestNewAccountForServer(
server: GithubServerPath,
login: String,
project: Project?,
parentComponent: Component? = null
): GithubAccount? =
login(
project, parentComponent,
GHLoginRequest(server = server, login = login, isLoginEditable = false, isCheckLoginUnique = true)
)?.registerAccount()
@RequiresEdt
fun requestNewAccountForDefaultServer(project: Project?, useToken: Boolean = false): GithubAccount? {
return GHLoginRequest(server = GithubServerPath.DEFAULT_SERVER, isCheckLoginUnique = true).let {
if (!useToken) it.loginWithOAuth(project, null) else it.loginWithToken(project, null)
}?.registerAccount()
}
internal fun isAccountUnique(name: String, server: GithubServerPath) =
accountManager.accounts.none { it.name == name && it.server.equals(server, true) }
@RequiresEdt
@JvmOverloads
fun requestReLogin(account: GithubAccount, project: Project?, parentComponent: Component? = null): Boolean =
login(
project, parentComponent,
GHLoginRequest(server = account.server, login = account.name)
)?.updateAccount(account) != null
@RequiresEdt
internal fun login(project: Project?, parentComponent: Component?, request: GHLoginRequest): GHAccountAuthData? =
if (request.server?.isGithubDotCom == true) request.loginWithOAuthOrToken(project, parentComponent)
else request.loginWithToken(project, parentComponent)
@RequiresEdt
internal fun removeAccount(account: GithubAccount) {
accountManager.removeAccount(account)
}
@RequiresEdt
internal fun updateAccountToken(account: GithubAccount, newToken: String) =
accountManager.updateAccount(account, newToken)
@RequiresEdt
internal fun registerAccount(name: String, server: GithubServerPath, token: String): GithubAccount =
registerAccount(GHAccountManager.createAccount(name, server), token)
@RequiresEdt
internal fun registerAccount(account: GithubAccount, token: String): GithubAccount {
accountManager.updateAccount(account, token)
return account
}
@TestOnly
fun clearAccounts() {
accountManager.updateAccounts(emptyMap())
}
fun getDefaultAccount(project: Project): GithubAccount? =
project.service<GithubProjectDefaultAccountHolder>().account
@TestOnly
fun setDefaultAccount(project: Project, account: GithubAccount?) {
project.service<GithubProjectDefaultAccountHolder>().account = account
}
@RequiresEdt
@JvmOverloads
fun ensureHasAccounts(project: Project?, parentComponent: Component? = null): Boolean =
hasAccounts() || requestNewAccount(project, parentComponent) != null
fun getSingleOrDefaultAccount(project: Project): GithubAccount? =
project.service<GithubProjectDefaultAccountHolder>().account
?: accountManager.accounts.singleOrNull()
@RequiresEdt
fun addListener(disposable: Disposable, listener: AccountsListener<GithubAccount>) = accountManager.addListener(disposable, listener)
companion object {
@JvmStatic
fun getInstance(): GithubAuthenticationManager = service()
}
}
private fun GHAccountAuthData.registerAccount(): GithubAccount =
GithubAuthenticationManager.getInstance().registerAccount(login, server, token)
private fun GHAccountAuthData.updateAccount(account: GithubAccount): String {
account.name = login
GithubAuthenticationManager.getInstance().updateAccountToken(account, token)
return token
} | apache-2.0 | 9bfecc6919a9ed713c69e7b3c0cc77c8 | 36.81761 | 140 | 0.771623 | 4.891782 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/profile/codeInspection/ui/DescriptionEditorPane.kt | 1 | 1613 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.profile.codeInspection.ui
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.ui.HintHint
import com.intellij.util.ui.HTMLEditorKitBuilder
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Point
import java.io.IOException
import java.io.StringReader
import javax.swing.JEditorPane
import javax.swing.text.html.HTMLEditorKit
open class DescriptionEditorPane : JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML) {
init {
isEditable = false
isOpaque = false
editorKit = HTMLEditorKitBuilder().withGapsBetweenParagraphs().withoutContentCss().build()
val css = (this.editorKit as HTMLEditorKit).styleSheet
css.addRule("a {overflow-wrap: anywhere;}")
css.addRule("pre {padding:10px;}")
}
override fun getBackground(): Color = UIUtil.getLabelBackground()
companion object {
const val EMPTY_HTML = "<html><body></body></html>"
}
}
fun JEditorPane.readHTML(text: String) {
try {
read(StringReader(text.replace("<pre>", "<pre class=\"editor-background\">")), null)
}
catch (e: IOException) {
throw RuntimeException(e)
}
}
fun JEditorPane.toHTML(text: @Nls String?, miniFontSize: Boolean): String {
val hintHint = HintHint(this, Point(0, 0))
hintHint.setFont(if (miniFontSize) UIUtil.getLabelFont(UIUtil.FontSize.SMALL) else StartupUiUtil.getLabelFont())
return HintUtil.prepareHintText(text!!, hintHint)
}
| apache-2.0 | 79169adb5bba506ba531e791c0373abb | 31.918367 | 120 | 0.753875 | 3.858852 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/HeightMap.kt | 1 | 4136 | package de.fabmax.kool.util
import de.fabmax.kool.math.clamp
import de.fabmax.kool.pipeline.TexFormat
import de.fabmax.kool.pipeline.TextureData2d
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
class HeightMap(val heightData: FloatArray, val width: Int, val height: Int) {
val minHeight: Float
val maxHeight: Float
init {
check(heightData.size == width * height) {
"Supplied height data has not the correct size: ${heightData.size} elements != $width x $height"
}
var min = Float.POSITIVE_INFINITY
var max = Float.NEGATIVE_INFINITY
for (i in heightData.indices) {
min = min(min, heightData[i])
max = max(max, heightData[i])
}
minHeight = min
maxHeight = max
}
fun getHeightLinear(x: Float, y: Float): Float {
val x0 = floor(x).toInt()
val x1 = x0 + 1
val xf = x - x0
val y0 = floor(y).toInt()
val y1 = y0 + 1
val yf = y - y0
val h00 = getHeight(x0, y0)
val h01 = getHeight(x0, y1)
val h10 = getHeight(x1, y0)
val h11 = getHeight(x1, y1)
val ha = h00 * (1f - yf) + h01 * yf
val hb = h10 * (1f - yf) + h11 * yf
return ha * (1f - xf) + hb * xf
}
fun getHeight(x: Int, y: Int): Float {
val cx = x.clamp(0, width - 1)
val cy = y.clamp(0, height - 1)
return heightData[cy * width + cx]
}
companion object {
/**
* Constructs a [HeightMap] from the provided [TextureData2d] object. Format must be either [TexFormat.R_F16]
* or [TexFormat.R]
*/
fun fromTextureData2d(textureData2d: TextureData2d, heightScale: Float, heightOffset: Float = 0f): HeightMap {
check(textureData2d.format == TexFormat.R_F16 || textureData2d.format == TexFormat.R) {
"Texture format must be either TexFormat.R_F16 or TexFormat.R"
}
val heightData = FloatArray(textureData2d.width * textureData2d.height)
if (textureData2d.data is Float32Buffer) {
val float32Buf = textureData2d.data as Float32Buffer
for (i in 0 until textureData2d.width * textureData2d.height) {
heightData[i] = float32Buf[i] * heightScale + heightOffset
}
} else {
logW { "Constructing height map from 8-bit texture data, consider using raw data for higher height resolution" }
val uint8Buf = textureData2d.data as Uint8Buffer
for (i in 0 until textureData2d.width * textureData2d.height) {
heightData[i] = ((uint8Buf[i].toInt() and 0xff) / 255f) * heightScale + heightOffset
}
}
return HeightMap(heightData, textureData2d.width, textureData2d.height)
}
/**
* Constructs a [HeightMap] from the provided binary buffer. Buffer content is expected to be a plain array of
* 16-bit integers with dimension [width] x [height]. If [width] and / or [height] are not specified, a square
* map is assumed.
*/
fun fromRawData(rawData: Uint8Buffer, heightScale: Float, width: Int = 0, height: Int = 0, heightOffset: Float = 0f): HeightMap {
val elems = rawData.capacity / 2
// if width and / or height are not supplied, a square map is assumed
val w = if (width > 0) width else sqrt(elems.toDouble()).toInt()
val h = if (height > 0) height else w
if (w * h != elems) {
throw IllegalArgumentException("Raw data size ($elems) does not match supplied size: $width x $height")
}
val heightData = FloatArray(elems)
for (i in 0 until elems) {
val ia = rawData[i*2].toInt() and 0xff
val ib = rawData[i*2+1].toInt() and 0xff
heightData[i] = ((ia or (ib shl 8)) / 65535f) * heightScale + heightOffset
}
return HeightMap(heightData, w, h)
}
}
} | apache-2.0 | dc4a153a1b0089fdcf1e49eafe2356f0 | 38.4 | 137 | 0.577853 | 3.801471 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/settings/Repository.kt | 1 | 3914 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <VREMSoftwareDevelopment@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.settings
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import androidx.preference.PreferenceManager
import com.vrem.wifianalyzer.R
inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) {
val editor: SharedPreferences.Editor = edit()
editor.func()
editor.apply()
}
class Repository(private val context: Context) {
fun initializeDefaultValues(): Unit = defaultValues(context, R.xml.settings, false)
fun registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener): Unit =
sharedPreferences().registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener)
fun save(key: Int, value: Int): Unit = save(key, value.toString())
fun save(key: Int, value: String): Unit = sharedPreferences().edit { putString(context.getString(key), value) }
fun stringAsInteger(key: Int, defaultValue: Int): Int =
string(key, defaultValue.toString()).toInt()
fun string(key: Int, defaultValue: String): String {
val keyValue: String = context.getString(key)
return try {
sharedPreferences().getString(keyValue, defaultValue) ?: defaultValue
} catch (e: Exception) {
sharedPreferences().edit { putString(keyValue, defaultValue) }
defaultValue
}
}
fun boolean(key: Int, defaultValue: Boolean): Boolean {
val keyValue: String = context.getString(key)
return try {
sharedPreferences().getBoolean(keyValue, defaultValue)
} catch (e: Exception) {
sharedPreferences().edit { putBoolean(keyValue, defaultValue) }
defaultValue
}
}
fun resourceBoolean(key: Int): Boolean = context.resources.getBoolean(key)
fun integer(key: Int, defaultValue: Int): Int {
val keyValue: String = context.getString(key)
return try {
sharedPreferences().getInt(keyValue, defaultValue)
} catch (e: Exception) {
sharedPreferences().edit { putString(keyValue, defaultValue.toString()) }
defaultValue
}
}
fun stringSet(key: Int, defaultValues: Set<String>): Set<String> {
val keyValue: String = context.getString(key)
return try {
sharedPreferences().getStringSet(keyValue, defaultValues)!!
} catch (e: Exception) {
sharedPreferences().edit { putStringSet(keyValue, defaultValues) }
defaultValues
}
}
fun saveStringSet(key: Int, values: Set<String>): Unit =
sharedPreferences().edit { putStringSet(context.getString(key), values) }
fun defaultValues(context: Context, resId: Int, readAgain: Boolean): Unit =
PreferenceManager.setDefaultValues(context, resId, readAgain)
fun defaultSharedPreferences(context: Context): SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context)
private fun sharedPreferences(): SharedPreferences = defaultSharedPreferences(context)
} | gpl-3.0 | de10ef4e1ff421bff761369f5fe6afd0 | 38.545455 | 124 | 0.702606 | 5.011524 | false | false | false | false |
siosio/intellij-community | platform/object-serializer/src/stateProperties/MapStoredProperty.kt | 1 | 2629 | // 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.serialization.stateProperties
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.JsonSchemaType
import com.intellij.openapi.components.StoredProperty
import com.intellij.openapi.components.StoredPropertyBase
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
class MapStoredProperty<K: Any, V>(value: MutableMap<K, V>?) : StoredPropertyBase<MutableMap<K, V>>() {
private val value: MutableMap<K, V> = value ?: MyMap()
override val jsonType: JsonSchemaType
get() = JsonSchemaType.OBJECT
override fun isEqualToDefault() = value.isEmpty()
override fun getValue(thisRef: BaseState) = value
override fun setValue(thisRef: BaseState, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") newValue: MutableMap<K, V>) {
if (doSetValue(value, newValue)) {
thisRef.intIncrementModificationCount()
}
}
private fun doSetValue(old: MutableMap<K, V>, new: Map<K, V>): Boolean {
if (old == new) {
return false
}
old.clear()
old.putAll(new)
return true
}
override fun equals(other: Any?) = this === other || (other is MapStoredProperty<*, *> && value == other.value)
override fun hashCode() = value.hashCode()
override fun toString() = if (isEqualToDefault()) "" else value.toString()
override fun setValue(other: StoredProperty<MutableMap<K, V>>): Boolean {
@Suppress("UNCHECKED_CAST")
return doSetValue(value, (other as MapStoredProperty<K, V>).value)
}
@Suppress("FunctionName")
fun __getValue() = value
override fun getModificationCount(): Long {
return when (value) {
is MyMap -> value.modificationCount
else -> {
var result = 0L
for (value in value.values) {
if (value is BaseState) {
result += value.modificationCount
}
else {
// or all values are BaseState or not
break
}
}
result
}
}
}
}
private class MyMap<K: Any, V> : Object2ObjectOpenHashMap<K, V>() {
@Volatile
var modificationCount = 0L
override fun put(key: K, value: V): V? {
val oldValue = super.put(key, value)
if (oldValue !== value) {
modificationCount++
}
return oldValue
}
// to detect a remove from iterator
override fun remove(key: K): V? {
val result = super.remove(key)
modificationCount++
return result
}
override fun clear() {
super.clear()
modificationCount++
}
} | apache-2.0 | 5628281fe46a807d29a1448df840a5a1 | 27.27957 | 140 | 0.664892 | 4.15981 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmarks/actions/ChooseBookmarkTypeAction.kt | 1 | 2398 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmarks.actions
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.ide.bookmarks.BookmarkBundle.message
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.popup.PopupState
import org.jetbrains.annotations.Nls
internal class ChooseBookmarkTypeAction : DumbAwareAction() {
private val popupState = PopupState.forPopup()
override fun update(event: AnActionEvent) {
val context = event.dataContext.context
event.presentation.isVisible = context != null
event.presentation.isEnabled = context != null && popupState.isHidden
event.presentation.text = getActionText(context?.bookmark?.type)
}
override fun actionPerformed(event: AnActionEvent) {
val context = event.dataContext.context ?: return
val current = context.bookmark?.type
val chooser = MnemonicChooser(context.manager, current) {
popupState.hidePopup()
if (current != it) context.setType(it)
}
val popup = JBPopupFactory.getInstance().createComponentPopupBuilder(chooser, chooser.buttons().first())
.setTitle(getPopupTitle(current))
.setFocusable(true)
.setRequestFocus(true)
.setMovable(false)
.setResizable(false)
.createPopup()
popupState.prepareToShow(popup)
context.getPointOnGutter(event.getData(CONTEXT_COMPONENT))?.let { popup.show(it) }
?: popup.showInBestPositionFor(event.dataContext)
}
@Nls
private fun getActionText(type: BookmarkType?) = when (type) {
null -> message("mnemonic.chooser.bookmark.create.action.text")
BookmarkType.DEFAULT -> message("mnemonic.chooser.mnemonic.assign.action.text")
else -> message("mnemonic.chooser.mnemonic.change.action.text")
}
@Nls
private fun getPopupTitle(type: BookmarkType?) = when (type) {
null -> message("mnemonic.chooser.bookmark.create.popup.title")
BookmarkType.DEFAULT -> message("mnemonic.chooser.mnemonic.assign.popup.title")
else -> message("mnemonic.chooser.mnemonic.change.popup.title")
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | e677c3fc176d3091ca2e94173bf91a1b | 38.966667 | 140 | 0.752294 | 4.416206 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleKtsImportTest.kt | 1 | 7367 | // 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.codeInsight.gradle
import com.intellij.build.SyncViewManager
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.ExtensionTestUtil
import com.intellij.testFramework.replaceService
import junit.framework.AssertionFailedError
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.applySuggestedScriptConfiguration
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.loader.DefaultScriptConfigurationLoader
import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoadingContext
import org.jetbrains.kotlin.idea.core.script.configuration.utils.areSimilar
import org.jetbrains.kotlin.idea.core.script.configuration.utils.getKtFile
import org.jetbrains.kotlin.idea.scripting.gradle.importing.KotlinGradleDslErrorReporter.Companion.build_script_errors_group
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import org.jetbrains.plugins.gradle.service.project.ProjectModelContributor
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import java.io.File
@RunWith(value = Parameterized::class)
class GradleKtsImportTest : KotlinGradleImportingTestCase() {
companion object {
@JvmStatic
@Suppress("ACCIDENTAL_OVERRIDE")
@Parameters(name = "{index}: with Gradle-{0}")
fun data(): Collection<Array<Any?>> = listOf(arrayOf("6.0.1"))
}
val projectDir: File
get() = File(GradleSettings.getInstance(myProject).linkedProjectsSettings.first().externalProjectPath)
private val scriptConfigurationManager: CompositeScriptConfigurationManager
get() = ScriptConfigurationManager.getInstance(myProject) as CompositeScriptConfigurationManager
override fun testDataDirName(): String {
return "gradleKtsImportTest"
}
@Test
@TargetVersions("6.0.1+")
fun testEmpty() {
configureByFiles()
importProject()
checkConfiguration("build.gradle.kts")
}
@Test
@TargetVersions("6.0.1+")
fun testError() {
var context: ProjectResolverContext? = null
val contributor =
ProjectModelContributor { _, _, resolverContext -> context = resolverContext }
ExtensionTestUtil.maskExtensions(
ProjectModelContributor.EP_NAME,
listOf(contributor) + ProjectModelContributor.EP_NAME.extensionList,
testRootDisposable
)
val events = mutableListOf<BuildEvent>()
val syncViewManager = object : SyncViewManager(myProject) {
override fun onEvent(buildId: Any, event: BuildEvent) {
events.add(event)
}
}
myProject.replaceService(SyncViewManager::class.java, syncViewManager, testRootDisposable)
configureByFiles()
val result = try {
importProject()
} catch (e: AssertionFailedError) {
e
}
assert(result is AssertionFailedError) { "Exception should be thrown" }
assertNotNull(context)
assert(context?.cancellationTokenSource?.token()?.isCancellationRequested == true)
val errors = events.filterIsInstance<MessageEventImpl>().filter { it.kind == MessageEvent.Kind.ERROR }
val buildScriptErrors = errors.filter { it.group == build_script_errors_group }
assertTrue(
"$build_script_errors_group error has not been reported among other errors: $errors",
buildScriptErrors.isNotEmpty()
)
}
@Test
@TargetVersions("6.0.1+")
fun testCompositeBuild() {
configureByFiles()
importProject()
checkConfiguration(
"settings.gradle.kts",
"build.gradle.kts",
"subProject/build.gradle.kts",
"subBuild/settings.gradle.kts",
"subBuild/build.gradle.kts",
"subBuild/subProject/build.gradle.kts",
"buildSrc/settings.gradle.kts",
"buildSrc/build.gradle.kts",
"buildSrc/subProject/build.gradle.kts"
)
}
private fun checkConfiguration(vararg files: String) {
val scripts = files.map {
KtsFixture(it).also { kts ->
assertTrue("Configuration for ${kts.file.path} is missing", scriptConfigurationManager.hasConfiguration(kts.psiFile))
kts.imported = scriptConfigurationManager.getConfiguration(kts.psiFile)!!
}
}
// reload configuration and check this it is not changed
scripts.forEach {
val reloadedConfiguration = scriptConfigurationManager.default.runLoader(
it.psiFile,
object : DefaultScriptConfigurationLoader(it.psiFile.project) {
override fun shouldRunInBackground(scriptDefinition: ScriptDefinition) = false
override fun loadDependencies(
isFirstLoad: Boolean,
ktFile: KtFile,
scriptDefinition: ScriptDefinition,
context: ScriptConfigurationLoadingContext
): Boolean {
val vFile = ktFile.originalFile.virtualFile
val result = getConfigurationThroughScriptingApi(ktFile, vFile, scriptDefinition)
context.saveNewConfiguration(vFile, result)
return true
}
}
)
requireNotNull(reloadedConfiguration)
// todo: script configuration can have different accessors, need investigation
// assertTrue(areSimilar(it.imported, reloadedConfiguration))
it.assertNoSuggestedConfiguration()
}
// clear memory cache and check everything loaded from FS
ScriptConfigurationManager.clearCaches(myProject)
scripts.forEach {
val fromFs = scriptConfigurationManager.getConfiguration(it.psiFile)!!
assertTrue(areSimilar(it.imported, fromFs))
}
}
inner class KtsFixture(val fileName: String) {
val file = projectDir.resolve(fileName)
val virtualFile get() = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)!!
val psiFile get() = myProject.getKtFile(virtualFile)!!
lateinit var imported: ScriptCompilationConfigurationWrapper
fun assertNoSuggestedConfiguration() {
assertFalse(virtualFile.applySuggestedScriptConfiguration(myProject))
}
}
}
| apache-2.0 | 1fc31eb199ee50e57ac1c9b5aa2d58b3 | 41.583815 | 158 | 0.691326 | 5.353924 | false | true | false | false |
jwren/intellij-community | platform/built-in-server/src/org/jetbrains/ide/InstallPluginService.kt | 1 | 6166 | // 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.ide
import com.google.gson.reflect.TypeToken
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.AppIcon
import com.intellij.util.PlatformUtils
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence
import com.intellij.util.io.getHostName
import com.intellij.util.io.origin
import com.intellij.util.net.NetUtils
import com.intellij.util.text.nullize
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.QueryStringDecoder
import java.io.OutputStream
import java.net.URI
import java.net.URISyntaxException
@Suppress("HardCodedStringLiteral")
internal class InstallPluginService : RestService() {
override fun getServiceName() = "installPlugin"
override fun isOriginAllowed(request: HttpRequest) = OriginCheckResult.ASK_CONFIRMATION
var isAvailable = true
private val trustedHosts = System.getProperty("idea.api.install.hosts.trusted", "").split(",")
private val trustedPredefinedHosts = setOf(
"marketplace.jetbrains.com",
"plugins.jetbrains.com",
"package-search.services.jetbrains.com",
"package-search.jetbrains.com"
)
override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? {
val pluginId = getStringParameter("pluginId", urlDecoder)
val passedPluginIds = getStringParameter("pluginIds", urlDecoder)
val action = getStringParameter("action", urlDecoder)
if (pluginId.isNullOrBlank() && passedPluginIds.isNullOrBlank()) {
return productInfo(request, context)
}
val pluginIds = if (pluginId.isNullOrBlank()) {
gson.fromJson(passedPluginIds, object : TypeToken<List<String?>?>() {}.type)
}
else {
listOf(pluginId)
}
return when (action) {
"checkCompatibility" -> checkCompatibility(request, context, pluginIds)
"install" -> installPlugin(request, context, pluginIds)
else -> productInfo(request, context)
}
}
@RequiresBackgroundThread
@RequiresReadLockAbsence
private fun checkCompatibility(
request: FullHttpRequest,
context: ChannelHandlerContext,
pluginIds: List<String>,
): Nothing? {
val marketplaceRequests = MarketplaceRequests.getInstance()
val compatibleUpdatesInfo = pluginIds
.mapNotNull { PluginId.findId(it) }
.map { id -> id.idString to (marketplaceRequests.getLastCompatiblePluginUpdate(id) != null) }
.let { info ->
if (info.size != 1) info
else listOf("compatible" to info[0].second)
}
//check if there is an update for this IDE with this ID.
val out = BufferExposingByteArrayOutputStream()
val writer = createJsonWriter(out)
writer.beginObject()
compatibleUpdatesInfo.forEach {
val (pluginId, value) = it
writer.name(pluginId).value(value)
}
writer.endObject()
writer.close()
send(out, request, context)
return null
}
private fun installPlugin(request: FullHttpRequest,
context: ChannelHandlerContext,
pluginIds: List<String>): Nothing? {
val plugins = pluginIds.mapNotNull { PluginId.findId(it) }
if (isAvailable) {
isAvailable = false
val effectiveProject = getLastFocusedOrOpenedProject() ?: ProjectManager.getInstance().defaultProject
ApplicationManager.getApplication().invokeLater(Runnable {
AppIcon.getInstance().requestAttention(effectiveProject, true)
installAndEnable(effectiveProject, plugins.toSet(), true) { }
isAvailable = true
}, effectiveProject.disposed)
}
sendOk(request, context)
return null
}
private fun productInfo(request: FullHttpRequest,
context: ChannelHandlerContext): Nothing? {
val out = BufferExposingByteArrayOutputStream()
writeIDEInfo(out)
send(out, request, context)
return null
}
private fun writeIDEInfo(out: OutputStream) {
val writer = createJsonWriter(out)
writer.beginObject()
var appName = ApplicationInfoEx.getInstanceEx().fullApplicationName
val build = ApplicationInfo.getInstance().build
if (!PlatformUtils.isIdeaUltimate()) {
val productName = ApplicationNamesInfo.getInstance().productName
appName = appName.replace("$productName ($productName)", productName)
appName = StringUtil.trimStart(appName, "JetBrains ")
}
writer.name("name").value(appName)
writer.name("buildNumber").value(build.asString())
writer.endObject()
writer.close()
}
override fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean {
val origin = request.origin
val originHost = try {
if (origin == null) null else URI(origin).host.nullize()
}
catch (ignored: URISyntaxException) {
return false
}
val hostName = getHostName(request)
if (hostName != null && !NetUtils.isLocalhost(hostName)) {
LOG.error("Expected 'request.hostName' to be localhost. hostName='$hostName', origin='$origin'")
}
return (originHost != null && (
trustedPredefinedHosts.contains(originHost) ||
trustedHosts.contains(originHost) ||
NetUtils.isLocalhost(originHost))) || super.isHostTrusted(request, urlDecoder)
}
}
| apache-2.0 | bb8a1ab45bb9814e23d60dc167a92374 | 35.922156 | 158 | 0.733701 | 4.717674 | false | false | false | false |
jwren/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitStashSilentlyAction.kt | 2 | 1966 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ThreeState
import git4idea.actions.GitStash
import git4idea.index.GitStageTracker
import git4idea.index.isStagingAreaAvailable
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.stash.createStashHandler
class GitStashSilentlyAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) {
e.presentation.isEnabledAndVisible = false
return
}
val repositories = GitRepositoryManager.getInstance(project).repositories
e.presentation.isVisible = e.isFromActionToolbar || repositories.isNotEmpty()
e.presentation.isEnabled = changedRoots(project, repositories).isNotEmpty()
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val repositories = GitRepositoryManager.getInstance(project).repositories
GitStash.runStashInBackground(project, changedRoots(project, repositories)) {
createStashHandler(project, it)
}
}
private fun changedRoots(project: Project, repositories: Collection<GitRepository>): Collection<VirtualFile> {
if (isStagingAreaAvailable(project)) {
val gitStageTracker = project.serviceIfCreated<GitStageTracker>() ?: return emptyList()
return gitStageTracker.state.changedRoots
}
return repositories.filter { repository ->
ChangeListManager.getInstance(project).haveChangesUnder(repository.root) != ThreeState.NO
}.map { it.root }
}
} | apache-2.0 | 080febc0dabb701bb7ddec3516d47e8f | 40.851064 | 120 | 0.786368 | 4.669834 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/VirtualStorageLvmAllocation.kt | 2 | 1058 | package com.github.kerubistan.kerub.model.dynamic
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.LvmStorageCapability
import java.math.BigInteger
import java.math.BigInteger.ZERO
import java.util.UUID
@JsonTypeName("lvm-allocation")
data class VirtualStorageLvmAllocation(
override val hostId: UUID,
override val capabilityId: UUID,
override val actualSize: BigInteger,
val path: String,
val pool: String? = null,
val vgName: String,
val mirrors: Byte = 0
) : VirtualStorageBlockDeviceAllocation {
@JsonIgnore
override fun getRedundancyLevel(): Byte = mirrors
init {
check(actualSize >= ZERO) {
"Actual size ($actualSize) must not be negative"
}
check(mirrors >= 0) {
"number of mirrors must be at least 0"
}
}
@JsonIgnore
override fun requires() = LvmStorageCapability::class
override fun resize(newSize: BigInteger): VirtualStorageAllocation = this.copy(actualSize = newSize)
override fun getPath(id: UUID) = path
} | apache-2.0 | 4a289cb6c8ba40b1fb3d68246cd679e2 | 26.153846 | 101 | 0.767486 | 3.918519 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/TopAppBarMediumTokens.kt | 3 | 1369 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object TopAppBarMediumTokens {
val ContainerColor = ColorSchemeKeyTokens.Surface
val ContainerElevation = ElevationTokens.Level0
val ContainerHeight = 112.0.dp
val ContainerShape = ShapeKeyTokens.CornerNone
val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint
val HeadlineColor = ColorSchemeKeyTokens.OnSurface
val HeadlineFont = TypographyKeyTokens.HeadlineSmall
val LeadingIconColor = ColorSchemeKeyTokens.OnSurface
val LeadingIconSize = 24.0.dp
val TrailingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val TrailingIconSize = 24.0.dp
} | apache-2.0 | 8b75893841337464838317e117dae5ab | 38.142857 | 75 | 0.772096 | 4.563333 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/FileStructureSuggester.kt | 2 | 2992 | package training.featuresSuggester.suggesters
import com.intellij.find.FindManager
import com.intellij.find.FindModel
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNamedElement
import training.featuresSuggester.FeatureSuggesterBundle
import training.featuresSuggester.NoSuggestion
import training.featuresSuggester.SuggesterSupport
import training.featuresSuggester.Suggestion
import training.featuresSuggester.actions.Action
import training.featuresSuggester.actions.EditorFindAction
import training.featuresSuggester.actions.EditorFocusGainedAction
class FileStructureSuggester : AbstractFeatureSuggester() {
override val id: String = "File structure"
override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("file.structure.name")
override val message = FeatureSuggesterBundle.message("file.structure.message")
override val suggestingActionId = "FileStructurePopup"
override val suggestingTipId = suggestingActionId
override val minSuggestingIntervalDays = 14
override val languages = listOf("JAVA", "kotlin", "Python", "JavaScript", "ECMAScript 6")
private var prevActionIsEditorFindAction = false
override fun getSuggestion(action: Action): Suggestion {
val language = action.language ?: return NoSuggestion
val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion
when (action) {
is EditorFindAction -> {
prevActionIsEditorFindAction = true
}
is EditorFocusGainedAction -> {
if (!prevActionIsEditorFindAction) return NoSuggestion // check that previous action is Find
val psiFile = action.psiFile ?: return NoSuggestion
val project = action.project ?: return NoSuggestion
val findModel = getFindModel(project)
val textToFind = findModel.stringToFind
val definition = langSupport.getDefinitionOnCaret(psiFile, action.editor.caretModel.offset)
if (definition is PsiNamedElement && langSupport.isFileStructureElement(definition) &&
definition.name?.contains(textToFind, !findModel.isCaseSensitive) == true
) {
prevActionIsEditorFindAction = false
return createSuggestion()
}
}
else -> {
prevActionIsEditorFindAction = false
NoSuggestion
}
}
return NoSuggestion
}
private fun SuggesterSupport.getDefinitionOnCaret(psiFile: PsiFile, caretOffset: Int): PsiElement? {
val offset = caretOffset - 1
if (offset < 0) return null
val curElement = psiFile.findElementAt(offset)
return if (curElement != null && isIdentifier(curElement)) {
curElement.parent
}
else {
null
}
}
private fun getFindModel(project: Project): FindModel {
val findManager = FindManager.getInstance(project)
val findModel = FindModel()
findModel.copyFrom(findManager.findInFileModel)
return findModel
}
}
| apache-2.0 | 3fea9ceaf434a02af9a13dbad3f5bf76 | 37.358974 | 106 | 0.75234 | 4.945455 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/rtmp/RtmpConnection.kt | 1 | 13895 | package com.haishinkit.rtmp
import android.util.Log
import com.haishinkit.event.Event
import com.haishinkit.event.EventDispatcher
import com.haishinkit.event.EventUtils
import com.haishinkit.event.IEventListener
import com.haishinkit.net.Responder
import com.haishinkit.rtmp.message.RtmpCommandMessage
import com.haishinkit.rtmp.message.RtmpMessage
import com.haishinkit.rtmp.message.RtmpMessageFactory
import com.haishinkit.util.URIUtil
import java.net.URI
import java.nio.BufferUnderflowException
import java.nio.ByteBuffer
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.ConcurrentHashMap
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.collections.MutableList
import kotlin.collections.dropLastWhile
import kotlin.collections.forEach
import kotlin.collections.iterator
import kotlin.collections.mapOf
import kotlin.collections.mutableListOf
import kotlin.collections.set
import kotlin.collections.toTypedArray
import kotlin.concurrent.schedule
/**
* flash.net.NetConnection for Kotlin
*/
@Suppress("unused")
open class RtmpConnection : EventDispatcher(null) {
/**
* NetStatusEvent#info.code for NetConnection
*/
@Suppress("unused")
enum class Code(val rawValue: String, val level: String) {
CALL_BAD_VERSION("NetConnection.Call.BadVersion", "error"),
CALL_FAILED("NetConnection.Call.Failed", "error"),
CALL_PROHIBITED("NetConnection.Call.Prohibited", "error"),
CONNECT_APP_SHUTDOWN("NetConnection.Connect.AppShutdown", "status"),
CONNECT_CLOSED("NetConnection.Connect.Closed", "status"),
CONNECT_FAILED("NetConnection.Connect.Failed", "error"),
CONNECT_IDLE_TIME_OUT("NetConnection.Connect.IdleTimeOut", "status"),
CONNECT_INVALID_APP("NetConnection.Connect.InvalidApp", "error"),
CONNECT_NETWORK_CHANGE("NetConnection.Connect.NetworkChange", "status"),
CONNECT_REJECTED("NetConnection.Connect.Rejected", "status"),
CONNECT_SUCCESS("NetConnection.Connect.Success", "status");
fun data(description: String): Map<String, Any> {
val data = HashMap<String, Any>()
data["code"] = rawValue
data["level"] = level
if (description.isNotEmpty()) {
data["description"] = description
}
return data
}
}
@Suppress("unused")
enum class SupportSound(val rawValue: Short) {
NONE(0x001),
ADPCM(0x002),
MP3(0x004),
INTEL(0x008),
UNUSED(0x0010),
NELLY8(0x0020),
NELLY(0x0040),
G711A(0x0080),
G711U(0x0100),
AAC(0x0200),
SPEEX(0x0800),
ALL(0x0FFF);
}
@Suppress("unused")
enum class SupportVideo(val rawValue: Short) {
UNUSED(0x001),
JPEG(0x002),
SORENSON(0x004),
HOMEBREW(0x008),
VP6(0x0010),
VP6_ALPHA(0x0020),
HOMEBREWV(0x0040),
H264(0x0080),
ALL(0x00FF);
}
enum class VideoFunction(val rawValue: Short) {
CLIENT_SEEK(1);
}
private inner class EventListener(private val connection: RtmpConnection) : IEventListener {
override fun handleEvent(event: Event) {
val data = EventUtils.toMap(event)
if (VERBOSE) {
Log.i(TAG, data.toString())
}
when (data["code"].toString()) {
Code.CONNECT_SUCCESS.rawValue -> {
timerTask = Timer().schedule(0, 1000) {
for (stream in streams) stream.value.on()
}
val message = messageFactory.createRtmpSetChunkSizeMessage()
message.size = DEFAULT_CHUNK_SIZE_S
message.chunkStreamID = RtmpChunk.CONTROL
connection.socket.chunkSizeS = DEFAULT_CHUNK_SIZE_S
connection.doOutput(RtmpChunk.ZERO, message)
}
}
}
}
/**
* The URI passed to the RTMPConnection.connect() method.
*/
var uri: URI? = null
private set
/**
* The URL of .swf.
*/
var swfUrl: String? = null
/**
* The URL of an HTTP referer.
*/
var pageUrl: String? = null
/**
* The name of application.
*/
var flashVer = DEFAULT_FLASH_VER
/**
* The outgoing RTMPChunkSize.
*/
var chunkSize: Int
get() = socket.chunkSizeS
set(value) {
socket.chunkSizeS = value
}
/**
* The object encoding for this RTMPConnection instance.
*/
var objectEncoding = DEFAULT_OBJECT_ENCODING
/**
* This instance connected to server(true) or not(false).
*/
val isConnected: Boolean
get() = socket.isConnected
/**
* The time to wait for TCP/IP Handshake done.
*/
var timeout: Int
get() = socket.timeout
set(value) {
socket.timeout = value
}
/**
* The statistics of total incoming bytes.
*/
val totalBytesIn: Long
get() = socket.totalBytesIn
/**
* The statistics of total outgoing bytes.
*/
val totalBytesOut: Long
get() = socket.totalBytesOut
internal val messages = ConcurrentHashMap<Short, RtmpMessage>()
internal val streams = ConcurrentHashMap<Int, RtmpStream>()
internal val streamsmap = ConcurrentHashMap<Short, Int>()
internal val responders = ConcurrentHashMap<Int, Responder>()
internal val socket = RtmpSocket(this)
internal var transactionID = 0
internal val messageFactory = RtmpMessageFactory(4)
private var timerTask: TimerTask? = null
set(value) {
timerTask?.cancel()
field = value
}
private var arguments: MutableList<Any?> = mutableListOf()
private val authenticator: RtmpAuthenticator by lazy {
RtmpAuthenticator(this)
}
init {
addEventListener(Event.RTMP_STATUS, authenticator)
addEventListener(Event.RTMP_STATUS, EventListener(this))
}
/**
* Calls a command or method on RTMP Server.
*/
open fun call(commandName: String, responder: Responder?, vararg arguments: Any) {
if (!isConnected) {
return
}
val listArguments = ArrayList<Any>(arguments.size)
for (`object` in arguments) {
listArguments.add(`object`)
}
val message = RtmpCommandMessage(objectEncoding)
message.chunkStreamID = RtmpChunk.COMMAND
message.streamID = 0
message.transactionID = ++transactionID
message.commandName = commandName
message.arguments = listArguments
if (responder != null) {
responders[transactionID] = responder
}
doOutput(RtmpChunk.ZERO, message)
}
/**
* Creates a two-way connection to an application on RTMP Server.
*/
open fun connect(command: String, vararg arguments: Any?) {
uri = URI.create(command)
val uri = this.uri ?: return
if (isConnected || !SUPPORTED_PROTOCOLS.containsKey(uri.scheme)) {
return
}
val port = uri.port
val isSecure = uri.scheme == "rtmps"
this.arguments.clear()
arguments.forEach { value -> this.arguments.add(value) }
socket.connect(
uri.host,
if (port == -1) SUPPORTED_PROTOCOLS[uri.scheme] ?: DEFAULT_PORT else port,
isSecure
)
}
/**
* Closes the connection from the server.
*/
open fun close() {
if (!isConnected) {
return
}
timerTask = null
for (stream in streams) {
stream.value.close()
streams.remove(stream.key)
}
socket.close(false)
}
/**
* Dispose the connection for a memory management.
*/
open fun dispose() {
timerTask = null
for (stream in streams) {
stream.value.dispose()
}
streams.clear()
}
internal fun doOutput(chunk: RtmpChunk, message: RtmpMessage) {
chunk.encode(socket, message)
message.release()
}
internal tailrec fun listen(buffer: ByteBuffer) {
val rollback = buffer.position()
try {
val first = buffer.get()
val chunk = RtmpChunk.chunk(first)
val chunkSizeC = socket.chunkSizeC
val chunkStreamID = chunk.getStreamID(buffer)
if (chunk == RtmpChunk.THREE) {
val message = messages[chunkStreamID]!!
val payload = message.payload
var remaining = payload.remaining()
if (chunkSizeC < remaining) {
remaining = chunkSizeC
}
if (buffer.position() + remaining <= buffer.limit()) {
payload.put(buffer.array(), buffer.position(), remaining)
buffer.position(buffer.position() + remaining)
} else {
buffer.position(rollback)
return
}
if (!payload.hasRemaining()) {
payload.flip()
message.decode(payload).execute(this)
}
} else {
val message = chunk.decode(chunkStreamID, this, buffer)
messages[chunkStreamID] = message
when (chunk) {
RtmpChunk.ZERO -> {
streamsmap[chunkStreamID] = message.streamID
}
RtmpChunk.ONE -> {
streamsmap[chunkStreamID]?.let {
message.streamID = it
}
}
else -> {
}
}
if (message.length <= chunkSizeC) {
message.decode(buffer).execute(this)
} else {
val payload = message.payload
if (buffer.position() + chunkSizeC <= buffer.limit()) {
payload.put(buffer.array(), buffer.position(), chunkSizeC)
buffer.position(buffer.position() + chunkSizeC)
} else {
buffer.position(rollback)
return
}
}
}
} catch (e: BufferUnderflowException) {
buffer.position(rollback)
throw e
} catch (e: IndexOutOfBoundsException) {
buffer.position(rollback)
throw e
}
if (buffer.hasRemaining()) {
listen(buffer)
}
}
internal fun createStream(stream: RtmpStream) {
call(
"createStream",
object : Responder {
override fun onResult(arguments: List<Any?>) {
for (s in streams) {
if (s.value == stream) {
streams.remove(s.key)
break
}
}
val id = (arguments[0] as Double).toInt()
stream.id = id
streams[id] = stream
stream.readyState = RtmpStream.ReadyState.OPEN
}
override fun onStatus(arguments: List<Any?>) {
Log.w("$TAG#onStatus", arguments.toString())
}
}
)
}
internal fun onSocketReadyStateChange(socket: RtmpSocket, readyState: RtmpSocket.ReadyState) {
if (VERBOSE) {
Log.d(TAG, readyState.toString())
}
when (readyState) {
RtmpSocket.ReadyState.Closed -> {
transactionID = 0
messages.clear()
streamsmap.clear()
responders.clear()
}
}
}
internal fun createConnectionMessage(uri: URI): RtmpMessage {
val paths = uri.path.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val message = RtmpCommandMessage(RtmpObjectEncoding.AMF0)
val commandObject = HashMap<String, Any?>()
var app = paths[1]
if (uri.query != null) {
app += "?" + uri.query
}
commandObject["app"] = app
commandObject["flashVer"] = flashVer
commandObject["swfUrl"] = swfUrl
commandObject["tcUrl"] = URIUtil.withoutUserInfo(uri)
commandObject["fpad"] = false
commandObject["capabilities"] = DEFAULT_CAPABILITIES
commandObject["audioCodecs"] = SupportSound.AAC.rawValue
commandObject["videoCodecs"] = SupportVideo.H264.rawValue
commandObject["videoFunction"] = VideoFunction.CLIENT_SEEK.rawValue
commandObject["pageUrl"] = pageUrl
commandObject["objectEncoding"] = objectEncoding.rawValue
message.chunkStreamID = RtmpChunk.COMMAND
message.streamID = 0
message.commandName = "connect"
message.transactionID = ++transactionID
message.commandObject = commandObject
message.arguments = arguments
if (VERBOSE) {
Log.d(TAG, message.toString())
}
return message
}
companion object {
const val DEFAULT_PORT = 1935
const val DEFAULT_FLASH_VER = "FMLE/3.0 (compatible; FMSc/1.0)"
val SUPPORTED_PROTOCOLS = mapOf("rtmp" to 1935, "rtmps" to 443)
val DEFAULT_OBJECT_ENCODING = RtmpObjectEncoding.AMF0
private val TAG = RtmpConnection::class.java.simpleName
private const val DEFAULT_CHUNK_SIZE_S = 1024 * 8
private const val DEFAULT_CAPABILITIES = 239
private const val VERBOSE = false
}
}
| bsd-3-clause | 1a16eefc67cdd9016d87a5e73984c06a | 31.8487 | 98 | 0.56819 | 4.648712 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonHolder.kt | 1 | 7485 | package eu.kanade.tachiyomi.ui.reader.viewer.webtoon
import android.support.v7.widget.RecyclerView
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.ui.reader.viewer.base.PageDecodeErrorLayout
import kotlinx.android.synthetic.main.chapter_image.view.*
import kotlinx.android.synthetic.main.item_webtoon_reader.view.*
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.subjects.PublishSubject
import rx.subjects.SerializedSubject
import java.io.File
/**
* Holder for webtoon reader for a single page of a chapter.
* All the elements from the layout file "item_webtoon_reader" are available in this class.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @constructor creates a new webtoon holder.
*/
class WebtoonHolder(private val view: View, private val adapter: WebtoonAdapter) :
RecyclerView.ViewHolder(view) {
/**
* Page of a chapter.
*/
private var page: Page? = null
/**
* Subscription for status changes of the page.
*/
private var statusSubscription: Subscription? = null
/**
* Layout of decode error.
*/
private var decodeErrorLayout: PageDecodeErrorLayout? = null
init {
with(view.image_view) {
setMaxBitmapDimensions(readerActivity.maxBitmapSize)
setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_FIXED)
setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_INSIDE)
setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_FIT_WIDTH)
setMinimumDpi(100)
setMinimumTileDpi(200)
setRegionDecoderClass(webtoonReader.regionDecoderClass)
setBitmapDecoderClass(webtoonReader.bitmapDecoderClass)
setVerticalScrollingParent(true)
setOnTouchListener(adapter.touchListener)
setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() {
override fun onImageLoaded() {
// When the image is loaded, reset the minimum height to avoid gaps
view.frame_container.minimumHeight = 30
}
override fun onImageLoadError(e: Exception) {
onImageDecodeError()
}
})
}
// Avoid to create a lot of view holders taking twice the screen height,
// saving memory and a possible OOM. When the first image is loaded in this holder,
// the minimum size will be removed.
// Doing this we get sequential holder instantiation.
view.frame_container.minimumHeight = view.resources.displayMetrics.heightPixels * 2
// Leave some space between progress bars
view.progress.minimumHeight = 300
view.frame_container.setOnTouchListener(adapter.touchListener)
view.retry_button.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_UP) {
readerActivity.presenter.retryPage(page)
}
true
}
}
/**
* Method called from [WebtoonAdapter.onBindViewHolder]. It updates the data for this
* holder with the given page.
*
* @param page the page to bind.
*/
fun onSetValues(page: Page) {
decodeErrorLayout?.let {
(view as ViewGroup).removeView(it)
decodeErrorLayout = null
}
this.page = page
observeStatus()
}
/**
* Observes the status of the page and notify the changes.
*
* @see processStatus
*/
private fun observeStatus() {
page?.let { page ->
val statusSubject = SerializedSubject(PublishSubject.create<Int>())
page.setStatusSubject(statusSubject)
statusSubscription?.unsubscribe()
statusSubscription = statusSubject.startWith(page.status)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { processStatus(it) }
webtoonReader.subscriptions.add(statusSubscription)
}
}
/**
* Called when the status of the page changes.
*
* @param status the new status of the page.
*/
private fun processStatus(status: Int) {
when (status) {
Page.QUEUE -> onQueue()
Page.LOAD_PAGE -> onLoading()
Page.DOWNLOAD_IMAGE -> onLoading()
Page.READY -> onReady()
Page.ERROR -> onError()
}
}
/**
* Unsubscribes from the status subscription.
*/
fun unsubscribeStatus() {
statusSubscription?.unsubscribe()
statusSubscription = null
}
/**
* Called when the page is loading.
*/
private fun onLoading() {
setRetryButtonVisible(false)
setImageVisible(false)
setProgressVisible(true)
}
/**
* Called when the page is ready.
*/
private fun onReady() {
setRetryButtonVisible(false)
setProgressVisible(false)
setImageVisible(true)
page?.imagePath?.let { path ->
if (File(path).exists()) {
view.image_view.setImage(ImageSource.uri(path))
view.progress.visibility = View.GONE
} else {
page?.status = Page.ERROR
}
}
}
/**
* Called when the page has an error.
*/
private fun onError() {
setImageVisible(false)
setProgressVisible(false)
setRetryButtonVisible(true)
}
/**
* Called when the page is queued.
*/
private fun onQueue() {
setImageVisible(false)
setRetryButtonVisible(false)
setProgressVisible(false)
}
/**
* Called when the image fails to decode.
*/
private fun onImageDecodeError() {
page?.let { page ->
decodeErrorLayout = PageDecodeErrorLayout(view.context, page, readerActivity.readerTheme,
{ readerActivity.presenter.retryPage(page) })
(view as ViewGroup).addView(decodeErrorLayout)
}
}
/**
* Sets the visibility of the progress bar.
*
* @param visible whether to show it or not.
*/
private fun setProgressVisible(visible: Boolean) {
view.progress.visibility = if (visible) View.VISIBLE else View.GONE
}
/**
* Sets the visibility of the image view.
*
* @param visible whether to show it or not.
*/
private fun setImageVisible(visible: Boolean) {
view.image_view.visibility = if (visible) View.VISIBLE else View.GONE
}
/**
* Sets the visibility of the retry button.
*
* @param visible whether to show it or not.
*/
private fun setRetryButtonVisible(visible: Boolean) {
view.retry_button.visibility = if (visible) View.VISIBLE else View.GONE
}
/**
* Property to get the reader activity.
*/
private val readerActivity: ReaderActivity
get() = adapter.fragment.readerActivity
/**
* Property to get the webtoon reader.
*/
private val webtoonReader: WebtoonReader
get() = adapter.fragment
} | gpl-3.0 | 0ebb8ba9ea8441cd95a7f00eb176ea01 | 30.062241 | 102 | 0.632198 | 4.776643 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/meterial/ImmersionBarDemoActivity.kt | 1 | 4290 | package com.zeke.demo.meterial
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.zeke.demo.R
import kotlinx.android.synthetic.main.activity_appbarlayout_demo.*
/**
* author:ZekeWang
* date:2021/2/28
* description:
* 沉浸式Demo测试
*
* - View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
* Activity全屏显示,但导航栏不会被隐藏覆盖,导航栏依然可见,Activity底部布局部分会被导航栏遮住(布局入侵)
* - View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
* Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态栏遮住。
* - View.SYSTEM_UI_FLAG_LAYOUT_STABLE
* 防止系统栏隐藏时内容区域大小发生变化
*/
class ImmersionBarDemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_appbarlayout_demo)
transparent_status?.setOnClickListener {
// 手动模式
// <= 4.4
// window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
// window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
// >= 5.0
// val flag = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
// window?.decorView?.systemUiVisibility = flag
// window?.statusBarColor = Color.TRANSPARENT
// window?.navigationBarColor = Color.TRANSPARENT
// 引用第三方库
ImmersionBar.with(this)
.transparentBar() // 透明状态栏和导航栏
.init()
}
hide_bars?.setOnClickListener {
ImmersionBar.with(this)
.fullScreen(true)
.hideBar(BarHide.FLAG_HIDE_BAR)
.init()
}
change_bars_color?.setOnClickListener {
// >= 5.0 设置状态栏颜色和Actionbar一样
// window?.statusBarColor = Color.RED
// window?.navigationBarColor = Color.RED
ImmersionBar.with(this)
.barColor(R.color.google_green)
.init()
}
hide_navigation_only?.setOnClickListener {
ImmersionBar.with(this)
.hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
.init()
}
change_navigation_color.setOnClickListener {
ImmersionBar.with(this)
.fullScreen(false)
.hideBar(BarHide.FLAG_SHOW_BAR)
.navigationBarColor(R.color.google_yellow)
.init()
}
reset_bars?.setOnClickListener {
ImmersionBar.with(this)
.fullScreen(false)
.hideBar(BarHide.FLAG_SHOW_BAR)
.barColor(R.color.black)
.init()
}
// Light模式 ---- 在 Android 6.0 的以上,状态栏支持字体变灰色,Android 8.0 以上,导航栏支持导航按钮变灰色
change_state_bar_text_color?.setOnClickListener {
//手动调用
// val flag = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
// or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
// window?.decorView?.systemUiVisibility = flag
// window?.statusBarColor = Color.TRANSPARENT
// window?.navigationBarColor = Color.TRANSPARENT
// 引用第三方库
ImmersionBar.with(this)
.fullScreen(true)
.hideBar(BarHide.FLAG_SHOW_BAR)
.barColor(R.color.transparent)
.statusBarDarkFont(true) //目的是为了增加:SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
.navigationBarDarkIcon(true) //目的是为了填加:SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
.init()
}
}
} | gpl-2.0 | f6fa2f1e8a6511a64f8cdefb4202b7e3 | 34.788991 | 90 | 0.588205 | 3.915663 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/duplicates/branchingMatch1.kt | 4 | 1331 | // WITH_RUNTIME
// SUGGESTED_NAMES: i, getT
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in test
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in test
// SIBLING:
fun test(a: Int): Int {
var b: Int = 1
val t = <selection>if (a > 0) {
b++
b + a
}
else {
b--
b - a
}</selection>
return t
}
fun foo1() {
val x = 1
var y: Int = x
println(
if (x > 0) {
y++
y + x
}
else {
y--
y - x
}
)
}
fun foo2(x: Int) {
var p: Int = 1
var q: Int
if (x > 0) {
p++
q = p + x
}
else {
p--
q = p - x
}
println(q)
}
fun foo3(x: Int): Int {
var p: Int = 1
if (x > 0) {
p++
return p + x
}
else {
p--
return p - x
}
}
fun foo4() {
val t: (Int) -> (Int) = {
var n = it
if (it > 0) {
n++
n + it
}
else {
n--
n - it
}
}
println(t(1))
}
fun foo5(x: Int): Int {
var p: Int = 1
if (x > 0) {
p++
val t = p + x
}
else {
p--
val u = p - x
}
}
| apache-2.0 | bf5a462bfbbabf10f5684979efc56ad9 | 14.125 | 66 | 0.349361 | 3.176611 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/InsertCurlyBracesToTemplateIntention.kt | 3 | 1602 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.core.RestoreCaret
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
class InsertCurlyBracesToTemplateIntention : SelfTargetingOffsetIndependentIntention<KtSimpleNameStringTemplateEntry>(
KtSimpleNameStringTemplateEntry::class.java, KotlinBundle.lazyMessage("insert.curly.braces.around.variable")
), LowPriorityAction {
override fun isApplicableTo(element: KtSimpleNameStringTemplateEntry): Boolean = true
override fun applyTo(element: KtSimpleNameStringTemplateEntry, editor: Editor?) {
val expression = element.expression ?: return
with(RestoreCaret(expression, editor)) {
val wrapped = element.replace(KtPsiFactory(element).createBlockStringTemplateEntry(expression))
val afterExpression = (wrapped as? KtStringTemplateEntryWithExpression)?.expression ?: return
restoreCaret(afterExpression, defaultOffset = { it.endOffset })
}
}
}
| apache-2.0 | 17dd3c0ba9a5623f3bd236ef7e1b707a | 50.677419 | 158 | 0.807116 | 5.235294 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-native/tests/test/org/jetbrains/kotlin/ide/konan/gradle/GradleNativeLibrariesInIDENamingTest.kt | 1 | 5614 | // 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.ide.konan.gradle
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vfs.VfsUtilCore.urlToPath
import org.jetbrains.kotlin.ide.konan.NativeLibraryKind
import org.jetbrains.kotlin.idea.configuration.externalCompilerVersion
import org.jetbrains.kotlin.idea.framework.detectLibraryKind
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.util.projectStructure.allModules
import org.jetbrains.kotlin.konan.library.konanCommonLibraryPath
import org.jetbrains.kotlin.konan.library.konanPlatformLibraryPath
import org.jetbrains.kotlin.platform.konan.isNative
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Assert.*
import org.junit.Test
import org.junit.runners.Parameterized
import java.io.File
class GradleNativeLibrariesInIDENamingTest15 : TestCaseWithFakeKotlinNative() {
// Test naming of Kotlin/Native libraries
@Test
fun testLibrariesNaming() {
configureProject()
importProject()
myProject.allModules().forEach { assertValidModule(it, projectPath) }
}
override fun getExternalSystemConfigFileName() = GradleConstants.KOTLIN_DSL_SCRIPT_NAME
override fun testDataDirName() = "nativeLibraries"
companion object {
@Parameterized.Parameters(name = "{index}: with Gradle-{0}")
@Throws(Throwable::class)
@JvmStatic
fun data() = listOf(arrayOf("4.10.2"))
}
}
private val NATIVE_LIBRARY_NAME_REGEX = Regex("^Kotlin/Native ([\\d\\w.-]+) - ([\\w\\d]+)( \\| \\[?([\\w\\d_]+)]?)?$")
private val NATIVE_LINUX_LIBRARIES = listOf(
"Kotlin/Native {version} - stdlib",
"Kotlin/Native {version} - linux | linux_x64",
"Kotlin/Native {version} - posix | linux_x64",
"Kotlin/Native {version} - zlib | linux_x64"
)
private val NATIVE_MACOS_LIBRARIES = listOf(
"Kotlin/Native {version} - stdlib",
"Kotlin/Native {version} - Foundation | macos_x64",
"Kotlin/Native {version} - UIKit | macos_x64",
"Kotlin/Native {version} - objc | macos_x64"
)
private val NATIVE_MINGW_LIBRARIES = listOf(
"Kotlin/Native {version} - stdlib",
"Kotlin/Native {version} - iconv | mingw_x64",
"Kotlin/Native {version} - opengl32 | mingw_x64",
"Kotlin/Native {version} - windows | mingw_x64"
)
private val Module.libraries
get() = ModuleRootManager.getInstance(this).orderEntries
.asSequence()
.filterIsInstance<LibraryOrderEntry>()
.mapNotNull { it.library }
private fun assertValidModule(module: Module, projectRoot: String) {
val (nativeLibraries, otherLibraries) = module.libraries.partition { library ->
detectLibraryKind(library.getFiles(OrderRootType.CLASSES)) == NativeLibraryKind
}
if (module.platform.isNative()) {
assertFalse("No Kotlin/Native libraries in $module", nativeLibraries.isEmpty())
nativeLibraries.forEach { assertValidNativeLibrary(it, projectRoot) }
val kotlinVersion = requireNotNull(module.externalCompilerVersion) {
"External compiler version should not be null"
}
val expectedNativeLibraryNames = when {
module.name.contains("linux", ignoreCase = true) -> NATIVE_LINUX_LIBRARIES
module.name.contains("macos", ignoreCase = true) -> NATIVE_MACOS_LIBRARIES
module.name.contains("mingw", ignoreCase = true) -> NATIVE_MINGW_LIBRARIES
else -> emptyList()
}.map { it.replace("{version}", kotlinVersion) }.sorted()
val actualNativeLibraryNames = nativeLibraries.map { it.name.orEmpty() }.sorted()
assertEquals("Different set of Kotlin/Native libraries in $module", expectedNativeLibraryNames, actualNativeLibraryNames)
} else {
assertTrue("Unexpected Kotlin/Native libraries in $module: $nativeLibraries", nativeLibraries.isEmpty())
}
otherLibraries.forEach(::assertValidNonNativeLibrary)
}
private fun assertValidNativeLibrary(library: Library, projectRoot: String) {
val fullName = library.name.orEmpty()
val result = NATIVE_LIBRARY_NAME_REGEX.matchEntire(fullName)
assertTrue("Invalid Kotlin/Native library name: $fullName", result?.groups?.size == 5)
val (_, name, _, platform) = result!!.destructured
val libraryUrls = library.getUrls(OrderRootType.CLASSES).toList()
assertTrue("Kotlin/Native library $fullName has multiple roots (${libraryUrls.size}): $libraryUrls", libraryUrls.size == 1)
val actualShortPath = File(urlToPath(libraryUrls.single()))
.relativeTo(File(projectRoot).resolve(DOUBLE_DOT_PATH).normalize())
.relativeTo(FAKE_KOTLIN_NATIVE_HOME_RELATIVE_PATH)
val expectedDirectoryName = if (name == "stdlib") name else "org.jetbrains.kotlin.native.$name"
val expectedShortPath = if (platform.isEmpty()) {
konanCommonLibraryPath(expectedDirectoryName)
} else {
konanPlatformLibraryPath(expectedDirectoryName, platform)
}
assertEquals("The short path of $fullName does not match its location", expectedShortPath, actualShortPath)
}
private fun assertValidNonNativeLibrary(library: Library) {
val name = library.name.orEmpty()
assertFalse("Invalid non-native library name: $name", name.contains("Kotlin/Native"))
}
| apache-2.0 | 1ce46fba08f4c30ad161b5704b84ad61 | 40.585185 | 158 | 0.725508 | 4.315142 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddRunToLambdaFix.kt | 5 | 1414 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
class AddRunToLambdaFix(element: KtLambdaExpression) : KotlinQuickFixAction<KtLambdaExpression>(element) {
override fun getText() = KotlinBundle.message("fix.add.return.before.lambda.expression")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val factory = KtPsiFactory(project)
element.replace(factory.createExpression("run ${element.text}"))
}
companion object Factory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val casted = Errors.UNUSED_LAMBDA_EXPRESSION.cast(diagnostic)
return listOf(AddRunToLambdaFix(casted.psiElement))
}
}
} | apache-2.0 | e6cdf5dfb840ba4d3535696365d0ed24 | 44.645161 | 158 | 0.769448 | 4.620915 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 1 | 31945 | // 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.updateSettings.impl
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.eventLog.fus.MachineIdManager
import com.intellij.notification.*
import com.intellij.notification.impl.NotificationsConfigurationImpl
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
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.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.reference.SoftReference
import com.intellij.util.Urls
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import org.jdom.JDOMException
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JComponent
import kotlin.Result
import kotlin.concurrent.withLock
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = logger<UpdateChecker>()
private const val DISABLED_UPDATE = "disabled_update.txt"
private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt"
private const val PRODUCT_DATA_TTL_MIN = 5L
private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled"
private const val MACHINE_ID_PARAMETER = "mid"
private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL }
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl
private val productDataLock = ReentrantLock()
private var productDataCache: SoftReference<Result<Product?>>? = null
private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap()
private val ourShownNotifications = MultiMap<NotificationKind, Notification>()
private var machineIdInitialized = false
/**
* Adding a plugin ID to this collection allows to exclude a plugin from a regular update check.
* Has no effect on non-bundled plugins.
*/
@Suppress("MemberVisibilityCanBePrivate")
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
init {
UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString())
UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get())
UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (ExternalUpdateManager.ACTUAL != null) {
val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName
UpdateRequestParameters.addParameter("manager", name)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
UpdateRequestParameters.addParameter("eap", "")
}
}
@JvmStatic
fun getNotificationGroup(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates")
@JvmStatic
fun getNotificationGroupForUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results")
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
return ActionCallback().also {
ProcessIOExecutorService.INSTANCE.execute {
doUpdateAndShowResult(
userInitiated = false,
preferDialog = false,
showSettingsLink = true,
callback = it,
)
}
}
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action passes customized update settings and forces results presentation in a dialog).
*/
@JvmStatic
@JvmOverloads
fun updateAndShowResult(
project: Project?,
customSettings: UpdateSettings? = null,
) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(
getProject(),
customSettings,
userInitiated = true,
preferDialog = isConditionalModal,
showSettingsLink = shouldStartInBackground(),
indicator = indicator,
)
override fun isConditionalModal(): Boolean = customSettings != null
override fun shouldStartInBackground(): Boolean = !isConditionalModal
})
}
@JvmStatic
private fun doUpdateAndShowResult(
project: Project? = null,
customSettings: UpdateSettings? = null,
userInitiated: Boolean,
preferDialog: Boolean,
showSettingsLink: Boolean,
indicator: ProgressIndicator? = null,
callback: ActionCallback? = null,
) {
if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) {
machineIdInitialized = true
val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "")
if (machineId != null) {
UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId)
}
}
val updateSettings = customSettings ?: UpdateSettings.getInstance()
val platformUpdates = getPlatformUpdates(updateSettings, indicator)
if (platformUpdates is PlatformUpdates.ConnectionError) {
if (userInitiated) {
showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog)
}
callback?.setRejected()
return
}
val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates(
(platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion,
indicator,
)
indicator?.text = IdeBundle.message("updates.external.progress")
val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator)
UpdateSettings.getInstance().saveLastCheckedInfo()
if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) {
val builder = HtmlBuilder()
internalErrors.forEach { (host, ex) ->
if (!builder.isEmpty) builder.br()
val message = host?.let {
IdeBundle.message("updates.plugins.error.message2", it, ex.message)
} ?: IdeBundle.message("updates.plugins.error.message1", ex.message)
builder.append(message)
}
externalErrors.forEach { (key, value) ->
if (!builder.isEmpty) builder.br()
builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message))
}
showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog)
}
ApplicationManager.getApplication().invokeLater {
fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) }
val enabledPlugins = nonIgnored(pluginUpdates.allEnabled)
val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled)
val forceDialog = preferDialog || userInitiated && !notificationsEnabled()
if (platformUpdates is PlatformUpdates.Loaded) {
showResults(
project,
platformUpdates,
updatedPlugins,
pluginUpdates.incompatible,
showNotification = userInitiated || WelcomeFrame.getInstance() != null,
forceDialog,
showSettingsLink,
)
}
else {
showResults(
project,
updatedPlugins,
customRepoPlugins,
externalUpdates,
enabledPlugins.isNotEmpty(),
userInitiated,
forceDialog,
showSettingsLink,
)
}
callback?.setDone()
}
}
@JvmOverloads
@JvmStatic
@JvmName("getPlatformUpdates")
internal fun getPlatformUpdates(
settings: UpdateSettings = UpdateSettings.getInstance(),
indicator: ProgressIndicator? = null,
): PlatformUpdates =
try {
indicator?.text = IdeBundle.message("updates.checking.platform")
val productData = loadProductData(indicator)
if (ExternalUpdateManager.ACTUAL != null || productData == null) {
PlatformUpdates.Empty
}
else {
UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates()
}
}
catch (e: Exception) {
LOG.infoWithDebug(e)
when (e) {
is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling user
else -> PlatformUpdates.ConnectionError(e)
}
}
@JvmStatic
@Throws(IOException::class, JDOMException::class)
fun loadProductData(indicator: ProgressIndicator?): Product? =
productDataLock.withLock {
val cached = SoftReference.dereference(productDataCache)
if (cached != null) return@withLock cached.getOrThrow()
val result = runCatching {
var url = Urls.newFromEncoded(updateUrl)
if (url.scheme != URLUtil.FILE_PROTOCOL) {
url = UpdateRequestParameters.amendUpdateRequest(url)
}
LOG.debug { "loading ${url}" }
HttpRequests.request(url)
.connect { JDOMUtil.load(it.getReader(indicator)) }
.let { parseUpdateData(it) }
?.also {
if (it.disableMachineId) {
PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true)
UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER)
}
}
}
productDataCache = SoftReference(result)
AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES)
return@withLock result.getOrThrow()
}
private fun clearProductDataCache() {
if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // longer means loading now, no much sense in clearing
productDataCache = null
productDataLock.unlock()
}
}
@ApiStatus.Internal
@JvmStatic
fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) {
if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
ApplicationManager.getApplication().executeOnPooledThread {
val updateable = collectUpdateablePlugins()
if (updateable.isNotEmpty()) {
findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null)
}
}
}
}
/**
* When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version,
* otherwise, returns versions compatible with the specified build.
*/
@RequiresBackgroundThread
@RequiresReadLockAbsence
@JvmOverloads
@JvmStatic
fun getInternalPluginUpdates(
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): InternalPluginResults {
indicator?.text = IdeBundle.message("updates.checking.plugins")
if (System.getProperty("idea.ignore.disabled.plugins") == null) {
val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build)
if (brokenPlugins.isNotEmpty()) {
PluginManagerCore.updateBrokenPlugins(brokenPlugins)
}
}
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) {
return InternalPluginResults(PluginUpdates())
}
val toUpdate = HashMap<PluginId, PluginDownloader>()
val toUpdateDisabled = HashMap<PluginId, PluginDownloader>()
val customRepoPlugins = HashMap<PluginId, PluginNode>()
val errors = LinkedHashMap<String?, Exception>()
val state = InstalledPluginsState.getInstance()
for (host in RepositoryHelper.getPluginHosts()) {
try {
if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator)
}
else {
RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor ->
val id = descriptor.pluginId
if (updateable.remove(id) != null) {
prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host)
}
// collect latest plugins from custom repos
val storedDescriptor = customRepoPlugins[id]
if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) {
customRepoPlugins[id] = descriptor
}
}
}
}
catch (e: Exception) {
LOG.info(
"failed to load plugins from ${host ?: "default repository"}: ${e.message}",
if (LOG.isDebugEnabled) e else null,
)
errors[host] = e
}
}
val incompatible = if (buildNumber == null) emptyList() else {
// collecting plugins that aren't going to be updated and are incompatible with the new build
// (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE)
updateable.values.asSequence()
.filterNotNull()
.filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) }
.toSet()
}
return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors)
}
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> {
val updateable = HashMap<PluginId, IdeaPluginDescriptor?>()
// installed plugins that could be updated (either downloaded or updateable bundled)
PluginManagerCore.getPlugins()
.filter { !it.isBundled || it.allowBundledUpdate() }
.associateByTo(updateable) { it.pluginId }
// plugins installed in an instance from which the settings were imported
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
Files.readAllLines(onceInstalled).forEach { line ->
val id = PluginId.getId(line.trim { it <= ' ' })
updateable.putIfAbsent(id, null)
}
}
catch (e: IOException) {
LOG.error(onceInstalled.toString(), e)
}
@Suppress("SSBasedInspection")
onceInstalled.toFile().deleteOnExit()
}
// excluding plugins that take care about their own updates
if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) {
excludedFromUpdateCheckPlugins.forEach {
val id = PluginId.getId(it)
val plugin = updateable[id]
if (plugin != null && plugin.isBundled) {
updateable.remove(id)
}
}
}
return updateable
}
@RequiresBackgroundThread
@RequiresReadLockAbsence
private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber?,
state: InstalledPluginsState,
indicator: ProgressIndicator?) {
val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator)
val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet()
val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber)
updateable.forEach { (id, descriptor) ->
val lastUpdate = updates.find { it.pluginId == id.idString }
if (lastUpdate != null &&
(descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor,
buildNumber) > 0)) {
runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) }
.onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it }
.onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) }
}
}
(toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) }
}
private fun prepareDownloader(state: InstalledPluginsState,
descriptor: PluginNode,
buildNumber: BuildNumber?,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
indicator: ProgressIndicator?,
host: String?) {
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber)
state.onDescriptorDownload(descriptor)
checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator)
}
@JvmOverloads
@JvmStatic
fun getExternalPluginUpdates(
updateSettings: UpdateSettings,
indicator: ProgressIndicator? = null,
): ExternalPluginResults {
val result = ArrayList<ExternalUpdate>()
val errors = LinkedHashMap<ExternalComponentSource, Exception>()
val manager = ExternalComponentManager.getInstance()
for (source in ExternalComponentManager.getComponentSources()) {
indicator?.checkCanceled()
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (siteResult.isNotEmpty()) {
result += ExternalUpdate(source, siteResult)
}
}
catch (e: Exception) {
LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null)
errors[source] = e
}
}
return ExternalPluginResults(result, errors)
}
@Throws(IOException::class)
@JvmOverloads
@JvmStatic
fun checkAndPrepareToInstall(
originalDownloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
) {
val pluginId = originalDownloader.id
val pluginVersion = originalDownloader.pluginVersion
val installedPlugin = PluginManagerCore.getPlugin(pluginId)
if (installedPlugin == null
|| pluginVersion == null
|| PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) {
val oldDownloader = ourUpdatedPlugins[pluginId]
val downloader = if (PluginManagerCore.isDisabled(pluginId)) {
originalDownloader
}
else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
val descriptor = originalDownloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator())
ourUpdatedPlugins[pluginId] = originalDownloader
}
originalDownloader
}
else {
oldDownloader
}
val descriptor = downloader.descriptor
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[pluginId] = downloader
}
}
}
private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) {
if (preferDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) }
}
else {
getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project)
}
}
@RequiresEdt
private fun showResults(
project: Project?,
updatedPlugins: List<PluginDownloader>,
customRepoPlugins: Collection<PluginNode>,
externalUpdates: Collection<ExternalUpdate>,
pluginsEnabled: Boolean,
userInitiated: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (pluginsEnabled) {
if (userInitiated) {
ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() }
}
val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() }
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins)
if (userInitiated) {
val updatedPluginNames = updatedPlugins.map { it.pluginName }
val (title, message) = when (updatedPluginNames.size) {
1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0])
else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" }
}
showNotification(
project,
NotificationKind.PLUGINS,
"plugins.update.available",
title,
message,
NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ ->
PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null)
},
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable),
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) {
ignorePlugins(updatedPlugins.map { it.descriptor })
})
}
}
}
if (externalUpdates.isNotEmpty()) {
ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (forceDialog) {
runnable()
}
else {
val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", "))
showNotification(
project, NotificationKind.EXTERNAL, "external.components.available", "", message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable))
}
}
}
else if (!pluginsEnabled) {
if (forceDialog) {
NoUpdatesDialog(showSettingsLink).show()
}
else if (userInitiated) {
showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText())
}
}
}
@RequiresEdt
private fun showResults(
project: Project?,
platformUpdates: PlatformUpdates.Loaded,
updatedPlugins: List<PluginDownloader>,
incompatiblePlugins: Collection<IdeaPluginDescriptor>,
showNotification: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (showNotification) {
ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() }
}
val runnable = {
UpdateInfoDialog(
project,
platformUpdates,
showSettingsLink,
updatedPlugins,
incompatiblePlugins,
).show()
}
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins)
if (showNotification) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project)
val message = IdeBundle.message(
"updates.new.build.notification.title",
ApplicationNamesInfo.getInstance().fullProductName,
platformUpdates.newBuild.version,
)
showNotification(
project,
NotificationKind.PLATFORM,
"ide.update.available",
"",
message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project)
runnable()
})
}
}
}
private fun notificationsEnabled(): Boolean =
NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS &&
NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE
private fun showNotification(project: Project?,
kind: NotificationKind,
displayId: String,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent message: String,
vararg actions: NotificationAction) {
val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION
val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type)
.setDisplayId(displayId)
.setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST)
notification.whenExpired { ourShownNotifications.remove(kind, notification) }
actions.forEach { notification.addAction(it) }
notification.notify(project)
ourShownNotifications.putValue(kind, notification)
}
@JvmStatic
val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) }
@JvmStatic
fun saveDisabledToUpdatePlugins() {
runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) }
.onFailure { LOG.error(it) }
}
@JvmStatic
@JvmName("isIgnored")
internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean =
descriptor.ignoredKey in ignoredPlugins
@JvmStatic
@JvmName("ignorePlugins")
internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) {
ignoredPlugins += descriptors.map { it.ignoredKey }
runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) }
.onFailure { LOG.error(it) }
UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors)
}
private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) }
private val IdeaPluginDescriptor.ignoredKey: String
get() = "${pluginId.idString}+${version}"
private fun readConfigLines(fileName: String): List<String> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
runCatching {
val file = Path.of(PathManager.getConfigPath(), fileName)
if (Files.isRegularFile(file)) {
return Files.readAllLines(file)
}
}.onFailure { LOG.error(it) }
}
return emptyList()
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) {
val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
@ApiStatus.Internal
fun testPlatformUpdate(
project: Project?,
updateDataText: String,
patchFile: File?,
forceUpdate: Boolean,
) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val currentBuild = ApplicationInfo.getInstance().build
val productCode = currentBuild.productCode
val checkForUpdateResult = if (forceUpdate) {
val node = JDOMUtil.load(updateDataText)
.getChild("product")
?.getChild("channel")
?: throw IllegalArgumentException("//channel missing")
val channel = UpdateChannel(node, productCode)
val newBuild = channel.builds.firstOrNull()
?: throw IllegalArgumentException("//build missing")
val patches = newBuild.patches.firstOrNull()
?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
PlatformUpdates.Loaded(newBuild, channel, patches)
}
else {
UpdateStrategy(
currentBuild,
parseUpdateData(updateDataText, productCode),
).checkForUpdates()
}
val dialog = when (checkForUpdateResult) {
is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile)
else -> NoUpdatesDialog(true)
}
dialog.show()
}
//<editor-fold desc="Deprecated stuff.">
@ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()")
@Suppress("DEPRECATION")
@JvmField
val NOTIFICATIONS =
NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID)
@get:ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() = disabledToUpdate.mapTo(TreeSet()) { it.idString }
@ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith(""))
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null }
//</editor-fold>
} | apache-2.0 | 748524f02b5ea8851e133363ed6f6f88 | 38.982478 | 158 | 0.696635 | 5.414407 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/ifExpression/ifBlock.kt | 12 | 217 | fun foo() {
var a = 0
var b = 0
<warning descr="SSR">if (true) {
a = 1
}</warning>
if (true) {
b = 2
}
<warning descr="SSR">if (true) a = 1</warning>
println(a + b)
}
| apache-2.0 | 850b73654f9fd931a60abb755454b018 | 14.5 | 50 | 0.428571 | 2.972603 | false | false | false | false |
pajato/Argus | app/src/main/java/com/pajato/argus/Video.kt | 1 | 1405 | package com.pajato.argus
/** A relatively simple POJO that stores the relevant data for each video to our database. */
open class Video(val title: String, val network: String) {
var type: String = MOVIE_KEY
var dateWatched: String = ""
var locationWatched: String = ""
constructor(title: String, network: String, type: String) : this(title, network) {
this.type = type
}
constructor(title: String, network: String, type: String, dateWatched: String, locationWatched: String) : this(title, network) {
this.type = type
this.dateWatched = dateWatched
this.locationWatched = locationWatched
}
companion object {
val TV_KEY = "tvShowKey"
val MOVIE_KEY = "movieKey"
}
}
/** A subset of the Video class that also tracks episodes and seasons. */
class Episodic(title: String, network: String) : Video(title, network, Video.TV_KEY) {
var season: Int = 1
var episode: Int = 1
constructor(title: String, network: String, season: Int, episode: Int) : this(title, network) {
this.season = season
this.episode = episode
}
constructor(title: String, network: String, season: Int, episode: Int, dateWatched: String,
locationWatched: String) : this(title, network, season, episode) {
this.dateWatched = dateWatched
this.locationWatched = locationWatched
}
}
| gpl-3.0 | d077ce7bc81362ef20d2c5aaa9513613 | 33.268293 | 132 | 0.659075 | 4.002849 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | uast/uast-common/src/org/jetbrains/uast/baseElements/UElement.kt | 2 | 5890 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* The common interface for all Uast elements.
*/
interface UElement {
/**
* Returns the element parent.
*/
val uastParent: UElement?
/**
* Returns the PSI element underlying this element. Note that some UElements are synthetic and do not have
* an underlying PSI element; this doesn't mean that they are invalid.
*/
val psi: PsiElement?
/**
* Returns true if this element is valid, false otherwise.
*/
val isPsiValid: Boolean
get() = psi?.isValid ?: true
/**
* Returns the list of comments for this element.
*/
val comments: List<UComment>
get() = emptyList()
/**
* Returns the log string (usually one line containing the class name and some additional information).
*
* Examples:
* UWhileExpression
* UBinaryExpression (>)
* UCallExpression (println)
* USimpleReferenceExpression (i)
* ULiteralExpression (5)
*
* @return the expression tree for this element.
* @see [UIfExpression] for example.
*/
fun asLogString(): String
/**
* Returns the string in pseudo-code.
*
* Output example (should be something like this):
* while (i > 5) {
* println("Hello, world")
* i--
* }
*
* @return the rendered text.
* @see [UIfExpression] for example.
*/
fun asRenderString(): String = asLogString()
/**
* Returns the string as written in the source file.
* Use this String only for logging and diagnostic text messages.
*
* @return the original text.
*/
fun asSourceString(): String = asRenderString()
/**
* Passes the element to the specified visitor.
*
* @param visitor the visitor to pass the element to.
*/
fun accept(visitor: UastVisitor) {
visitor.visitElement(this)
visitor.afterVisitElement(this)
}
/**
* Passes the element to the specified typed visitor.
*
* @param visitor the visitor to pass the element to.
*/
fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitElement(this, data)
}
/**
* This is transitional type, all its content will be moved to `UElement` as soon as all implementations will implement it,
* and someday this interface will be dropped.
*/
@ApiStatus.Experimental
interface JvmDeclarationUElement : UElement {
/**
* Returns the PSI element in original (physical) tree to which this UElement corresponds.
* **Note**: that some UElements are synthetic and do not have an underlying PSI element;
* this doesn't mean that they are invalid.
*/
val sourcePsi: PsiElement?
get() = psi
/**
* Returns the element which try to mimic Java-api psi element: [com.intellij.psi.PsiClass], [com.intellij.psi.PsiMethod] or [com.intellij.psi.PsiAnnotation] etc.
* Will return null if this UElement doesn't have Java representation or it is not implemented.
*/
val javaPsi: PsiElement?
get() = psi
/**
* Returns the PSI element underlying this element. Note that some UElements are synthetic and do not have
* an underlying PSI element; this doesn't mean that they are invalid.
*
* **Node for implementors**: please implement both [sourcePsi] and [javaPsi] fields or make them return `null` explicitly
* if implementing is not possible. Redirect `psi` to one of them keeping existing behavior, use [sourcePsi] if nothing else is specified.
*/
@Deprecated("ambiguous psi element, use `sourcePsi` or `javaPsi`", ReplaceWith("javaPsi"))
override val psi: PsiElement?
}
/**
* Experimental API
*/
val UElement?.sourcePsiElement: PsiElement?
get() = fun(): PsiElement? {
val element = (this as? JvmDeclarationUElement)?.sourcePsi ?: return null;
// All following is a workaround for KT-21025 when returned `sourcePsi` is not actually a source psi
// and also it is a copy of a similar hack in `AbstractBaseUastLocalInspectionTool` in 173-branch
// Refer IDEA-CR-25636 and IDEA-CR-25766
val desiredFile = this?.getContainingUFile()?.psi ?: return element
fun inFile(element: PsiElement): Boolean {
val file = element.containingFile ?: return false
return file.viewProvider === desiredFile.viewProvider
}
if (inFile(element)) return element
val navigationElement = element.navigationElement ?: return element
if (inFile(navigationElement)) return navigationElement
// last resort
val elementAtSamePosition = desiredFile.findElementAt(navigationElement.textRange.startOffset)
return if (elementAtSamePosition != null && elementAtSamePosition.text == navigationElement.text) {
elementAtSamePosition
}
else element // it can't be helped
}()
@ApiStatus.Experimental
@SuppressWarnings("unchecked")
fun <T : PsiElement> UElement?.getAsJavaPsiElement(clazz: Class<T>): T? = when (this) {
is JvmDeclarationUElement -> this.javaPsi
else -> this?.psi
}?.takeIf { clazz.isAssignableFrom(it.javaClass) } as? T
/**
* Returns a sequence including this element and its containing elements.
*/
val UElement.withContainingElements: Sequence<UElement>
get() = generateSequence(this, UElement::uastParent)
| apache-2.0 | ac6abd1e1e5412e5dbbb03e3437c33ab | 31.905028 | 164 | 0.706791 | 4.362963 | false | false | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/internal/TestCaseExecutor.kt | 1 | 10806 | package io.kotest.core.internal
import io.kotest.core.TimeoutExecutionContext
import io.kotest.core.extensions.TestCaseExtension
import io.kotest.core.extensions.resolvedTestCaseExtensions
import io.kotest.core.spec.invokeAfterInvocation
import io.kotest.core.spec.invokeAllAfterTestCallbacks
import io.kotest.core.spec.invokeAllBeforeTestCallbacks
import io.kotest.core.spec.invokeBeforeInvocation
import io.kotest.core.test.NestedTest
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestCaseExecutionListener
import io.kotest.core.test.TestContext
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestStatus
import io.kotest.core.test.TestType
import io.kotest.core.test.resolvedInvocationTimeout
import io.kotest.core.test.resolvedTimeout
import io.kotest.core.test.withCoroutineContext
import io.kotest.fp.Try
import io.kotest.mpp.log
import io.kotest.mpp.replay
import io.kotest.mpp.timeInMillis
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withTimeout
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.math.min
/**
* Thrown when a test times out.
*/
data class TimeoutException(val duration: Long) : Exception("Test did not complete within ${duration}ms")
/**
* Validates that a [TestCase] is compatible on the actual platform. For example, in JS we can only
* support certain spec styles due to limitations in the underlying test runners.
*/
typealias ValidateTestCase = (TestCase) -> Unit
/**
* Returns a [TestResult] for the given throwable and test execution duration.
*/
typealias ToTestResult = (Throwable?, Long) -> TestResult
/**
* Executes a single [TestCase].
* Uses a [TestCaseExecutionListener] to notify callers of events in the test.
*
* The [TimeoutExecutionContext] is used to provide a way of executing functions on the underlying platform
* in a way that best utilizes threads or the lack of on that platform.
*
* If the given test case fails to validate via [validateTestCase], then this method throws.
*/
class TestCaseExecutor(
private val listener: TestCaseExecutionListener,
private val executionContext: TimeoutExecutionContext,
private val validateTestCase: ValidateTestCase,
private val toTestResult: ToTestResult,
) {
suspend fun execute(testCase: TestCase, context: TestContext): TestResult {
log { "TestCaseExecutor: execute entry point [testCase=${testCase.displayName}, context=$context]" }
validateTestCase(testCase)
val start = timeInMillis()
val extensions = testCase.resolvedTestCaseExtensions()
return intercept(testCase, context, start, extensions).apply {
when (status) {
TestStatus.Ignored -> listener.testIgnored(testCase)
else -> listener.testFinished(testCase, this)
}
}
}
/**
* Recursively runs the extensions until no extensions are left, at which point the test
* is executed and the result returned.
*/
private suspend fun intercept(
testCase: TestCase,
context: TestContext,
start: Long,
extensions: List<TestCaseExtension>,
): TestResult {
val innerExecute: suspend (TestCase, TestContext) -> TestResult = { tc, ctx ->
executeIfEnabled(tc) { executeActiveTest(tc, ctx, start) }
}
val execute = extensions.foldRight(innerExecute) { extension, execute ->
{ testCase, context ->
extension.intercept(testCase) {
// the user's intercept method is free to change the context of the coroutine
// to support this, we should switch the context used by the test case context
val newContext = context.withCoroutineContext(coroutineContext)
execute(it, newContext)
}
}
}
return execute(testCase, context)
}
/**
* Checks the enabled status of a [TestCase] before invoking it.
* If the test is disabled, then [TestResult.ignored] is returned.
*/
private suspend fun executeIfEnabled(testCase: TestCase, ifEnabled: suspend () -> TestResult): TestResult {
// if the test case is active we execute it, otherwise we just invoke the callback with ignored
val enabled = testCase.isEnabled()
return when (enabled.isEnabled) {
true -> {
log { "${testCase.description.testPath()} is enabled" }
ifEnabled()
}
false -> {
log { "${testCase.description.testPath()} is disabled" }
TestResult.ignored(enabled)
}
}
}
/**
* Executes a test taking care of invoking user level listeners.
* The test is always marked as started at this stage.
*
* If the before-test listeners fail, then the test is not executed, but the after-test listeners
* are executed, and the returned result contains the listener exception.
*
* If the test itself fails, then the after-test listeners are executed,
* and the returned result is generated from the test exception.
*
* If the after-test listeners fail, then the returned result is taken from the listener exception
* and any result from the test itself is ignored.
*
* Essentially, the after-test listeners are always attempted, and any error from invoking the before, test,
* or after code is returned as higher priority than the result from the test case itself.
*/
private suspend fun executeActiveTest(
testCase: TestCase,
context: TestContext,
start: Long,
): TestResult {
log { "Executing active test $testCase with context $context" }
listener.testStarted(testCase)
return testCase
.invokeAllBeforeTestCallbacks()
.flatMap { invokeTestCase(executionContext, it, context, start) }
.fold(
{
toTestResult(it, timeInMillis() - start).apply {
testCase.invokeAllAfterTestCallbacks(this)
}
},
{ result ->
testCase.invokeAllAfterTestCallbacks(result)
.fold(
{ toTestResult(it, timeInMillis() - start) },
{ result }
)
}
)
}
/**
* Invokes the given [TestCase] on the given executor.
*/
private suspend fun invokeTestCase(
ec: TimeoutExecutionContext,
testCase: TestCase,
context: TestContext,
start: Long,
): Try<TestResult> = Try {
log { "invokeTestCase $testCase" }
if (testCase.config.invocations > 1 && testCase.type == TestType.Container)
error("Cannot execute multiple invocations in parent tests")
val t = executeAndWait(ec, testCase, context)
log { "TestCaseExecutor: Test returned with error $t" }
val result = toTestResult(t, timeInMillis() - start)
log { "Test completed with result $result" }
result
}
/**
* Invokes the given [TestCase] handling timeouts.
*/
private suspend fun executeAndWait(
ec: TimeoutExecutionContext,
testCase: TestCase,
context: TestContext,
): Throwable? {
// this timeout applies to the test itself. If the test has multiple invocations then
// this timeout applies across all invocations. In other words, if a test has invocations = 3,
// each test takes 300ms, and a timeout of 800ms, this would fail, becauase 3 x 300 > 800.
val timeout = testCase.resolvedTimeout()
log { "TestCaseExecutor: Test [${testCase.displayName}] will execute with timeout $timeout" }
// this timeout applies to each inovation. If a test has invocations = 3, and this timeout
// is set to 300ms, then each individual invocation must complete in under 300ms.
// invocation timeouts are not applied to TestType.Container only TestType.Test
val invocationTimeout = testCase.resolvedInvocationTimeout()
log { "TestCaseExecutor: Test [${testCase.displayName}] will execute with invocationTimeout $invocationTimeout" }
// we don't want any errors in the test to propagate out and cancel all the coroutines used for
// the specs / parent tests, therefore we install a supervisor job
return supervisorScope {
try {
// all platforms support coroutine based interruption
// this is the test level timeout
withTimeout(timeout) {
ec.executeWithTimeoutInterruption(timeout) {
// depending on the test type, we execute with an invocation timeout
when (testCase.type) {
TestType.Container -> executeInScope(testCase, context)
TestType.Test ->
// not all platforms support executing with an interruption based timeout
// because it uses background threads to interrupt
replay(
testCase.config.invocations,
testCase.config.threads,
{ testCase.invokeBeforeInvocation(it) },
{ testCase.invokeAfterInvocation(it) }) {
ec.executeWithTimeoutInterruption(invocationTimeout) {
withTimeout(invocationTimeout) {
executeInScope(testCase, context)
}
}
}
}
}
}
null
} catch (e: TimeoutCancellationException) {
log { "TestCaseExecutor: TimeoutCancellationException $e" }
when (testCase.type) {
TestType.Container -> TimeoutException(timeout)
TestType.Test -> TimeoutException(min(timeout, invocationTimeout))
}
} catch (t: Throwable) {
log { "TestCaseExecutor: Throwable $t" }
t
} catch (e: AssertionError) {
log { "TestCaseExecutor: AssertionError $e" }
e
}
}
}
/**
* Execute the test case wrapped in a scope, so that we wait for any child coroutines created
* by the user's test case.
*/
private suspend fun executeInScope(testCase: TestCase, context: TestContext) = coroutineScope {
val contextp = object : TestContext {
override val testCase: TestCase = context.testCase
override val coroutineContext: CoroutineContext = this@coroutineScope.coroutineContext
override suspend fun registerTestCase(nested: NestedTest) = context.registerTestCase(nested)
}
testCase.executeWithBehaviours(contextp)
}
}
| mit | 329706e9acdf0d5344e04e4701edb208 | 39.022222 | 119 | 0.65658 | 5.014385 | false | true | false | false |
migafgarcia/programming-challenges | advent_of_code/2018/solutions/day_4_b.kt | 1 | 2687 | import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.Calendar
fun main(args: Array<String>) {
val regex = Regex("\\[(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})] (.+)")
val beginsShiftRegex = Regex("Guard #(\\d+) begins shift")
val wakesUpRegex = Regex("wakes up")
val fallsAsleepRegex = Regex("falls asleep")
val FALLS_ASLEEP = -1
val WAKES_UP = -2
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")
val schedule = ArrayList<Pair<Date, Int>>()
File(args[0]).forEachLine { line ->
val results = regex.find(line)!!.groupValues
var date = dateFormat.parse(results[1])
val c = Calendar.getInstance()
c.time = date
c.add(Calendar.YEAR, 1000)
date = c.time
val action = results[2]
schedule.add(when {
action.matches(beginsShiftRegex) -> {
Pair(date, beginsShiftRegex.find(action)!!.groupValues[1].toInt())
}
action.matches(wakesUpRegex) -> {
Pair(date, WAKES_UP)
}
action.matches(fallsAsleepRegex) -> {
Pair(date, FALLS_ASLEEP)
}
else -> throw Exception("Error reading line: $line")
})
}
schedule.sortBy { (first) -> first }
val map = HashMap<Int, ArrayList<Pair<Int, Int>>>()
var currentId = -1
var startSleep = -1L
schedule.forEach { (first, second) ->
val c = GregorianCalendar.getInstance()
when (second) {
WAKES_UP -> {
c.time = Date(startSleep)
val f = c.get(Calendar.MINUTE)
c.time = Date(first.time)
val s = c.get(Calendar.MINUTE)
map[currentId]!!.add(Pair(f, s))
}
FALLS_ASLEEP -> startSleep = first.time
else -> {
currentId = second
startSleep = -1L
map.putIfAbsent(currentId, ArrayList())
}
}
}
var current = Triple(0, 0, 0) // ID, minute, times
map.forEach { entry ->
val minuteMap = HashMap<Int, Int>()
entry.value.forEach { (first, second) ->
for (i in first until second) {
minuteMap.computeIfAbsent(i, { 0 })
minuteMap.computeIfPresent(i, { _, u -> u + 1 })
}
}
val minute = minuteMap.maxBy { entry -> entry.value }
if (minute != null) {
if (minute.value > current.third) {
current = Triple(entry.key, minute.key, minute.value)
}
}
}
println(current.first * current.second)
}
| mit | 9c10c579189585bb4c68fba849c86815 | 26.418367 | 82 | 0.519911 | 3.963127 | false | false | false | false |
rest-assured/rest-assured | modules/spring-mock-mvc-kotlin-extensions/src/main/kotlin/io/restassured/module/mockmvc/kotlin/extensions/RestAssuredMockMvcKotlinExtensions.kt | 2 | 2868 | @file:Suppress("FunctionName")
package io.restassured.module.mockmvc.kotlin.extensions
import io.restassured.internal.ResponseSpecificationImpl
import io.restassured.module.mockmvc.RestAssuredMockMvc.`when`
import io.restassured.module.mockmvc.RestAssuredMockMvc.given
import io.restassured.module.mockmvc.internal.MockMvcRestAssuredResponseImpl
import io.restassured.module.mockmvc.internal.ValidatableMockMvcResponseImpl
import io.restassured.module.mockmvc.response.MockMvcResponse
import io.restassured.module.mockmvc.response.ValidatableMockMvcResponse
import io.restassured.module.mockmvc.specification.MockMvcRequestAsyncSender
import io.restassured.module.mockmvc.specification.MockMvcRequestSender
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
import io.restassured.response.ExtractableResponse
/**
* A wrapper around [given] that starts building the request part of the test.
* @see given
*/
fun Given(block: MockMvcRequestSpecification.() -> MockMvcRequestSpecification): MockMvcRequestSpecification =
given().run(block)
/**
* A wrapper around [ MockMvcRequestSpecification.when ] that configures how the request is dispatched.
* @see MockMvcRequestSpecification.when
*/
infix fun MockMvcRequestSpecification.When(
block: MockMvcRequestAsyncSender.() ->
MockMvcResponse
): MockMvcResponse =
`when`().run(block)
/**
* A wrapper around [ io.restassured.module.mockmvc.RestAssuredMockMvc.when ] that configures how the request is dispatched.
* @see io.restassured.module.mockmvc.RestAssuredMockMvc.when
*/
fun When(block: MockMvcRequestSender.() -> MockMvcRestAssuredResponseImpl): MockMvcRestAssuredResponseImpl =
`when`().run(block)
/**
* A wrapper around [then] that allow configuration of response expectations.
* @see then
*/
infix fun MockMvcResponse.Then(block: ValidatableMockMvcResponse.() -> Unit): ValidatableMockMvcResponse = then()
.also(doIfValidatableResponseImpl {
forceDisableEagerAssert()
})
.apply(block)
.also(doIfValidatableResponseImpl {
forceValidateResponse()
})
/**
* A wrapper around [ExtractableResponse] that allow for extract data out of the response
* @see ExtractableResponse
*/
infix fun <T> MockMvcResponse.Extract(block: ExtractableResponse<MockMvcResponse>.() -> T): T =
then().extract().run(block)
/**
* A wrapper around [ExtractableResponse] that allow for extract data out of the response
* @see ExtractableResponse
*/
infix fun <T> ValidatableMockMvcResponse.Extract(
block: ExtractableResponse<MockMvcResponse>.() -> T
): T = extract().run(block)
// End main wrappers
private fun doIfValidatableResponseImpl(
fn: ResponseSpecificationImpl.() -> Unit
): (ValidatableMockMvcResponse) -> Unit = { resp ->
if (resp is ValidatableMockMvcResponseImpl) {
fn(resp.responseSpec)
}
}
| apache-2.0 | d847e5751661a76ce6f5ed353ee49246 | 36.246753 | 124 | 0.779289 | 4.255193 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/data/repository/UsedFileRepository.kt | 1 | 1071 | package com.ivanovsky.passnotes.data.repository
import com.ivanovsky.passnotes.data.ObserverBus
import com.ivanovsky.passnotes.data.entity.FSAuthority
import com.ivanovsky.passnotes.data.entity.UsedFile
import com.ivanovsky.passnotes.data.repository.db.dao.UsedFileDao
class UsedFileRepository(
private val dao: UsedFileDao,
private val bus: ObserverBus
) {
fun getAll(): List<UsedFile> {
return dao.all
}
fun findByUid(fileUid: String, fsAuthority: FSAuthority): UsedFile? {
return dao.all
.firstOrNull { file: UsedFile? -> fileUid == file!!.fileUid && fsAuthority == file.fsAuthority }
}
fun insert(file: UsedFile): UsedFile {
val id = dao.insert(file)
bus.notifyUsedFileDataSetChanged()
return file.copy(id = id.toInt())
}
fun update(file: UsedFile) {
if (file.id == null) return
dao.update(file)
bus.notifyUsedFileContentChanged(file.id)
}
fun remove(id: Int) {
dao.remove(id)
bus.notifyUsedFileDataSetChanged()
}
} | gpl-2.0 | 800d4d7d6fb3ef199e0e9c6ff8d131b2 | 23.930233 | 108 | 0.670401 | 3.966667 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/view/QuranImagePageLayout.kt | 2 | 2584 | package com.quran.labs.androidquran.view
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener
import com.quran.labs.androidquran.ui.util.PageController
import com.quran.labs.androidquran.util.QuranSettings
/**
* Layout class for a single Arabic page of the Quran, with margins/background.
* <p>
* Note that the image of the Quran page to be displayed is set by users of this class by calling
* {@link #getImageView()} and calling the appropriate methods on that view.
*/
open class QuranImagePageLayout(context: Context) : QuranPageLayout(context) {
private lateinit var imageView: HighlightingImageView
init {
this.initialize()
}
override fun generateContentView(context: Context, isLandscape: Boolean): View {
imageView = HighlightingImageView(context).apply {
adjustViewBounds = true
setIsScrollable(isLandscape && shouldWrapWithScrollView(), isLandscape)
}
return imageView
}
override fun updateView(quranSettings: QuranSettings) {
super.updateView(quranSettings)
imageView.setNightMode(quranSettings.isNightMode, quranSettings.nightModeTextBrightness, quranSettings.nightModeBackgroundBrightness)
}
override fun setPageController(controller: PageController?, pageNumber: Int) {
super.setPageController(controller, pageNumber)
val gestureDetector = GestureDetector(context, PageGestureDetector())
val gestureListener = OnTouchListener { _, event ->
gestureDetector.onTouchEvent(event)
}
imageView.setOnTouchListener(gestureListener)
imageView.isClickable = true
imageView.isLongClickable = true
}
fun getImageView(): HighlightingImageView = imageView
inner class PageGestureDetector : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean = true
override fun onSingleTapUp(event: MotionEvent): Boolean {
return pageController.handleTouchEvent(
event,
AyahSelectedListener.EventType.SINGLE_TAP,
pageNumber
)
}
override fun onDoubleTap(event: MotionEvent): Boolean {
return pageController.handleTouchEvent(
event,
AyahSelectedListener.EventType.DOUBLE_TAP,
pageNumber
)
}
override fun onLongPress(event: MotionEvent) {
pageController.handleTouchEvent(
event,
AyahSelectedListener.EventType.LONG_PRESS,
pageNumber
)
}
}
}
| gpl-3.0 | 9bf7bac6816c465f19fdc80307a570b2 | 31.708861 | 137 | 0.749226 | 4.838951 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/hle/manager/MemoryManager.kt | 1 | 11307 | @file:Suppress("CanBeVal")
package com.soywiz.kpspemu.hle.manager
import com.soywiz.kds.*
import com.soywiz.korge.util.*
import com.soywiz.korge.util.NativeThreadLocal
import com.soywiz.korio.error.*
import com.soywiz.korio.lang.*
import com.soywiz.korio.util.*
import com.soywiz.kpspemu.*
import com.soywiz.krypto.encoding.*
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
import kotlin.collections.MutableMap
import kotlin.collections.arrayListOf
import kotlin.collections.filter
import kotlin.collections.firstOrNull
import kotlin.collections.indexOfFirst
import kotlin.collections.indexOfLast
import kotlin.collections.map
import kotlin.collections.maxBy
import kotlin.collections.set
import kotlin.collections.sortedBy
import kotlin.collections.toMap
import com.soywiz.korio.lang.invalidOp as invalidOp1
class MemoryManager(val emulator: Emulator) {
val memoryPartitionsUid: MutableMap<Int, MemoryPartition> = LinkedHashMap<Int, MemoryPartition>()
init {
reset()
}
val kernelPartition: MemoryPartition get() = this.memoryPartitionsUid[MemoryPartitions.Kernel0]!!
val userPartition: MemoryPartition get() = this.memoryPartitionsUid[MemoryPartitions.User]!!
val stackPartition: MemoryPartition get() = this.memoryPartitionsUid[MemoryPartitions.UserStacks]!!
fun reset() {
this.memoryPartitionsUid.clear()
this.memoryPartitionsUid[MemoryPartitions.Kernel0] =
MemoryPartition("Kernel Partition 1", 0x88000000, 0x88300000, false)
//this.memoryPartitionsUid[MemoryPartitions.User] = new MemoryPartition("User Partition", 0x08800000, 0x08800000 + 0x100000 * 32, false);
//this.memoryPartitionsUid[MemoryPartitions.UserStacks] = new MemoryPartition("User Stacks Partition", 0x08800000, 0x08800000 + 0x100000 * 32, false);
this.memoryPartitionsUid[MemoryPartitions.User] =
MemoryPartition("User Partition", 0x08800000, 0x08800000 + 0x100000 * 24, false)
this.memoryPartitionsUid[MemoryPartitions.UserStacks] =
MemoryPartition("User Stacks Partition", 0x08800000, 0x08800000 + 0x100000 * 24, false)
this.memoryPartitionsUid[MemoryPartitions.VolatilePartition] =
MemoryPartition("Volatile Partition", 0x08400000, 0x08800000, false)
}
}
open class MemoryPartitions(val id: Int) {
companion object {
const val Kernel0 = 0
const val User = 2
const val VolatilePartition = 5
const val UserStacks = 6
}
}
enum class MemoryAnchor(val id: Int) {
Low(0),
High(1),
Address(2),
LowAligned(3),
HighAligned(4);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun invoke(index: Int) = BY_ID[index] ?: invalidOp1("Can't find index $index in class")
}
}
class OutOfMemoryError(message: String) : Exception(message)
data class MemoryPartition(
var name: String,
val low: Long,
val high: Long,
var allocated: Boolean,
val parent: MemoryPartition? = null
) {
val low_i: Int get() = low.toInt()
val high_i: Int get() = high.toInt()
@NativeThreadLocal
companion object {
val ZERO = 0L
val DUMMY = MemoryPartition("dummy", 0.0, 0.0, false, null)
inline operator fun invoke(
name: String,
low: Number,
high: Number,
allocated: Boolean,
parent: MemoryPartition? = null
) = MemoryPartition(name, low.toLong(), high.toLong(), allocated, parent)
}
// Actual address
var address: Long = low
private val _childPartitions = arrayListOf<MemoryPartition>()
val free: Boolean get() = !allocated
val size: Long get() = this.high - this.low
val root: MemoryPartition get() = this.parent?.root ?: this
val childPartitions: ArrayList<MemoryPartition>
get() {
if (this._childPartitions.isEmpty()) {
this._childPartitions.add(MemoryPartition("", this.low, this.high, false, this))
}
return this._childPartitions
}
fun contains(address: Long): Boolean = address >= this.low && address < this.high
fun deallocate() {
this.allocated = false
this.parent?.cleanup()
}
fun allocate(size: Long, anchor: MemoryAnchor, address: Long = ZERO, name: String = ""): MemoryPartition {
when (anchor) {
MemoryAnchor.LowAligned, // @TODO: aligned!
MemoryAnchor.Low -> return this.allocateLow(size, name)
MemoryAnchor.High -> return this.allocateHigh(size, name)
MemoryAnchor.Address -> return this.allocateSet(size, address, name)
else -> throw Error("Not implemented anchor %d:%s".format(anchor, anchor))
}
}
inline fun allocate(
size: Number,
anchor: MemoryAnchor,
address: Number = ZERO,
name: String = ""
): MemoryPartition = allocate(size.toLong(), anchor, address.toLong(), name)
inline fun allocateSet(size: Number, addressLow: Number, name: String = ""): MemoryPartition =
allocateSet(size.toLong(), addressLow.toLong(), name)
inline fun allocateLow(size: Number, name: String = ""): MemoryPartition = this.allocateLow(size.toLong(), name)
inline fun allocateHigh(size: Number, name: String = "", alignment: Int = 1): MemoryPartition =
this.allocateHigh(size.toLong(), name)
fun allocateSet(size: Long, addressLow: Long, name: String = ""): MemoryPartition {
var childs = this.childPartitions
var addressHigh = addressLow + size
if (!this.contains(addressLow) || !this.contains(addressHigh)) {
throw OutOfMemoryError(
"Can't allocate [%08X-%08X] in [%08X-%08X]".format(
addressLow,
addressHigh,
this.low,
this.high
)
)
}
val index = childs.indexOfFirst { it.contains(addressLow) }
if (index < 0) {
println("address: %08X, size: %d".format(addressLow, size))
println(this)
throw Error("Can't find the segment")
}
var child = childs[index]
if (child.allocated) throw Error("Memory already allocated")
if (!child.contains(addressHigh - 1)) throw Error("Can't fit memory")
var p1 = MemoryPartition("", child.low, addressLow, false, this)
var p2 = MemoryPartition(name, addressLow, addressHigh, true, this)
var p3 = MemoryPartition("", addressHigh, child.high, false, this)
childs.splice(index, 1, p1, p2, p3)
this.cleanup()
return p2
}
fun allocateLow(size: Long, name: String = ""): MemoryPartition =
this.allocateLowHigh(size, low = true, name = name)
fun allocateHigh(size: Long, name: String = "", alignment: Int = 1): MemoryPartition =
this.allocateLowHigh(size, low = false, name = name)
private fun _validateChilds() {
var childs = this.childPartitions
if (childs[0].low != this.low) throw Error("First child low doesn't match container low")
if (childs[childs.size - 1].high != this.high) throw Error("Last child high doesn't match container high")
for (n in 0 until childs.size - 1) {
if (childs[n + 0].high != childs[n + 1].low) throw Error("Children at $n are not contiguous")
}
}
private fun allocateLowHigh(size: Long, low: Boolean, name: String = ""): MemoryPartition {
var childs = this.childPartitions
val index = if (low) {
childs.indexOfFirst { it.free && it.size >= size }
} else {
childs.indexOfLast { it.free && it.size >= size }
}
if (index < 0) throw OutOfMemoryError("Can't find a partition with $size available")
var child = childs[index]
val unallocatedChild: MemoryPartition
val allocatedChild: MemoryPartition
if (low) {
var p1 = child.low
var p2 = child.low + size
var p3 = child.high
allocatedChild = MemoryPartition(name, p1, p2, true, this)
unallocatedChild = MemoryPartition("", p2, p3, false, this)
childs.splice(index, 1, allocatedChild, unallocatedChild)
} else {
var p1 = child.low
var p2 = child.high - size
var p3 = child.high
unallocatedChild = MemoryPartition("", p1, p2, false, this)
allocatedChild = MemoryPartition(name, p2, p3, true, this)
childs.splice(index, 1, unallocatedChild, allocatedChild)
}
this.cleanup()
return allocatedChild
}
fun unallocate() {
this.name = ""
this.allocated = false
this.parent?.cleanup()
}
private fun cleanup() {
var startTotalFreeMemory = this.getTotalFreeMemory()
this._validateChilds()
// join contiguous free memory
var childs = this.childPartitions
if (childs.size >= 2) {
var n = 0
while (n < childs.size - 1) {
var l = childs[n + 0]
var r = childs[n + 1]
if (!l.allocated && !r.allocated) {
val new = MemoryPartition("", l.low, r.high, false, this)
//console.log('joining', child, c1, child.low, c1.high);
childs.splice(n, 2, new)
//println("l: $l")
//println("r: $r")
//println("new: $new")
} else {
n++
}
}
}
// remove empty segments
run {
var n = 0
while (n < childs.size) {
var child = childs[n]
if (!child.allocated && child.size == ZERO) {
childs.splice(n, 1)
} else {
n++
}
}
}
this._validateChilds()
var endTotalFreeMemory = this.getTotalFreeMemory()
if (endTotalFreeMemory != startTotalFreeMemory) {
println("assertion failed [1]! : $startTotalFreeMemory,$endTotalFreeMemory")
}
}
val nonAllocatedPartitions get() = this.childPartitions.filter { !it.allocated }
fun getTotalFreeMemory(): Long =
this.nonAllocatedPartitions.reduceAcumulate(ZERO) { prev, item -> item.size + prev }
fun getMaxContiguousFreeMemory(): Long = this.nonAllocatedPartitions.maxByOrNull { it.size }?.size ?: ZERO
fun getTotalFreeMemoryInt(): Int = this.getTotalFreeMemory().toInt()
fun getMaxContiguousFreeMemoryInt(): Int = this.getMaxContiguousFreeMemory().toInt()
private fun findFreeChildWithSize(size: Int) = Unit
fun toString2() = "MemoryPartition('$name', ${low.toInt().shex}-${high.toInt().shex} size=$size)"
fun dump() {
println("DUMP: ${this.toString2()}")
for (child in childPartitions.filter { it.allocated }.sortedBy { it.low }) {
println(" - ${child.toString2()}")
}
}
fun getAtLow(ptr: Long): MemoryPartition? {
// @TODO: Optimize!
return childPartitions.firstOrNull { it.low == ptr }
}
}
| mit | d908ced5b12916861b24485328d9a6d0 | 34.781646 | 158 | 0.612364 | 4.198663 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/libjamiclient/src/main/kotlin/net/jami/account/LinkDevicePresenter.kt | 1 | 2585 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Alexandre Lision <alexandre.lision@savoirfairelinux.com>
* Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.jami.account
import io.reactivex.rxjava3.core.Scheduler
import net.jami.model.Account
import net.jami.mvp.RootPresenter
import net.jami.services.AccountService
import java.net.SocketException
import javax.inject.Inject
import javax.inject.Named
class LinkDevicePresenter @Inject constructor(
private val mAccountService: AccountService,
@Named("UiScheduler")
private var mUiScheduler: Scheduler
) : RootPresenter<LinkDeviceView>() {
private var mAccountID: String? = null
fun startAccountExport(password: String?) {
if (view == null) {
return
}
view?.showExportingProgress()
mCompositeDisposable.add(mAccountService
.exportOnRing(mAccountID!!, password!!)
.observeOn(mUiScheduler)
.subscribe({ pin: String -> view?.showPIN(pin) })
{ error: Throwable ->
view?.dismissExportingProgress()
when (error) {
is IllegalArgumentException -> view?.showPasswordError()
is SocketException -> view?.showNetworkError()
else -> view?.showGenericError()
}
})
}
fun setAccountId(accountID: String) {
mCompositeDisposable.clear()
mAccountID = accountID
val account = mAccountService.getAccount(accountID)
if (account != null)
view?.accountChanged(account)
mCompositeDisposable.add(mAccountService.getObservableAccountUpdates(accountID)
.observeOn(mUiScheduler)
.subscribe { a: Account -> view?.accountChanged(a) })
}
companion object {
private val TAG = LinkDevicePresenter::class.simpleName!!
}
} | gpl-3.0 | 96de4d5d8f22d0943c0b124f5a2468f8 | 35.928571 | 87 | 0.671827 | 4.533333 | false | false | false | false |
tmarsteel/kotlin-prolog | stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/essential/string/string_chars__2.kt | 1 | 1126 | package com.github.prologdb.runtime.stdlib.essential.string
import com.github.prologdb.runtime.ArgumentError
import com.github.prologdb.runtime.PrologInvocationContractViolationException
import com.github.prologdb.runtime.stdlib.nativeConversionRule
import com.github.prologdb.runtime.term.Atom
import com.github.prologdb.runtime.term.PrologList
import com.github.prologdb.runtime.term.PrologString
val BuiltinStringChars2 = nativeConversionRule<PrologString, PrologList>(
"string_chars",
{ str -> PrologList(str.characters.map { Atom(it.toString()) }) },
{ list ->
if (list.tail != null) throw ArgumentError(1, "must not have a tail.")
val stringCharsTarget = CharArray(list.elements.size)
list.elements.forEachIndexed { index, listElement ->
if (listElement is Atom && listElement.name.length == 1) {
stringCharsTarget[index] = listElement.name[0]
}
else throw PrologInvocationContractViolationException("Type Error: expected character, found ${listElement.prologTypeName}")
}
PrologString(stringCharsTarget)
}
) | mit | eebefe1c5891d61db7af4ba4a8ebcf01 | 42.346154 | 136 | 0.731794 | 4.29771 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/ui/BaseTopActivity.kt | 1 | 13733 | package com.battlelancer.seriesguide.ui
import android.content.ContentResolver
import android.content.Intent
import android.content.SyncStatusObserver
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.activity.addCallback
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatDelegate
import com.battlelancer.seriesguide.BuildConfig
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.SgApp.Companion.getServicesComponent
import com.battlelancer.seriesguide.backend.CloudSetupActivity
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.dataliberation.BackupSettings
import com.battlelancer.seriesguide.dataliberation.DataLiberationActivity
import com.battlelancer.seriesguide.preferences.MoreOptionsActivity
import com.battlelancer.seriesguide.stats.StatsActivity
import com.battlelancer.seriesguide.sync.AccountUtils
import com.battlelancer.seriesguide.ui.ShowsActivity
import com.battlelancer.seriesguide.util.SupportTheDev
import com.battlelancer.seriesguide.util.SupportTheDev.buildSnackbar
import com.battlelancer.seriesguide.util.Utils
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.snackbar.Snackbar
import timber.log.Timber
/**
* Activities at the top of the navigation hierarchy, displaying a bottom navigation bar.
* Implementers must set it up with [setupBottomNavigation].
*
* They should also override [snackbarParentView] and supply a CoordinatorLayout.
* It is used to show snack bars for important warnings (e.g. auto backup failed, Cloud signed out).
*
* Also provides support for an optional sync progress bar (see [setupSyncProgressBar]).
*/
abstract class BaseTopActivity : BaseMessageActivity() {
private var syncProgressBar: View? = null
private var syncObserverHandle: Any? = null
private var snackbar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onBackPressedDispatcher.addCallback {
finish()
// Use a custom animation when navigating away from a top activity
// but not when exiting the app (use the default system animations).
if (!isTaskRoot) {
overridePendingTransition(
R.anim.activity_fade_enter_sg,
R.anim.activity_fade_exit_sg
)
}
}
}
override fun setupActionBar() {
super.setupActionBar()
supportActionBar?.setHomeButtonEnabled(false)
}
fun setupBottomNavigation(@IdRes selectedItemId: Int) {
val bottomNav = findViewById<BottomNavigationView>(R.id.bottomNavigation)
bottomNav.selectedItemId = selectedItemId
bottomNav.setOnItemSelectedListener { item ->
onNavItemClick(item.itemId)
false // Do not change selected item.
}
}
private fun onNavItemClick(itemId: Int) {
var launchIntent: Intent? = null
when (itemId) {
R.id.navigation_item_shows -> {
if (this is ShowsActivity) {
onSelectedCurrentNavItem()
return
}
launchIntent = Intent(this, ShowsActivity::class.java)
.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP
or Intent.FLAG_ACTIVITY_NEW_TASK
or Intent.FLAG_ACTIVITY_SINGLE_TOP
)
}
R.id.navigation_item_lists -> {
if (this is ListsActivity) {
onSelectedCurrentNavItem()
return
}
launchIntent = Intent(this, ListsActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
R.id.navigation_item_movies -> {
if (this is MoviesActivity) {
onSelectedCurrentNavItem()
return
}
launchIntent = Intent(this, MoviesActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
R.id.navigation_item_stats -> {
if (this is StatsActivity) {
onSelectedCurrentNavItem()
return
}
launchIntent = Intent(this, StatsActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
R.id.navigation_item_more -> {
if (this is MoreOptionsActivity) {
onSelectedCurrentNavItem()
return
}
launchIntent = Intent(this, MoreOptionsActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
}
if (launchIntent != null) {
startActivity(launchIntent)
overridePendingTransition(R.anim.activity_fade_enter_sg, R.anim.activity_fade_exit_sg)
}
}
/**
* Called if the currently active nav item was clicked.
* Implementing activities might want to use this to scroll contents to the top.
*/
protected open fun onSelectedCurrentNavItem() {
// Do nothing by default.
}
/**
* Implementing classes may call this in [onCreate] to set up a
* progress bar which displays when syncing.
*/
protected fun setupSyncProgressBar(@IdRes progressBarId: Int) {
syncProgressBar = findViewById<View>(progressBarId)
.also { it.visibility = View.GONE }
}
override fun onStart() {
super.onStart()
if (Utils.hasAccessToX(this) && HexagonSettings.shouldValidateAccount(this)) {
onShowCloudAccountWarning()
}
if (SupportTheDev.shouldAsk(this)) {
askForSupport()
}
}
override fun onResume() {
super.onResume()
if (syncProgressBar != null) {
// watch for sync state changes
syncStatusObserver.onStatusChanged(0)
val mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING or
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE
syncObserverHandle = ContentResolver.addStatusChangeListener(mask, syncStatusObserver)
}
}
override fun onPause() {
super.onPause()
// stop listening to sync state changes
if (syncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(syncObserverHandle)
syncObserverHandle = null
}
}
override fun onStop() {
super.onStop()
// dismiss any snackbar to avoid it getting restored
// if condition that led to its display is no longer true
val snackbar = snackbar
if (snackbar != null && snackbar.isShown) {
snackbar.dismiss()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (BuildConfig.DEBUG) {
menu.add(0, 0, 0, "[Debug] Switch theme")
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == OPTIONS_SWITCH_THEME_ID) {
val isNightMode =
AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES
AppCompatDelegate.setDefaultNightMode(
if (isNightMode) {
AppCompatDelegate.MODE_NIGHT_NO
} else {
AppCompatDelegate.MODE_NIGHT_YES
}
)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onLastAutoBackupFailed() {
val snackbar = snackbar
if (snackbar != null && snackbar.isShown) {
Timber.d("NOT showing auto backup failed message: existing snackbar.")
return
}
val newSnackbar = Snackbar.make(
snackbarParentView,
R.string.autobackup_failed,
Snackbar.LENGTH_INDEFINITE
)
// Manually increase max lines.
val textView = newSnackbar.view
.findViewById<TextView>(com.google.android.material.R.id.snackbar_text)
textView.maxLines = 5
newSnackbar
.addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar, event: Int) {
if (event == DISMISS_EVENT_ACTION
|| event == DISMISS_EVENT_SWIPE) {
Timber.i("Has seen last auto backup failed.")
BackupSettings.setHasSeenLastAutoBackupFailed(this@BaseTopActivity)
}
}
})
.setAction(R.string.preferences) {
startActivity(
DataLiberationActivity.intentToShowAutoBackup(
this
)
)
}
.show()
this.snackbar = newSnackbar
}
override fun onAutoBackupMissingFiles() {
val snackbar = snackbar
if (snackbar != null && snackbar.isShown) {
Timber.d("NOT showing backup files warning: existing snackbar.")
return
}
val newSnackbar = Snackbar.make(
snackbarParentView,
R.string.autobackup_files_missing,
Snackbar.LENGTH_INDEFINITE
)
// Manually increase max lines.
val textView = newSnackbar.view
.findViewById<TextView>(com.google.android.material.R.id.snackbar_text)
textView.maxLines = 5
newSnackbar.setAction(R.string.preferences) {
startActivity(
DataLiberationActivity.intentToShowAutoBackup(this)
)
}
newSnackbar.show()
this.snackbar = newSnackbar
}
protected fun onShowCloudAccountWarning() {
val snackbar = snackbar
if (snackbar != null && snackbar.isShown) {
Timber.d("NOT showing Cloud account warning: existing snackbar.")
return
}
val newSnackbar = Snackbar
.make(
snackbarParentView, R.string.hexagon_signed_out,
Snackbar.LENGTH_INDEFINITE
)
newSnackbar.addCallback(object : Snackbar.Callback() {
override fun onDismissed(snackbar: Snackbar, event: Int) {
if (event == DISMISS_EVENT_SWIPE) {
// user has dismissed warning, so disable Cloud
val hexagonTools = getServicesComponent(this@BaseTopActivity)
.hexagonTools()
hexagonTools.removeAccountAndSetDisabled()
}
}
}).setAction(R.string.hexagon_signin) {
// forward to cloud setup which can help fix the account issue
startActivity(Intent(this@BaseTopActivity, CloudSetupActivity::class.java))
}.show()
this.snackbar = newSnackbar
}
private fun askForSupport() {
val snackbar = snackbar
if (snackbar != null && snackbar.isShown) {
Timber.d("NOT asking for support: existing snackbar.")
return
}
val newSnackbar = buildSnackbar(this, snackbarParentView)
newSnackbar.show()
this.snackbar = newSnackbar
}
/**
* Shows or hides the indeterminate sync progress indicator inside this activity layout.
*/
private fun setSyncProgressVisibility(isVisible: Boolean) {
val syncProgressBar = syncProgressBar
if (syncProgressBar == null ||
syncProgressBar.visibility == (if (isVisible) View.VISIBLE else View.GONE)) {
// not enabled or already in desired state, avoid replaying animation
return
}
syncProgressBar.startAnimation(
AnimationUtils.loadAnimation(
syncProgressBar.context,
if (isVisible) R.anim.fade_in else R.anim.fade_out
)
)
syncProgressBar.visibility =
if (isVisible) View.VISIBLE else View.GONE
}
/**
* Create a new anonymous SyncStatusObserver. It's attached to the app's ContentResolver in
* onResume(), and removed in onPause(). If a sync is active or pending, a progress bar is
* shown.
*/
private val syncStatusObserver = object : SyncStatusObserver {
/** Callback invoked with the sync adapter status changes. */
override fun onStatusChanged(which: Int) {
runOnUiThread(Runnable {
/**
* The SyncAdapter runs on a background thread. To update the
* UI, onStatusChanged() runs on the UI thread.
*/
val account = AccountUtils.getAccount(this@BaseTopActivity)
if (account == null) {
// no account setup
setSyncProgressVisibility(false)
return@Runnable
}
// Test the ContentResolver to see if the sync adapter is active.
val syncActive = ContentResolver.isSyncActive(
account, SgApp.CONTENT_AUTHORITY
)
setSyncProgressVisibility(syncActive)
})
}
}
companion object {
private const val OPTIONS_SWITCH_THEME_ID = 0
}
} | apache-2.0 | 9170e398931d7909df0b3f525d0d8697 | 36.320652 | 100 | 0.602563 | 5.253634 | false | false | false | false |
PrashamTrivedi/AndroidExternalFileWriter | androidexternalfilewriter-kotlin/src/main/java/com/celites/androidexternalfilewriter_kotlin/KotlinStorageAccessFileWriter.kt | 1 | 15213 | package com.celites.androidexternalfilewriter_kotlin
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.preference.PreferenceManager
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.provider.DocumentFile
import android.text.TextUtils
import com.celites.kutils.isEmptyString
import com.celites.kutils.remove
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
/**
* Created by Prasham on 4/11/2016.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class KotlinStorageAccessFileWriter(private val requestCode: Int) {
public val PARENT_URI_KEY = "APP_EXTERNAL_PARENT_FILE_URI"
var activity: Activity? = null
set(value) {
value?.let {
field = value
context = value
initProcessWithActivity(requestCode, value)
}
}
var fragment: Fragment? = null
set(value) {
value?.let {
field = value
context = value.context as Context
initProcessWithFragment(requestCode, value)
}
}
public fun startWithContext(context: Context) {
this.context = context
val isExternalDirAvailable = isExternalDirAvailable()
if (isExternalDirAvailable) {
createAppDirectory()
}
}
lateinit var context: Context
lateinit var appCacheDirectory: DocumentFile
lateinit var appDirectory: DocumentFile
lateinit var externalCacheDirectory: DocumentFile
lateinit var externalParentFile: DocumentFile
lateinit var preferences: SharedPreferences
private val canNotCreateDirectory = "Can not create directory: "
private val canNotWriteFile = "Can not write file: "
@RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun initProcessWithActivity(requestCode: Int,
activity: Activity) {
initCacheDirs()
preferences = PreferenceManager.getDefaultSharedPreferences(context)
val isExternalDirAvailable = isExternalDirAvailable()
if (!isExternalDirAvailable) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
activity.startActivityForResult(intent, requestCode)
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun initProcessWithFragment(requestCode: Int,
fragment: Fragment) {
initCacheDirs()
preferences = PreferenceManager.getDefaultSharedPreferences(context)
val isExternalDirAvailable = isExternalDirAvailable()
if (!isExternalDirAvailable) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
fragment.startActivityForResult(intent, requestCode)
}
}
fun isExternalDirAvailable(context: Context = this.context): Boolean {
initCacheDirs(context)
preferences = PreferenceManager.getDefaultSharedPreferences(context)
val externalDirUrl = preferences.getString(PARENT_URI_KEY, "")
val isExternalDirEmpty = externalDirUrl.isEmptyString()
if (!isExternalDirEmpty) {
externalParentFile = DocumentFile.fromTreeUri(context, Uri.parse(externalDirUrl))
try {
createAppDirectory(context)
} catch (e: Exception) {
preferences.remove(PARENT_URI_KEY)
return false
}
}
return !isExternalDirEmpty
}
private fun initCacheDirs(context: Context = this.context) {
val dirs = ContextCompat.getExternalCacheDirs(context)
externalCacheDirectory = if (dirs.size > 1) {
val dir = dirs[1]
if (dir != null) {
DocumentFile.fromFile(dir)
} else {
DocumentFile.fromFile(dirs[0])
}
} else {
DocumentFile.fromFile(dirs[0])
}
}
/**
* Creates subdirectory in parent directory
* @param parentDirectory
* * : Parent directory where directory with "directoryName" should be created
* *
* @param displayName
* * name of subdirectory
* *
* *
* @return File object of created subdirectory
* *
* *
* @throws ExternalFileWriterException
* * if external storage is not available
*/
fun createSubDirectory(displayName: String, parentDirectory: DocumentFile): DocumentFile {
getAppDirectory()
return if (isDirectoryExists(displayName, parentDirectory)) {
parentDirectory.createDirectory(displayName)
} else {
parentDirectory.findFile(displayName)
}
}
/**
* Check whether directory with given name exists in parentDirectory or not.
* @param directoryName
* * : Name of the directory to check.
* *
* @param parentDirectory
* * : Parent directory where directory with "directoryName" should be present
* *
* *
* @return true if a directory with "directoryName" exists, false otherwise
*/
fun isDirectoryExists(displayName: String, parentDirectory: DocumentFile): Boolean {
val file = parentDirectory.findFile(displayName)
return file != null && file.isDirectory
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun hasPermissions(file: DocumentFile): Boolean {
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
val filterForPermission = persistedUriPermissions.filter { it.uri == file.uri && it.isReadPermission && it.isWritePermission }
return filterForPermission.isNotEmpty()
}
/** Creates app directory */
private fun createAppDirectory(context: Context = this.context) {
val directoryName = context.getString(context.applicationInfo.labelRes)
appDirectory = if (isDirectoryExists(directoryName, externalParentFile)) {
externalParentFile.findFile(directoryName)
} else {
externalParentFile.createDirectory(directoryName)
}
appCacheDirectory = if (isDirectoryExists(directoryName, externalCacheDirectory)) {
externalCacheDirectory.findFile(directoryName)
} else {
externalCacheDirectory.createDirectory(directoryName)
}
}
/**
* Creates subdirectory in application directory
* @param directoryName
* * name of subdirectory
* *
* *
* @return File object of created subdirectory
* *
* *
* @throws ExternalFileWriterException
* * if external storage is not available
*/
fun createSubdirectory(directoryName: String, inCache: Boolean = false): DocumentFile? {
getAppDirectory()
val appDirectory = getAppDirectory(inCache)
return if (!isDirectoryExists(directoryName, inCache)) {
appDirectory.createDirectory(directoryName)
} else {
appDirectory.findFile(directoryName)
}
}
fun getAppDirectory(inCache: Boolean = false): DocumentFile {
return if (inCache) appCacheDirectory else appDirectory
}
/**
* Checks whether directory with given name exists in AppDirectory
* @param directoryName
* * : Name of the directory to check.
* *
* *
* @return true if a directory with "directoryName" exists, false otherwise
*/
fun isDirectoryExists(displayName: String, inCache: Boolean): Boolean {
val file = getDocumentFile(displayName, inCache)
return file != null && file.isDirectory
}
private fun getDocumentFile(displayName: String, inCache: Boolean): DocumentFile? {
val appDirectory = getAppDirectory(inCache)
return appDirectory.findFile(displayName)
}
fun handleResult(requestCode: Int, resultCode: Int, data: Intent?,
handlingFinished: () -> Unit = {},
askForPersistableUriPermission: Boolean = true) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == this.requestCode) {
data?.let {
val treeUri = it.data
if (askForPersistableUriPermission) {
val takeFlags = it.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
context.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
}
externalParentFile = DocumentFile.fromTreeUri(context, treeUri)
preferences.edit().putString(PARENT_URI_KEY, externalParentFile.uri.toString()).apply()
createAppDirectory()
handlingFinished()
}
}
}
}
/**
* Check whether file with given name exists in parentDirectory or not.
* @param fileName
* * : Name of the file to check.
* *
* @param parentDirectory
* * : Parent directory where directory with "fileName" should be present
* *
* *
* @return true if a file with "fileName" exists, false otherwise
*/
fun isFileExists(displayName: String, inCache: Boolean = false): Boolean {
val file = getDocumentFile(displayName, inCache)
return file != null && file.isFile
}
@Throws(FileNotFoundException::class)
fun writeDataToFile(fileName: String, mimeType: String, data: ByteArray,
inCache: Boolean = false) {
val appDir = getAppDirectory(inCache)
writeDataToFile(appDir, fileName, data, mimeType)
}
/**
* Writes data to the file. The file will be created in the directory name same as app.
* @param fileName
* * name of the file
* *
* @param data
* * data to write
* *
* *
* @throws ExternalFileWriterException
* * if external storage is not available or free space is less than size of the data
*/
@Throws(FileNotFoundException::class)
fun writeDataToFile(parent: DocumentFile, fileName: String, data: ByteArray, mimeType: String,
onFileWritten: (DocumentFile) -> Unit = {}) {
val file = createFile(fileName, parent, mimeType)
writeDataToFile(file = file, data = data, onFileWritten = onFileWritten)
}
private fun createFile(fileName: String, parent: DocumentFile,
mimeType: String) = if (!isFileExists(fileName, parent)) {
parent.createFile(mimeType, fileName)
} else {
parent.findFile(fileName)
}
/**
* Write byte array to file. Will show error if given file is a directory.
* @param file
* * : File where data is to be written.
* *
* @param data
* * byte array which you want to write a file. If size of this is greater than size available, it will show error.
*/
@Throws(FileNotFoundException::class) private fun writeDataToFile(file: DocumentFile,
data: ByteArray,
onFileWritten: (DocumentFile) -> Unit = {}) {
val fileDescriptor = context.contentResolver.openFileDescriptor(file.uri, "w")
val out: FileOutputStream?
if (fileDescriptor != null) {
out = FileOutputStream(fileDescriptor.fileDescriptor)
try {
out.write(data)
out.close()
onFileWritten(file)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
/**
* Checks whether file with given name exists in AppDirectory
* @param fileName
* * : Name of the file to check.
* *
* *
* @return true if a file with "directoryName" exists, false otherwise
*/
fun isFileExists(displayName: String, parentDirectory: DocumentFile): Boolean {
val file = parentDirectory.findFile(displayName)
return file != null && file.isFile
}
@Throws(FileNotFoundException::class)
fun writeDataToFile(fileName: String, mimeType: String, data: String, inCache: Boolean,
onFileWritten: (DocumentFile) -> Unit = {}) {
val appDir = getAppDirectory(inCache)
writeDataToFile(parent = appDir, fileName = fileName, data = data, mimeType = mimeType,
onFileWritten = onFileWritten)
}
/**
* Write data in file of a parent directory
* @param parent
* * parent directory
* *
* @param fileName
* * desired filename
* *
* @param data
* * data
* *
* *
* @throws ExternalFileWriterException
* * if external storage is not available or free space is less than size of the data
*/
@Throws(FileNotFoundException::class)
fun writeDataToFile(parent: DocumentFile, fileName: String, data: String, mimeType: String,
onFileWritten: (DocumentFile) -> Unit = {}) {
val file = createFile(fileName, parent, mimeType)
writeDataToFile(file = file, data = data, onFileWritten = onFileWritten)
}
/**
* Write byte array to file. Will show error if given file is a directory.
* @param file
* * : File where data is to be written.
* *
* @param data
* * String which you want to write a file. If size of this is greater than size available, it will show error.
*/
@Throws(FileNotFoundException::class) private fun writeDataToFile(file: DocumentFile,
data: String,
onFileWritten: (DocumentFile) -> Unit = {}) {
val stringBuffer = data.toByteArray()
writeDataToFile(file = file, data = stringBuffer, onFileWritten = onFileWritten)
}
@Throws(FileNotFoundException::class)
fun writeDataToTimeStampedFile(mimeType: String, data: String, extension: String,
filePrefix: String = "", inCache: Boolean,
onFileWritten: (DocumentFile) -> Unit = {}) {
val appDir = getAppDirectory(inCache)
val fileExtension = if (TextUtils.isEmpty(extension)) "" else "." + extension
val fileName = "$filePrefix${System.currentTimeMillis()}$fileExtension"
writeDataToFile(parent = appDir, fileName = fileName, data = data, mimeType = mimeType,
onFileWritten = onFileWritten)
}
@Throws(FileNotFoundException::class)
fun writeDataToTimeStampedFile(mimeType: String, data: ByteArray, extension: String,
filePrefix: String = "", inCache: Boolean,
onFileWritten: (DocumentFile) -> Unit) {
val appDir = getAppDirectory(inCache)
val fileExtension = if (TextUtils.isEmpty(extension)) "" else "." + extension
val fileName = "$filePrefix${System.currentTimeMillis()}$fileExtension"
writeDataToFile(parent = appDir, fileName = fileName, data = data, mimeType = mimeType,
onFileWritten = onFileWritten)
}
@Throws(FileNotFoundException::class)
fun writeDataToTimeStampedFile(mimeType: String, data: String, extension: String, filePrefix: String = "", parent: DocumentFile,
onFileWritten: (DocumentFile) -> Unit = {}) {
val fileExtension = if (TextUtils.isEmpty(extension)) "" else "." + extension
val fileName = "$filePrefix${System.currentTimeMillis()}$fileExtension"
writeDataToFile(parent = parent, fileName = fileName, data = data, mimeType = mimeType,
onFileWritten = onFileWritten)
}
@Throws(FileNotFoundException::class)
fun writeDataToTimeStampedFile(mimeType: String, data: ByteArray, extension: String, filePrefix: String = "", parent: DocumentFile,
onFileWritten: (DocumentFile) -> Unit = {}) {
val fileExtension = if (TextUtils.isEmpty(extension)) "" else "." + extension
val fileName = "$filePrefix${System.currentTimeMillis()}$fileExtension"
writeDataToFile(parent = parent, fileName = fileName, data = data, mimeType = mimeType,
onFileWritten = onFileWritten)
}
private fun createFile(fileName: String, inCache: Boolean, mimeType: String): DocumentFile {
return createFile(fileName, getAppDirectory(inCache), mimeType)
}
public fun moveFile(file: DocumentFile, destinationDir: DocumentFile): Boolean {
copyFile(destinationDir, file)
return file.delete()
}
public fun KotlinStorageAccessFileWriter.copyFile(destinationDir: DocumentFile,
file: DocumentFile,
onFileWritten: (DocumentFile) -> Unit = {}) {
val bytesFromFile = getBytesFromFile(file)
writeDataToFile(parent = destinationDir, fileName = file.name, data = bytesFromFile,
mimeType = file.type, onFileWritten = onFileWritten)
}
public fun getBytesFromFile(file: DocumentFile): ByteArray {
val inputStream = context.contentResolver.openInputStream(file.uri)
return inputStream.readBytes()
}
} | apache-2.0 | bd5041fe5939ab990c2502ed3afc7a5d | 31.859611 | 132 | 0.72162 | 4.086221 | false | false | false | false |
dslomov/intellij-community | plugins/settings-repository/src/util.kt | 26 | 1111 | /*
* 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.intellij.openapi.util.text.StringUtil
import java.nio.ByteBuffer
public fun String?.nullize(): String? = StringUtil.nullize(this)
public fun byteBufferToBytes(byteBuffer: ByteBuffer): ByteArray {
if (byteBuffer.hasArray() && byteBuffer.arrayOffset() == 0) {
val bytes = byteBuffer.array()
if (bytes.size() == byteBuffer.limit()) {
return bytes
}
}
val bytes = ByteArray(byteBuffer.limit())
byteBuffer.get(bytes)
return bytes
} | apache-2.0 | c18b493aac4bc23d6a25114248386fa4 | 31.705882 | 75 | 0.732673 | 4.084559 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/types/RustUnitType.kt | 1 | 888 | package org.rust.lang.core.types
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.RustFnElement
import org.rust.lang.core.psi.RustTraitItemElement
import org.rust.lang.core.types.unresolved.RustUnresolvedTypeBase
import org.rust.lang.core.types.visitors.RustTypeVisitor
import org.rust.lang.core.types.visitors.RustUnresolvedTypeVisitor
object RustUnitType : RustUnresolvedTypeBase(), RustType {
override fun getTraitsImplementedIn(project: Project): Sequence<RustTraitItemElement> =
emptySequence()
override fun getNonStaticMethodsIn(project: Project): Sequence<RustFnElement> =
emptySequence()
override fun <T> accept(visitor: RustTypeVisitor<T>): T = visitor.visitUnitType(this)
override fun <T> accept(visitor: RustUnresolvedTypeVisitor<T>): T = visitor.visitUnitType(this)
override fun toString(): String = "()"
}
| mit | be526f7794cf9084d1c6cfebb24c5290 | 36 | 99 | 0.782658 | 3.946667 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/ui/auth/AuthActivity.kt | 1 | 4106 | package com.jeremiahzucker.pandroid.ui.auth
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
import com.jeremiahzucker.pandroid.R
import com.jeremiahzucker.pandroid.ui.base.BaseActivity
import com.jeremiahzucker.pandroid.ui.main.MainActivity
import kotlinx.android.synthetic.main.activity_auth.*
/**
* AuthActivity
*
* Author: Jeremiah Zucker
* Date: 8/29/2017
* Desc: A login screen that offers login via username/password.
*/
class AuthActivity : BaseActivity(), AuthContract.View {
private val TAG: String = AuthActivity::class.java.simpleName
private var presenter: AuthContract.Presenter = AuthPresenter() // TODO: Inject
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
// Set up the login form.
password.setOnEditorActionListener(
TextView.OnEditorActionListener { _, id, _ ->
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin()
return@OnEditorActionListener true
}
false
}
)
sign_in_button.setOnClickListener { attemptLogin() }
}
override fun onResume() {
super.onResume()
presenter.attach(this)
}
override fun onPause() {
super.onPause()
presenter.detach()
}
/**
* Shows the progress UI and hides the login form.
*/
override fun showProgress(show: Boolean) {
val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
login_form.visibility = if (show) View.GONE else View.VISIBLE
login_form.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 0 else 1).toFloat())
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
login_form.visibility = if (show) View.GONE else View.VISIBLE
}
}
)
login_progress.visibility = if (show) View.VISIBLE else View.GONE
login_progress.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 1 else 0).toFloat())
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
login_progress.visibility = if (show) View.VISIBLE else View.GONE
}
}
)
}
override fun showMain() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
override fun clearErrors() {
password.error = null
username.error = null
}
override fun showErrorUsernameRequired() = showErrorOnField(username, getString(R.string.error_field_required))
override fun showErrorUsernameInvalid() = showErrorOnField(username, getString(R.string.error_invalid_username))
override fun showErrorPasswordRequired() = showErrorOnField(password, getString(R.string.error_field_required))
override fun showErrorPasswordInvalid() = showErrorOnField(password, getString(R.string.error_invalid_password))
override fun showErrorPasswordIncorrect() = showErrorOnField(password, getString(R.string.error_incorrect_password))
override fun showErrorNetwork(throwable: Throwable) {
Snackbar.make(auth_root, throwable.message.toString(), Snackbar.LENGTH_LONG)
}
private fun showErrorOnField(view: EditText, error: String) {
view.error = error
view.requestFocus()
}
private fun attemptLogin() {
presenter.attemptLogin(username.text.toString(), password.text.toString())
}
}
| mit | f227f92fb66afb48a07386852d8ccb26 | 34.704348 | 120 | 0.652947 | 4.807963 | false | false | false | false |
Bettehem/Messenger | app/src/main/java/com/github/bettehem/messenger/tools/ui/CustomNotification.kt | 1 | 2721 | package com.github.bettehem.messenger.tools.ui
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.support.v4.app.NotificationCompat
import com.github.bettehem.androidtools.notification.CustomNotification
import com.github.bettehem.messenger.MainActivity
import com.github.bettehem.messenger.R
@JvmOverloads fun notification(context: Context, title: String, message: String, isSecretMessage: Boolean, intent : Intent = Intent(context, MainActivity::class.java)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "messenger_notification"
val channelName = "Messenger Notifications"
val channelDescription = "Shows notifications when you get a message or request etc."
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, channelName, importance)
channel.description = channelDescription
//set notification light
channel.enableLights(true)
channel.lightColor = Color.MAGENTA
channel.enableVibration(true)
//create channel
notificationManager.createNotificationChannel(channel)
//create notification
val notificationBuilder = NotificationCompat.Builder(context, channelId)
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
notificationBuilder.setContentTitle(title)
notificationBuilder.setContentText(message)
notificationBuilder.setChannelId(channelId)
notificationBuilder.setContentIntent(PendingIntent.getActivity(context, context.hashCode(), intent, PendingIntent.FLAG_ONE_SHOT))
notificationBuilder.setAutoCancel(true)
notificationBuilder.setStyle(NotificationCompat.BigTextStyle().bigText(message))
val notification = notificationBuilder.build()
notificationManager.notify(channel.id.hashCode(), notification)
} else {
//TODO: implement user icons
//TODO: add settings check if has notifications disabled
if (isSecretMessage) {
//TODO: Remove hard-coded string
CustomNotification.make(context, R.mipmap.ic_launcher, title, message, Intent(context, MainActivity::class.java), false, true).show()
} else {
CustomNotification.make(context, R.mipmap.ic_launcher, title, message, Intent(context, MainActivity::class.java), false, true).show()
}
}
} | gpl-3.0 | 1c48b4284d7dc64fb99b4c638c2d470d | 45.931034 | 169 | 0.747152 | 5.057621 | false | false | false | false |
pixis/TraktTV | app/src/main/java/com/pixis/traktTV/screen_main/MainActivity.kt | 2 | 2537 | package com.pixis.traktTV.screen_main
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.MenuItem
import com.pixis.traktTV.R
class MainActivity: AppCompatActivity() {
lateinit var drawerLayout: DrawerLayout
lateinit var viewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout
setSupportActionBar(findViewById(R.id.toolbar) as Toolbar)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener { menuItem ->
menuItem.isChecked = true
onOptionsItemSelected(menuItem)
drawerLayout.closeDrawers()
true
}
viewPager = findViewById(R.id.viewpager) as ViewPager
viewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
val fragments = listOf(MoviesFragment(), ShowsFragment(), MoviesFragment())
val titles = listOf("Trending Movies", "Trending Shows", "Watchlist")
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
override fun getPageTitle(position: Int): CharSequence {
return titles[position]
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
android.R.id.home -> {
drawerLayout.openDrawer(Gravity.START)
return true
}
R.id.nav_movies -> {viewPager.setCurrentItem(0, false); return true}
R.id.nav_shows -> {viewPager.setCurrentItem(1, false); return true}
R.id.nav_watchlist -> {viewPager.setCurrentItem(2, false); return true}
else -> super.onOptionsItemSelected(item)
}
}
} | apache-2.0 | 4143b3ea0129eaf060a436dcd6642e6c | 35.257143 | 87 | 0.671659 | 5.003945 | false | false | false | false |
robinverduijn/gradle | subprojects/instant-execution-report/src/main/kotlin/elmish/Component.kt | 1 | 2206 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package elmish
import org.w3c.dom.Element
import kotlin.browser.document
/**
* An user interface component built according to [the Elm Architecture](https://guide.elm-lang.org/architecture/)
* pattern.
*
* @param M the model type (also called the state type)
* @param I the intent type (also called the update, action or message type)
*/
interface Component<M, I> {
fun view(model: M): View<I>
fun step(intent: I, model: M): M
}
/**
* Defines a [Component] given its [view] and [step] functions.
*
* ```
* mountComponentAt(
* elementById("playground"),
* component<Int, Unit>(
* view = { model ->
* span(
* attributes {
* onClick { Unit }
* },
* "You clicked me $model time(s)."
* )
* },
* step = { _, model ->
* model + 1
* }
* ),
* 0
* )
* ```
*/
fun <M, I> component(view: (M) -> View<I>, step: (I, M) -> M): Component<M, I> = object : Component<M, I> {
override fun view(model: M): View<I> = view(model)
override fun step(intent: I, model: M): M = step(intent, model)
}
fun <M, I> mountComponentAt(
element: Element,
component: Component<M, I>,
init: M
) {
fun loop(model: M) {
render(
component.view(model),
into = element
) { intent -> loop(component.step(intent, model)) }
}
loop(init)
println("Component mounted at #${element.id}.")
}
fun elementById(id: String): Element =
document.getElementById(id) ?: throw IllegalStateException("'$id' element missing")
| apache-2.0 | 7d0090b87d2296a8269a5d61bbbee9a7 | 24.356322 | 114 | 0.615141 | 3.569579 | false | false | false | false |
7hens/KDroid | sample/src/test/java/cn/thens/kdroid/ml/util/GaussianDistribution.kt | 1 | 822 | package cn.thens.kdroid.ml.util
import androidx.annotation.FloatRange
import java.util.*
class GaussianDistribution(private val mean: Double, @FloatRange(from = 0.0) private val variance: Double, private val random: Random = Random()) {
init {
if (variance < 0.0) {
throw IllegalArgumentException("Variance must be non-negative value.")
}
}
fun random(): Double {
var r = 0.0
while (r == 0.0) {
r = random.nextDouble()
}
val c = Math.sqrt(-2.0 * Math.log(r))
return if (random.nextDouble() < 0.5) {
c * Math.sin(2.0 * Math.PI * random.nextDouble()) * variance + mean
} else {
c * Math.cos(2.0 * Math.PI * random.nextDouble()) * variance + mean
}
}
} | apache-2.0 | de3ef4c991786f1e9d1061abdc79603e | 25.466667 | 147 | 0.545012 | 3.877358 | false | false | false | false |
iZettle/wrench | wrench-app/src/main/java/com/izettle/wrench/oss/list/OssLoading.kt | 1 | 3495 | package com.izettle.wrench.oss.list
import android.content.Context
import com.izettle.wrench.oss.LicenceMetadata
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.util.*
object OssLoading {
fun getThirdPartyLicenceMetadata(context: Context): ArrayList<LicenceMetadata> {
val thirdPartyLicenseMetadata = resourcePartToString(context.applicationContext, "third_party_license_metadata", 0L, -1)
val thirdPartyLicences = thirdPartyLicenseMetadata.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val licenceMetadataArrayList = ArrayList<LicenceMetadata>(thirdPartyLicences.size)
for (licenceString in thirdPartyLicences) {
val indexOfSpace = licenceString.indexOf(' ')
val byteInformation = licenceString.substring(0, indexOfSpace).split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val validByteInformation = byteInformation.size == 2 && indexOfSpace > 0
if (!validByteInformation) {
if (licenceString.isNotEmpty()) {
throw IllegalStateException("Invalid license meta-data line:\n$licenceString")
} else {
throw IllegalStateException("Invalid license meta-data line:\n")
}
}
val byteStart = java.lang.Long.parseLong(byteInformation[0])
val byteEnd = Integer.parseInt(byteInformation[1])
licenceMetadataArrayList.add(LicenceMetadata(licenceString.substring(indexOfSpace + 1), byteStart, byteEnd))
}
return licenceMetadataArrayList
}
fun getThirdPartyLicence(context: Context, licenceMetadata: LicenceMetadata): String {
val skipBytes = licenceMetadata.skipBytes
val length = licenceMetadata.length
return resourcePartToString(context, "third_party_licenses", skipBytes, length)
}
private fun resourcePartToString(context: Context, resourceName: String, skipBytes: Long, length: Int): String {
val resources = context.resources
return inputStreamPartToString(resources.openRawResource(resources.getIdentifier(resourceName, "raw", context.packageName)), skipBytes, length)
}
private fun inputStreamPartToString(inputStream: InputStream, skipBytes: Long, length: Int): String {
val buffer = ByteArray(1024)
val byteArrayOutputStream = ByteArrayOutputStream()
try {
inputStream.skip(skipBytes)
val totalBytesToRead = if (length > 0) length else Integer.MAX_VALUE
var bytesLeftToRead = totalBytesToRead
while (true) {
val bytesRead = inputStream.read(buffer, 0, Math.min(bytesLeftToRead, 1024))
if (bytesLeftToRead <= 0 || bytesRead == -1) {
inputStream.close()
break
}
byteArrayOutputStream.write(buffer, 0, bytesRead)
bytesLeftToRead -= bytesRead
}
} catch (exception: IOException) {
throw RuntimeException("Failed to read license or metadata text.", exception)
}
try {
return byteArrayOutputStream.toString("UTF-8")
} catch (exception: UnsupportedEncodingException) {
throw RuntimeException("Unsupported encoding UTF8. This should always be supported.", exception)
}
}
}
| mit | fe61b80eff2e4cbaf45cbe710f0d5382 | 43.240506 | 151 | 0.66867 | 5.109649 | false | true | false | false |
nasahapps/Material-Design-Toolbox | app/src/main/java/com/nasahapps/mdt/example/ui/mock/MockFragment.kt | 1 | 1088 | package com.nasahapps.mdt.example.ui.mock
import android.os.Bundle
import android.support.v4.widget.TextViewCompat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nasahapps.mdt.example.ui.BaseFragment
/**
* Created by Hakeem on 4/17/16.
*/
class MockFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = TextView(context)
TextViewCompat.setTextAppearance(v, android.support.v7.appcompat.R.style.TextAppearance_AppCompat)
v.text = "Page ${arguments.getInt(EXTRA_PAGE)}"
v.gravity = Gravity.CENTER
return v
}
companion object {
private val EXTRA_PAGE = "page"
fun newInstance(page: Int): MockFragment {
val args = Bundle()
args.putInt(EXTRA_PAGE, page)
val fragment = MockFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | fdac8e1b988562da1003feff3ab28143 | 26.2 | 117 | 0.681985 | 4.184615 | false | false | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/view/ShrinkTextView.kt | 1 | 2239 | package jp.blanktar.ruumusic.view
import android.widget.TextView
import android.content.Context
import android.util.AttributeSet
import android.graphics.Paint
import android.util.TypedValue
class ShrinkTextView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {
val namespace = "http://ruumusic.blanktar.jp/view"
var minTextSize = attrs.getAttributeFloatValue(namespace, "min_size", 0.0f)
set(x) {
field = x
updateTextSize()
}
val firstLineMinTextSize: Float
get() {
if (secondLine) {
return (maxTextSize + minTextSize) * 0.5f
} else {
return minTextSize
}
}
var maxTextSize = attrs.getAttributeFloatValue(namespace, "max_size", 120.0f)
set(x) {
field = x
updateTextSize()
}
var secondLine = attrs.getAttributeBooleanValue(namespace, "secondLine", false)
set(x) {
field = x
updateTextSize()
}
var resizingEnabled = true
fun calcTextWidth(size: Float): Float {
val p = Paint()
p.textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, resources.displayMetrics)
return p.measureText(text.toString())
}
fun updateTextSize() {
if (!resizingEnabled) {
textSize = maxTextSize
return
}
var temp = maxTextSize
while (measuredWidth < calcTextWidth(temp) && temp > firstLineMinTextSize) {
temp--
}
if (secondLine && measuredWidth < calcTextWidth(temp)) {
while (measuredWidth * 1.8 > calcTextWidth(temp) && temp < maxTextSize) {
temp++
}
while (measuredWidth * 1.8 < calcTextWidth(temp) && temp > minTextSize) {
temp--
}
}
textSize = temp
}
override fun onMeasure(width: Int, height: Int) {
super.onMeasure(width, height)
if (measuredWidth > 0) {
updateTextSize()
}
}
override fun setText(text: CharSequence, buf: TextView.BufferType) {
super.setText(text, buf)
updateTextSize()
}
}
| mit | 7372c51766da92aacd76e67892856f20 | 25.341176 | 106 | 0.575257 | 4.550813 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/PreferenceGroup.kt | 1 | 3330 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.components
import androidx.compose.animation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.ContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.material3.MaterialTheme as Material3Theme
@Composable
fun PreferenceGroup(
modifier: Modifier = Modifier,
heading: String? = null,
description: String? = null,
showDescription: Boolean = true,
showDividers: Boolean = true,
dividerStartIndent: Dp = 0.dp,
dividerEndIndent: Dp = 0.dp,
dividersToSkip: Int = 0,
content: @Composable () -> Unit
) {
Column(modifier = modifier) {
PreferenceGroupHeading(heading)
Surface(
modifier = Modifier.padding(horizontal = 16.dp),
shape = MaterialTheme.shapes.large,
tonalElevation = 1.dp
) {
if (showDividers) {
DividerColumn(
startIndent = dividerStartIndent,
endIndent = dividerEndIndent,
content = content,
dividersToSkip = dividersToSkip
)
} else {
Column {
content()
}
}
}
PreferenceGroupDescription(description, showDescription)
}
}
@Composable
fun PreferenceGroupHeading(heading: String?) {
if (heading != null) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier
.height(48.dp)
.padding(horizontal = 32.dp)
.fillMaxWidth(),
) {
Text(
text = heading,
style = Material3Theme.typography.titleSmall,
color = Material3Theme.colorScheme.primary,
)
}
} else {
Spacer(modifier = Modifier.requiredHeight(8.dp))
}
}
@Composable
fun PreferenceGroupDescription(description: String? = null, showDescription: Boolean = true) {
description?.let {
ExpandAndShrink(visible = showDescription) {
Row(modifier = Modifier.padding(start = 32.dp, end = 32.dp, top = 16.dp)) {
Text(
text = it,
style = Material3Theme.typography.bodyMedium,
color = LocalContentColor.current.copy(alpha = ContentAlpha.medium)
)
}
}
}
}
| gpl-3.0 | 1c6e57728fbc4bb1a3c5005e7ad226e2 | 31.647059 | 94 | 0.623423 | 4.690141 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/test/kotlin/net/dinkla/raytracer/lights/PointLightTest.kt | 1 | 849 | package net.dinkla.raytracer.lights
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.math.Point3D
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class PointLightTest {
@Test
fun `construct a point light with defaults for ls and color`() {
val location = Point3D(1, 2, 3)
val p = PointLight(location)
assertEquals(1.0, p.ls)
assertEquals(Color.WHITE, p.color)
assertEquals(location, p.location)
}
@Test
fun `construct a point light without defaults`() {
val location = Point3D(1, 2, 3)
val ls = 0.12
val color = Color(0.12, 0.23, 0.34)
val p = PointLight(location, ls, color)
assertEquals(ls, p.ls)
assertEquals(color, p.color)
assertEquals(location, p.location)
}
} | apache-2.0 | f2ed019a835725b3a33669143381a128 | 28.310345 | 68 | 0.652532 | 3.659483 | false | true | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/bugreport/UploaderService.kt | 1 | 2176 | package app.lawnchair.bugreport
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.android.launcher3.R
import kotlinx.coroutines.*
import java.util.*
class UploaderService : Service() {
private var job: Job? = null
private val scope = CoroutineScope(Dispatchers.IO) + CoroutineName("UploaderService")
private val uploadQueue: Queue<BugReport> = LinkedList()
override fun onBind(intent: Intent): IBinder {
TODO("not implemented")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return START_REDELIVER_INTENT
uploadQueue.offer(intent.getParcelableExtra("report"))
if (job == null) {
job = scope.launch {
startUpload()
stopSelf()
}
}
return START_STICKY
}
private suspend fun startUpload() {
while (uploadQueue.isNotEmpty()) {
val report = uploadQueue.poll()!!
try {
report.link = UploaderUtils.upload(report)
} catch (e: Throwable) {
Log.d("UploaderService", "failed to upload bug report", e)
report.uploadError = true
} finally {
sendBroadcast(Intent(this, BugReportReceiver::class.java)
.setAction(BugReportReceiver.UPLOAD_COMPLETE_ACTION)
.putExtra("report", report))
}
}
}
override fun onCreate() {
super.onCreate()
Log.d("DUS", "onCreate")
startForeground(101, NotificationCompat.Builder(this, BugReportReceiver.statusChannelId)
.setSmallIcon(R.drawable.ic_bug_notification)
.setContentTitle(getString(R.string.dogbin_uploading))
.setColor(ContextCompat.getColor(this, R.color.bugNotificationColor))
.setPriority(NotificationCompat.PRIORITY_MIN)
.build())
}
override fun onDestroy() {
super.onDestroy()
job?.cancel()
}
}
| gpl-3.0 | c84a2a1d89cefce8fee197e76c8a912e | 31 | 96 | 0.620404 | 4.699784 | false | false | false | false |
Doctoror/FuckOffMusicPlayer | data/src/main/java/com/doctoror/fuckoffmusicplayer/data/playback/unit/PlaybackServiceUnitWakeLock.kt | 2 | 1832 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.data.playback.unit
import android.annotation.SuppressLint
import android.content.Context
import android.os.PowerManager
import android.support.annotation.VisibleForTesting
import com.doctoror.fuckoffmusicplayer.data.lifecycle.ServiceLifecycleObserver
@VisibleForTesting
const val WAKE_LOCK_TAG = "WakelockAcquirer"
class PlaybackServiceUnitWakeLock(private val context: Context) : ServiceLifecycleObserver {
private var wakeLock: PowerManager.WakeLock? = null
override fun onCreate() {
acquireWakeLock()
}
override fun onDestroy() {
releaseWakeLock()
}
@SuppressLint("WakelockTimeout") // Should be held until released.
private fun acquireWakeLock() {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager?
if (powerManager != null) {
val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG)
wakeLock.acquire()
this.wakeLock = wakeLock
}
}
private fun releaseWakeLock() {
wakeLock?.apply {
if (isHeld) {
release()
}
}
wakeLock = null
}
}
| apache-2.0 | 05b49deed1093c7fb1e6908bf3cdebc7 | 30.586207 | 98 | 0.702511 | 4.649746 | false | false | false | false |
MaisonWan/AppFileExplorer | FileExplorer/src/main/java/com/domker/app/explorer/fragment/PhoneInfoFragment.kt | 1 | 4062 | package com.domker.app.explorer.fragment
import android.Manifest
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import com.domker.app.explorer.R
import com.domker.app.explorer.helper.PermissionHelper
import com.domker.app.explorer.util.DrawableUtils
import com.domker.app.explorer.util.PhoneInfo
import com.domker.app.explorer.util.hideMenu
/**
* 手机信息
* @author wanlipeng
*/
class PhoneInfoFragment : BaseFragment() {
private lateinit var mAdapter: ArrayAdapter<String>
private val mData = ArrayList<String>()
private lateinit var mListView: ListView
private lateinit var permissionHelper: PermissionHelper
override fun init(context: Context, view: View) {
activity.title = getString(R.string.fe_title_phone_info)
mAdapter = ArrayAdapter(context, R.layout.fe_phone_info_item, mData)
mListView = view.findViewById(R.id.listView)
permissionHelper = PermissionHelper(context)
}
override fun initAssistButtonDrawable(context: Context): Drawable? {
return DrawableUtils.getDrawable(context, R.drawable.fe_ic_refresh_black)
}
override fun onAssistButtonClick(view: View) {
initData(activity)
mAdapter.notifyDataSetChanged()
mListView.smoothScrollToPosition(0)
}
override fun onShown(context: Context) {
if (permissionHelper.check(Manifest.permission.READ_PHONE_STATE)) {
initData(context)
}
mListView.adapter = mAdapter
}
override fun initLayoutId(): Int = R.layout.fe_phone_info_layout
override fun onBackPressed(): Boolean = false
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
menu?.hideMenu()
}
/**
* 初始化设备信息
*/
private fun initData(context: Context) {
val util = PhoneInfo(context)
mData.clear()
val totalMemory = util.getTotalMemory()
val showTotalMemory = String.format("Total Memory : %s", totalMemory)
mData.add(showTotalMemory)
val availMemory = util.getAvailMemory()
val showAvailMemory = String.format("Avail Memory : %s", availMemory)
mData.add(showAvailMemory)
val maxHeap = util.getAppMaxHeapSize()
val appMaxHeap = String.format("App Max Heap Size : %dKB(%.2fMB)", maxHeap, maxHeap / 1024.0f)
mData.add(appMaxHeap)
val totalHeap = util.getAppTotalHeapSize()
val appTotalHeap = String.format("App Total Heap Size : %dKB(%.2fMB)", totalHeap, totalHeap / 1024.0f)
mData.add(appTotalHeap)
val freeHeap = util.getAppFreeHeapSize()
val appFreeHeap = String.format("App Free Heap Size : %dKB(%.2fMB)", freeHeap, freeHeap / 1024.0f)
mData.add(appFreeHeap)
val sdkVersion = String.format("SDK Version : %s", util.getSdkVersion())
mData.add(sdkVersion)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 6.0以上新增,查看双卡信息
mData.add(String.format("IMEI-1 : %s", util.getImei(0)))
mData.add(String.format("IMEI-2 : %s", util.getImei(1)))
} else {
mData.add(String.format("IMEI : %s", util.getImei()))
}
val imsi = String.format("IMSI : %s", util.getImsi())
mData.add(imsi)
val androidId = String.format("Android ID : %s", util.getAndroidID())
mData.add(androidId)
val macAddress = String.format("Mac Address : %s", util.getMacAddress())
mData.add(macAddress)
mData.add("Screen Size : " + util.getScreenSize(activity))
mData.add("Scaled Density : " + util.getDpiDensity())
mData.add("Density DPI : " + util.getDensityDpi())
mData.add("Density: " + util.getDensity())
mData.addAll(util.getOsBuildInfo())
}
}
| apache-2.0 | 2309a0446b5f0f101e69e7ec38c41194 | 33.637931 | 110 | 0.66899 | 3.935357 | false | false | false | false |
http4k/http4k | http4k-testing/strikt/src/main/kotlin/org/http4k/strikt/uri.kt | 1 | 370 | package org.http4k.strikt
import org.http4k.core.Uri
import strikt.api.Assertion
val Assertion.Builder<Uri>.path get() = get(Uri::path)
val Assertion.Builder<Uri>.query get() = get(Uri::query)
val Assertion.Builder<Uri>.authority get() = get(Uri::authority)
val Assertion.Builder<Uri>.host get() = get(Uri::host)
val Assertion.Builder<Uri>.port get() = get(Uri::port)
| apache-2.0 | 9a88dbf30c24e4fe8670a056f08d1567 | 36 | 64 | 0.743243 | 3.109244 | false | false | false | false |
http4k/http4k | http4k-security/digest/src/main/kotlin/org/http4k/security/digest/DigestAuthProvider.kt | 1 | 2952 | package org.http4k.security.digest
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.security.NonceGenerator
import org.http4k.security.NonceVerifier
import java.security.MessageDigest
/**
* For use in servers. Verifies digest credentials and generates challenge responses
*
* TODO add support for opaque in challenge. Unknown if it needs to be verified, or how it should be generated (i.e. static, user-specific, etc.)
* The IOT device I used for testing constantly returned the same opaque
*/
enum class DigestMode(val authHeaderName: String, val challengeHeaderName: String) {
Standard("Authorization", "WWW-Authenticate"),
Proxy("Proxy-Authorization", "Proxy-Authenticate")
}
class DigestAuthProvider(
private val realm: String,
private val passwordLookup: (String) -> String?,
private val qop: List<Qop>,
private val algorithm: String,
private val nonceGenerator: NonceGenerator,
private val nonceVerifier: NonceVerifier = { true },
private val digestMode: DigestMode = DigestMode.Standard
) {
fun digestCredentials(request: Request): DigestCredential? {
return request
.header(digestMode.authHeaderName)
?.let { DigestCredential.fromHeader(it) }
}
fun verify(credentials: DigestCredential, method: Method): Boolean {
val digestEncoder = DigestEncoder(MessageDigest.getInstance("MD5"))
// verify credentials pertain to this provider
if (credentials.algorithm != null && credentials.algorithm != algorithm) return false
if (credentials.realm != realm) return false
if (!nonceVerifier(credentials.nonce)) return false
if (qop.isNotEmpty() && (credentials.qop == null || credentials.qop !in qop)) return false
if (qop.isEmpty() && credentials.qop != null) return false
// verify credentials digest matches expected digest
val password = passwordLookup(credentials.username) ?: return false
val expectedDigest = digestEncoder(
method = method,
realm = realm,
qop = credentials.qop,
username = credentials.username,
password = password,
nonce = credentials.nonce,
cnonce = credentials.cnonce,
nonceCount = credentials.nonceCount,
digestUri = credentials.digestUri
)
val incomingDigest = credentials.responseBytes()
return MessageDigest.isEqual(incomingDigest, expectedDigest)
}
fun generateChallenge(): Response {
val header = DigestChallenge(
realm = realm,
nonce = nonceGenerator(),
algorithm = algorithm,
qop = qop,
opaque = null
)
return Response(UNAUTHORIZED).header(digestMode.challengeHeaderName, header.toHeaderValue())
}
}
| apache-2.0 | 6b48ab977aba5d54787bde1f10449acb | 36.846154 | 146 | 0.682927 | 4.569659 | false | false | false | false |