repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/PropertiesDialog.kt | 1 | 16097 | package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.content.res.Resources
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.exifinterface.media.ExifInterface
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import kotlinx.android.synthetic.main.dialog_properties.view.*
import kotlinx.android.synthetic.main.item_property.view.*
import java.io.File
import java.util.*
class PropertiesDialog() {
private lateinit var mInflater: LayoutInflater
private lateinit var mPropertyView: ViewGroup
private lateinit var mResources: Resources
private lateinit var mActivity: Activity
private lateinit var mDialogView: View
private var mCountHiddenItems = false
/**
* A File Properties dialog constructor with an optional parameter, usable at 1 file selected
*
* @param activity request activity to avoid some Theme.AppCompat issues
* @param path the file path
* @param countHiddenItems toggle determining if we will count hidden files themselves and their sizes (reasonable only at directory properties)
*/
constructor(activity: Activity, path: String, countHiddenItems: Boolean = false) : this() {
if (!activity.getDoesFilePathExist(path) && !path.startsWith("content://")) {
activity.toast(String.format(activity.getString(R.string.source_file_doesnt_exist), path))
return
}
mActivity = activity
mInflater = LayoutInflater.from(activity)
mResources = activity.resources
mDialogView = mInflater.inflate(R.layout.dialog_properties, null)
mCountHiddenItems = countHiddenItems
mPropertyView = mDialogView.properties_holder!!
addProperties(path)
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
if (!path.startsWith("content://") && path.canModifyEXIF() && activity.isPathOnInternalStorage(path)) {
if ((isRPlus() && Environment.isExternalStorageManager()) || (!isRPlus() && activity.hasPermission(PERMISSION_WRITE_STORAGE))) {
builder.setNeutralButton(R.string.remove_exif, null)
}
}
builder.apply {
mActivity.setupDialogStuff(mDialogView, this, R.string.properties) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
removeEXIFFromPath(path)
}
}
}
}
private fun addProperties(path: String) {
val fileDirItem = FileDirItem(path, path.getFilenameFromPath(), mActivity.getIsPathDirectory(path))
addProperty(R.string.name, fileDirItem.name)
addProperty(R.string.path, fileDirItem.getParentPath())
addProperty(R.string.size, "…", R.id.properties_size)
ensureBackgroundThread {
val fileCount = fileDirItem.getProperFileCount(mActivity, mCountHiddenItems)
val size = fileDirItem.getProperSize(mActivity, mCountHiddenItems).formatSize()
val directChildrenCount = if (fileDirItem.isDirectory) {
fileDirItem.getDirectChildrenCount(mActivity, mCountHiddenItems).toString()
} else {
0
}
this.mActivity.runOnUiThread {
(mDialogView.findViewById<LinearLayout>(R.id.properties_size).property_value as TextView).text = size
if (fileDirItem.isDirectory) {
(mDialogView.findViewById<LinearLayout>(R.id.properties_file_count).property_value as TextView).text = fileCount.toString()
(mDialogView.findViewById<LinearLayout>(R.id.properties_direct_children_count).property_value as TextView).text =
directChildrenCount.toString()
}
}
if (!fileDirItem.isDirectory) {
val projection = arrayOf(MediaStore.Images.Media.DATE_MODIFIED)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${MediaStore.MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(path)
val cursor = mActivity.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val dateModified = cursor.getLongValue(MediaStore.Images.Media.DATE_MODIFIED) * 1000L
updateLastModified(mActivity, mDialogView, dateModified)
} else {
updateLastModified(mActivity, mDialogView, fileDirItem.getLastModified(mActivity))
}
}
val exif = if (isNougatPlus() && mActivity.isPathOnOTG(fileDirItem.path)) {
ExifInterface((mActivity as BaseSimpleActivity).getFileInputStreamSync(fileDirItem.path)!!)
} else if (isNougatPlus() && fileDirItem.path.startsWith("content://")) {
try {
ExifInterface(mActivity.contentResolver.openInputStream(Uri.parse(fileDirItem.path))!!)
} catch (e: Exception) {
return@ensureBackgroundThread
}
} else if (mActivity.isRestrictedSAFOnlyRoot(path)) {
try {
ExifInterface(mActivity.contentResolver.openInputStream(mActivity.getAndroidSAFUri(path))!!)
} catch (e: Exception) {
return@ensureBackgroundThread
}
} else {
try {
ExifInterface(fileDirItem.path)
} catch (e: Exception) {
return@ensureBackgroundThread
}
}
val latLon = FloatArray(2)
if (exif.getLatLong(latLon)) {
mActivity.runOnUiThread {
addProperty(R.string.gps_coordinates, "${latLon[0]}, ${latLon[1]}")
}
}
val altitude = exif.getAltitude(0.0)
if (altitude != 0.0) {
mActivity.runOnUiThread {
addProperty(R.string.altitude, "${altitude}m")
}
}
}
}
when {
fileDirItem.isDirectory -> {
addProperty(R.string.direct_children_count, "…", R.id.properties_direct_children_count)
addProperty(R.string.files_count, "…", R.id.properties_file_count)
}
fileDirItem.path.isImageSlow() -> {
fileDirItem.getResolution(mActivity)?.let { addProperty(R.string.resolution, it.formatAsResolution()) }
}
fileDirItem.path.isAudioSlow() -> {
fileDirItem.getDuration(mActivity)?.let { addProperty(R.string.duration, it) }
fileDirItem.getTitle(mActivity)?.let { addProperty(R.string.song_title, it) }
fileDirItem.getArtist(mActivity)?.let { addProperty(R.string.artist, it) }
fileDirItem.getAlbum(mActivity)?.let { addProperty(R.string.album, it) }
}
fileDirItem.path.isVideoSlow() -> {
fileDirItem.getDuration(mActivity)?.let { addProperty(R.string.duration, it) }
fileDirItem.getResolution(mActivity)?.let { addProperty(R.string.resolution, it.formatAsResolution()) }
fileDirItem.getArtist(mActivity)?.let { addProperty(R.string.artist, it) }
fileDirItem.getAlbum(mActivity)?.let { addProperty(R.string.album, it) }
}
}
if (fileDirItem.isDirectory) {
addProperty(R.string.last_modified, fileDirItem.getLastModified(mActivity).formatDate(mActivity))
} else {
addProperty(R.string.last_modified, "…", R.id.properties_last_modified)
try {
addExifProperties(path, mActivity)
} catch (e: Exception) {
mActivity.showErrorToast(e)
return
}
if (mActivity.baseConfig.appId.removeSuffix(".debug") == "com.simplemobiletools.filemanager.pro") {
addProperty(R.string.md5, "…", R.id.properties_md5)
ensureBackgroundThread {
val md5 = if (mActivity.isRestrictedSAFOnlyRoot(path)) {
mActivity.contentResolver.openInputStream(mActivity.getAndroidSAFUri(path))?.md5()
} else {
File(path).md5()
}
mActivity.runOnUiThread {
if (md5 != null) {
(mDialogView.findViewById<LinearLayout>(R.id.properties_md5).property_value as TextView).text = md5
} else {
mDialogView.findViewById<LinearLayout>(R.id.properties_md5).beGone()
}
}
}
}
}
}
private fun updateLastModified(activity: Activity, view: View, timestamp: Long) {
activity.runOnUiThread {
(view.findViewById<LinearLayout>(R.id.properties_last_modified).property_value as TextView).text = timestamp.formatDate(activity)
}
}
/**
* A File Properties dialog constructor with an optional parameter, usable at multiple items selected
*
* @param activity request activity to avoid some Theme.AppCompat issues
* @param path the file path
* @param countHiddenItems toggle determining if we will count hidden files themselves and their sizes
*/
constructor(activity: Activity, paths: List<String>, countHiddenItems: Boolean = false) : this() {
mActivity = activity
mInflater = LayoutInflater.from(activity)
mResources = activity.resources
mDialogView = mInflater.inflate(R.layout.dialog_properties, null)
mCountHiddenItems = countHiddenItems
mPropertyView = mDialogView.properties_holder
val fileDirItems = ArrayList<FileDirItem>(paths.size)
paths.forEach {
val fileDirItem = FileDirItem(it, it.getFilenameFromPath(), activity.getIsPathDirectory(it))
fileDirItems.add(fileDirItem)
}
val isSameParent = isSameParent(fileDirItems)
addProperty(R.string.items_selected, paths.size.toString())
if (isSameParent) {
addProperty(R.string.path, fileDirItems[0].getParentPath())
}
addProperty(R.string.size, "…", R.id.properties_size)
addProperty(R.string.files_count, "…", R.id.properties_file_count)
ensureBackgroundThread {
val fileCount = fileDirItems.sumByInt { it.getProperFileCount(activity, countHiddenItems) }
val size = fileDirItems.sumByLong { it.getProperSize(activity, countHiddenItems) }.formatSize()
activity.runOnUiThread {
(mDialogView.findViewById<LinearLayout>(R.id.properties_size).property_value as TextView).text = size
(mDialogView.findViewById<LinearLayout>(R.id.properties_file_count).property_value as TextView).text = fileCount.toString()
}
}
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
if (!paths.any { it.startsWith("content://") } && paths.any { it.canModifyEXIF() } && paths.any { activity.isPathOnInternalStorage(it) }) {
if ((isRPlus() && Environment.isExternalStorageManager()) || (!isRPlus() && activity.hasPermission(PERMISSION_WRITE_STORAGE))) {
builder.setNeutralButton(R.string.remove_exif, null)
}
}
builder.apply {
mActivity.setupDialogStuff(mDialogView, this, R.string.properties) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
removeEXIFFromPaths(paths)
}
}
}
}
private fun addExifProperties(path: String, activity: Activity) {
val exif = if (isNougatPlus() && activity.isPathOnOTG(path)) {
ExifInterface((activity as BaseSimpleActivity).getFileInputStreamSync(path)!!)
} else if (isNougatPlus() && path.startsWith("content://")) {
try {
ExifInterface(activity.contentResolver.openInputStream(Uri.parse(path))!!)
} catch (e: Exception) {
return
}
} else if (activity.isRestrictedSAFOnlyRoot(path)) {
try {
ExifInterface(activity.contentResolver.openInputStream(activity.getAndroidSAFUri(path))!!)
} catch (e: Exception) {
return
}
} else {
ExifInterface(path)
}
val dateTaken = exif.getExifDateTaken(activity)
if (dateTaken.isNotEmpty()) {
addProperty(R.string.date_taken, dateTaken)
}
val cameraModel = exif.getExifCameraModel()
if (cameraModel.isNotEmpty()) {
addProperty(R.string.camera, cameraModel)
}
val exifString = exif.getExifProperties()
if (exifString.isNotEmpty()) {
addProperty(R.string.exif, exifString)
}
}
private fun removeEXIFFromPath(path: String) {
ConfirmationDialog(mActivity, "", R.string.remove_exif_confirmation) {
try {
ExifInterface(path).removeValues()
mActivity.toast(R.string.exif_removed)
mPropertyView.properties_holder.removeAllViews()
addProperties(path)
} catch (e: Exception) {
mActivity.showErrorToast(e)
}
}
}
private fun removeEXIFFromPaths(paths: List<String>) {
ConfirmationDialog(mActivity, "", R.string.remove_exif_confirmation) {
try {
paths.filter { mActivity.isPathOnInternalStorage(it) && it.canModifyEXIF() }.forEach {
ExifInterface(it).removeValues()
}
mActivity.toast(R.string.exif_removed)
} catch (e: Exception) {
mActivity.showErrorToast(e)
}
}
}
private fun isSameParent(fileDirItems: List<FileDirItem>): Boolean {
var parent = fileDirItems[0].getParentPath()
for (file in fileDirItems) {
val curParent = file.getParentPath()
if (curParent != parent) {
return false
}
parent = curParent
}
return true
}
private fun addProperty(labelId: Int, value: String?, viewId: Int = 0) {
if (value == null) {
return
}
mInflater.inflate(R.layout.item_property, mPropertyView, false).apply {
property_value.setTextColor(mActivity.getProperTextColor())
property_label.setTextColor(mActivity.getProperTextColor())
property_label.text = mResources.getString(labelId)
property_value.text = value
mPropertyView.properties_holder.addView(this)
setOnLongClickListener {
mActivity.copyToClipboard(property_value.value)
true
}
if (labelId == R.string.gps_coordinates) {
setOnClickListener {
mActivity.showLocationOnMap(value)
}
}
if (viewId != 0) {
id = viewId
}
}
}
}
| gpl-3.0 | b341672b36386255921a2c036ad25fc3 | 42.117962 | 148 | 0.600323 | 5.110582 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/ANGLE_texture_compression_dxt.kt | 1 | 1596 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val ANGLE_texture_compression_dxt1 = "ANGLETextureCompressionDXT1".nativeClassGLES("ANGLE_texture_compression_dxt1", postfix = ANGLE) {
documentation =
"Native bindings to the ${registryLink("ANGLE", "ANGLE_texture_compression_dxt")} extension."
IntConstant(
"Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.",
"COMPRESSED_RGB_S3TC_DXT1_ANGLE"..0x83F0,
"COMPRESSED_RGBA_S3TC_DXT1_ANGLE"..0x83F1
)
}
val ANGLE_texture_compression_dxt3 = "ANGLETextureCompressionDXT3".nativeClassGLES("ANGLE_texture_compression_dxt3", postfix = ANGLE) {
documentation =
"Native bindings to the ${registryLink("ANGLE", "ANGLE_texture_compression_dxt")} extension."
IntConstant(
"Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.",
"COMPRESSED_RGBA_S3TC_DXT3_ANGLE"..0x83F2
)
}
val ANGLE_texture_compression_dxt5 = "ANGLETextureCompressionDXT5".nativeClassGLES("ANGLE_texture_compression_dxt5", postfix = ANGLE) {
documentation =
"Native bindings to the ${registryLink("ANGLE", "ANGLE_texture_compression_dxt")} extension."
IntConstant(
"Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.",
"COMPRESSED_RGBA_S3TC_DXT5_ANGLE"..0x83F3
)
} | bsd-3-clause | 845f94d0ae4a1b02279fa56025e2ebee | 37.02381 | 138 | 0.769424 | 3.578475 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/DownloadFile.kt | 1 | 3053 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data
import org.andstatus.app.context.MyStorage
import org.andstatus.app.util.IsEmpty
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.Taggable
import java.io.File
import java.util.*
class DownloadFile(filename: String) : IsEmpty {
private val filename: String
private val file: File?
/** Existence is checked at the moment of the object creation */
val existed: Boolean
override val isEmpty: Boolean
get() {
return file == null
}
fun existsNow(): Boolean {
return file != null && nonEmpty && file.exists() && file.isFile()
}
fun getFile(): File? {
return file
}
fun getFilePath(): String {
return if (file == null) "" else file.absolutePath
}
fun getSize(): Long {
return if (file != null && existsNow()) file.length() else 0
}
fun getFilename(): String {
return filename
}
/** returns true if the file existed and was deleted */
fun delete(): Boolean {
return deleteFileLogged(file)
}
private fun deleteFileLogged(file: File?): Boolean {
var deleted = false
if (file != null && existsNow()) {
deleted = file.delete()
if (deleted) {
MyLog.v(this) { "Deleted file $file" }
} else {
MyLog.e(this, "Couldn't delete file $file")
}
}
return deleted
}
override fun toString(): String {
return (Taggable.anyToTag(this)
+ " filename:" + filename
+ if (existed) ", existed" else "")
}
override fun hashCode(): Int {
val prime = 31
var result = 1
result = prime * result + filename.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is DownloadFile) {
return false
}
return filename == other.filename
}
companion object {
val EMPTY: DownloadFile = DownloadFile("")
}
init {
Objects.requireNonNull(filename)
this.filename = filename
if (filename.isEmpty()) {
file = null
existed = false
} else {
file = MyStorage.newMediaFile(filename)
existed = existsNow()
}
}
}
| apache-2.0 | bc93ee9fc65cbc38c5e296a52d70f897 | 26.017699 | 75 | 0.588929 | 4.46345 | false | false | false | false |
stfalcon-studio/uaroads_android | app/src/main/java/com/stfalcon/new_uaroads_android/common/data/preferences/SettingsImpl.kt | 1 | 3913 | /*
* Copyright (c) 2017 stfalcon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stfalcon.new_uaroads_android.common.data.preferences
import android.content.Context
import android.content.SharedPreferences
/*
* Created by troy379 on 13.04.17.
*/
class SettingsImpl(val context: Context) : Settings {
override fun setAuthorized(isAuthorized: Boolean) {
getEditor().putBoolean(IS_AUTHORIZED, isAuthorized).apply()
}
override fun isAuthorized(): Boolean = getReader().getBoolean(IS_AUTHORIZED, false)
override fun setUserEmail(email: String?) {
getEditor().putString(USER_EMAIL, email).apply()
}
override fun getUserEmail(): String? = getReader().getString(USER_EMAIL, null)
override fun enableWifiOnlyMode(enabled: Boolean) {
getEditor().putBoolean(SEND_WIFI_ONLY, enabled).apply()
}
override fun isWifiOnlyEnabled(): Boolean = getReader().getBoolean(SEND_WIFI_ONLY, true)
override fun sendRoutesAutomatically(enabled: Boolean) {
getEditor().putBoolean(SEND_ROUTES_AUTOMATICALLY, enabled).apply()
}
override fun isSendRoutesAutomatically(): Boolean
= getReader().getBoolean(SEND_ROUTES_AUTOMATICALLY, true)
override fun enableAutostart(enabled: Boolean) {
getEditor().putBoolean(USE_AUTOSTART, enabled).apply()
}
override fun isAutostartEnabled(): Boolean = getReader().getBoolean(USE_AUTOSTART, true)
override fun enableNotification(enabled: Boolean) {
getEditor().putBoolean(SHOW_NOTIFICATION, enabled).apply()
}
override fun isNotificationEnabled(): Boolean = getReader().getBoolean(SHOW_NOTIFICATION, false)
override fun enablePitSound(enabled: Boolean) {
getEditor().putBoolean(PLAY_SOUND_ON_PIT, enabled).apply()
}
override fun isPitSoundEnabled(): Boolean = getReader().getBoolean(PLAY_SOUND_ON_PIT, false)
override fun enableAutostartSound(enabled: Boolean) {
getEditor().putBoolean(PLAY_SOUND_ON_AUTOSTART, enabled).apply()
}
override fun isAutostartSoundEnabled(): Boolean = getReader().getBoolean(PLAY_SOUND_ON_AUTOSTART, false)
override fun enableDevMode(enabled: Boolean) {
getEditor().putBoolean(IS_DEV_MODE, enabled).apply()
}
override fun isDevModeEnabled(): Boolean = getReader().getBoolean(IS_DEV_MODE, false)
override fun isFirstLaunch(): Boolean {
return getReader().getBoolean(IS_FIRST_LAUNCH, true)
}
override fun setFirstLaunch(isFirst: Boolean) {
getEditor().putBoolean(IS_FIRST_LAUNCH, isFirst).apply()
}
override fun setChangelogShown(isShown: Boolean) {
getEditor().putBoolean(IS_CHANGELOG_SHOWN, isShown).apply() }
override fun isChangelogShown(): Boolean {
return getReader().getBoolean(IS_CHANGELOG_SHOWN, false)
}
override fun setLastDistance(lastDistance: Float) {
getEditor().putFloat(LAST_DISTANCE, lastDistance).apply()
}
override fun getLastDistance(): Float {
return getReader().getFloat(LAST_DISTANCE, 0f)
}
private fun getReader(): SharedPreferences {
return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
}
private fun getEditor(): SharedPreferences.Editor {
return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit()
}
} | apache-2.0 | 2f5234b06e47af9a20cccdd723f47de3 | 33.946429 | 108 | 0.706363 | 4.431484 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/video/dto/VideoVideoFiles.kt | 1 | 2623 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.video.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
/**
* @param external - URL of the external player
* @param mp4240 - URL of the mpeg4 file with 240p quality
* @param mp4360 - URL of the mpeg4 file with 360p quality
* @param mp4480 - URL of the mpeg4 file with 480p quality
* @param mp4720 - URL of the mpeg4 file with 720p quality
* @param mp41080 - URL of the mpeg4 file with 1080p quality
* @param mp41440 - URL of the mpeg4 file with 2K quality
* @param mp42160 - URL of the mpeg4 file with 4K quality
* @param flv320 - URL of the flv file with 320p quality
*/
data class VideoVideoFiles(
@SerializedName("external")
val external: String? = null,
@SerializedName("mp4_240")
val mp4240: String? = null,
@SerializedName("mp4_360")
val mp4360: String? = null,
@SerializedName("mp4_480")
val mp4480: String? = null,
@SerializedName("mp4_720")
val mp4720: String? = null,
@SerializedName("mp4_1080")
val mp41080: String? = null,
@SerializedName("mp4_1440")
val mp41440: String? = null,
@SerializedName("mp4_2160")
val mp42160: String? = null,
@SerializedName("flv_320")
val flv320: String? = null
)
| mit | be16bcd858c4e7caf1d3d8b839d8cafd | 40.634921 | 81 | 0.680518 | 3.956259 | false | false | false | false |
ligee/kotlin-jupyter | build-plugin/src/build/PythonPackageTasksConfigurator.kt | 1 | 4197 | package build
import build.util.makeTaskName
import org.gradle.api.Project
import org.gradle.api.tasks.Exec
import org.gradle.kotlin.dsl.register
import java.io.ByteArrayInputStream
class PythonPackageTasksConfigurator(
private val project: Project,
private val settings: RootSettingsExtension,
) {
fun registerTasks() {
prepareCondaTasks()
preparePyPiTasks()
}
private fun prepareCondaTasks() {
val specs = settings.condaTaskSpecs
val packageSettings = specs.packageSettings
project.tasks.register<Exec>(CONDA_PACKAGE_TASK) {
group = CONDA_GROUP
dependsOn(makeTaskName(settings.cleanInstallDirTaskPrefix, false), PREPARE_PACKAGE_TASK)
commandLine("conda-build", "conda", "--output-folder", packageSettings.dir)
workingDir(settings.distribBuildDir)
doLast {
project.copy {
from(settings.distribBuildDir.resolve(packageSettings.dir).resolve("noarch").resolve(packageSettings.fileName))
into(settings.artifactsDir)
}
}
}
project.tasks.named(PUBLISH_LOCAL_TASK) {
dependsOn(CONDA_PACKAGE_TASK)
}
specs.registerTasks(settings) { taskSpec ->
project.tasks.register(taskSpec.taskName) {
group = CONDA_GROUP
val artifactPath = settings.artifactsDir.resolve(packageSettings.fileName)
if (!artifactPath.exists()) {
dependsOn(makeTaskName(settings.cleanInstallDirTaskPrefix, false), CONDA_PACKAGE_TASK)
}
doLast {
project.exec {
commandLine(
"anaconda",
"login",
"--username",
taskSpec.credentials.username,
"--password",
taskSpec.credentials.password
)
standardInput = ByteArrayInputStream("yes".toByteArray())
}
project.exec {
commandLine("anaconda", "upload", "-u", taskSpec.username, artifactPath.toString())
}
}
}
}
}
private fun preparePyPiTasks() {
val specs = settings.pyPiTaskSpecs
val packageSettings = specs.packageSettings
project.tasks.register<Exec>(PYPI_PACKAGE_TASK) {
group = PYPI_GROUP
dependsOn(PREPARE_PACKAGE_TASK)
if (settings.isLocalBuild) {
dependsOn(INSTALL_COMMON_REQUIREMENTS_TASK)
}
commandLine(
"python",
settings.setupPy,
"bdist_wheel",
"--dist-dir",
packageSettings.dir
)
workingDir(settings.distribBuildDir)
doLast {
project.copy {
from(settings.distribBuildDir.resolve(packageSettings.dir).resolve(packageSettings.fileName))
into(settings.artifactsDir)
}
}
}
project.tasks.named(PUBLISH_LOCAL_TASK) {
dependsOn(PYPI_PACKAGE_TASK)
}
specs.registerTasks(settings) { taskSpec ->
project.tasks.register<Exec>(taskSpec.taskName) {
group = PYPI_GROUP
workingDir(settings.artifactsDir)
val artifactPath = settings.artifactsDir.resolve(packageSettings.fileName)
if (settings.isLocalBuild) {
dependsOn(INSTALL_COMMON_REQUIREMENTS_TASK)
}
if (!artifactPath.exists()) {
dependsOn(PYPI_PACKAGE_TASK)
}
commandLine(
"twine", "upload",
"-u", taskSpec.username,
"-p", taskSpec.password,
"--repository-url", taskSpec.repoURL,
packageSettings.fileName
)
}
}
}
}
| apache-2.0 | 02a9abd1ace8e399155a3402fb70bac6 | 32.846774 | 131 | 0.522993 | 5.24625 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/libcommon/ImageFragment.kt | 1 | 6607 | package com.serenegiant.libcommon
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.*
import com.serenegiant.graphics.BitmapHelper
import com.serenegiant.mediastore.ImageLoader
import com.serenegiant.mediastore.LoaderDrawable
import com.serenegiant.mediastore.MediaInfo
import com.serenegiant.view.MotionEventUtils
import com.serenegiant.view.ViewTransformDelegater
import com.serenegiant.widget.ZoomImageView
import java.io.IOException
import kotlin.math.sign
/**
* 静止画表示用のFragment
* FIXME MainFragmentで選択したのと違う映像が読み込まれる!!
*/
class ImageFragment: BaseFragment() {
private var mInfo: MediaInfo? = null
private var mImageView: ZoomImageView? = null
override fun onAttach(context: Context) {
super.onAttach(context)
requireActivity().title = getString(R.string.title_galley)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (DEBUG) Log.v(TAG, "onCreateView:")
return inflater.inflate(R.layout.fragment_image, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (DEBUG) Log.v(TAG, "onViewCreated:")
var args = savedInstanceState
if (args == null) {
args = arguments
}
if (args != null) {
mInfo = args.getParcelable(ARG_MEDIA_INFO)
}
initView(view)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (DEBUG) Log.v(TAG, "onSaveInstanceState:")
val args = arguments
if (args != null) {
outState.putAll(args)
}
}
override fun onDestroy() {
if (DEBUG) Log.v(TAG, "onDestroy:")
super.onDestroy()
}
//--------------------------------------------------------------------------------
private fun initView(rootView: View) {
if (DEBUG) Log.v(TAG, "initView:" + mInfo!!.uri)
mImageView = rootView.findViewById(R.id.image_view)
mImageView!!.setOnClickListener {
v -> if (DEBUG) Log.v(TAG, "onClick:$v")
}
mImageView!!.enableHandleTouchEvent = (ViewTransformDelegater.TOUCH_ENABLED_MOVE
or ViewTransformDelegater.TOUCH_ENABLED_ZOOM
or ViewTransformDelegater.TOUCH_ENABLED_ROTATE)
mImageView!!.viewTransformListener = object: ViewTransformDelegater.ViewTransformListener {
override fun onStateChanged(view: View, newState: Int) {
if (newState == ViewTransformDelegater.STATE_NON) {
if (DEBUG) Log.v(TAG, "onStateChanged:scale=${mImageView!!.scale}")
}
}
override fun onTransformed(view: View, transform: Matrix) {
if (DEBUG) Log.v(TAG, "onTransformed:${transform}")
}
}
mImageView!!.setOnGenericMotionListener(object : View.OnGenericMotionListener {
override fun onGenericMotion(v: View?, event: MotionEvent?): Boolean {
if (MotionEventUtils.isFromSource(event!!, InputDevice.SOURCE_CLASS_POINTER)) {
when (event.action) {
MotionEvent.ACTION_HOVER_MOVE -> {
if (DEBUG) Log.v(TAG, "onGenericMotion:ACTION_HOVER_MOVE")
// process the mouse hover movement...
return true
}
MotionEvent.ACTION_SCROLL -> {
if (DEBUG) Log.v(TAG, "onGenericMotion:ACTION_SCROLL")
// process the scroll wheel movement...
val vScroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (vScroll != 0.0f) {
mImageView!!.setScaleRelative(1.0f + vScroll.sign / 10.0f) // 1.1か0.9
}
return true
}
}
}
return false
}
})
if (USU_LOADER_DRAWABLE) {
var drawable = mImageView!!.drawable
if (drawable !is LoaderDrawable) {
drawable = ImageLoaderDrawable(
requireContext(), -1, -1)
mImageView!!.setImageDrawable(drawable)
}
(drawable as LoaderDrawable).startLoad(mInfo!!)
} else {
queueEvent({
// mImageView.setImageURI(mInfo.getUri());
try {
val bitmap = BitmapHelper.asBitmap(
requireContext().contentResolver, mInfo!!.id)
runOnUiThread ({
mImageView!!.setImageBitmap(bitmap)
})
} catch (e: IOException) {
Log.w(TAG, e)
popBackStack()
}
})
}
}
//--------------------------------------------------------------------------------
private class ImageLoaderDrawable(context: Context,
width: Int, height: Int) : LoaderDrawable(context, width, height) {
override fun createImageLoader(): ImageLoader {
return MyImageLoader(this)
}
override fun checkCache(id: Long): Bitmap? {
return null
}
public override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
}
}
private class MyImageLoader(parent: ImageLoaderDrawable)
: ImageLoader(parent) {
override fun loadBitmap(context: Context,
info: MediaInfo,
requestWidth: Int, requestHeight: Int): Bitmap {
var result: Bitmap?
try {
result = BitmapHelper.asBitmap(context.contentResolver, info.id)
if (result != null) {
val w = result.width
val h = result.height
val bounds = Rect()
mParent.copyBounds(bounds)
val cx = bounds.centerX()
val cy = bounds.centerY()
bounds[cx - w / 2, cy - h / w, cx + w / 2] = cy + h / 2
(mParent as ImageLoaderDrawable).onBoundsChange(bounds)
}
} catch (e: IOException) {
if (DEBUG) Log.w(TAG, e)
result = loadDefaultBitmap(context, R.drawable.ic_error_outline_red_24dp)
}
return result!!
}
}
companion object {
private const val DEBUG = true // set false on production
private val TAG = ImageFragment::class.java.simpleName
private const val USU_LOADER_DRAWABLE = false
private const val ARG_MEDIA_INFO = "ARG_MEDIA_INFO"
@JvmStatic
fun newInstance(info: MediaInfo): ImageFragment {
val fragment = ImageFragment()
val args = Bundle()
args.putParcelable(ARG_MEDIA_INFO, info)
fragment.arguments = args
return fragment
}
}
} | apache-2.0 | 58a79d895b186585d84c93c565cf7db1 | 29.474419 | 93 | 0.687529 | 3.635405 | false | false | false | false |
otormaigh/UL.DashNav | app/src/main/kotlin/ie/elliot/uldashnav/ui/view/ListHeader.kt | 1 | 4530 | package ie.elliot.uldashnav.ui.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.support.v4.content.ContextCompat
import android.support.v4.widget.Space
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import ie.elliot.uldashnav.R
/**
* @author Elliot Tormey
* @since 12/02/2017
*/
class ListHeader(context: Context, attributeSet: AttributeSet) : LinearLayout(context, attributeSet) {
private val headerPaint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) }
private var headerHeight: Int = 0
private val minHeight: Float
private val maxHeight: Float by lazy { resources.getDimension(R.dimen.height_list_header) }
private val titleParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
private val titleMinWidth by lazy { context.resources.getDimension(R.dimen.min_width_list_title) }
private val titleMaxWidth by lazy { context.resources.getDimension(R.dimen.width_list_title) }
// Views
private val title by lazy { CircleBar(context, attributeSet, R.color.background_title, R.dimen.radius_title) }
init {
val androidTypedArray = context.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize))
minHeight = context.resources.getDimension(androidTypedArray.getResourceId(0, 0))
androidTypedArray.recycle()
orientation = VERTICAL
gravity = Gravity.CENTER_HORIZONTAL
headerPaint.style = Paint.Style.FILL
headerPaint.color = ContextCompat.getColor(context, R.color.colorPrimary)
title.layoutParams = titleParams
title.shouldAnimate = false
addView(title, resources.getDimension(R.dimen.width_list_title).toInt(), WRAP_CONTENT)
val spaceParams = LinearLayout.LayoutParams(0, 1, 1f)
val space = Space(context)
space.layoutParams = spaceParams
addView(space)
val pageIndicator = PageIndicator(context)
pageIndicator.indicatorCount = 5
addView(pageIndicator)
setWillNotDraw(false)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
headerHeight = measuredHeight
setMeasuredDimension(widthMeasureSpec, headerHeight)
}
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawRect(Rect(0, 0, measuredWidth, headerHeight), headerPaint)
}
fun setRecyclerView(recyclerView: RecyclerView) {
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
changeViewSize(title, false, dy, titleMinWidth, titleMaxWidth, title.layoutParams.width)
changeViewSize(this@ListHeader, true, dy, minHeight, maxHeight, layoutParams.height)
// Only request layout if its not in the middle of one already.
if (!isInLayout) {
requestLayout()
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
})
}
private fun changeViewSize(view: View, isHeight: Boolean, changeBy: Int, minVal: Float, maxVal: Float, currentVal: Int) {
// Only allow height change
// IF : currentVal is above minimum AND below maximum.
// OR : currentVal is below OR is minimum and changeBy is increasing height
// OR : currentVal is above OR is maximum and changeBy is decreasing height
if ((currentVal > minVal && currentVal < maxVal)
|| (currentVal <= minVal && changeBy < 0)
|| currentVal >= maxVal && changeBy > 0) {
var newVal: Int = currentVal - (changeBy / 3)
// If newVal is below minVal, reset.
if (newVal < minVal) {
newVal = minVal.toInt()
}
if (isHeight) {
view.layoutParams.height = newVal
} else {
view.layoutParams.width = newVal
}
}
}
} | mit | 8d8a5c890182740c975a4b08240501ec | 38.060345 | 125 | 0.674834 | 4.598985 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/undo/UndoOsmQuestTable.kt | 1 | 1780 | package de.westnordost.streetcomplete.data.osm.osmquest.undo
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryTable
object UndoOsmQuestTable {
const val NAME = "osm_quests_undo"
const val NAME_MERGED_VIEW = "osm_quests_full_undo"
object Columns {
const val QUEST_ID = "quest_id"
const val QUEST_TYPE = "quest_type"
const val ELEMENT_ID = "element_id"
const val ELEMENT_TYPE = "element_type"
const val TAG_CHANGES = "tag_changes"
const val CHANGES_SOURCE = "changes_source"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.QUEST_ID} INTEGER PRIMARY KEY,
${Columns.QUEST_TYPE} varchar(255) NOT NULL,
${Columns.TAG_CHANGES} blob NOT NULL,
${Columns.CHANGES_SOURCE} varchar(255) NOT NULL,
${Columns.ELEMENT_ID} int NOT NULL,
${Columns.ELEMENT_TYPE} varchar(255) NOT NULL,
CONSTRAINT same_osm_quest UNIQUE (
${Columns.QUEST_TYPE},
${Columns.ELEMENT_ID},
${Columns.ELEMENT_TYPE}
),
CONSTRAINT element_key FOREIGN KEY (
${Columns.ELEMENT_TYPE},
${Columns.ELEMENT_ID}
) REFERENCES ${ElementGeometryTable.NAME} (
${ElementGeometryTable.Columns.ELEMENT_TYPE},
${ElementGeometryTable.Columns.ELEMENT_ID}
)
);"""
const val MERGED_VIEW_CREATE = """
CREATE VIEW $NAME_MERGED_VIEW AS
SELECT * FROM $NAME
INNER JOIN ${ElementGeometryTable.NAME} USING (
${ElementGeometryTable.Columns.ELEMENT_TYPE},
${ElementGeometryTable.Columns.ELEMENT_ID}
);"""
}
| gpl-3.0 | a1d1fc81776581313a699d877fda6acf | 36.083333 | 82 | 0.583708 | 4.438903 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2285.kt | 1 | 752 | package leetcode
/**
* https://leetcode.com/problems/maximum-total-importance-of-roads/
*/
class Problem2285 {
fun maximumImportance(n: Int, roads: Array<IntArray>): Long {
val roadToCount = mutableMapOf<Int, Int>()
for ((a, b) in roads) {
roadToCount[a] = (roadToCount[a] ?: 0) + 1
roadToCount[b] = (roadToCount[b] ?: 0) + 1
}
var value = n
val roadToValue = mutableMapOf<Int, Int>()
for (entry in roadToCount.entries.sortedByDescending { it.value }) {
roadToValue[entry.key] = value--
}
var answer = 0L
for ((a, b) in roads) {
answer += (roadToValue[a] ?: 0) + (roadToValue[b] ?: 0)
}
return answer
}
}
| mit | 0ba49b27b79d34e646f0874706986f82 | 30.333333 | 76 | 0.546543 | 3.63285 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/vfs/EditedVirtualFile.kt | 1 | 2245 | /*
* 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.core.vfs
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileSystem
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class EditedVirtualFile(
val original: VirtualFile,
val contents: String,
private val modificationStampValue: Long
) : VirtualFile() {
override fun getName(): String = original.name
override fun getFileSystem(): VirtualFileSystem = original.fileSystem
override fun getPath(): String = original.path
override fun isWritable(): Boolean = false
override fun isDirectory(): Boolean = original.isDirectory
override fun isValid(): Boolean = original.isValid
override fun getParent(): VirtualFile? = original.parent
override fun getChildren(): Array<VirtualFile>? = original.children
@Throws(IOException::class)
override fun getOutputStream(requestor: Any, newModificationStamp: Long, newTimeStamp: Long): OutputStream {
throw UnsupportedOperationException()
}
@Throws(IOException::class)
override fun contentsToByteArray(): ByteArray = contents.toByteArray(charset)
override fun getTimeStamp(): Long = original.timeStamp
override fun getModificationStamp(): Long = modificationStampValue
override fun getLength(): Long = contents.length.toLong()
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {
original.refresh(asynchronous, recursive, postRunnable)
}
@Throws(IOException::class)
override fun getInputStream(): InputStream = contents.byteInputStream(charset)
}
| apache-2.0 | 4cf79274ea6e26f02a3ba59caaf4d8b1 | 33.015152 | 112 | 0.747884 | 4.817597 | false | false | false | false |
fhanik/spring-security | config/src/test/kotlin/org/springframework/security/config/web/servlet/session/SessionFixationDslTests.kt | 1 | 7479 | /*
* Copyright 2002-2020 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
*
* 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 org.springframework.security.config.web.servlet.session
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.mock.web.MockHttpSession
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.config.web.servlet.invoke
import org.springframework.security.config.test.SpringTestRule
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
/**
* Tests for [SessionFixationDsl]
*
* @author Eleftheria Stein
*/
class SessionFixationDslTests {
@Rule
@JvmField
var spring = SpringTestRule()
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `session fixation when strategy is new session then new session created and attributes are not preserved`() {
this.spring.register(NewSessionConfig::class.java, UserDetailsConfig::class.java).autowire()
val givenSession = MockHttpSession()
val givenSessionId = givenSession.id
givenSession.clearAttributes()
givenSession.setAttribute("name", "value")
val result = this.mockMvc.perform(MockMvcRequestBuilders.get("/")
.with(httpBasic("user", "password"))
.session(givenSession))
.andReturn()
val resultingSession = result.request.getSession(false)
assertThat(resultingSession).isNotEqualTo(givenSession)
assertThat(resultingSession!!.id).isNotEqualTo(givenSessionId)
assertThat(resultingSession.getAttribute("name")).isNull()
}
@EnableWebSecurity
open class NewSessionConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
sessionManagement {
sessionFixation {
newSession()
}
}
httpBasic { }
}
}
}
@Test
fun `session fixation when strategy is migrate session then new session created and attributes are preserved`() {
this.spring.register(MigrateSessionConfig::class.java, UserDetailsConfig::class.java).autowire()
val givenSession = MockHttpSession()
val givenSessionId = givenSession.id
givenSession.clearAttributes()
givenSession.setAttribute("name", "value")
val result = this.mockMvc.perform(MockMvcRequestBuilders.get("/")
.with(httpBasic("user", "password"))
.session(givenSession))
.andReturn()
val resultingSession = result.request.getSession(false)
assertThat(resultingSession).isNotEqualTo(givenSession)
assertThat(resultingSession!!.id).isNotEqualTo(givenSessionId)
assertThat(resultingSession.getAttribute("name")).isEqualTo("value")
}
@EnableWebSecurity
open class MigrateSessionConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
sessionManagement {
sessionFixation {
migrateSession()
}
}
httpBasic { }
}
}
}
@Test
fun `session fixation when strategy is change session id then session id changes and attributes preserved`() {
this.spring.register(ChangeSessionIdConfig::class.java, UserDetailsConfig::class.java).autowire()
val givenSession = MockHttpSession()
val givenSessionId = givenSession.id
givenSession.clearAttributes()
givenSession.setAttribute("name", "value")
val result = this.mockMvc.perform(MockMvcRequestBuilders.get("/")
.with(httpBasic("user", "password"))
.session(givenSession))
.andReturn()
val resultingSession = result.request.getSession(false)
assertThat(resultingSession).isEqualTo(givenSession)
assertThat(resultingSession!!.id).isNotEqualTo(givenSessionId)
assertThat(resultingSession.getAttribute("name")).isEqualTo("value")
}
@EnableWebSecurity
open class ChangeSessionIdConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
sessionManagement {
sessionFixation {
changeSessionId()
}
}
httpBasic { }
}
}
}
@Test
fun `session fixation when strategy is none then session does not change`() {
this.spring.register(NoneConfig::class.java, UserDetailsConfig::class.java).autowire()
val givenSession = MockHttpSession()
val givenSessionId = givenSession.id
givenSession.clearAttributes()
givenSession.setAttribute("name", "value")
val result = this.mockMvc.perform(MockMvcRequestBuilders.get("/")
.with(httpBasic("user", "password"))
.session(givenSession))
.andReturn()
val resultingSession = result.request.getSession(false)
assertThat(resultingSession).isEqualTo(givenSession)
assertThat(resultingSession!!.id).isEqualTo(givenSessionId)
assertThat(resultingSession.getAttribute("name")).isEqualTo("value")
}
@EnableWebSecurity
open class NoneConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
sessionManagement {
sessionFixation {
none()
}
}
httpBasic { }
}
}
}
@Configuration
open class UserDetailsConfig {
@Bean
open fun userDetailsService(): UserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
return InMemoryUserDetailsManager(userDetails)
}
}
}
| apache-2.0 | 8a51a3762046458210e081a94c4e48df | 37.353846 | 117 | 0.658912 | 5.403902 | false | true | false | false |
da1z/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/ExternalModuleListStorage.kt | 1 | 2109 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.module.impl
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.ProjectModelElement
import com.intellij.openapi.roots.ProjectModelExternalSource
import org.jdom.Element
@State(name = "ExternalModuleListStorage", storages = arrayOf(Storage("modules.xml")))
internal class ExternalModuleListStorage(private val project: Project) : PersistentStateComponent<Element>, ProjectModelElement {
var loadedState: Set<ModulePath>? = null
private set
override fun getState(): Element {
val e = Element("state")
if (!project.isExternalStorageEnabled) {
return e
}
val moduleManager = ModuleManagerImpl.getInstanceImpl(project)
moduleManager.writeExternal(e, getFilteredModuleList(project, moduleManager.modules, true))
return e
}
override fun loadState(state: Element) {
loadedState = ModuleManagerImpl.getPathsToModuleFiles(state)
}
override fun getExternalSource(): ProjectModelExternalSource? {
val externalProjectSystemRegistry = ExternalProjectSystemRegistry.getInstance()
for (module in ModuleManagerImpl.getInstanceImpl(project).modules) {
externalProjectSystemRegistry.getExternalSource(module)?.let {
return it
}
}
return null
}
}
fun getFilteredModuleList(project: Project, modules: Array<Module>, isExternal: Boolean): List<Module> {
if (!project.isExternalStorageEnabled) {
return modules.asList()
}
val externalProjectSystemRegistry = ExternalProjectSystemRegistry.getInstance()
return modules.filter { (externalProjectSystemRegistry.getExternalSource(it) != null) == isExternal }
} | apache-2.0 | 7a037bb12b81bf2fff228e0dcc3d8136 | 38.811321 | 140 | 0.788525 | 4.962353 | false | false | false | false |
apollostack/apollo-android | apollo-runtime-kotlin/src/commonMain/kotlin/com/apollographql/apollo3/network/ws/ApolloWebSocketNetworkTransport.kt | 1 | 9995 | package com.apollographql.apollo3.network.ws
import com.apollographql.apollo3.exception.ApolloWebSocketException
import com.apollographql.apollo3.exception.ApolloWebSocketServerException
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.ExecutionContext
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.Subscription
import com.apollographql.apollo3.api.internal.json.Utils
import com.apollographql.apollo3.api.fromResponse
import com.apollographql.apollo3.dispatcher.ApolloCoroutineDispatcher
import com.apollographql.apollo3.exception.ApolloParseException
import com.apollographql.apollo3.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.internal.json.BufferedSinkJsonWriter
import com.apollographql.apollo3.network.NetworkTransport
import com.apollographql.apollo3.subscription.ApolloOperationMessageSerializer
import com.apollographql.apollo3.subscription.OperationClientMessage
import com.apollographql.apollo3.subscription.OperationMessageSerializer
import com.apollographql.apollo3.subscription.OperationMessageSerializer.Companion.toByteString
import com.apollographql.apollo3.subscription.OperationServerMessage
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.broadcast
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeout
import okio.Buffer
import okio.ByteString
@ExperimentalCoroutinesApi
/**
* Apollo GraphQL WS protocol implementation:
* https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md
*/
class ApolloWebSocketNetworkTransport(
private val webSocketFactory: WebSocketFactory,
private val connectionParams: Map<String, Any?> = emptyMap(),
private val connectionAcknowledgeTimeoutMs: Long = 10_000,
private val idleTimeoutMs: Long = 60_000,
private val connectionKeepAliveTimeoutMs: Long = -1,
private val serializer: OperationMessageSerializer = ApolloOperationMessageSerializer
) : NetworkTransport {
private val mutex = Mutex()
private var graphQLWebsocketConnection: GraphQLWebsocketConnection? = null
override fun <D : Operation.Data> execute(
request: ApolloRequest<D>,
responseAdapterCache: ResponseAdapterCache,
): Flow<ApolloResponse<D>> {
val dispatcherContext = requireNotNull(
request.executionContext[ApolloCoroutineDispatcher] ?: request.executionContext[ApolloCoroutineDispatcher]
)
return getServerConnection(dispatcherContext).flatMapLatest { serverConnection ->
serverConnection
.subscribe()
.filter { message -> message !is OperationServerMessage.ConnectionAcknowledge }
.takeWhile { message -> message !is OperationServerMessage.Complete || message.id != request.requestUuid.toString() }
.mapNotNull { message -> message.process(request, responseAdapterCache) }
.onStart {
serverConnection.send(
OperationClientMessage.Start(
subscriptionId = request.requestUuid.toString(),
subscription = request.operation as Subscription<*>,
responseAdapterCache = responseAdapterCache,
autoPersistSubscription = false,
sendSubscriptionDocument = true
)
)
}.onCompletion { cause ->
if (cause == null) {
serverConnection.send(
OperationClientMessage.Stop(request.requestUuid.toString())
)
}
}
}
}
private fun <D : Operation.Data> OperationServerMessage.process(
request: ApolloRequest<D>,
responseAdapterCache: ResponseAdapterCache
): ApolloResponse<D>? {
return when (this) {
is OperationServerMessage.Error -> {
if (id == request.requestUuid.toString()) {
throw ApolloWebSocketServerException(
message = "Failed to execute GraphQL operation",
payload = payload
)
}
null
}
is OperationServerMessage.Data -> {
if (id == request.requestUuid.toString()) {
val buffer = Buffer().apply {
BufferedSinkJsonWriter(buffer)
.apply { Utils.writeToJson(payload, this) }
.flush()
}
val response = try {
request.operation.fromResponse(
source = buffer,
responseAdapterCache = responseAdapterCache
)
} catch (e: Exception) {
throw ApolloParseException(
message = "Failed to parse GraphQL network response",
cause = e
)
}
response.copy(
requestUuid = request.requestUuid,
executionContext = ExecutionContext.Empty
)
} else null
}
else -> null
}
}
private fun getServerConnection(dispatcher: ApolloCoroutineDispatcher): Flow<GraphQLWebsocketConnection> {
return flow {
val connection = mutex.withLock {
if (graphQLWebsocketConnection?.isClosedForReceive() != false) {
graphQLWebsocketConnection = openServerConnection(dispatcher)
}
graphQLWebsocketConnection
}
emit(connection)
}.filterNotNull()
}
private suspend fun openServerConnection(dispatcher: ApolloCoroutineDispatcher): GraphQLWebsocketConnection {
return try {
withTimeout(connectionAcknowledgeTimeoutMs) {
val webSocketConnection = webSocketFactory.open(
mapOf(
"Sec-WebSocket-Protocol" to "graphql-ws"
)
)
webSocketConnection.send(OperationClientMessage.Init(connectionParams).toByteString(serializer))
while (serializer.readServerMessage(Buffer().write(webSocketConnection.receive()))
!is OperationServerMessage.ConnectionAcknowledge) {
// await for connection acknowledgement
}
GraphQLWebsocketConnection(
webSocketConnection = webSocketConnection,
idleTimeoutMs = idleTimeoutMs,
connectionKeepAliveTimeoutMs = connectionKeepAliveTimeoutMs,
defaultDispatcher = dispatcher.coroutineDispatcher,
serializer = serializer
)
}
} catch (e: TimeoutCancellationException) {
throw ApolloWebSocketException(
message = "Failed to establish GraphQL websocket connection with the server, timeout.",
cause = e
)
} catch (e: Exception) {
throw ApolloWebSocketException(
message = "Failed to establish GraphQL websocket connection with the server.",
cause = e
)
}
}
private class GraphQLWebsocketConnection(
val webSocketConnection: WebSocketConnection,
val idleTimeoutMs: Long,
val connectionKeepAliveTimeoutMs: Long,
private val serializer: OperationMessageSerializer,
defaultDispatcher: CoroutineDispatcher
) {
private val messageChannel: BroadcastChannel<ByteString> = webSocketConnection.broadcast(Channel.CONFLATED)
private val coroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher)
private val mutex = Mutex()
private var activeSubscriptionCount = 0
private var idleTimeoutJob: Job? = null
private var connectionKeepAliveTimeoutJob: Job? = null
suspend fun isClosedForReceive(): Boolean {
return mutex.withLock {
webSocketConnection.isClosedForReceive
}
}
fun send(message: OperationClientMessage) {
webSocketConnection.send(message.toByteString(serializer))
}
fun subscribe(): Flow<OperationServerMessage> {
return messageChannel.openSubscription()
.consumeAsFlow()
.onStart { onSubscribed() }
.onCompletion { onUnsubscribed() }
.map { data -> serializer.readServerMessage(Buffer().write(data)) }
.onEach { message ->
if (message is OperationServerMessage.ConnectionKeepAlive) onConnectionKeepAlive()
}
}
private suspend fun onSubscribed() {
mutex.withLock {
activeSubscriptionCount++
idleTimeoutJob?.cancel()
}
}
private suspend fun onUnsubscribed() {
mutex.withLock {
if (--activeSubscriptionCount == 0 && idleTimeoutMs > 0) {
idleTimeoutJob?.cancel()
connectionKeepAliveTimeoutJob?.cancel()
idleTimeoutJob = coroutineScope.launch {
delay(idleTimeoutMs)
close()
}
}
}
}
private suspend fun onConnectionKeepAlive() {
mutex.withLock {
if (activeSubscriptionCount > 0 && connectionKeepAliveTimeoutMs > 0) {
connectionKeepAliveTimeoutJob?.cancel()
connectionKeepAliveTimeoutJob = coroutineScope.launch {
delay(idleTimeoutMs)
close()
}
}
}
}
private suspend fun close() {
mutex.withLock {
webSocketConnection.close()
}
}
}
}
| mit | ebd4b31e077268f1365d41bee7c8bfc8 | 36.434457 | 127 | 0.69935 | 5.473713 | false | false | false | false |
esqr/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/di/modules/RepositoryModule.kt | 1 | 1887 | package io.github.feelfreelinux.wykopmobilny.di.modules
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesRepository
import io.github.feelfreelinux.wykopmobilny.api.mywykop.MyWykopApi
import io.github.feelfreelinux.wykopmobilny.api.mywykop.MyWykopRepository
import io.github.feelfreelinux.wykopmobilny.api.pm.PMApi
import io.github.feelfreelinux.wykopmobilny.api.pm.PMRepository
import io.github.feelfreelinux.wykopmobilny.api.pm.PMRetrofitApi
import io.github.feelfreelinux.wykopmobilny.api.stream.StreamApi
import io.github.feelfreelinux.wykopmobilny.api.stream.StreamRepository
import io.github.feelfreelinux.wykopmobilny.api.tag.TagApi
import io.github.feelfreelinux.wykopmobilny.api.tag.TagRepository
import io.github.feelfreelinux.wykopmobilny.api.user.UserApi
import io.github.feelfreelinux.wykopmobilny.api.user.UserRepository
import io.github.feelfreelinux.wykopmobilny.utils.api.CredentialsPreferencesApi
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
class RepositoryModule {
@Provides
@Singleton
fun provideEntriesApi(retrofit: Retrofit) : EntriesApi = EntriesRepository(retrofit)
@Provides
@Singleton
fun provideMyWykopApi(retrofit: Retrofit) : MyWykopApi = MyWykopRepository(retrofit)
@Provides
@Singleton
fun provideStreamApi(retrofit: Retrofit) : StreamApi = StreamRepository(retrofit)
@Provides
@Singleton
fun proviteTagApi(retrofit: Retrofit) : TagApi = TagRepository(retrofit)
@Provides
@Singleton
fun provideUserApi(retrofit: Retrofit, credentialsPreferencesApi : CredentialsPreferencesApi) : UserApi = UserRepository(retrofit, credentialsPreferencesApi)
@Provides
@Singleton
fun providePMApi(retrofit: Retrofit) : PMApi = PMRepository(retrofit)
} | mit | 5ed57bb05a78ac9c17b208ec4e2ade7a | 39.170213 | 161 | 0.823529 | 4.429577 | false | false | false | false |
maiconhellmann/pomodoro | app/src/main/kotlin/br/com/maiconhellmann/pomodoro/util/extension/ViewExtension.kt | 1 | 652 | package br.com.maiconhellmann.pomodoro.util.extension
import android.support.design.widget.Snackbar
import android.view.View
fun View.visible(){
this.visibility = View.VISIBLE
}
fun View.gone(){
this.visibility = View.GONE
}
fun View.invisible(){
this.visibility = View.INVISIBLE
}
fun View.snackbar(resId: Int, duration: Int = Snackbar.LENGTH_SHORT) {
snackbar(this.resources.getString(resId), duration)
}
fun View.snackbar(msg: String, duration: Int = Snackbar.LENGTH_SHORT) {
Snackbar.make(this, msg, duration).show()
}
fun View.longSnackbar(resId: Int) {
snackbar(resId, Snackbar.LENGTH_LONG)
}
| apache-2.0 | 1d8a75af5ccc67eedc6c5d1699f036d4 | 24.08 | 71 | 0.708589 | 3.449735 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpExtendedBolusTransaction.kt | 1 | 2346 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.database.interfaces.end
/**
* Creates or updates the extended bolus from pump synchronization
*/
class SyncPumpExtendedBolusTransaction(private val extendedBolus: ExtendedBolus) : Transaction<SyncPumpExtendedBolusTransaction.TransactionResult>() {
override fun run(): TransactionResult {
extendedBolus.interfaceIDs.pumpId ?: extendedBolus.interfaceIDs.pumpType
?: extendedBolus.interfaceIDs.pumpSerial
?: throw IllegalStateException("Some pump ID is null")
val result = TransactionResult()
val existing = database.extendedBolusDao.findByPumpIds(extendedBolus.interfaceIDs.pumpId!!, extendedBolus.interfaceIDs.pumpType!!, extendedBolus.interfaceIDs.pumpSerial!!)
if (existing != null) {
if (existing.interfaceIDs.endId == null &&
(existing.timestamp != extendedBolus.timestamp ||
existing.amount != extendedBolus.amount ||
existing.duration != extendedBolus.duration)
) {
existing.timestamp = extendedBolus.timestamp
existing.amount = extendedBolus.amount
existing.duration = extendedBolus.duration
database.extendedBolusDao.updateExistingEntry(existing)
result.updated.add(existing)
}
} else {
val running = database.extendedBolusDao.getExtendedBolusActiveAt(extendedBolus.timestamp).blockingGet()
if (running != null) {
val pctRun = (extendedBolus.timestamp - running.timestamp) / running.duration.toDouble()
running.amount *= pctRun
running.end = extendedBolus.timestamp
running.interfaceIDs.endId = extendedBolus.interfaceIDs.pumpId
database.extendedBolusDao.updateExistingEntry(running)
result.updated.add(running)
}
database.extendedBolusDao.insertNewEntry(extendedBolus)
result.inserted.add(extendedBolus)
}
return result
}
class TransactionResult {
val inserted = mutableListOf<ExtendedBolus>()
val updated = mutableListOf<ExtendedBolus>()
}
} | agpl-3.0 | 8bcbbdf85f9482be751dfa26a7dcc8bd | 45.94 | 179 | 0.672208 | 5.735941 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/WithListSoftLinksEntityImpl.kt | 3 | 8540 | 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.PersistentEntityId
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.SoftLinkable
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class WithListSoftLinksEntityImpl: WithListSoftLinksEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField var _myName: String? = null
override val myName: String
get() = _myName!!
@JvmField var _links: List<NameId>? = null
override val links: List<NameId>
get() = _links!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: WithListSoftLinksEntityData?): ModifiableWorkspaceEntityBase<WithListSoftLinksEntity>(), WithListSoftLinksEntity.Builder {
constructor(): this(WithListSoftLinksEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity WithListSoftLinksEntity 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().isMyNameInitialized()) {
error("Field WithListSoftLinksEntity#myName should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WithListSoftLinksEntity#entitySource should be initialized")
}
if (!getEntityData().isLinksInitialized()) {
error("Field WithListSoftLinksEntity#links should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var myName: String
get() = getEntityData().myName
set(value) {
checkModificationAllowed()
getEntityData().myName = value
changedProperty.add("myName")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var links: List<NameId>
get() = getEntityData().links
set(value) {
checkModificationAllowed()
getEntityData().links = value
changedProperty.add("links")
}
override fun getEntityData(): WithListSoftLinksEntityData = result ?: super.getEntityData() as WithListSoftLinksEntityData
override fun getEntityClass(): Class<WithListSoftLinksEntity> = WithListSoftLinksEntity::class.java
}
}
class WithListSoftLinksEntityData : WorkspaceEntityData.WithCalculablePersistentId<WithListSoftLinksEntity>(), SoftLinkable {
lateinit var myName: String
lateinit var links: List<NameId>
fun isMyNameInitialized(): Boolean = ::myName.isInitialized
fun isLinksInitialized(): Boolean = ::links.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
for (item in links) {
result.add(item)
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
for (item in links) {
index.index(this, item)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
for (item in links) {
val removedItem_item = mutablePreviousSet.remove(item)
if (!removedItem_item) {
index.index(this, item)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val links_data = links.map {
val it_data = if (it == oldLink) {
changed = true
newLink as NameId
}
else {
null
}
if (it_data != null) {
it_data
}
else {
it
}
}
if (links_data != null) {
links = links_data
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<WithListSoftLinksEntity> {
val modifiable = WithListSoftLinksEntityImpl.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): WithListSoftLinksEntity {
val entity = WithListSoftLinksEntityImpl()
entity._myName = myName
entity._links = links
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return AnotherNameId(myName)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return WithListSoftLinksEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as WithListSoftLinksEntityData
if (this.myName != other.myName) return false
if (this.entitySource != other.entitySource) return false
if (this.links != other.links) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as WithListSoftLinksEntityData
if (this.myName != other.myName) return false
if (this.links != other.links) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + links.hashCode()
return result
}
} | apache-2.0 | f9c959252101e47a6f21c69a7e228e5f | 34.148148 | 152 | 0.624473 | 5.92233 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SwapBinaryExpressionIntention.kt | 2 | 3924 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.util.PsiPrecedences
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.types.expressions.OperatorConventions
class SwapBinaryExpressionIntention : SelfTargetingIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("flip.binary.expression")
), LowPriorityAction {
companion object {
private val SUPPORTED_OPERATIONS: Set<KtSingleValueToken> by lazy {
setOf(PLUS, MUL, OROR, ANDAND, EQEQ, EXCLEQ, EQEQEQ, EXCLEQEQEQ, GT, LT, GTEQ, LTEQ)
}
private val SUPPORTED_OPERATION_NAMES: Set<String> by lazy {
SUPPORTED_OPERATIONS.asSequence().mapNotNull { OperatorConventions.BINARY_OPERATION_NAMES[it]?.asString() }.toSet() +
setOf("xor", "or", "and", "equals")
}
}
override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean {
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
if (leftSubject(element) == null || rightSubject(element) == null) {
return false
}
val operationToken = element.operationToken
val operationTokenText = opRef.text
if (operationToken in SUPPORTED_OPERATIONS
|| operationToken == IDENTIFIER && operationTokenText in SUPPORTED_OPERATION_NAMES
) {
setTextGetter(KotlinBundle.lazyMessage("flip.0", operationTokenText))
return true
}
return false
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
// Have to use text here to preserve names like "plus"
val convertedOperator = when (val operator = element.operationReference.text!!) {
">" -> "<"
"<" -> ">"
"<=" -> ">="
">=" -> "<="
else -> operator
}
val left = leftSubject(element) ?: return
val right = rightSubject(element) ?: return
val rightCopy = right.copied()
val leftCopy = left.copied()
left.replace(rightCopy)
right.replace(leftCopy)
element.replace(KtPsiFactory(element).createExpressionByPattern("$0 $convertedOperator $1", element.left!!, element.right!!))
}
private fun leftSubject(element: KtBinaryExpression): KtExpression? =
firstDescendantOfTighterPrecedence(element.left, PsiPrecedences.getPrecedence(element), KtBinaryExpression::getRight)
private fun rightSubject(element: KtBinaryExpression): KtExpression? =
firstDescendantOfTighterPrecedence(element.right, PsiPrecedences.getPrecedence(element), KtBinaryExpression::getLeft)
private fun firstDescendantOfTighterPrecedence(
expression: KtExpression?,
precedence: Int,
getChild: KtBinaryExpression.() -> KtExpression?
): KtExpression? {
if (expression is KtBinaryExpression) {
val expressionPrecedence = PsiPrecedences.getPrecedence(expression)
if (!PsiPrecedences.isTighter(expressionPrecedence, precedence)) {
return firstDescendantOfTighterPrecedence(expression.getChild(), precedence, getChild)
}
}
return expression
}
}
| apache-2.0 | 989f866e04fb1401afa6a6920553430a | 42.120879 | 158 | 0.695464 | 4.967089 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/statistic/ShortcutConflictState.kt | 1 | 9159 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.statistic
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.key.ShortcutOwner
import com.maddyhome.idea.vim.key.ShortcutOwnerInfo
import java.awt.event.InputEvent
import java.awt.event.InputEvent.CTRL_DOWN_MASK
import java.awt.event.InputEvent.SHIFT_DOWN_MASK
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
internal class ShortcutConflictState : ApplicationUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): Set<MetricEvent> {
val metrics = mutableSetOf<MetricEvent>()
keyStrokes.forEach { keystroke ->
getHandlersForShortcut(keystroke)
.filter { !setOf(HandledModes.INSERT_UNDEFINED, HandledModes.NORMAL_UNDEFINED, HandledModes.VISUAL_AND_SELECT_UNDEFINED).contains(it) }
.forEach { mode ->
metrics += HANDLER.metric(keystroke.toReadableString(), mode)
println(keystroke.toReadableString())
}
}
return metrics
}
private fun getHandlersForShortcut(shortcut: KeyStroke): List<HandledModes> {
val modes = VimPlugin.getKey().shortcutConflicts[shortcut] ?: return listOf(HandledModes.NORMAL_UNDEFINED, HandledModes.INSERT_UNDEFINED, HandledModes.VISUAL_AND_SELECT_UNDEFINED)
return when (modes) {
is ShortcutOwnerInfo.AllModes -> {
when (modes.owner) {
ShortcutOwner.IDE -> listOf(HandledModes.NORMAL_IDE, HandledModes.INSERT_IDE, HandledModes.VISUAL_AND_SELECT_IDE)
ShortcutOwner.VIM -> listOf(HandledModes.NORMAL_VIM, HandledModes.INSERT_VIM, HandledModes.VISUAL_AND_SELECT_VIM)
ShortcutOwner.UNDEFINED -> listOf(HandledModes.NORMAL_UNDEFINED, HandledModes.INSERT_UNDEFINED, HandledModes.VISUAL_AND_SELECT_UNDEFINED)
}
}
is ShortcutOwnerInfo.PerMode -> {
val result = mutableListOf<HandledModes>()
when (modes.normal) {
ShortcutOwner.IDE -> result.add(HandledModes.NORMAL_IDE)
ShortcutOwner.VIM -> result.add(HandledModes.NORMAL_VIM)
ShortcutOwner.UNDEFINED -> result.add(HandledModes.NORMAL_UNDEFINED)
}
when (modes.insert) {
ShortcutOwner.IDE -> result.add(HandledModes.INSERT_IDE)
ShortcutOwner.VIM -> result.add(HandledModes.INSERT_VIM)
ShortcutOwner.UNDEFINED -> result.add(HandledModes.INSERT_UNDEFINED)
}
when (modes.visual) {
ShortcutOwner.IDE -> result.add(HandledModes.VISUAL_AND_SELECT_IDE)
ShortcutOwner.VIM -> result.add(HandledModes.VISUAL_AND_SELECT_VIM)
ShortcutOwner.UNDEFINED -> result.add(HandledModes.VISUAL_AND_SELECT_UNDEFINED)
}
result
}
}
}
companion object {
private val GROUP = EventLogGroup("vim.handlers", 1)
private val keyStrokes = listOf(
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
)
private val KEY_STROKE = EventFields.String("key_stroke", keyStrokes.map { it.toReadableString() })
private val HANDLER_MODE = EventFields.Enum<HandledModes>("handler")
private val HANDLER = GROUP.registerEvent("vim.handler", KEY_STROKE, HANDLER_MODE)
}
}
private fun KeyStroke.toReadableString(): String {
val result = StringBuilder()
val modifiers = this.modifiers
if (modifiers > 0) {
result.append(preprocessKeys(InputEvent.getModifiersExText(modifiers)))
.append("+")
}
result.append(KeyEvent.getKeyText(this.keyCode))
return result.toString()
}
private fun preprocessKeys(string: String): String {
return string.replace("⌃", "Ctrl").replace("⇧", "Shift")
}
private enum class HandledModes {
NORMAL_UNDEFINED,
NORMAL_IDE,
NORMAL_VIM,
INSERT_UNDEFINED,
INSERT_IDE,
INSERT_VIM,
VISUAL_AND_SELECT_UNDEFINED,
VISUAL_AND_SELECT_IDE,
VISUAL_AND_SELECT_VIM,
}
| mit | a2e7827735ae8d1724e1e24d67e4ca75 | 47.184211 | 183 | 0.701912 | 3.843409 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/ProjectExtensionsTest.kt | 1 | 6565 | package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectFactory
import org.gradle.api.Project
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.plugins.Convention
import org.gradle.api.reflect.TypeOf
import org.junit.Assert.fail
import org.junit.Test
@Suppress("deprecation")
class ProjectExtensionsTest {
@Test
fun `can get generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.the<NamedDomainObjectContainer<List<String>>>()
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.configure<NamedDomainObjectContainer<List<String>>> {}
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can get convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<org.gradle.api.plugins.JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java)))
.thenReturn(javaConvention)
project.the<org.gradle.api.plugins.JavaPluginConvention>()
inOrder(convention) {
verify(convention).findByType(any<TypeOf<org.gradle.api.plugins.JavaPluginConvention>>())
verify(convention).findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<org.gradle.api.plugins.JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(any<TypeOf<*>>()))
.thenReturn(null)
whenever(convention.findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java)))
.thenReturn(javaConvention)
project.configure<org.gradle.api.plugins.JavaPluginConvention> {}
inOrder(convention) {
verify(convention).findByType(any<TypeOf<org.gradle.api.plugins.JavaPluginConvention>>())
verify(convention).findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `the() falls back to throwing getByType when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<org.gradle.api.plugins.JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.getByType(eq(conventionType)))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.the<org.gradle.api.plugins.JavaPluginConvention>()
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java))
verify(convention).getByType(eq(conventionType))
verifyNoMoreInteractions()
}
}
@Test
fun `configure() falls back to throwing configure when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<org.gradle.api.plugins.JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.configure(eq(conventionType), any<Action<org.gradle.api.plugins.JavaPluginConvention>>()))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.configure<org.gradle.api.plugins.JavaPluginConvention> {}
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(org.gradle.api.plugins.JavaPluginConvention::class.java))
verify(convention).configure(eq(conventionType), any<Action<org.gradle.api.plugins.JavaPluginConvention>>())
verifyNoMoreInteractions()
}
}
@Test
fun container() {
val project = mock<Project> {
on { container(any<Class<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
on { container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
}
project.container<String>()
inOrder(project) {
verify(project).container(String::class.java)
verifyNoMoreInteractions()
}
project.container { "some" }
inOrder(project) {
verify(project).container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>())
verifyNoMoreInteractions()
}
}
}
| apache-2.0 | 0d3f728afe759d5ed842fb5caa209989 | 34.106952 | 143 | 0.664737 | 5.10101 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/base/BaseSize.kt | 1 | 3742 | package org.hexworks.zircon.api.data.base
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Rect
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.shape.RectangleFactory
import kotlin.math.max
import kotlin.math.min
/**
* Base class for implementing [Size].
*/
abstract class BaseSize : Size {
override operator fun plus(other: Size) = Size.create(width + other.width, height + other.height)
override operator fun minus(other: Size) = Size.create(
width = max(0, width - other.width),
height = max(0, height - other.height)
)
override operator fun component1() = width
override operator fun component2() = height
override fun compareTo(other: Size) = (this.width * this.height).compareTo(other.width * other.height)
override val isUnknown: Boolean
get() = this === Size.unknown()
override val isNotUnknown: Boolean
get() = this !== Size.unknown()
private val rect: Rect by lazy {
Rect.create(Position.defaultPosition(), this)
}
override fun fetchPositions(): Iterable<Position> = Iterable {
var currY = 0
var currX = 0
val endX = width
val endY = height
object : Iterator<Position> {
override fun hasNext() = currY < endY && currX < endX
override fun next(): Position {
return Position.create(currX, currY).also {
currX++
if (currX == endX) {
currY++
if (currY < endY) {
currX = 0
}
}
}
}
}
}
override fun fetchBoundingBoxPositions(): Set<Position> {
return RectangleFactory
.buildRectangle(Position.defaultPosition(), this)
.positions
}
override fun fetchTopLeftPosition() = Position.topLeftCorner()
override fun fetchTopRightPosition() = Position.create(width - 1, 0)
override fun fetchBottomLeftPosition() = Position.create(0, height - 1)
override fun fetchBottomRightPosition() = Position.create(width - 1, height - 1)
override fun withWidth(width: Int): Size {
if (this.width == width) {
return this
}
return Size.create(width, this.height)
}
override fun withHeight(height: Int): Size {
if (this.height == height) {
return this
}
return Size.create(this.width, height)
}
override fun withRelativeWidth(delta: Int): Size {
if (delta == 0) {
return this
}
return withWidth(width + delta)
}
override fun withRelativeHeight(delta: Int): Size {
if (delta == 0) {
return this
}
return this.withHeight(height + delta)
}
override fun withRelative(delta: Size): Size {
return this.withRelativeHeight(delta.height).withRelativeWidth(delta.width)
}
override fun max(other: Size): Size {
return withWidth(max(width, other.width))
.withHeight(max(height, other.height))
}
override fun min(other: Size): Size {
return withWidth(min(width, other.width))
.withHeight(min(height, other.height))
}
override fun with(size: Size): Size {
if (equals(size)) {
return this
}
return size
}
override fun containsPosition(position: Position) = rect.containsPosition(position)
override fun toPosition() = Position.create(width, height)
override fun toRect(): Rect = rect
override fun toRect(position: Position): Rect = Rect.create(position, this)
}
| apache-2.0 | ba3343e73e3f6f4548d60d085d1419d7 | 27.348485 | 106 | 0.596472 | 4.376608 | false | false | false | false |
timfreiheit/PreferencesDelegate | library/src/main/kotlin/de/timfreiheit/preferencesdelegate/PreferencesDelegate.kt | 1 | 19919 | package de.timfreiheit.preferencesdelegate
import android.content.SharedPreferences
/**
*
* Created by timfreiheit on 15.05.15.
*/
public interface ProvidePreferences {
var sharedPreferences: SharedPreferences
}
public object PreferencesDelegate {
//start delegates with ProvidePreferences
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun int(
builder: (BasePreferencesDelegate<ProvidePreferences, Int?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Int?> {
return any(type = BaseIntType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun intNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, Int>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Int> {
return anyNotNull(type = BaseIntType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun long(
builder: (BasePreferencesDelegate<ProvidePreferences, Long?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Long?> {
return any(type = BaseLongType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun longNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, Long>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Long> {
return anyNotNull(type = BaseLongType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun string(
builder: (BasePreferencesDelegate<ProvidePreferences, String?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, String?> {
return any(type = BaseStringType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun stringNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, String>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, String> {
return anyNotNull(type = BaseStringType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun bool(
builder: (BasePreferencesDelegate<ProvidePreferences, Boolean?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Boolean?> {
return any(type = BaseBooleanType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun boolNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, Boolean>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Boolean> {
return anyNotNull(type = BaseBooleanType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun float(
builder: (BasePreferencesDelegate<ProvidePreferences, Float?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Float?> {
return any(type = BaseFloatType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun floatNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, Float>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Float> {
return anyNotNull(type = BaseFloatType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* @param builder init key and default value
*/
public fun stringSet(
builder: (BasePreferencesDelegate<ProvidePreferences, Set<String>?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Set<String>?> {
return any(type = BaseStringSetType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
* The instance of the SharedPreferences are provided over
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param builder init key and default value
*/
public fun stringSetNotNull(
builder: (BasePreferencesDelegate<ProvidePreferences, Set<String>>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, Set<String>> {
return anyNotNull(type = BaseStringSetType, builder = builder)
}
//end delegates with ProvidePreferences
//start delegates without ProvidePreferences
//users must give an extra instance of SharedPreferences
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun int(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Int?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Int?> {
return any(prefs = prefs, type = BaseIntType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun intNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Int>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Int> {
return anyNotNull(prefs = prefs, type = BaseIntType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun long(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Long?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Long?> {
return any(prefs = prefs, type = BaseLongType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun longNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Long>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Long> {
return anyNotNull(prefs = prefs, type = BaseLongType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun string(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, String?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, String?> {
return any(prefs = prefs, type = BaseStringType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun stringNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, String>.() -> Unit)? = null
): BasePreferencesDelegate<Any, String> {
return anyNotNull(prefs = prefs, type = BaseStringType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun bool(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Boolean?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Boolean?> {
return any(prefs = prefs, type = BaseBooleanType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun boolNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Boolean>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Boolean> {
return anyNotNull(prefs = prefs, type = BaseBooleanType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun float(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Float?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Float?> {
return any(prefs = prefs, type = BaseFloatType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun floatNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Float>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Float> {
return anyNotNull(prefs = prefs, type = BaseFloatType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun stringSet(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Set<String>?>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Set<String>?> {
return any(prefs = prefs, type = BaseStringSetType, builder = builder)
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param prefs the SharedPreferences where the property values are stored.
* @param builder init key and default value
*/
public fun stringSetNotNull(
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, Set<String>>.() -> Unit)? = null
): BasePreferencesDelegate<Any, Set<String>> {
return anyNotNull(prefs = prefs, type = BaseStringSetType, builder = builder)
}
//end delegates without ProvidePreferences
//generic delegates
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param type the type which is used to parse the raw value
* @param builder init key and default value
*/
public fun any<F, T : Any?>(
type: GenericType<F, T>,
builder: (BasePreferencesDelegate<ProvidePreferences, T?>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, T?> {
var delegate = PreferencesDelegateWithProvider<F, T?>(
type = NullableType(type))
if (builder != null) {
delegate.builder()
}
return delegate
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param type the type which is used to parse the raw value
* @param builder init key and default value
*/
public fun anyNotNull<F, T : Any>(
type: GenericType<F, T>,
builder: (BasePreferencesDelegate<ProvidePreferences, T>.() -> Unit)? = null
): BasePreferencesDelegate<ProvidePreferences, T> {
var delegate = PreferencesDelegateWithProvider(
type = type)
if (builder != null) {
delegate.builder()
}
return delegate
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* @param type the type which is used to parse the raw value
* @param builder init key and default value
*/
public fun any<F, T : Any?>(
type: GenericType<F, T>,
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, T?>.() -> Unit)? = null
): BasePreferencesDelegateGeneric<Any, F, T?> {
var delegate = PreferencesDelegateWithoutProvider<F, T?>(
sharedPreferences = prefs,
type = NullableType(type))
if (builder != null) {
delegate.builder()
}
return delegate
}
/**
* Returns a property delegate for a read-only property that takes its value from a SharedPreferences,
* using the property name or the defined key in the builder as the key.
*
* Trying to read the property before the initial value has been
* assigned and not having an defaultValue results in an exception.
*
* @param type the type which is used to parse the raw value
* @param builder init key and default value
*/
public fun anyNotNull<F, T : Any>(
type: GenericType<F, T>,
prefs: SharedPreferences,
builder: (BasePreferencesDelegate<Any, T>.() -> Unit)? = null
): BasePreferencesDelegateGeneric<Any, F, T> {
var delegate = PreferencesDelegateWithoutProvider<F, T>(
sharedPreferences = prefs,
type = NullableType(type))
if (builder != null) {
delegate.builder()
}
return delegate
}
} | apache-2.0 | 71e574809e1498ca28496d65937bf8ed | 40.761006 | 106 | 0.667805 | 4.926787 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PostModelUploadStatusTracker.kt | 1 | 2761 | package org.wordpress.android.ui.posts
import android.annotation.SuppressLint
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.UploadStore
import org.wordpress.android.ui.uploads.UploadActionUseCase
import org.wordpress.android.ui.uploads.UploadService
import org.wordpress.android.viewmodel.posts.PostListItemUploadStatus
import kotlin.math.roundToInt
import javax.inject.Inject
/**
* This is a temporary class to make the PostListViewModel more manageable. Please feel free to refactor it any way
* you see fit.
*/
class PostModelUploadStatusTracker @Inject constructor(
private val uploadStore: UploadStore,
private val uploadActionUseCase: UploadActionUseCase
) {
/*
Using `SparseArray` is results in ArrayIndexOutOfBoundsException when we are trying to put a new item. Although
the reason for the crash is unclear, this defeats the whole purpose of using a `SparseArray`. Furthermore,
`SparseArray` is actually not objectively better than using a `HashMap` and in this case `HashMap` should perform
better due to higher number of items.
https://github.com/wordpress-mobile/WordPress-Android/issues/11487
*/
@SuppressLint("UseSparseArrays")
private val uploadStatusMap = HashMap<Int, PostListItemUploadStatus>()
fun getUploadStatus(post: PostModel, siteModel: SiteModel): PostListItemUploadStatus {
uploadStatusMap[post.id]?.let { return it }
val uploadError = uploadStore.getUploadErrorForPost(post)
val isUploadingOrQueued = UploadService.isPostUploadingOrQueued(post)
val hasInProgressMediaUpload = UploadService.hasInProgressMediaUploadsForPost(post)
val newStatus = PostListItemUploadStatus(
uploadError = uploadError,
mediaUploadProgress = (UploadService.getMediaUploadProgressForPost(post) * 100).roundToInt(),
isUploading = UploadService.isPostUploading(post),
isUploadingOrQueued = isUploadingOrQueued,
isQueued = UploadService.isPostQueued(post),
isUploadFailed = uploadStore.isFailedPost(post),
hasInProgressMediaUpload = hasInProgressMediaUpload,
hasPendingMediaUpload = UploadService.hasPendingMediaUploadsForPost(post),
isEligibleForAutoUpload = uploadActionUseCase.isEligibleForAutoUpload(siteModel, post),
uploadWillPushChanges = uploadActionUseCase.uploadWillPushChanges(post)
)
uploadStatusMap[post.id] = newStatus
return newStatus
}
fun invalidateUploadStatus(localPostIds: List<Int>) {
localPostIds.forEach { uploadStatusMap.remove(it) }
}
}
| gpl-2.0 | 3b401025336f66874fb71fa987b5371d | 48.303571 | 117 | 0.747555 | 4.939177 | false | false | false | false |
MER-GROUP/intellij-community | platform/configuration-store-impl/src/XmlElementStorage.kt | 2 | 9189 | /*
* 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 com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.SmartHashSet
import gnu.trove.THashMap
import org.jdom.Attribute
import org.jdom.Element
abstract class XmlElementStorage protected constructor(protected val fileSpec: String,
protected val rootElementName: String,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = RoamingType.DEFAULT,
provider: StreamProvider? = null) : StorageBaseEx<StateMap>() {
val roamingType: RoamingType = roamingType ?: RoamingType.DEFAULT
private val provider: StreamProvider? = if (provider == null || roamingType == RoamingType.DISABLED || !provider.isApplicable(fileSpec, this.roamingType)) null else provider
protected abstract fun loadLocalData(): Element?
override final fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean) = storageData.getState(componentName, archive)
override fun archiveState(storageData: StateMap, componentName: String, serializedState: Element?) {
storageData.archive(componentName, serializedState)
}
override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName)
override fun loadData(): StateMap {
val element: Element?
// we don't use local data if has stream provider
if (provider != null && provider.enabled) {
try {
element = loadDataFromProvider()
dataLoadedFromProvider(element)
}
catch (e: Exception) {
LOG.error(e)
element = null
}
}
else {
element = loadLocalData()
}
return if (element == null) StateMap.EMPTY else loadState(element)
}
protected open fun dataLoadedFromProvider(element: Element?) {
}
private fun loadDataFromProvider() = JDOMUtil.load(provider!!.read(fileSpec, roamingType))
private fun loadState(element: Element): StateMap {
beforeElementLoaded(element)
return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor, true))
}
fun setDefaultState(element: Element) {
element.setName(rootElementName)
storageDataRef.set(loadState(element))
}
override fun startExternalization() = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData())
protected abstract fun createSaveSession(states: StateMap): StateStorage.ExternalizationSession
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
val oldData = storageDataRef.get()
val newData = getStorageData(true)
if (oldData == null) {
LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}" }
componentNames.addAll(newData.keys())
}
else {
val changedComponentNames = oldData.getChangedComponentNames(newData)
LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}" }
if (!ContainerUtil.isEmpty(changedComponentNames)) {
componentNames.addAll(changedComponentNames)
}
}
}
private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) {
if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) {
LOG.warn("Old storage data is not equal to current, new storage data was set anyway")
}
}
abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() {
private var copiedStates: MutableMap<String, Any>? = null
private val newLiveStates = THashMap<String, Element>()
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStates == null) null else this
override fun setSerializedState(componentName: String, element: Element?) {
element?.normalizeRootName()
if (copiedStates == null) {
copiedStates = setStateAndCloneIfNeed(componentName, element, originalStates, newLiveStates)
}
else {
updateState(copiedStates!!, componentName, element, newLiveStates)
}
}
override fun save() {
val stateMap = StateMap.fromMap(copiedStates!!)
var element = save(stateMap, storage.rootElementName, newLiveStates)
if (element == null || JDOMUtil.isEmpty(element)) {
element = null
}
else {
storage.beforeElementSaved(element)
}
val provider = storage.provider
if (provider != null && provider.enabled) {
if (element == null) {
provider.delete(storage.fileSpec, storage.roamingType)
}
else {
// we should use standard line-separator (\n) - stream provider can share file content on any OS
provider.write(storage.fileSpec, element.toBufferExposingByteArray(), storage.roamingType)
}
}
else {
saveLocally(element)
}
storage.setStates(originalStates, stateMap)
}
protected abstract fun saveLocally(element: Element?)
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun beforeElementSaved(element: Element) {
if (pathMacroSubstitutor != null) {
try {
pathMacroSubstitutor.collapsePaths(element)
}
finally {
pathMacroSubstitutor.reset()
}
}
}
public fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) {
if (roamingType == RoamingType.DISABLED) {
// storage roaming was changed to DISABLED, but settings repository has old state
return
}
try {
val newElement = if (deleted) null else loadDataFromProvider()
val states = storageDataRef.get()
if (newElement == null) {
// if data was loaded, mark as changed all loaded components
if (states != null) {
changedComponentNames.addAll(states.keys())
setStates(states, null)
}
}
else if (states != null) {
val newStates = loadState(newElement)
changedComponentNames.addAll(states.getChangedComponentNames(newStates))
setStates(states, newStates)
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
fun save(states: StateMap, rootElementName: String, newLiveStates: Map<String, Element>? = null): Element? {
if (states.isEmpty()) {
return null
}
val rootElement = Element(rootElementName)
for (componentName in states.keys()) {
val element = states.getElement(componentName, newLiveStates)
// name attribute should be first
val elementAttributes = element.attributes
if (elementAttributes.isEmpty()) {
element.setAttribute(FileStorageCoreUtil.NAME, componentName)
}
else {
var nameAttribute: Attribute? = element.getAttribute(FileStorageCoreUtil.NAME)
if (nameAttribute == null) {
nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName)
elementAttributes.add(0, nameAttribute)
}
else {
nameAttribute.setValue(componentName)
if (elementAttributes.get(0) != nameAttribute) {
elementAttributes.remove(nameAttribute)
elementAttributes.add(0, nameAttribute)
}
}
}
rootElement.addContent(element)
}
return rootElement
}
fun Element.normalizeRootName(): Element {
if (parent != null) {
LOG.warn("State element must not have parent ${JDOMUtil.writeElement(this)}")
detach()
}
setName(FileStorageCoreUtil.COMPONENT)
return this
}
// newStorageData - myStates contains only live (unarchived) states
private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> {
val bothStates = keys().toMutableSet()
bothStates.retainAll(newStates.keys())
val diffs = SmartHashSet<String>()
diffs.addAll(newStates.keys())
diffs.addAll(keys())
diffs.removeAll(bothStates)
for (componentName in bothStates) {
compare(componentName, newStates, diffs)
}
return diffs
} | apache-2.0 | ffb6da1cfc5f757df03c171c168f78b3 | 35.468254 | 175 | 0.697138 | 5.035068 | false | false | false | false |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/ytime/controller/YTimePunchesActivity.kt | 1 | 14527 | package edu.byu.suite.features.ytime.controller
import android.annotation.SuppressLint
import android.app.TimePickerDialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.TimePicker
import edu.byu.suite.R
import edu.byu.suite.features.ytime.model.YTimeDay
import edu.byu.suite.features.ytime.model.YTimePunch
import edu.byu.suite.features.ytime.model.YTimePunchWrapper
import edu.byu.suite.features.ytime.service.PunchesClient
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuSwipeOnlyCallback
import edu.byu.support.ByuViewHolder
import edu.byu.support.activity.ByuRecyclerViewActivity
import edu.byu.support.adapter.HeaderAdapter
import edu.byu.support.login.account.AccountInformation
import edu.byu.support.retrofit.ByuCallback
import edu.byu.support.retrofit.ByuError
import edu.byu.support.retrofit.ByuSuccessCallback
import edu.byu.support.utils.*
import kotlinx.android.synthetic.main.ytime_activity_punches.*
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Response
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.collections.ArrayList
import kotlin.math.roundToInt
/**
* Created by poolguy on 5/23/17
*/
class YTimePunchesActivity: ByuRecyclerViewActivity() {
companion object {
const val YTIME_DAY_EXTRA = "yTimeDay"
const val EMPLOYEE_RECORD_EXTRA = "employeeRecord"
const val DATE_EXTRA = "date"
private const val TOTAL_HOURS_FORMAT = "Total: %dh %02dm"
private const val MILLISECONDS_IN_HOUR = 3600000.0
private val TOOLBAR_DATE_FORMAT
get() = SimpleDateFormat("EEE MMM d, yyyy", Locale.US)
}
private val corrections = mutableListOf<YTimePunch>()
private lateinit var yTimeDay: YTimeDay
private lateinit var date: Date
private lateinit var adapter: PunchAdapter
private var employeeRecord = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState, R.layout.ytime_activity_punches)
yTimeDay = intent.getParcelableExtra(YTIME_DAY_EXTRA)
employeeRecord = intent.getIntExtra(EMPLOYEE_RECORD_EXTRA, 0)
date = intent.getDateExtra(DATE_EXTRA)
title = TOOLBAR_DATE_FORMAT.format(date)
val rows = ArrayList<Any>(yTimeDay.punches ?: emptyList())
// TOTAL_HOURS_FORMAT displays the total time worked by the user in the format hh:mm. We get the hours the user has worked by rounding down totalTimeWorked, and we
// get the minute value by multiplying the decimal value of totalTimeWorked by 60 and rounding the result.
getTotalHours()?.let { totalTimeWorked -> rows.add(HeaderAdapter.Header(String.format(TOTAL_HOURS_FORMAT, totalTimeWorked.roundDown(), ((totalTimeWorked % 1) * 60).roundToInt()))) }
adapter = PunchAdapter(rows)
ItemTouchHelper(object: ByuSwipeOnlyCallback<YTimePunch>(adapter, this@YTimePunchesActivity, ByuSwipeOnlyCallback.LEFT_AND_RIGHT) {
override fun getSwipeFlags(viewHolder: RecyclerView.ViewHolder) = if ((adapter.get(viewHolder.adapterPosition) as? YTimePunch)?.deletablePair ?: 0 > 0) LEFT_AND_RIGHT else NEITHER_DIRECTION
override fun onSwiped(swipedItem: YTimePunch, direction: Int) {
deleteDuplicatePunch(swipedItem)
}
override fun getColorForBothDirections(swipedItem: YTimePunch) = R.color.byu_red
override fun getIconResForBothDirections(swipedItem: YTimePunch) = R.drawable.icon_default_swipe_delete
}).attachToRecyclerView(recyclerView)
setAdapter(adapter)
submitCorrectionsButton.setOnClickListener { _ ->
showProgressDialog(getString(R.string.submitting_corrections_loading_message))
correctExceptions()
adapter.clearCorrections(true)
}
cancelButton.setOnClickListener { adapter.clearCorrections() }
}
override fun getEmptyDataText(): String = getString(R.string.no_punches_for_day)
private fun getTotalHours(): Double? {
if (yTimeDay.hasException || yTimeDay.punches.isNullOrEmpty()) {
return null
}
val punches = yTimeDay.punches ?: emptyList<YTimePunch>()
var totalHoursWorked = punches.fold(0.0) { total, nextPunch -> total + (nextPunch.hoursWorked ?: 0.0) }
punches.firstOrNull()?.let {
// If the first punch was an out-punch then we have to add the time from the start of the day until that punch
if (!it.clockIn) {
val momentOfPunch = it.getPunchCalendarInstance(date)
val startOfDay = (momentOfPunch.clone() as Calendar).setTime(0, 0, 0)
totalHoursWorked += (momentOfPunch.timeInMillis - startOfDay.timeInMillis) / MILLISECONDS_IN_HOUR
}
}
punches.lastOrNull()?.let {
// If the last punch was an in-punch then we have to calculate the elapsed time following that punch ourselves
if (it.clockIn) {
val momentOfPunch = it.getPunchCalendarInstance(date)
val rightNow = Calendar.getInstance()
return if (TOOLBAR_DATE_FORMAT.format(date) == TOOLBAR_DATE_FORMAT.format(rightNow.time)) {
// If we are viewing the list of punches for the current day, then we calculate the time that has elapsed between the last punch and now
totalHoursWorked + (rightNow.timeInMillis - momentOfPunch.timeInMillis) / MILLISECONDS_IN_HOUR
} else {
// If we are viewing the list of punches for a past day, then just calculate the time between the last in-punch and the end of the day (midnight)
val endOfDay = (momentOfPunch.clone() as Calendar).setTime(23, 59, 59)
totalHoursWorked + (endOfDay.timeInMillis - momentOfPunch.timeInMillis) / MILLISECONDS_IN_HOUR
}
}
}
return totalHoursWorked
}
private fun correctExceptions() {
val correctionCallCount = AtomicInteger(corrections.size)
var anyFailed = false
fun onFinished() {
if (correctionCallCount.decrementAndGet() == 0) {
dismissProgressDialog()
if (anyFailed) {
showErrorDialog(getString(R.string.correction_error_message))
} else {
displayToast(getString(R.string.successful_correction_message, if (corrections.size == 1) " was" else "s were"), true)
}
}
}
corrections.forEach {
enqueueCall(PunchesClient().getApi(this).correctException(AccountInformation.getCleanByuId(this), YTimePunchWrapper(it)), object: ByuCallback<Any>(this, null, PunchesClient.PATH_TO_READABLE_ERROR) {
override fun onSuccess(call: Call<Any>, response: Response<Any>) {
onFinished()
}
override fun onFailure(call: Call<Any>, byuError: ByuError) {
anyFailed = true
onFinished()
}
})
}
}
private fun deleteDuplicatePunch(duplicatePunch: YTimePunch) {
showProgressDialog()
enqueueCall(PunchesClient().getApi(this).deleteDuplicatePunch(AccountInformation.getCleanByuId(this), employeeRecord, yTimeDay.date, duplicatePunch.sequenceNumber), object: ByuSuccessCallback<ResponseBody>(this, pathToReadableError = PunchesClient.PATH_TO_READABLE_ERROR) {
override fun onSuccess(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
dismissProgressDialog()
displayToast(getString(R.string.successful_delete_punch_message))
yTimeDay.punches?.let { punchList ->
// Remove the deleted punch from the punchList so that the find function below gives us the other punch in the deletable pair
punchList.remove(duplicatePunch)
// Find the other punch in the deletable pair and set deletablePair = 0 so that the UI will display it like a normal punch
punchList.find { it.deletablePair == duplicatePunch.deletablePair }?.let { otherDuplicate ->
otherDuplicate.deletablePair = 0
recyclerView.adapter.notifyItemChanged(recyclerView.adapter.list.indexOf(otherDuplicate))
}
// Remove the deleted punch from the adapter's list so that it will no longer show up in the recycler view
recyclerView.adapter.list.indexOf(duplicatePunch).let { duplicatePunchIndex ->
recyclerView.adapter.list.removeAt(duplicatePunchIndex)
recyclerView.adapter.notifyItemRemoved(duplicatePunchIndex)
}
}
}
})
}
private inner class PunchAdapter(list: List<Any>): HeaderAdapter<YTimePunch>(list) {
override fun getBodyViewHolder(parent: ViewGroup, viewType: Int) = PunchViewHolder(inflate(parent, R.layout.default_list_item_detail))
fun clearCorrections(saveCorrections: Boolean = false) {
list.filterIsInstance<YTimePunch>().filter { it.isCorrection }.forEach { correction ->
if (saveCorrections) {
// Display the corrections as legitimate, non-editable punches
correction.isCorrection = false
} else {
// Revert all corrections that were made back to exceptions
list[list.indexOf(correction)] = YTimePunch(correction.clockIn, punchTime = "")
}
}
corrections.clear()
notifyDataSetChanged()
submitCorrectionsButton.visibility = View.GONE
cancelButton.visibility = View.GONE
}
private inner class PunchViewHolder(itemView: View): ByuViewHolder<YTimePunch>(itemView) {
private val textView: TextView = itemView.findViewById(R.id.textView)
private val detailTextView: TextView = itemView.findViewById(R.id.detailText)
@SuppressLint("NewApi")
override fun bind(data: YTimePunch, listener: ByuClickListener<YTimePunch>?) {
super.bind(data, listener)
fun setUpCell(text: String = data.getFormattedTime(), textColor: Int = getColorFromRes(R.color.textDark), detailTextColor: Int = getColorFromRes(R.color.textLight), clickListener: View.OnClickListener? = null) {
textView.text = text
detailTextView.text = data.getDetailText()
textView.setTextColor(textColor)
detailTextView.setTextColor(detailTextColor)
itemView.isEnabled = clickListener != null
itemView.setOnClickListener(clickListener)
}
fun setUpEditableCell(text: String) {
setUpCell(text, getColorFromRes(R.color.textLight), getColorFromRes(R.color.red), View.OnClickListener {
// If the exception being corrected is not the first punch in the list, minTime = the time of the preceding punch, otherwise minTime = 12:00am
val minTime = if (adapterPosition != 0) (get(adapterPosition - 1) as YTimePunch).getPunchCalendarInstance(date) else Calendar.getInstance().setTime(0, 0, 0)
// If the exception being corrected is not the last punch in the list, maxTime = the time of the following punch, otherwise maxTime = 11:59pm
val maxTime = if (adapterPosition != itemCount - 1) (get(adapterPosition + 1) as YTimePunch).getPunchCalendarInstance(date) else Calendar.getInstance().setTime(23, 59, 59)
YTimeTimePickerDialog(this@YTimePunchesActivity, minTime, maxTime) { _, hourOfDay, minute ->
val correction = YTimePunch(data.clockIn, employeeRecord = employeeRecord, isCorrection = true).apply { setDateTime(Calendar.getInstance().apply { time = yTimeDay.dateAsDate() }.apply { setTime(hourOfDay, minute, 0) }.time, true) }
dismissProgressDialog()
corrections.replaceOrAdd(correction, data)
list[adapterPosition] = correction
notifyItemChanged(adapterPosition)
submitCorrectionsButton.visibility = View.VISIBLE
cancelButton.visibility = View.VISIBLE
}.show()
})
}
when {
data.isException() -> setUpEditableCell(getString(R.string.tap_to_correct))
data.isCorrection -> setUpEditableCell(data.getFormattedTime())
data.isDeletable() -> setUpCell(detailTextColor = getColorFromRes(R.color.red), clickListener = View.OnClickListener {
showAlertDialog(message = getString(R.string.delete_punch_verification), positiveListener = { _, _ -> deleteDuplicatePunch(data) })
})
else -> setUpCell()
}
}
}
}
// This class allows us to set a minimum and maximum time that the user can choose between to correct an exception.
// (see https://stackoverflow.com/questions/13516389/android-timepickerdialog-set-max-time?noredirect=1&lq=1)
private class YTimeTimePickerDialog(context: Context, minTime: Calendar, maxTime: Calendar, callBack: (TimePicker, Int, Int) -> Unit):
TimePickerDialog(context, when {
// The clock TimePicker became the default in Lollipop, but our min/max time bounds don't work for the clock TimePickers on any OS before Nougat, so we use the Spinner in these cases.
Build.VERSION.SDK_INT < Build.VERSION_CODES.N -> R.style.TimePickerDialog_Spinner
// Use the clock TimePicker if the device's OS is Nougat or newer.
else -> R.style.TimePickerDialog
// We add a minute to minTime because the user shouldn't be able to create a punch that is the same time as the previous punch.
}, callBack, minTime.apply { add(Calendar.MINUTE, 1) }.get(Calendar.HOUR_OF_DAY), minTime.get(Calendar.MINUTE), false) {
companion object {
private val calendar = Calendar.getInstance()
private val dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT)
}
private val minHour = minTime.get(Calendar.HOUR_OF_DAY)
private val minMinute = minTime.get(Calendar.MINUTE)
// We subtract a minute from maxTime because the user shouldn't be able to create a punch that is the same time as the following punch.
private val maxHour = maxTime.apply { add(Calendar.MINUTE, -1) }.get(Calendar.HOUR_OF_DAY)
private val maxMinute = maxTime.get(Calendar.MINUTE)
private var currentHour = minHour
private var currentMinute = minMinute
override fun onTimeChanged(view: TimePicker?, hourOfDay: Int, minute: Int) {
currentHour = when {
hourOfDay in minHour..maxHour -> hourOfDay // The user selected an hour within the time frame
hourOfDay + 12 in minHour..maxHour -> hourOfDay + 12 // The user selected an hour within the time frame, but we need to switch from AM to PM
hourOfDay - 12 in minHour..maxHour -> hourOfDay - 12 // The user selected an hour within the time frame, but we need to switch from PM to AM
hourOfDay < minHour -> minHour // The user selected an hour that was too early
else -> maxHour // The user selected an hour that was too late
}
currentMinute = when {
currentHour == minHour && minute < minMinute -> minMinute
currentHour == maxHour && minute > maxMinute -> maxMinute
else -> minute
}
updateTime(currentHour, currentMinute)
updateDialogTitle(currentHour, currentMinute)
}
private fun updateDialogTitle(hourOfDay: Int, minute: Int) {
calendar.setTime(hourOfDay, minute)
setTitle(dateFormat.format(calendar.time))
}
}
}
| apache-2.0 | 30429f8fc9b0f46805dc1bb9804eb6a4 | 48.077703 | 275 | 0.748813 | 3.820884 | false | false | false | false |
Carighan/kotlin-koans | test/iii_conventions/N26InRangeKtTest.kt | 10 | 1789 | package iii_conventions
import iii_conventions.test.s
import org.junit.Assert.assertEquals
import org.junit.Test
class N26InRangeKtTest {
fun doTest(date: MyDate, first: MyDate, last: MyDate, shouldBeInRange: Boolean) {
val message = "The date ${date.s} should${if (shouldBeInRange) "" else "n't"} be in range: ${first.s}..${last.s}"
assertEquals(message, shouldBeInRange, checkInRange(date, first, last))
}
/* Month numbering starts with 0 (0-Jan, 1-Feb, ... 11-Dec) */
@Test fun testInRange() {
doTest(MyDate(2014, 3, 22), MyDate(2014, 1, 1), MyDate(2015, 1, 1), shouldBeInRange = true)
}
@Test fun testBefore() {
doTest(MyDate(2013, 3, 22), MyDate(2014, 1, 1), MyDate(2015, 1, 1), shouldBeInRange = false)
}
@Test fun testAfter() {
doTest(MyDate(2015, 3, 22), MyDate(2014, 1, 1), MyDate(2015, 1, 1), shouldBeInRange = false)
}
@Test fun testEqualsToBegin() {
doTest(MyDate(2014, 3, 22), MyDate(2014, 3, 22), MyDate(2015, 1, 1), shouldBeInRange = true)
}
@Test fun testEqualsToEnd() {
doTest(MyDate(2015, 1, 1), MyDate(2014, 3, 22), MyDate(2015, 1, 1), shouldBeInRange = true)
}
@Test fun testInOneDayRange() {
doTest(MyDate(2015, 1, 1), MyDate(2015, 1, 1), MyDate(2015, 1, 1), shouldBeInRange = true)
}
@Test fun testInvalidRange() {
doTest(MyDate(2014, 2, 1), MyDate(2015, 1, 1), MyDate(2014, 1, 1), shouldBeInRange = false)
}
@Test fun testInvalidRangeEqualsToBegin() {
doTest(MyDate(2015, 1, 1), MyDate(2015, 1, 1), MyDate(2014, 1, 1), shouldBeInRange = false)
}
@Test fun testInvalidRangeEqualsToEnd() {
doTest(MyDate(2014, 1, 1), MyDate(2015, 1, 1), MyDate(2014, 1, 1), shouldBeInRange = false)
}
} | mit | 9d9b21b66cf946bf4da377ce10846cdd | 35.530612 | 121 | 0.626607 | 3.394687 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/InRange.kt | 4 | 2674 | // WITH_STDLIB
@OptIn(ExperimentalStdlibApi::class)
fun test(obj : Int) {
if (obj > 10) {
if (<warning descr="Condition 'obj in 1..5' is always false">obj in 1..5</warning>) {}
if (<warning descr="Condition 'obj !in 1..5' is always true">obj !in 1..5</warning>) {}
if (<warning descr="Condition 'obj in 1..<5' is always false">obj in 1..<5</warning>) {}
if (<warning descr="Condition 'obj !in 1..<5' is always true">obj !in 1..<5</warning>) {}
}
if (obj in 1..10) {
if (<warning descr="Condition 'obj !in 0..11' is always false">obj !in 0..11</warning>) {}
if (<warning descr="Condition 'obj in 1..10' is always true">obj in 1..10</warning>) {}
if (<warning descr="Condition 'obj in 1..<11' is always true">obj in 1..<11</warning>) {}
if (obj in 1 until 10) {}
if (obj in 1..<10) {}
if (<warning descr="Condition 'obj in 1 until 11' is always true">obj in 1 until 11</warning>) {}
if (<warning descr="Condition 'obj in 1..<11' is always true">obj in 1..<11</warning>) {}
if (<warning descr="Condition 'obj in 20..30' is always false">obj in 20..30</warning>) {}
if (<warning descr="Condition 'obj in -10..-5' is always false">obj in -10..-5</warning>) {}
}
if (obj in 20..30) {
if (<warning descr="Condition 'obj in 1..10' is always false">obj in 1..10</warning>) {}
if (<warning descr="Condition 'obj in 1..<11' is always false">obj in 1..<11</warning>) {}
}
if (obj in 1..<10) {
if (<warning descr="Condition 'obj >= 10' is always false">obj >= 10</warning>) {}
}
if (1 in obj..10) {
if (<warning descr="Condition 'obj > 10' is always false">obj > 10</warning>) {}
if (<warning descr="Condition 'obj >= 10' is always false">obj >= 10</warning>) {}
if (<warning descr="Condition 'obj > 1' is always false">obj > 1</warning>) {}
if (<warning descr="Condition 'obj <= 1' is always true">obj <= 1</warning>) {}
}
if (1 in obj..<10) {
if (<warning descr="Condition 'obj > 10' is always false">obj > 10</warning>) {}
if (<warning descr="Condition 'obj >= 10' is always false">obj >= 10</warning>) {}
if (<warning descr="Condition 'obj > 1' is always false">obj > 1</warning>) {}
if (<warning descr="Condition 'obj <= 1' is always true">obj <= 1</warning>) {}
}
if (1 in -1..<obj) {
if (<warning descr="Condition 'obj >= 2' is always true">obj >= 2</warning>) {}
if (<warning descr="Condition 'obj < 2' is always false">obj < 2</warning>) {}
}
}
fun test(a:Long, b:Long): Boolean {
return a in 1 until b
}
| apache-2.0 | e905c7034bb6d58719d42c30eca50fa8 | 50.423077 | 105 | 0.568063 | 3.509186 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/rtmp/message/RtmpCommandMessage.kt | 1 | 2987 | package com.haishinkit.rtmp.message
import com.haishinkit.amf.Amf0Deserializer
import com.haishinkit.amf.Amf0Serializer
import com.haishinkit.event.Event
import com.haishinkit.rtmp.RtmpConnection
import com.haishinkit.rtmp.RtmpObjectEncoding
import java.nio.ByteBuffer
import java.util.ArrayList
/**
* 7.1.1. Command Message (20, 17)
*/
internal class RtmpCommandMessage(private val objectEncoding: RtmpObjectEncoding) :
RtmpMessage(objectEncoding.commandType) {
var commandName: String? = null
var transactionID = 0
var commandObject: Map<String, Any?>? = null
var arguments: List<Any?> = mutableListOf()
override var length: Int = CAPACITY
override fun encode(buffer: ByteBuffer): RtmpMessage {
if (type == TYPE_AMF3_COMMAND) {
buffer.put(0x00.toByte())
}
val serializer = Amf0Serializer(buffer)
serializer.putString(commandName)
serializer.putDouble(transactionID.toDouble())
serializer.putMap(commandObject)
for (`object` in arguments) {
serializer.putObject(`object`)
}
return this
}
override fun decode(buffer: ByteBuffer): RtmpMessage {
val position = buffer.position()
val deserializer = Amf0Deserializer(buffer)
commandName = deserializer.string
transactionID = deserializer.double.toInt()
commandObject = deserializer.map
val arguments = ArrayList<Any?>()
while (buffer.position() - position != length) {
arguments.add(deserializer.`object`)
}
this.arguments = arguments
return this
}
override fun execute(connection: RtmpConnection): RtmpMessage {
val responders = connection.responders
if (responders.containsKey(transactionID)) {
val responder = responders[transactionID]
when (commandName) {
"_result" -> {
responder?.onResult(arguments)
return this
}
"_error" -> {
responder?.onStatus(arguments)
return this
}
}
responders.remove(transactionID)
return this
}
when (commandName) {
"close" -> {
connection.close()
}
"onStatus" -> {
val stream = connection.streams[streamID]
stream?.dispatchEventWith(
Event.RTMP_STATUS,
false,
if (arguments.isEmpty()) null else arguments[0]
)
}
else -> {
connection.dispatchEventWith(
Event.RTMP_STATUS,
false,
if (arguments.isEmpty()) null else arguments[0]
)
}
}
return this
}
companion object {
private const val CAPACITY = 1024
}
}
| bsd-3-clause | 7a55342bd456915d2839fc6b2e85fe5f | 30.114583 | 83 | 0.568798 | 5.02862 | false | false | false | false |
Lizhny/BigDataFortuneTelling | baseuilib/src/main/java/com/bdft/baseuilib/widget/indicator/DotIndicator.kt | 1 | 2827 | package com.bdft.baseuilib.widget.indicator
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import com.bdft.baselibrary.utils.ui.UIUtils
import com.socks.library.KLog
/**
* ${}
* Created by spark_lizhy on 2017/10/27.
*/
class DotIndicator @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
val TAG = "DotIndicator"
val DEAFULT_DOT_NUM = 0
val MAX_DOT_NUM = 9
val DOT_SIZE = 8
var mCurrentSelection = 0
var mDotNum = DEAFULT_DOT_NUM
val mDotViews: ArrayList<DotView>
get() = arrayListOf()
fun init(context: Context, dotNum: Int): DotIndicator {
orientation = HORIZONTAL
gravity = Gravity.CENTER
mDotNum = if (dotNum == 0) {
DEAFULT_DOT_NUM
} else {
dotNum
}
buildDotView(context)
visibility = if (dotNum < 1) {
View.GONE
} else {
View.VISIBLE
}
setCurrentSelection(0)
return this
}
private fun buildDotView(context: Context) {
for (i in 0..mDotNum) {
val dotView = DotView(context)
dotView.isSelected = false
val params = LayoutParams(UIUtils.px2Dip(DOT_SIZE).toInt(), UIUtils.px2Dip(DOT_SIZE).toInt())
if (i == 0) {
params.leftMargin = 0
} else {
params.leftMargin = UIUtils.dip2Px(6f).toInt()
}
addView(dotView, params)
mDotViews.add(dotView)
}
}
private fun getCurrentSelecttion(): Int = mCurrentSelection
public fun setCurrentSelection(selection: Int) {
mCurrentSelection = selection
for (dotView: DotView in mDotViews) {
dotView.isSelected = false
}
if (selection >= 0 && selection < mDotViews.size) {
mDotViews[selection].isSelected = true
} else {
KLog.e(TAG, "the selection can not over mDotViews size")
}
}
public fun getDotNum(): Int = mDotNum
fun setDotViewNum(num: Int) {
if (num < 1 || num > MAX_DOT_NUM) {
KLog.e(TAG, "num必须在1~" + MAX_DOT_NUM + "之间哦")
}
if (num <= 1) {
removeAllViews()
visibility = View.GONE
}
if (mDotNum != num) {
mDotNum = num
removeAllViews()
mDotViews.clear()
buildDotView(context)
setCurrentSelection(0)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
mDotViews.clear()
KLog.i(TAG, "清除DotIndicator引用")
}
} | apache-2.0 | 9fe998baa4a7576d167e756abfcae11b | 25.490566 | 105 | 0.57321 | 4.140118 | false | false | false | false |
KotlinBy/bkug.by | data/src/main/kotlin/by/bkug/data/Meetup10.kt | 1 | 2689 | package by.bkug.data
import org.intellij.lang.annotations.Language
@Language("markdown")
val meetup10 = """
Встреча нашего сообщества состоится 6 сентября, в [Space](http://eventspace.by).
## Программа:
### Приветственный кофе (18:40 - 19:00)
Вас ждут печеньки, чай и кофе.
### Введение в OPENRNDR - Сергей Крюков (19:00 - 19:50)
Продолжаю тему "нецелевого" использования языка Kotlin. В этот раз поговорим об OPENRNDR — фреймворке для креативного программирования, как убеждают его авторы. Так ли это? Проверим на практике.
<img class="circle_150" src="https://bkug.by/wp-content/uploads/2018/08/siarhei_krukau.jpg" alt="Сергей Крюков" />
Сергей Крюков, пишет на Java чтобы оплачивать счета. Играется с Kotlin чтобы отдохнуть от этого.
### Kotlin/JS - Роман Артемьев (20:00 - 20:50)
В докладе речь пойдет про Kotlin/JS, я расскажу что это такое и зачем нужно в контексте Kotlin MPP (Multiplatform Projects). Покопаемся под капотом у компилятора, познакомимся с полезными тулами для разработки на Kotlin/JS. Немного затроним будущее этого направления языка, а также постараемся ответить на самые волнующие сообщество вопросы. Приходите, будет интересно!
<img class="circle_150" src="https://bkug.by/wp-content/uploads/2018/08/roman_artemev.jpg" alt="Роман Артемьев" />
Артемьев Роман, работаю в команде Kotlin/JS. До того, как присоединтся к команде JetBrains, разрабатывал JVM и хакал CoreCLR. С удовльствием делюсь знаниями и готов отвечать на любые вопросы.
* **Дата проведения**: 6 сентября
* **Время**: 19:00–21:00
* **Место проведения**: ул. Октябрьская, 16А – EventSpace. Парковка и вход через ул. Октябрьскую, 10б.
Для участия во встрече необходима предварительная [регистрация](https://goo.gl/forms/8LVC8tNL209HhDnp2).
[huge_it_maps id="2"]
""".trimIndent()
| gpl-3.0 | 099c6cfab01fcd92441b4071e1c2fb39 | 45.947368 | 369 | 0.764013 | 2.126341 | false | false | false | false |
marius-m/wt4 | components/src/test/java/lt/markmerkk/AccountAvailabilityInteractorOAuthTest.kt | 1 | 3937 | package lt.markmerkk
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.whenever
import lt.markmerkk.utils.AccountAvailablility
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class AccountAvailabilityInteractorOAuthTest {
@Mock lateinit var userSettings: UserSettings
@Mock lateinit var jiraClientProvider: JiraClientProvider
lateinit var accountAvailablility: AccountAvailablility
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
accountAvailablility = AccountAvailabilityOAuth(userSettings, jiraClientProvider)
}
@Test
fun valid() {
// Assemble
doReturn(Mocks.createJiraOAuthPreset(
host = "hostname",
privateKey = "private_key",
consumerKey = "consumer_key"
)).whenever(userSettings).jiraOAuthPreset()
doReturn(Mocks.createJiraOAuthCreds(
tokenSecret = "tokey_secret",
accessKey = "access_key"
)).whenever(userSettings).jiraOAuthCreds()
doReturn(Mocks.createJiraUser()).whenever(userSettings).jiraUser()
val result = accountAvailablility.isAccountReadyForSync()
assertThat(result).isTrue()
}
@Test
fun noPreset() {
// Assemble
doReturn(Mocks.createJiraOAuthPreset(
host = "",
privateKey = "",
consumerKey = ""
)).whenever(userSettings).jiraOAuthPreset()
doReturn(Mocks.createJiraOAuthCreds(
tokenSecret = "tokey_secret",
accessKey = "access_key"
)).whenever(userSettings).jiraOAuthCreds()
doReturn(Mocks.createJiraUser()).whenever(userSettings).jiraUser()
val result = accountAvailablility.isAccountReadyForSync()
assertThat(result).isFalse()
}
@Test
fun noCreds() {
// Assemble
doReturn(Mocks.createJiraOAuthPreset(
host = "hostname",
privateKey = "private_key",
consumerKey = "consumer_key"
)).whenever(userSettings).jiraOAuthPreset()
doReturn(Mocks.createJiraOAuthCreds(
tokenSecret = "",
accessKey = ""
)).whenever(userSettings).jiraOAuthCreds()
doReturn(Mocks.createJiraUser()).whenever(userSettings).jiraUser()
val result = accountAvailablility.isAccountReadyForSync()
assertThat(result).isFalse()
}
@Test
fun emptyUser() {
// Assemble
doReturn(Mocks.createJiraOAuthPreset(
host = "hostname",
privateKey = "private_key",
consumerKey = "consumer_key"
)).whenever(userSettings).jiraOAuthPreset()
doReturn(Mocks.createJiraOAuthCreds(
tokenSecret = "tokey_secret",
accessKey = "access_key"
)).whenever(userSettings).jiraOAuthCreds()
doReturn(Mocks.createJiraUserEmpty()).whenever(userSettings).jiraUser()
val result = accountAvailablility.isAccountReadyForSync()
assertThat(result).isFalse()
}
@Test
fun clientError() {
// Assemble
doReturn(Mocks.createJiraOAuthPreset(
host = "hostname",
privateKey = "private_key",
consumerKey = "consumer_key"
)).whenever(userSettings).jiraOAuthPreset()
doReturn(Mocks.createJiraOAuthCreds(
tokenSecret = "tokey_secret",
accessKey = "access_key"
)).whenever(userSettings).jiraOAuthCreds()
doReturn(Mocks.createJiraUser()).whenever(userSettings).jiraUser()
doReturn(true).whenever(jiraClientProvider).hasError()
val result = accountAvailablility.isAccountReadyForSync()
assertThat(result).isFalse()
}
} | apache-2.0 | 967bcc463578762831903d6071e6da2c | 31.816667 | 89 | 0.630429 | 4.896766 | false | true | false | false |
jovr/imgui | core/src/main/kotlin/imgui/internal/generic helpers.kt | 1 | 32052 | package imgui.internal
import glm_.*
import glm_.vec1.Vec1i
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import glm_.vec4.Vec4
import imgui.*
import imgui.api.g
import kool.BYTES
import kool.rem
import uno.kotlin.NUL
import unsigned.toBigInt
import unsigned.toUInt
import java.math.BigInteger
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.StandardCharsets
import kotlin.math.abs
import kotlin.reflect.KMutableProperty0
//-----------------------------------------------------------------------------
// [SECTION] Generic helpers
//-----------------------------------------------------------------------------
/** Unsaturated, for display purpose */
fun F32_TO_INT8_UNBOUND(_val: Float) = (_val * 255f + if (_val >= 0) 0.5f else -0.5f).i
/** Saturated, always output 0..255 */
fun F32_TO_INT8_SAT(_val: Float) = (saturate(_val) * 255f + 0.5f).i
fun round(f: Float): Float = (f + 0.5f).i.f
// -----------------------------------------------------------------------------------------------------------------
// Error handling
// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
// -----------------------------------------------------------------------------------------------------------------
//#ifndef IMGUI_USER_ERROR
//#define IMGUI_USER_ERROR(_EXPR, _MSG) IM_ASSERT((_EXPR) && (_MSG)) // Recoverable User Error
//#endif
// -----------------------------------------------------------------------------------------------------------------
// Helpers: Hashing
// -----------------------------------------------------------------------------------------------------------------
fun fileLoadToMemory(filename: String): CharArray? =
ClassLoader.getSystemResourceAsStream(filename)?.use { s ->
val bytes = s.readBytes()
CharArray(bytes.size) { bytes[it].c }
}
/** [JVM] */
fun hash(data: Int, seed: Int = 0): ID {
val buffer = ByteBuffer.allocate(Int.BYTES).order(ByteOrder.LITTLE_ENDIAN) // as C
buffer.putInt(0, data)
return hash(buffer, seed)
}
/** [JVM] */
fun hash(data: IntArray, seed: Int = 0): ID {
val buffer = ByteBuffer.allocate(data.size * Int.BYTES).order(ByteOrder.LITTLE_ENDIAN) // as C
for (i in data.indices) buffer.putInt(i * Int.BYTES, data[i])
val bytes = ByteArray(buffer.rem) { buffer[it] }
return hashStr(String(bytes, StandardCharsets.ISO_8859_1), bytes.size, seed)
}
/** CRC32 needs a 1KB lookup table (not cache friendly)
* Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
* - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. */
val GCrc32LookupTable = longArrayOf(
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D)
.map { it.i }.toIntArray()
/** Known size hash
* It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
* FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. */
fun hash(data: ByteArray, seed: Int = 0): ID {
var crc = seed.inv()
val crc32Lut = GCrc32LookupTable
var b = 0
var dataSize = data.size
while (dataSize-- != 0)
crc = (crc ushr 8) xor crc32Lut[(crc and 0xFF) xor data[b++].toUInt()]
return crc.inv()
}
/** Known size hash
* It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
* FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. */
fun hash(data: ByteBuffer, seed: Int = 0): ID {
var crc = seed.inv()
val crc32Lut = GCrc32LookupTable
var dataSize = data.rem
while (dataSize-- != 0)
crc = (crc ushr 8) xor crc32Lut[(crc and 0xFF) xor data.get().toUInt()]
return crc.inv()
}
fun hashStr(data: String, dataSize_: Int = 0, seed_: Int = 0): ID {
/*
convert to "Extended ASCII" Windows-1252 (CP1252) https://en.wikipedia.org/wiki/Windows-1252
this caused crashes with `-` which in CP1252 is 150, while on UTF16 is 8211
*/
// val data = data_.toByteArray(Charset.forName("Cp1252"))
val ast = '#'//.b
val seed = seed_.inv()
var crc = seed
var src = 0
val crc32Lut = GCrc32LookupTable
var dataSize = dataSize_
if (dataSize != 0)
while (dataSize-- != 0) {
val c = data[src++]
if (c == ast && data[src] == ast && data[src + 1] == ast)
crc = seed
crc = (crc ushr 8) xor crc32Lut[(crc and 0xFF) xor c.i]
}
else
while (src < data.length) {
val c = data[src++]
if (c == ast && data.getOrNull(src) == ast && data.getOrNull(src + 1) == ast)
crc = seed
// val b = crc ushr 8
// val d = crc and 0xFF
// val e = d xor c.b.toUnsignedInt
// crc = b xor crc32Lut[e]
crc = (crc ushr 8) xor crc32Lut[(crc and 0xFF) xor c.b.toUInt()] // unsigned -> avoid negative values being passed as indices
}
return crc.inv()
}
// Helpers: Color Blending
fun alphaBlendColors(colA: Int, colB: Int): Int {
val t = ((colB ushr COL32_A_SHIFT) and 0xFF) / 255.f
val r = lerp((colA ushr COL32_R_SHIFT) and 0xFF, (colB ushr COL32_R_SHIFT) and 0xFF, t)
val g = lerp((colA ushr COL32_G_SHIFT) and 0xFF, (colB ushr COL32_G_SHIFT) and 0xFF, t)
val b = lerp((colA ushr COL32_B_SHIFT) and 0xFF, (colB ushr COL32_B_SHIFT) and 0xFF, t)
return COL32(r, g, b, 0xFF)
}
// -----------------------------------------------------------------------------------------------------------------
// Helpers: Bit manipulation
// -----------------------------------------------------------------------------------------------------------------
val Int.isPowerOfTwo: Boolean
get() = this != 0 && (this and (this - 1)) == 0
val Int.upperPowerOfTwo: Int
get() {
var v = this - 1
v = v or (v ushr 1)
v = v or (v ushr 2)
v = v or (v ushr 4)
v = v or (v ushr 8)
v = v or (v ushr 16)
v++
return v
}
// -----------------------------------------------------------------------------------------------------------------
// Helpers: String, Formatting
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
// -----------------------------------------------------------------------------------------------------------------
//IMGUI_API int ImStricmp(const char* str1, const char* str2);
//IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count);
// [JVM] => System.arrayCopy
//IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count);
//IMGUI_API char* ImStrdup(const char* str);
//IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str);
fun strchrRange(str: ByteArray, strBegin: Int, strEnd: Int, c: Char): Int {
for (i in strBegin until strEnd)
if (str[i] == c.b)
return i
return -1
}
val CharArray.strlenW: Int
get() {
var n = 0
while (this[n] != NUL) n++
return n
}
//IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line
//IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
//IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
/** Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position.
* We use this in situation where the cost is negligible. */
fun trimBlanks(buf: CharArray): CharArray {
var p = 0
while (buf[p] == ' ' || buf[p] == '\t') // Leading blanks
p++
val start = p
p = buf.size // end of string
while (p > start && (buf[p - 1] == ' ' || buf[p - 1] == '\t')) // Trailing blanks
p--
return when (start) {
0 -> buf
else -> CharArray(p - start) { buf[start + it] }
}
}
//IMGUI_API const char* ImStrSkipBlank(const char* str);
//IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3);
fun formatString(buf: ByteArray, fmt: String, vararg args: Any): Int {
val bytes = fmt.format(g.style.locale, *args).toByteArray()
bytes.copyInto(buf) // TODO IndexOutOfBoundsException?
return bytes.size.also { w -> buf[w] = 0 }
}
//IMGUI_API const char* ImParseFormatFindStart(const char* format);
//IMGUI_API const char* ImParseFormatFindEnd(const char* format);
//IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size);
//IMGUI_API int ImParseFormatPrecision(const char* format, int default_value);
fun charIsBlankA(c: Int): Boolean = c == ' '.i || c == '\t'.i
val Char.isBlankA: Boolean
get() = this == ' ' || this == '\t'
fun charIsBlankW(c: Int): Boolean = c == ' '.i || c == '\t'.i || c == 0x3000
val Char.isBlankW: Boolean
get() = this == ' ' || this == '\t' || i == 0x3000
// -----------------------------------------------------------------------------------------------------------------
// Helpers: UTF-8 <> wchar
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// -----------------------------------------------------------------------------------------------------------------
/** return output UTF-8 bytes count */
fun textStrToUtf8(buf: ByteArray, text: CharArray): Int {
var b = 0
var t = 0
while (b < buf.size && t < text.size && text[t] != NUL) {
val c = text[t++].i
if (c < 0x80)
buf[b++] = c.b
else
b += textCharToUtf8(buf, b, c)
}
if (b < buf.size) buf[b] = 0
return b
}
/** Based on stb_to_utf8() from github.com/nothings/stb/
* ~ImTextCharToUtf8 */
fun textCharToUtf8(buf: ByteArray, b: Int, c: Int): Int {
if (c < 0x80) {
buf[b + 0] = c.b
return 1
}
if (c < 0x800) {
if (buf.size < b + 2) return 0
buf[b + 0] = (0xc0 + (c ushr 6)).b
buf[b + 1] = (0x80 + (c and 0x3f)).b
return 2
}
if (c < 0x10000) {
if (buf.size < 3) return 0
buf[0] = (0xe0 + (c ushr 12)).b
buf[1] = (0x80 + ((c ushr 6) and 0x3f)).b
buf[2] = (0x80 + (c and 0x3f)).b
return 3
}
if (c <= 0x10FFFF) {
if (buf.size < b + 4) return 0
buf[b + 0] = (0xf0 + (c ushr 18)).b
buf[b + 1] = (0x80 + ((c ushr 12) and 0x3f)).b
buf[b + 2] = (0x80 + ((c ushr 6) and 0x3f)).b
buf[b + 3] = (0x80 + (c and 0x3f)).b
return 4
}
// Invalid code point, the max unicode is 0x10FFFF
return 0
}
///** read one character. return input UTF-8 bytes count
// * @return [JVM] [char: Int, bytes: Int] */
//fun textCharFromUtf8(text: ByteArray, textBegin: Int = 0, textEnd: Int = text.strlen()): Pair<Int, Int> {
// var str = textBegin
// fun s(i: Int = 0) = text[i + str].toUInt()
// fun spp() = text[str++].toUInt()
// val invalid = UNICODE_CODEPOINT_INVALID // will be invalid but not end of string
// if ((s() and 0x80) == 0) return spp() to 1
// if ((s() and 0xe0) == 0xc0) {
// if (textEnd != 0 && textEnd - str < 2) return invalid to 1
// if (s() < 0xc2) return invalid to 2
// var c = (spp() and 0x1f) shl 6
// if ((s() and 0xc0) != 0x80) return invalid to 2
// c += (spp() and 0x3f)
// return c to 2
// }
// if ((s() and 0xf0) == 0xe0) {
// if (textEnd != 0 && textEnd - str < 3) return invalid to 1
// if (s() == 0xe0 && (s(1) < 0xa0 || s(1) > 0xbf)) return invalid to 3
// if (s() == 0xed && s(1) > 0x9f) return invalid to 3 // str[1] < 0x80 is checked below
// var c = (spp() and 0x0f) shl 12
// if ((s() and 0xc0) != 0x80) return invalid to 3
// c += (spp() and 0x3f) shl 6
// if ((s() and 0xc0) != 0x80) return invalid to 3
// c += spp() and 0x3f
// return c to 3
// }
// if ((s() and 0xf8) == 0xf0) {
// if (textEnd != 0 && textEnd - str < 4) return invalid to 1
// if (s() > 0xf4) return invalid to 4
// if (s() == 0xf0 && (s(1) < 0x90 || s(1) > 0xbf)) return invalid to 4
// if (s() == 0xf4 && s(1) > 0x8f) return invalid to 4 // str[1] < 0x80 is checked below
// var c = (spp() and 0x07) shl 18
// if ((s() and 0xc0) != 0x80) return invalid to 4
// c += (spp() and 0x3f) shl 12
// if ((s() and 0xc0) != 0x80) return invalid to 4
// c += (spp() and 0x3f) shl 6
// if ((s() and 0xc0) != 0x80) return invalid to 4
// c += spp() and 0x3f
// // utf-8 encodings of values used in surrogate pairs are invalid
// if ((c and 0xFFFFF800.i) == 0xD800) return invalid to 4
// // If codepoint does not fit in ImWchar, use replacement character U+FFFD instead
// if (c >= UNICODE_CODEPOINT_MAX) c = UNICODE_CODEPOINT_INVALID
// return c to 4
// }
// return 0 to 0
//}
private val lengths = intArrayOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0)
private val masks = intArrayOf(0x00, 0x7f, 0x1f, 0x0f, 0x07)
private val mins = intArrayOf(0x400000, 0, 0x80, 0x800, 0x10000)
private val shiftc = intArrayOf(0, 18, 12, 6, 0)
private val shifte = intArrayOf(0, 6, 4, 2, 0)
/** read one character. return input UTF-8 bytes count
*
* Convert UTF-8 to 32-bit character, process single character input.
* Based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8)
* We handle UTF-8 decoding error by skipping forward.
*
* @return [JVM] [char: Int, bytes: Int]
*
* ~ImTextCharFromUtf8 */
fun textCharFromUtf8(text: ByteArray, begin: Int = 0, textEnd: Int = text.strlen()): Pair<Int, Int> {
var end = textEnd
val len = lengths[text[begin].i ushr 3]
var wanted = len + (len == 0).i
if (textEnd == -1)
end = len + if (len == 0) 1 else 0 // Max length, nulls will be taken into account.
// Copy at most 'len' bytes, stop copying at 0 or past in_text_end.
val s = ByteArray(4)
s[0] = if (begin + 0 < end) text[begin + 0] else 0
s[1] = if (s[0] != 0.b && begin + 1 < end) text[begin + 1] else 0
s[2] = if (s[1] != 0.b && begin + 2 < end) text[begin + 2] else 0
s[3] = if (s[2] != 0.b && begin + 3 < end) text[begin + 3] else 0
// Assume a four-byte character and load four bytes. Unused bits are shifted out.
var outChar = (s[0].i and masks[len]) shl 18
outChar = outChar or ((s[1].i and 0x3f) shl 12)
outChar = outChar or ((s[2].i and 0x3f) shl 6)
outChar = outChar or ((s[3].i and 0x3f) shl 0)
outChar = outChar ushr shiftc[len]
// Accumulate the various error conditions.
var e = (outChar < mins[len]).i shl 6 // non-canonical encoding
e = e or (((outChar ushr 11) == 0x1b).i shl 7) // surrogate half?
e = e or ((outChar > UNICODE_CODEPOINT_MAX).i shl 8) // out of range?
e = e or ((s[1].i and 0xc0) ushr 2)
e = e or ((s[2].i and 0xc0) ushr 4)
e = e or (s[3].i ushr 6)
e = e xor 0x2a // top two bits of each tail byte correct?
e = e ushr shifte[len]
if (e != 0) {
// No bytes are consumed when *in_text == 0 || in_text == in_text_end.
// One byte is consumed in case of invalid first byte of in_text.
// All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
// Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
wanted = min(wanted, s[0].bool.i + s[1].bool.i + s[2].bool.i + s[3].bool.i)
outChar = UNICODE_CODEPOINT_INVALID
}
return outChar to wanted
}
/** return input UTF-8 bytes count */
fun textStrFromUtf8(buf: CharArray, text: ByteArray, textEnd: Int = text.size, textRemaining: Vec1i? = null): Int {
var b = 0
var t = 0
while (b < buf.lastIndex && t < textEnd && text[t] != 0.b) {
val (c, bytes) = textCharFromUtf8(text, t, textEnd)
t += bytes
if (c == 0)
break
buf[b++] = c.c
}
if (b < buf.size) buf[b] = NUL
textRemaining?.put(t)
return b
}
/** ~ImTextStrFromUtf8 */
fun CharArray.textStr(src: CharArray): Int {
var i = 0
while (i < size) {
if (src[i] == NUL) break
this[i] = src[i++]
}
return i
}
/** return number of UTF-8 code-points (NOT bytes count)
* ~ImTextCountCharsFromUtf8 */
fun textCountCharsFromUtf8(text: ByteArray, textEnd: Int = text.size): Int {
var charCount = 0
var t = 0
while (t < textEnd && text[t] != 0.b) {
val (c, bytes) = textCharFromUtf8(text, t, textEnd)
t += bytes
if (c == 0)
break
charCount++
}
return charCount
}
/** return number of bytes to express one char in UTF-8 */
fun textCountUtf8BytesFromChar(text: ByteArray, textEnd: Int): Int {
val (_, bytes) = textCharFromUtf8(text, textEnd = textEnd)
return bytes
}
/** return number of bytes to express one char in UTF-8 */
fun String.countUtf8BytesFromChar(textEnd: Int) = kotlin.math.min(length, textEnd)
/** return number of bytes to express string in UTF-8
* overload with textBegin = 0 */
fun textCountUtf8BytesFromStr(text: CharArray, textEnd: Int): Int = textCountUtf8BytesFromStr(text, 0, textEnd)
/** return number of bytes to express string in UTF-8 */
fun textCountUtf8BytesFromStr(text: CharArray, textBegin: Int, textEnd: Int): Int {
var bytesCount = 0
var t = textBegin
while (t < textEnd && text[t] != NUL) {
val c = text[t++].i
if (c < 0x80)
bytesCount++
else
bytesCount += textCountUtf8BytesFromChar(c)
}
return bytesCount
}
fun textCountUtf8BytesFromChar(c: Int) = when {
c < 0x80 -> 1
c < 0x800 -> 2
c < 0x10000 -> 3
c <= 0x10FFFF -> 4
else -> 3
}
/** Find beginning-of-line
* ~ImStrbolW */
infix fun CharArray.beginOfLine(midLine: Int): Int {
var res = midLine
while (res > 0 && this[res - 1] != '\n') res--
return res
}
val Vec2.lengthSqr: Float
get() = x * x + y * y
// -----------------------------------------------------------------------------------------------------------------
// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double
// (Exceptionally using templates here but we could also redefine them for those types)
// -----------------------------------------------------------------------------------------------------------------
fun swap(a: KMutableProperty0<Float>, b: KMutableProperty0<Float>) {
val tmp = a()
a.set(b())
b.set(tmp)
}
/** Byte, Short versions */
fun addClampOverflow(a: Int, b: Int, mn: Int, mx: Int): Int = when {
b < 0 && (a < mn - b) -> mn
b > 0 && (a > mx - b) -> mx
else -> a + b
}
fun subClampOverflow(a: Int, b: Int, mn: Int, mx: Int): Int = when {
b > 0 && (a < mn + b) -> mn
b < 0 && (a > mx + b) -> mx
else -> a - b
}
/** Int versions */
fun addClampOverflow(a: Long, b: Long, mn: Long, mx: Long): Long = when {
b < 0 && (a < mn - b) -> mn
b > 0 && (a > mx - b) -> mx
else -> a + b
}
fun subClampOverflow(a: Long, b: Long, mn: Long, mx: Long): Long = when {
b > 0 && (a < mn + b) -> mn
b < 0 && (a > mx + b) -> mx
else -> a - b
}
/** Ulong versions */
fun addClampOverflow(a: BigInteger, b: BigInteger, mn: BigInteger, mx: BigInteger): BigInteger = when {
b < 0.toBigInt() && (a < mn - b) -> mn
b > 0.toBigInt() && (a > mx - b) -> mx
else -> a + b
}
fun subClampOverflow(a: BigInteger, b: BigInteger, mn: BigInteger, mx: BigInteger): BigInteger = when {
b > 0.toBigInt() && (a < mn + b) -> mn
b < 0.toBigInt() && (a > mx + b) -> mx
else -> a - b
}
// -----------------------------------------------------------------------------------------------------------------
// Misc maths helpers
// -----------------------------------------------------------------------------------------------------------------
fun floor(a: Float): Float = a.i.f
fun floor(a: Vec2): Vec2 = Vec2(floor(a.x), floor(a.y))
fun lerp(a: Float, b: Float, t: Float): Float = a + (b - a) * t
fun lerp(a: Double, b: Double, t: Float): Double = a + (b - a) * t
fun lerp(a: Int, b: Int, t: Float): Int = (a + (b - a) * t).i
fun lerp(a: Long, b: Long, t: Float): Long = (a + (b - a) * t).L
fun modPositive(a: Int, b: Int): Int = (a + b) % b
// TODO -> glm
fun Vec2.lerp(b: Vec2, t: Float): Vec2 = Vec2(x + (b.x - x) * t, y + (b.y - y) * t)
fun Vec2.lerp(b: Vec2, t: Vec2): Vec2 = Vec2(x + (b.x - x) * t.x, y + (b.y - y) * t.y)
fun Vec2.lerp(b: Vec2i, t: Vec2): Vec2 = Vec2(x + (b.x - x) * t.x, y + (b.y - y) * t.y)
fun Vec2i.lerp(b: Vec2i, t: Vec2): Vec2 = Vec2(x + (b.x - x) * t.x, y + (b.y - y) * t.y)
fun Vec4.lerp(b: Vec4, t: Float): Vec4 = Vec4 { lerp(this[it], b[it], t) }
fun saturate(f: Float): Float = if (f < 0f) 0f else if (f > 1f) 1f else f
infix fun Vec2.invLength(failValue: Float): Float {
val d = x * x + y * y
if (d > 0f)
return 1f / glm.sqrt(d)
return failValue
}
fun Vec2.rotate(cosA: Float, sinA: Float) = Vec2(x * cosA - y * sinA, x * sinA + y * cosA)
fun linearSweep(current: Float, target: Float, speed: Float) = when {
current < target -> glm.min(current + speed, target)
current > target -> glm.max(current - speed, target)
else -> current
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
fun bezierCubicCalc(p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, t: Float): Vec2 {
val u = 1f - t
val w1 = u * u * u
val w2 = 3 * u * u * t
val w3 = 3 * u * t * t
val w4 = t * t * t
return Vec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y)
}
/** For curves with explicit number of segments */
fun bezierCubicClosestPoint(p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, p: Vec2, numSegments: Int): Vec2 {
assert(numSegments > 0) { "Use ImBezierClosestPointCasteljau()" }
val pLast = Vec2(p1)
val pClosest = Vec2()
var pClosestDist2 = Float.MAX_VALUE
val tStep = 1f / numSegments
for (iStep in 1..numSegments) {
val pCurrent = bezierCubicCalc(p1, p2, p3, p4, tStep * iStep)
val pLine = lineClosestPoint(pLast, pCurrent, p)
val dist2 = (p - pLine).lengthSqr
if (dist2 < pClosestDist2) {
pClosest put pLine
pClosestDist2 = dist2
}
pLast put pCurrent
}
return pClosest
}
/** For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol
*
* tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
* Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically. */
fun bezierCubicClosestPointCasteljau(p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, p: Vec2, tessTol: Float): Vec2 {
assert(tessTol > 0f)
val pLast = p1 // [JVM] careful, same instance!
val pClosest = Vec2()
val pClosestDist2 = Float.MAX_VALUE
// [JVM] we dont need the return value
bezierCubicClosestPointCasteljauStep(p, pClosest, pLast, pClosestDist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tessTol, 0)
return pClosest
}
fun bezierQuadraticCalc(p1: Vec2, p2: Vec2, p3: Vec2, t: Float): Vec2 {
val u = 1f - t
val w1 = u * u
val w2 = 2 * u * t
val w3 = t * t
return Vec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y)
}
/** Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
*
* [JVM] p, pClosest, pLast, pClosestDist2 are supposed to modify the given instance
* [JVM] @return pClosestDist2
*/
fun bezierCubicClosestPointCasteljauStep(p: Vec2, pClosest: Vec2, pLast: Vec2, pClosestDist2: Float,
x1: Float, y1: Float, x2: Float, y2: Float, x3: Float, y3: Float,
x4: Float, y4: Float, tessTol: Float, level: Int): Float {
var res = pClosestDist2
val dx = x4 - x1
val dy = y4 - y1
var d2 = ((x2 - x4) * dy - (y2 - y4) * dx)
var d3 = ((x3 - x4) * dy - (y3 - y4) * dx)
d2 = if (d2 >= 0) d2 else -d2
d3 = if (d3 >= 0) d3 else -d3
if ((d2 + d3) * (d2 + d3) < tessTol * (dx * dx + dy * dy)) {
val pCurrent = Vec2(x4, y4)
val pLine = lineClosestPoint(pLast, pCurrent, p)
val dist2 = (p - pLine).lengthSqr
if (dist2 < pClosestDist2) {
pClosest put pLine
res = dist2 // pClosestDist2 = dist2
}
pLast put pCurrent
} else if (level < 10) {
val x12 = (x1 + x2) * 0.5f
val y12 = (y1 + y2) * 0.5f
val x23 = (x2 + x3) * 0.5f
val y23 = (y2 + y3) * 0.5f
val x34 = (x3 + x4) * 0.5f
val y34 = (y3 + y4) * 0.5f
val x123 = (x12 + x23) * 0.5f
val y123 = (y12 + y23) * 0.5f
val x234 = (x23 + x34) * 0.5f
val y234 = (y23 + y34) * 0.5f
val x1234 = (x123 + x234) * 0.5f
val y1234 = (y123 + y234) * 0.5f
res = bezierCubicClosestPointCasteljauStep(p, pClosest, pLast, res, x1, y1, x12, y12, x123, y123, x1234, y1234, tessTol, level + 1)
res = bezierCubicClosestPointCasteljauStep(p, pClosest, pLast, res, x1234, y1234, x234, y234, x34, y34, x4, y4, tessTol, level + 1)
}
return res
}
fun lineClosestPoint(a: Vec2, b: Vec2, p: Vec2): Vec2 {
val ap = p - a
val abDir = b - a
val dot = ap.x * abDir.x + ap.y * abDir.y
return when {
dot < 0f -> a
else -> {
val abLenSqr = abDir.x * abDir.x + abDir.y * abDir.y
return when {
dot > abLenSqr -> b
else -> a + abDir * dot / abLenSqr
}
}
}
}
fun triangleContainsPoint(a: Vec2, b: Vec2, c: Vec2, p: Vec2): Boolean {
val b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0f
val b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0f
val b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0f
return b1 == b2 && b2 == b3
}
fun triangleClosestPoint(a: Vec2, b: Vec2, c: Vec2, p: Vec2): Vec2 {
val projAB = lineClosestPoint(a, b, p)
val projBC = lineClosestPoint(b, c, p)
val projCA = lineClosestPoint(c, a, p)
val dist2AB = (p - projAB).lengthSqr
val dist2BC = (p - projBC).lengthSqr
val dist2CA = (p - projCA).lengthSqr
val m = glm.min(dist2AB, glm.min(dist2BC, dist2CA))
return when (m) {
dist2AB -> projAB
dist2BC -> projBC
else -> projCA
}
}
fun triangleBarycentricCoords(a: Vec2, b: Vec2, c: Vec2, p: Vec2): FloatArray {
val v0 = b - a
val v1 = c - a
val v2 = p - a
val denom = v0.x * v1.y - v1.x * v0.y
val outV = (v2.x * v1.y - v1.x * v2.y) / denom
val outW = (v0.x * v2.y - v2.x * v0.y) / denom
val outU = 1f - outV - outW
return floatArrayOf(outU, outV, outW)
}
fun triangleArea(a: Vec2, b: Vec2, c: Vec2): Float =
abs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f
fun getDirQuadrantFromDelta(dx: Float, dy: Float) = when {
abs(dx) > abs(dy) -> when {
dx > 0f -> Dir.Right
else -> Dir.Left
}
else -> when {
dy > 0f -> Dir.Down
else -> Dir.Up
}
}
// Helper: ImBitArray class (wrapper over ImBitArray functions)
// Store 1-bit per value. NOT CLEARED by constructor.
//template<int BITCOUNT>
class BitArray(val bitCount: Int) {
val storage = IntArray((bitCount + 31) ushr 5)
fun clearAllBits() = storage.fill(0)
fun setAllBits() = storage.fill(255)
fun mask(n: Int): Int = 1 shl (n and 31)
infix fun testBit(n: Int): Boolean {
assert(n < bitCount)
return storage[n ushr 5] has mask(n)
}
infix fun setBit(n: Int) {
assert(n < bitCount)
storage[n ushr 5] = storage[n ushr 5] or mask(n)
}
infix fun clearBit(n: Int) {
assert(n < bitCount)
storage[n ushr 5] = storage[n ushr 5] wo mask(n)
}
fun setBitRange(n_: Int, n2_: Int) { // Works on range [n..n2)
var n = n_
val n2 = n2_ - 1
while (n <= n2) {
val aMod = n and 31
val bMod = (if (n2 > (n or 31)) 31 else n2 and 31) + 1
val mask = ((1L shl bMod) - 1).i wo ((1L shl aMod) - 1).i
storage[n ushr 5] = storage[n ushr 5] or mask
n = (n + 32) wo 31
}
}
} | mit | 5f4ad5f6513876dce666012bed29f6ab | 40.146341 | 199 | 0.564083 | 2.887568 | false | false | false | false |
google/android-fhir | engine/src/test/java/com/google/android/fhir/sync/download/DownloaderImplTest.kt | 1 | 9150 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.sync.download
import com.google.android.fhir.SyncDownloadContext
import com.google.android.fhir.sync.DataSource
import com.google.android.fhir.sync.DownloadState
import com.google.common.truth.Truth.assertThat
import java.net.UnknownHostException
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.runBlocking
import org.hl7.fhir.r4.model.Bundle
import org.hl7.fhir.r4.model.Observation
import org.hl7.fhir.r4.model.OperationOutcome
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DownloaderImplTest {
val searchPageParamToSearchResponseBundleMap =
mapOf(
"patient-page1" to
Bundle().apply {
type = Bundle.BundleType.SEARCHSET
addLink(
Bundle.BundleLinkComponent().apply {
relation = "next"
url = "url-to-server/patient-page2"
}
)
addEntry(Bundle.BundleEntryComponent().setResource(Patient().apply { id = "Patient-1" }))
},
"patient-page2" to
Bundle().apply {
type = Bundle.BundleType.SEARCHSET
addEntry(Bundle.BundleEntryComponent().setResource(Patient().apply { id = "Patient-2" }))
},
"observation-page1" to
Bundle().apply {
type = Bundle.BundleType.SEARCHSET
addLink(
Bundle.BundleLinkComponent().apply {
relation = "next"
url = "url-to-server/observation-page2"
}
)
addEntry(
Bundle.BundleEntryComponent().setResource(Observation().apply { id = "Observation-1" })
)
},
"observation-page2" to
Bundle().apply {
type = Bundle.BundleType.SEARCHSET
addEntry(
Bundle.BundleEntryComponent().setResource(Observation().apply { id = "Observation-2" })
)
}
)
@Test
fun `downloader with patient and observations should download successfully`() = runBlocking {
val downloader =
DownloaderImpl(
object : DataSource {
override suspend fun download(path: String): Resource {
return when {
path.contains("patient-page1") ->
searchPageParamToSearchResponseBundleMap["patient-page1"]!!
path.contains("patient-page2") ->
searchPageParamToSearchResponseBundleMap["patient-page2"]!!
path.contains("observation-page1") ->
searchPageParamToSearchResponseBundleMap["observation-page1"]!!
path.contains("observation-page2") ->
searchPageParamToSearchResponseBundleMap["observation-page2"]!!
else -> OperationOutcome()
}
}
override suspend fun upload(bundle: Bundle): Resource {
TODO("Not yet implemented")
}
},
ResourceParamsBasedDownloadWorkManager(
mapOf(
ResourceType.Patient to mapOf("param" to "patient-page1"),
ResourceType.Observation to mapOf("param" to "observation-page1")
)
)
)
val result = mutableListOf<DownloadState>()
downloader.download(
object : SyncDownloadContext {
override suspend fun getLatestTimestampFor(type: ResourceType): String? = null
}
)
.collect { result.add(it) }
assertThat(result.filterIsInstance<DownloadState.Started>())
.containsExactly(
DownloadState.Started(ResourceType.Bundle),
)
assertThat(
result.filterIsInstance<DownloadState.Success>().flatMap { it.resources }.map { it.id }
)
.containsExactly("Patient-1", "Patient-2", "Observation-1", "Observation-2")
.inOrder()
}
@Test
fun `downloader with patient and observations should return failure in case of server or network error`() =
runBlocking {
val downloader =
DownloaderImpl(
object : DataSource {
override suspend fun download(path: String): Resource {
return when {
path.contains("patient-page1") ->
searchPageParamToSearchResponseBundleMap["patient-page1"]!!
path.contains("patient-page2") ->
OperationOutcome().apply {
addIssue(
OperationOutcome.OperationOutcomeIssueComponent().apply {
diagnostics = "Server couldn't fulfil the request."
}
)
}
path.contains("observation-page1") ->
searchPageParamToSearchResponseBundleMap["observation-page1"]!!
path.contains("observation-page2") ->
throw UnknownHostException(
"Url host can't be found. Check if device is connected to internet."
)
else -> OperationOutcome()
}
}
override suspend fun upload(bundle: Bundle): Resource {
TODO("Upload not tested in this path")
}
},
ResourceParamsBasedDownloadWorkManager(
mapOf(
ResourceType.Patient to mapOf("param" to "patient-page1"),
ResourceType.Observation to mapOf("param" to "observation-page1")
)
)
)
val result = mutableListOf<DownloadState>()
downloader.download(
object : SyncDownloadContext {
override suspend fun getLatestTimestampFor(type: ResourceType) = null
}
)
.collect { result.add(it) }
assertThat(result.filterIsInstance<DownloadState.Started>())
.containsExactly(
DownloadState.Started(ResourceType.Bundle),
)
assertThat(result.filterIsInstance<DownloadState.Failure>()).hasSize(2)
assertThat(result.filterIsInstance<DownloadState.Failure>().map { it.syncError.resourceType })
.containsExactly(ResourceType.Patient, ResourceType.Observation)
.inOrder()
assertThat(
result.filterIsInstance<DownloadState.Failure>().map { it.syncError.exception.message }
)
.containsExactly(
"Server couldn't fulfil the request.",
"Url host can't be found. Check if device is connected to internet."
)
.inOrder()
}
@Test
fun `downloader with patient and observations should continue to download observations if patient download fail`() =
runBlocking {
val downloader =
DownloaderImpl(
object : DataSource {
override suspend fun download(path: String): Resource {
return when {
path.contains("patient-page1") || path.contains("patient-page2") ->
OperationOutcome().apply {
addIssue(
OperationOutcome.OperationOutcomeIssueComponent().apply {
diagnostics = "Server couldn't fulfil the request."
}
)
}
path.contains("observation-page1") ->
searchPageParamToSearchResponseBundleMap["observation-page1"]!!
path.contains("observation-page2") ->
searchPageParamToSearchResponseBundleMap["observation-page2"]!!
else -> OperationOutcome()
}
}
override suspend fun upload(bundle: Bundle): Resource {
TODO("Not yet implemented")
}
},
ResourceParamsBasedDownloadWorkManager(
mapOf(
ResourceType.Patient to mapOf("param" to "patient-page1"),
ResourceType.Observation to mapOf("param" to "observation-page1")
)
)
)
val result = mutableListOf<DownloadState>()
downloader.download(
object : SyncDownloadContext {
override suspend fun getLatestTimestampFor(type: ResourceType) = null
}
)
.collect { result.add(it) }
assertThat(result.filterIsInstance<DownloadState.Started>())
.containsExactly(
DownloadState.Started(ResourceType.Bundle),
)
assertThat(result.filterIsInstance<DownloadState.Failure>().map { it.syncError.resourceType })
.containsExactly(ResourceType.Patient)
assertThat(
result
.filterIsInstance<DownloadState.Success>()
.flatMap { it.resources }
.filterIsInstance<Observation>()
)
.hasSize(2)
}
}
| apache-2.0 | 674c6f7d0f02b4f7e19d6251d0a9bf7b | 34.465116 | 118 | 0.618579 | 4.882604 | false | false | false | false |
retomerz/intellij-community | platform/configuration-store-impl/src/SchemeManagerImpl.kt | 2 | 30055 | /*
* 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 com.intellij.configurationStore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.AbstractExtensionPointBean
import com.intellij.openapi.options.*
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.tracker.VirtualFileTracker
import com.intellij.util.*
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.URLUtil
import com.intellij.util.text.UniqueNameGenerator
import gnu.trove.THashMap
import gnu.trove.THashSet
import gnu.trove.TObjectObjectProcedure
import org.jdom.Document
import org.jdom.Element
import org.xmlpull.mxp1.MXParser
import org.xmlpull.v1.XmlPullParser
import java.io.IOException
import java.io.InputStream
import java.nio.file.Path
import java.util.*
import java.util.function.Function
class SchemeManagerImpl<T : Scheme, E : ExternalizableScheme>(val fileSpec: String,
private val processor: SchemeProcessor<E>,
private val provider: StreamProvider?,
private val ioDirectory: Path,
val roamingType: RoamingType = RoamingType.DEFAULT,
virtualFileTrackerDisposable: Disposable? = null,
val presentableName: String? = null) : SchemesManager<T, E>(), SafeWriteRequestor {
private val schemes = ArrayList<T>()
private val readOnlyExternalizableSchemes = THashMap<String, ExternalizableScheme>()
/**
* Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance.
*/
private @Volatile var currentPendingSchemeName: String? = null
private var currentScheme: T? = null
private var directory: VirtualFile? = null
private val schemeExtension: String
private val updateExtension: Boolean
private val filesToDelete = THashSet<String>()
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
private val schemeToInfo = THashMap<ExternalizableScheme, ExternalInfo>(ContainerUtil.identityStrategy())
private val useVfs = virtualFileTrackerDisposable != null
init {
if (processor is SchemeExtensionProvider) {
schemeExtension = processor.schemeExtension
updateExtension = processor.isUpgradeNeeded
}
else {
schemeExtension = FileStorageCoreUtil.DEFAULT_EXT
updateExtension = false
}
if (useVfs && (provider == null || !provider.enabled)) {
try {
refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable)
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
private fun refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable: Disposable?) {
// store refreshes root directory, so, we don't need to use refreshAndFindFile
val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return
this.directory = directory
directory.children
if (directory is NewVirtualFile) {
directory.markDirty()
}
directory.refresh(true, false, {
addVfsListener(virtualFileTrackerDisposable)
})
}
private fun addVfsListener(virtualFileTrackerDisposable: Disposable?) {
service<VirtualFileTracker>().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.toAbsolutePath().systemIndependentPath}", object : VirtualFileAdapter() {
override fun contentsChanged(event: VirtualFileEvent) {
if (event.requestor != null || !isMy(event)) {
return
}
val oldScheme = findExternalizableSchemeByFileName(event.file.name)
var oldCurrentScheme: T? = null
if (oldScheme != null) {
oldCurrentScheme = currentScheme
@Suppress("UNCHECKED_CAST")
removeScheme(oldScheme as T)
processor.onSchemeDeleted(oldScheme)
}
val newScheme = readSchemeFromFile(event.file, false)
if (newScheme != null) {
processor.initScheme(newScheme)
processor.onSchemeAdded(newScheme)
updateCurrentScheme(oldCurrentScheme, newScheme)
}
}
private fun updateCurrentScheme(oldCurrentScheme: T?, newCurrentScheme: E? = null) {
if (oldCurrentScheme != currentScheme && currentScheme == null) {
@Suppress("UNCHECKED_CAST")
setCurrent(newCurrentScheme as T? ?: schemes.firstOrNull())
}
}
override fun fileCreated(event: VirtualFileEvent) {
if (event.requestor != null) {
return
}
if (event.file.isDirectory) {
val dir = getDirectory()
if (event.file == dir) {
for (file in dir.children) {
if (isMy(file)) {
schemeCreatedExternally(file)
}
}
}
}
else if (isMy(event)) {
schemeCreatedExternally(event.file)
}
}
private fun schemeCreatedExternally(file: VirtualFile) {
val readScheme = readSchemeFromFile(file, false)
if (readScheme != null) {
processor.initScheme(readScheme)
processor.onSchemeAdded(readScheme)
}
}
override fun fileDeleted(event: VirtualFileEvent) {
if (event.requestor != null) {
return
}
var oldCurrentScheme = currentScheme
if (event.file.isDirectory) {
val dir = directory
if (event.file == dir) {
directory = null
removeExternalizableSchemes()
}
}
else if (isMy(event)) {
val scheme = findExternalizableSchemeByFileName(event.file.name) ?: return
@Suppress("UNCHECKED_CAST")
removeScheme(scheme as T)
processor.onSchemeDeleted(scheme)
}
updateCurrentScheme(oldCurrentScheme)
}
}, false, virtualFileTrackerDisposable!!)
}
override fun loadBundledScheme(resourceName: String, requestor: Any, convertor: ThrowableConvertor<Element, T, Throwable>) {
try {
val url = if (requestor is AbstractExtensionPointBean)
requestor.loaderForClass.getResource(resourceName)
else
DecodeDefaultsUtil.getDefaults(requestor, resourceName)
if (url == null) {
LOG.error("Cannot read scheme from $resourceName")
return
}
val element = loadElement(URLUtil.openStream(url))
val scheme = convertor.convert(element)
if (scheme is ExternalizableScheme) {
val fileName = PathUtilRt.getFileName(url.path)
val extension = getFileExtension(fileName, true)
val info = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension)
info.hash = element.getTreeHash()
info.schemeName = scheme.name
val oldInfo = schemeToInfo.put(scheme, info)
LOG.assertTrue(oldInfo == null)
val oldScheme = readOnlyExternalizableSchemes.put(scheme.name, scheme)
if (oldScheme != null) {
LOG.warn("Duplicated scheme ${scheme.name} - old: $oldScheme, new $scheme")
}
}
schemes.add(scheme)
}
catch (e: Throwable) {
LOG.error("Cannot read scheme from $resourceName", e)
}
}
private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String {
return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) {
schemeExtension
}
else if (StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT)) {
DEFAULT_EXT
}
else if (allowAny) {
PathUtil.getFileExtension(fileName.toString())!!
}
else {
throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out")
}
}
private fun isMy(event: VirtualFileEvent) = isMy(event.file)
private fun isMy(file: VirtualFile) = StringUtilRt.endsWithIgnoreCase(file.nameSequence, schemeExtension)
override fun loadSchemes(): Collection<E> {
val newSchemesOffset = schemes.size
if (provider != null && provider.enabled) {
provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly ->
val scheme = loadScheme(name, input, true)
if (readOnly && scheme != null) {
readOnlyExternalizableSchemes.put(scheme.name, scheme)
}
true
}
}
else {
ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) {
for (file in it) {
if (file.isDirectory()) {
continue
}
try {
loadScheme(file.fileName.toString(), file.inputStream(), true)
}
catch (e: Throwable) {
LOG.error("Cannot read scheme $file", e)
}
}
}
}
val list = SmartList<E>()
for (i in newSchemesOffset..schemes.size - 1) {
@Suppress("UNCHECKED_CAST")
val scheme = schemes.get(i) as E
processor.initScheme(scheme)
list.add(scheme)
@Suppress("UNCHECKED_CAST")
processPendingCurrentSchemeName(scheme as T)
}
return list
}
fun reload() {
// we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously)
removeExternalizableSchemes()
loadSchemes()
}
private fun removeExternalizableSchemes() {
// todo check is bundled/read-only schemes correctly handled
for (i in schemes.indices.reversed()) {
val scheme = schemes.get(i)
@Suppress("UNCHECKED_CAST")
if (scheme is ExternalizableScheme && getState(scheme as E) != SchemeProcessor.State.NON_PERSISTENT) {
if (scheme == currentScheme) {
currentScheme = null
}
processor.onSchemeDeleted(scheme)
}
}
retainExternalInfo(schemes)
}
private fun findExternalizableSchemeByFileName(fileName: String): E? {
for (scheme in schemes) {
@Suppress("UNCHECKED_CAST")
if (scheme is ExternalizableScheme && fileName == "${scheme.fileName}$schemeExtension") {
return scheme as E
}
}
return null
}
private fun isOverwriteOnLoad(existingScheme: ExternalizableScheme): Boolean {
if (readOnlyExternalizableSchemes.get(existingScheme.name) === existingScheme) {
// so, bundled scheme is shadowed
return true
}
val info = schemeToInfo.get(existingScheme)
// scheme from file with old extension, so, we must ignore it
return info != null && schemeExtension != info.fileExtension
}
private class SchemeDataHolderImpl(private val bytes: ByteArray, private val externalInfo: ExternalInfo) : SchemeDataHolder {
override fun read(): Element {
val element = loadElement(bytes.inputStream().reader())
if (externalInfo.hash == 0) {
externalInfo.hash = element.getTreeHash()
}
return element
}
}
private fun loadScheme(fileName: CharSequence, input: InputStream, duringLoad: Boolean): E? {
try {
return doLoadScheme(fileName, input, duringLoad)
}
catch (e: Throwable) {
LOG.error("Cannot read scheme $fileName", e)
return null
}
}
private fun doLoadScheme(fileName: CharSequence, input: InputStream, duringLoad: Boolean): E? {
val extension = getFileExtension(fileName, false)
if (duringLoad && filesToDelete.isNotEmpty() && filesToDelete.contains(fileName.toString())) {
LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete")
return null
}
val fileNameWithoutExtension = fileName.subSequence(0, fileName.length - extension.length).toString()
fun checkExisting(schemeName: String): Boolean {
if (!duringLoad) {
return true
}
findSchemeByName(schemeName)?.let { existingScheme ->
if (existingScheme is ExternalizableScheme && isOverwriteOnLoad(existingScheme)) {
removeScheme(existingScheme)
}
else {
if (schemeExtension != extension && schemeToInfo.get(existingScheme as Scheme)?.fileNameWithoutExtension == fileNameWithoutExtension) {
// 1.oldExt is loading after 1.newExt - we should delete 1.oldExt
filesToDelete.add(fileName.toString())
}
else {
// We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name.
// It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it.
LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"$schemeName\"")
}
return false
}
}
return true
}
fun createInfo(schemeName: String, element: Element?): ExternalInfo {
val info = ExternalInfo(fileNameWithoutExtension, extension)
element?.let {
info.hash = it.getTreeHash()
}
info.schemeName = schemeName
return info
}
var scheme: E? = null
if (processor is LazySchemeProcessor) {
val bytes = input.readBytes()
val parser = MXParser()
parser.setInput(bytes.inputStream().reader())
var eventType = parser.eventType
read@ do {
when (eventType) {
XmlPullParser.START_TAG -> {
val schemeName = parser.getAttributeValue(null, "name")
if (!checkExisting(schemeName)) {
return null
}
val externalInfo = createInfo(schemeName, null)
scheme = processor.createScheme(SchemeDataHolderImpl(bytes, externalInfo), Function { parser.getAttributeValue(null, it) }, duringLoad)
schemeToInfo.put(scheme, externalInfo)
break@read
}
}
eventType = parser.next()
}
while (eventType != XmlPullParser.END_DOCUMENT)
}
else {
val element = loadElement(input)
scheme = processor.readScheme(element, duringLoad) ?: return null
val schemeName = scheme.name
if (!checkExisting(schemeName)) {
return null
}
schemeToInfo.put(scheme, createInfo(schemeName, element))
}
@Suppress("UNCHECKED_CAST")
if (duringLoad) {
schemes.add(scheme as T)
}
else {
addScheme(scheme as T)
}
return scheme
}
private val ExternalizableScheme.fileName: String?
get() = schemeToInfo[this]?.fileNameWithoutExtension
private fun canRead(name: CharSequence) = updateExtension && StringUtilRt.endsWithIgnoreCase(name, DEFAULT_EXT) || StringUtilRt.endsWithIgnoreCase(name, schemeExtension)
private fun readSchemeFromFile(file: VirtualFile, duringLoad: Boolean): E? {
val fileName = file.nameSequence
if (file.isDirectory || !canRead(fileName)) {
return null
}
try {
return loadScheme(fileName, file.inputStream, duringLoad)
}
catch (e: Throwable) {
LOG.error("Cannot read scheme $fileName", e)
return null
}
}
fun save(errors: MutableList<Throwable>) {
var hasSchemes = false
val nameGenerator = UniqueNameGenerator()
val schemesToSave = SmartList<E>()
for (scheme in schemes) {
@Suppress("UNCHECKED_CAST")
if (scheme is ExternalizableScheme) {
val state = getState(scheme as E)
if (state == SchemeProcessor.State.NON_PERSISTENT) {
continue
}
hasSchemes = true
if (state != SchemeProcessor.State.UNCHANGED) {
schemesToSave.add(scheme)
}
val fileName = scheme.fileName
if (fileName != null && !isRenamed(scheme)) {
nameGenerator.addExistingName(fileName)
}
}
}
for (scheme in schemesToSave) {
try {
saveScheme(scheme, nameGenerator)
}
catch (e: Throwable) {
errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e))
}
}
if (!filesToDelete.isEmpty) {
deleteFiles(errors)
// remove empty directory only if some file was deleted - avoid check on each save
if (!hasSchemes && (provider == null || !provider.enabled)) {
removeDirectoryIfEmpty(errors)
}
}
}
private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) {
ioDirectory.directoryStreamIfExists {
for (file in it) {
if (!file.isHidden()) {
LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists")
return@removeDirectoryIfEmpty
}
}
}
LOG.info("Remove schemes directory ${ioDirectory.fileName}")
directory = null
var deleteUsingIo = !useVfs
if (!deleteUsingIo) {
val dir = getDirectory()
if (dir != null) {
runWriteAction {
try {
dir.delete(this)
}
catch (e: IOException) {
deleteUsingIo = true
errors.add(e)
}
}
}
}
if (deleteUsingIo) {
errors.catch { ioDirectory.deleteRecursively() }
}
}
private fun getState(scheme: E) = processor.getState(scheme)
private fun saveScheme(scheme: E, nameGenerator: UniqueNameGenerator) {
var externalInfo: ExternalInfo? = schemeToInfo[scheme]
val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension
val parent = processor.writeScheme(scheme)
val element = if (parent == null || parent is Element) parent as Element? else (parent as Document).detachRootElement()
if (JDOMUtil.isEmpty(element)) {
externalInfo?.scheduleDelete()
return
}
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.name, false))
}
val newHash = element!!.getTreeHash()
if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && newHash == externalInfo.hash) {
return
}
// save only if scheme differs from bundled
val bundledScheme = readOnlyExternalizableSchemes[scheme.name]
if (bundledScheme != null && schemeToInfo[bundledScheme]?.hash == newHash) {
externalInfo?.scheduleDelete()
return
}
val fileName = fileNameWithoutExtension!! + schemeExtension
// file will be overwritten, so, we don't need to delete it
filesToDelete.remove(fileName)
// stream provider always use LF separator
val byteOut = element.toBufferExposingByteArray()
var providerPath: String?
if (provider != null && provider.enabled) {
providerPath = fileSpec + '/' + fileName
if (!provider.isApplicable(providerPath, roamingType)) {
providerPath = null
}
}
else {
providerPath = null
}
// if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation)
val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension)
if (providerPath == null) {
if (useVfs) {
var file: VirtualFile? = null
var dir = getDirectory()
if (dir == null || !dir.isValid) {
dir = createDir(ioDirectory, this)
directory = dir
}
if (renamed) {
file = dir.findChild(externalInfo!!.fileName)
if (file != null) {
runWriteAction {
file!!.rename(this, fileName)
}
}
}
if (file == null) {
file = getFile(fileName, dir, this)
}
runWriteAction {
file!!.getOutputStream(this).use {
byteOut.writeTo(it)
}
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete()
}
ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size())
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete()
}
provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType)
}
if (externalInfo == null) {
externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension)
schemeToInfo.put(scheme, externalInfo)
}
else {
externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension)
}
externalInfo.hash = newHash
externalInfo.schemeName = scheme.name
}
private fun ExternalInfo.scheduleDelete() {
filesToDelete.add(fileName)
}
private fun isRenamed(scheme: ExternalizableScheme): Boolean {
val info = schemeToInfo[scheme]
return info != null && scheme.name != info.schemeName
}
private fun deleteFiles(errors: MutableList<Throwable>) {
val deleteUsingIo: Boolean
if (provider != null && provider.enabled) {
deleteUsingIo = false
for (name in filesToDelete) {
errors.catch {
val spec = "$fileSpec/$name"
if (provider.isApplicable(spec, roamingType)) {
provider.delete(spec, roamingType)
}
}
}
}
else if (!useVfs) {
deleteUsingIo = true
}
else {
val dir = getDirectory()
deleteUsingIo = dir == null
if (!deleteUsingIo) {
var token: AccessToken? = null
try {
for (file in dir!!.children) {
if (filesToDelete.contains(file.name)) {
if (token == null) {
token = WriteAction.start()
}
errors.catch {
file.delete(this)
}
}
}
}
finally {
if (token != null) {
token.finish()
}
}
}
}
if (deleteUsingIo) {
for (name in filesToDelete) {
errors.catch { ioDirectory.resolve(name).delete() }
}
}
filesToDelete.clear()
}
private fun getDirectory(): VirtualFile? {
var result = directory
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath)
directory = result
}
return result
}
override fun getRootDirectory() = ioDirectory.toFile()
override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) {
val oldCurrentScheme = currentScheme
if (removeCondition == null) {
schemes.clear()
}
else {
schemes.removeAll { removeCondition.value(it) }
}
retainExternalInfo(newSchemes)
schemes.addAll(newSchemes)
if (oldCurrentScheme != newCurrentScheme) {
if (newCurrentScheme != null) {
currentScheme = newCurrentScheme
}
else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) {
currentScheme = schemes.firstOrNull()
}
if (oldCurrentScheme != currentScheme) {
processor.onCurrentSchemeChanged(oldCurrentScheme)
}
}
}
private fun retainExternalInfo(newSchemes: List<T>) {
if (schemeToInfo.isEmpty) {
return
}
schemeToInfo.retainEntries(TObjectObjectProcedure { scheme, info ->
if (readOnlyExternalizableSchemes[scheme.name] == scheme) {
return@TObjectObjectProcedure true
}
for (t in newSchemes) {
// by identity
if (t === scheme) {
if (filesToDelete.isNotEmpty()) {
filesToDelete.remove("${info.fileName}")
}
return@TObjectObjectProcedure true
}
}
info.scheduleDelete()
false
})
}
override fun addNewScheme(scheme: T, replaceExisting: Boolean) {
var toReplace = -1
for (i in schemes.indices) {
val existing = schemes.get(i)
if (existing.name == scheme.name) {
if (!Comparing.equal<Class<out Scheme>>(existing.javaClass, scheme.javaClass)) {
LOG.warn("'${scheme.name}' ${existing.javaClass.simpleName} replaced with ${scheme.javaClass.simpleName}")
}
toReplace = i
if (replaceExisting && existing is ExternalizableScheme) {
val oldInfo = schemeToInfo.remove(existing)
if (oldInfo != null && scheme is ExternalizableScheme && !schemeToInfo.containsKey(scheme)) {
schemeToInfo.put(scheme, oldInfo)
}
}
break
}
}
if (toReplace == -1) {
schemes.add(scheme)
}
else if (replaceExisting || scheme !is ExternalizableScheme) {
schemes[toReplace] = scheme
}
else {
scheme.renameScheme(UniqueNameGenerator.generateUniqueName(scheme.name, collectExistingNames(schemes)))
schemes.add(scheme)
}
if (scheme is ExternalizableScheme && filesToDelete.isNotEmpty()) {
val info = schemeToInfo[scheme]
if (info != null) {
filesToDelete.remove("${info.fileName}")
}
}
processPendingCurrentSchemeName(scheme)
}
private fun collectExistingNames(schemes: Collection<T>): Collection<String> {
val result = THashSet<String>(schemes.size)
for (scheme in schemes) {
result.add(scheme.name)
}
return result
}
override fun clearAllSchemes() {
schemeToInfo.forEachValue {
it.scheduleDelete()
true
}
currentScheme = null
schemes.clear()
schemeToInfo.clear()
}
override fun getAllSchemes() = Collections.unmodifiableList(schemes)
override fun findSchemeByName(schemeName: String): T? {
for (scheme in schemes) {
if (scheme.name == schemeName) {
return scheme
}
}
return null
}
override fun setCurrent(scheme: T?, notify: Boolean) {
currentPendingSchemeName = null
val oldCurrent = currentScheme
currentScheme = scheme
if (notify && oldCurrent != scheme) {
processor.onCurrentSchemeChanged(oldCurrent)
}
}
override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) {
currentPendingSchemeName = schemeName
val scheme = if (schemeName == null) null else findSchemeByName(schemeName)
// don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment)
if (scheme != null || schemeName == null) {
setCurrent(scheme, notify)
}
}
override fun getCurrentScheme() = currentScheme
override fun getCurrentSchemeName() = currentScheme?.name ?: currentPendingSchemeName
private fun processPendingCurrentSchemeName(newScheme: T) {
if (newScheme.name == currentPendingSchemeName) {
setCurrent(newScheme, false)
}
}
override fun removeScheme(scheme: T) {
for (i in schemes.size - 1 downTo 0) {
val s = schemes[i]
if (scheme.name == s.name) {
if (currentScheme == s) {
currentScheme = null
}
if (s is ExternalizableScheme) {
schemeToInfo.remove(s)?.scheduleDelete()
}
schemes.removeAt(i)
break
}
}
}
override fun getAllSchemeNames() = if (schemes.isEmpty()) emptyList() else schemes.map { it.name }
override fun isMetadataEditable(scheme: E) = !readOnlyExternalizableSchemes.containsKey(scheme.name)
private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) {
// we keep it to detect rename
var schemeName: String? = null
var hash = 0
val fileName: String
get() = "$fileNameWithoutExtension$fileExtension"
fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) {
fileNameWithoutExtension = nameWithoutExtension
fileExtension = extension
}
override fun toString() = fileName
}
override fun toString() = fileSpec
}
private fun ExternalizableScheme.renameScheme(newName: String) {
if (newName != name) {
name = newName
LOG.assertTrue(newName == name)
}
}
private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) {
try {
runnable()
}
catch (e: Throwable) {
add(e)
}
}
fun createDir(ioDir: Path, requestor: Any): VirtualFile {
ioDir.createDirectories()
val parentFile = ioDir.parent
val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile))
return getFile(ioDir.fileName.toString(), parentVirtualFile, requestor)
}
fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile {
return parent.findChild(fileName) ?: runWriteAction { parent.createChildData(requestor, fileName) }
} | apache-2.0 | bece4f715857fc5f102a00fd41feb938 | 31.042644 | 229 | 0.647945 | 4.807262 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/activity/AdminReportActivity.kt | 1 | 3781 | package com.tungnui.abccomputer.activity
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.adapter.NotificationAdapter
import com.tungnui.abccomputer.data.constant.AppConstants
import com.tungnui.abccomputer.data.sqlite.NotificationDBController
import com.tungnui.abccomputer.model.NotificationModel
import com.tungnui.abccomputer.utils.ActivityUtils
import java.util.ArrayList
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.ValueDependentColor
import com.jjoe64.graphview.series.BarGraphSeries
import com.jjoe64.graphview.GraphView
import com.tungnui.abccomputer.api.CategoryService
import com.tungnui.abccomputer.api.ProductService
import com.tungnui.abccomputer.api.ReportServices
import com.tungnui.abccomputer.api.ServiceGenerator
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
class AdminReportActivity : AppCompatActivity() {
private var mCompositeDisposable: CompositeDisposable
val reportService: ReportServices
init {
mCompositeDisposable = CompositeDisposable()
reportService = ServiceGenerator.createService(ReportServices::class.java)
}
private var mToolbar: Toolbar? = null
private var emptyView: TextView? = null
private var data:ArrayList<DataPoint>?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initVars()
initialView()
initFunctionality()
initialListener()
}
private fun initVars() {
data = ArrayList<DataPoint>()
}
private fun initialView() {
setContentView(R.layout.activity_admin_report)
mToolbar = findViewById<View>(R.id.toolbar) as Toolbar
emptyView = findViewById<View>(R.id.emptyView) as TextView
setSupportActionBar(mToolbar)
supportActionBar?.title = getString(R.string.notifications)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
val graph = findViewById<View>(R.id.graph) as GraphView
val series = BarGraphSeries(arrayOf(DataPoint(0.0, -1.0), DataPoint(1.0, 5.0), DataPoint(2.0, 3.0), DataPoint(3.0, 2.0), DataPoint(4.0, 6.0)))
graph.addSeries(series)
// styling
series.setValueDependentColor { data -> Color.rgb(data.x.toInt() * 255 / 4, Math.abs(data.y * 255 / 6).toInt(), 100) }
series.spacing = 50
// draw values on top
series.isDrawValuesOnTop = true
series.valuesOnTopColor = Color.RED
//series.setValuesOnTopSize(50);
}
private fun initFunctionality() {
}
private fun initialListener() {
mToolbar?.setNavigationOnClickListener { finish() }
}
fun getTopSallerReport(){
// Load popular product
var disposable = reportService.getTopSaller()
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
if (response != null) {
for (item in response){
//data.add(DataPoint(item.title, item.quantity))
}
}
},
{ error ->
})
mCompositeDisposable.add(disposable)
}
override fun onResume() {
super.onResume()
}
} | mit | 75893a3682804c90fe3147b75ce88ae2 | 34.679245 | 150 | 0.694525 | 4.72035 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtClassDef.kt | 6 | 5509 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInspection.dataFlow.TypeConstraint
import com.intellij.codeInspection.dataFlow.TypeConstraints
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperClassifiers
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import java.util.*
import java.util.stream.Stream
import kotlin.streams.asStream
class KtClassDef(val cls: ClassDescriptor) : TypeConstraints.ClassDef {
override fun isInheritor(superClassQualifiedName: String): Boolean =
cls.getAllSuperClassifiers().any { superClass ->
superClass is ClassDescriptor && correctFqName(superClass.fqNameUnsafe) == superClassQualifiedName
}
override fun isInheritor(superType: TypeConstraints.ClassDef): Boolean =
superType is KtClassDef && cls.isSubclassOf(superType.cls)
override fun isConvertible(other: TypeConstraints.ClassDef): Boolean {
if (other !is KtClassDef) return false
// TODO: support sealed
if (isInterface && other.isInterface) return true
if (isInterface && !other.isFinal) return true
if (other.isInterface && !isFinal) return true
return isInheritor(other) || other.isInheritor(this)
}
override fun isInterface(): Boolean = cls.kind == ClassKind.INTERFACE
override fun isEnum(): Boolean = cls.kind == ClassKind.ENUM_CLASS
override fun isFinal(): Boolean = cls.modality == Modality.FINAL
override fun isAbstract(): Boolean = cls.modality == Modality.ABSTRACT
override fun getEnumConstant(ordinal: Int): PsiEnumConstant? {
val psiClass = (cls.toSourceElement as? PsiSourceElement)?.psi.asPsiClass() ?: return null
var cur = 0
for (field in psiClass.fields) {
if (field is PsiEnumConstant) {
if (cur == ordinal) return field
cur++
}
}
return null
}
override fun getQualifiedName(): String = correctFqName(cls.fqNameUnsafe)
override fun superTypes(): Stream<TypeConstraints.ClassDef> =
cls.getAllSuperClassifiers().filterIsInstance<ClassDescriptor>().map(::KtClassDef).asStream()
override fun toPsiType(project: Project): PsiType? =
DescriptorToSourceUtilsIde.getAnyDeclaration(project, cls).asPsiClass()
?.let { JavaPsiFacade.getElementFactory(project).createType(it) }
override fun equals(other: Any?): Boolean {
return other is KtClassDef && other.cls.typeConstructor == cls.typeConstructor
}
override fun hashCode(): Int = Objects.hashCode(cls.name.hashCode())
override fun toString(): String = qualifiedName
private fun correctFqName(fqNameUnsafe: FqNameUnsafe): String =
JavaToKotlinClassMap.mapKotlinToJava(fqNameUnsafe)?.asFqNameString() ?: fqNameUnsafe.asString()
companion object {
fun getClassConstraint(context: KtElement, name: FqNameUnsafe): TypeConstraint.Exact {
val descriptor = context.findModuleDescriptor().resolveClassByFqName(name.toSafe(), NoLookupLocation.FROM_IDE)
return if (descriptor == null) TypeConstraints.unresolved(name.asString())
else TypeConstraints.exactClass(KtClassDef(descriptor))
}
fun fromJvmClassName(context: KtElement, jvmClassName: String): TypeConstraints.ClassDef? {
var fqName = FqName.fromSegments(jvmClassName.split(Regex("[$/]")))
if (jvmClassName.startsWith("java/")) {
fqName = JavaToKotlinClassMap.mapJavaToKotlin(fqName)?.asSingleFqName() ?: fqName
}
val descriptor = context.findModuleDescriptor().resolveClassByFqName(fqName, NoLookupLocation.FROM_IDE)
return if (descriptor == null) null else KtClassDef(descriptor)
}
fun typeConstraintFactory(context: KtElement): TypeConstraints.TypeConstraintFactory {
return TypeConstraints.TypeConstraintFactory { fqn ->
var fqName = FqName.fromSegments(fqn.split("."))
if (fqn.startsWith("java.")) {
fqName = JavaToKotlinClassMap.mapJavaToKotlin(fqName)?.asSingleFqName() ?: fqName
}
getClassConstraint(context, fqName.toUnsafe())
}
}
}
}
private fun PsiElement?.asPsiClass(): PsiClass? = when (this) {
is PsiClass -> this
is KtClassOrObject -> toLightClass()
else -> null
} | apache-2.0 | 80f5fb6bb6ad7e6862354436e4c66882 | 44.53719 | 122 | 0.724814 | 5.017304 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/KoresPart.kt | 1 | 3580 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.github.jonathanxd.kores
import com.github.jonathanxd.kores.base.Access
import com.github.jonathanxd.kores.base.Alias
import com.github.jonathanxd.kores.base.InstructionWrapper
import com.github.jonathanxd.kores.base.Typed
import com.github.jonathanxd.kores.builder.Builder
import com.github.jonathanxd.kores.type.NullType
import com.github.jonathanxd.kores.type.`is`
import com.github.jonathanxd.kores.type.isPrimitive
import com.github.jonathanxd.kores.type.koresType
import java.lang.reflect.Type
/**
* A KoresPart is the heart of Kores, all elements that can appear in the code must extend KoresPart.
*
* All interfaces that have a concrete implementation and extends [KoresPart] must provide a
* `builder` method that return a builder instance with defined default values.
*
*/
interface KoresPart {
/**
* This builder may or may not accept null values, it depends on implementation.
*/
fun builder(): Builder<KoresPart, *> = SelfBuilder(this)
class SelfBuilder(val self: KoresPart) : Builder<KoresPart, SelfBuilder> {
override fun build(): KoresPart = self
}
}
/**
* Returns true if the type of this [KoresPart] is primitive
*/
val KoresPart.isPrimitive: Boolean
get() = this.type.isPrimitive
/**
* Gets the type of [KoresPart]
*/
val KoresPart.type: Type
get() = this.typeOrNull ?: throw IllegalArgumentException("Cannot infer type of part '$this'!")
/**
* Gets the type of [KoresPart] or null if receiver is not a [Typed] instance.
*/
val KoresPart.typeOrNull: Type?
get() = (this as? Typed)?.type?.let {
if (it.`is`(NullType))
Types.OBJECT
else it
} ?: (this as? InstructionWrapper)?.wrappedInstruction?.also {
if (it == this)
throw IllegalStateException("InstructionWrapper wrapping itself.")
}?.typeOrNull ?: (this as? Access)?.let {
when (it) {
Access.THIS, Access.LOCAL, Access.STATIC -> Alias.THIS.koresType
Access.SUPER -> Alias.SUPER.koresType
}
} ?: (this as? Instruction)?.getLeaveType() ?: (this as? Instructions)?.getLeaveType()
| mit | 5efd9a23cc51633134aea62115f4a26c | 38.777778 | 118 | 0.703631 | 4.272076 | false | false | false | false |
sachil/Essence | app/src/main/java/xyz/sachil/essence/repository/DetailRepository.kt | 1 | 790 | package xyz.sachil.essence.repository
import android.util.Log
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import xyz.sachil.essence.model.cache.CacheDatabase
import xyz.sachil.essence.model.net.NetClient
import xyz.sachil.essence.model.net.bean.Detail
class DetailRepository : KoinComponent {
companion object {
private const val TAG = "DetailRepository"
}
private val database: CacheDatabase by inject()
private val netClient: NetClient by inject()
suspend fun getDetail(id: String): Detail {
var detail = database.detailDao().getDetail(id)
if (detail == null) {
detail = netClient.getDetail(id)
database.detailDao().insertDetail(detail)
}
return detail
}
} | apache-2.0 | 78ef5fba7f5b0ece3616df1985309d60 | 28.296296 | 55 | 0.710127 | 4.179894 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/AbstractCommitChangesAction.kt | 3 | 2193 | // 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.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.actions.AbstractCommonCheckinAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.vcsUtil.VcsUtil.getFilePath
abstract class AbstractCommitChangesAction : AbstractCommonCheckinAction() {
override fun getRoots(dataContext: VcsContext): Array<FilePath> =
ProjectLevelVcsManager.getInstance(dataContext.project!!).allVersionedRoots.map { getFilePath(it) }.toTypedArray()
override fun approximatelyHasRoots(dataContext: VcsContext): Boolean = ProjectLevelVcsManager.getInstance(
dataContext.project!!).hasAnyMappings()
override fun update(vcsContext: VcsContext, presentation: Presentation) {
super.update(vcsContext, presentation)
if (presentation.isEnabledAndVisible) {
val changes = vcsContext.selectedChanges
if (vcsContext.place == ActionPlaces.CHANGES_VIEW_POPUP) {
val changeLists = vcsContext.selectedChangeLists
presentation.isEnabled =
if (changeLists.isNullOrEmpty()) !changes.isNullOrEmpty() else changeLists.size == 1 && !changeLists[0].changes.isEmpty()
}
if (presentation.isEnabled && !changes.isNullOrEmpty()) {
disableIfAnyHijackedChanges(vcsContext.project!!, presentation, changes)
}
}
}
private fun disableIfAnyHijackedChanges(project: Project, presentation: Presentation, changes: Array<Change>) {
val manager = ChangeListManager.getInstance(project)
val hasHijackedChanges = changes.any { it.fileStatus == FileStatus.HIJACKED && manager.getChangeList(it) == null }
presentation.isEnabled = !hasHijackedChanges
}
} | apache-2.0 | de81df5644f855572db41173605dd6f1 | 43.77551 | 140 | 0.782946 | 4.559252 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ByteArrayNode.kt | 1 | 941 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
@DependsOn(Node::class)
class ByteArrayNode : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<Node>() }
.and { it.interfaces.isEmpty() }
.and { it.instanceFields.size == 1 }
.and { it.instanceFields.all { it.type == ByteArray::class.type } }
.and { it.instanceMethods.isEmpty() }
class byteArray : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type }
}
} | mit | 7a7782fc1caef49be71c33a69cb8a1f9 | 41.818182 | 89 | 0.726886 | 3.970464 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/InsertCurlyBracesToTemplateIntention.kt | 1 | 1610 | // 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.project).createBlockStringTemplateEntry(expression))
val afterExpression = (wrapped as? KtStringTemplateEntryWithExpression)?.expression ?: return
restoreCaret(afterExpression, defaultOffset = { it.endOffset })
}
}
}
| apache-2.0 | 2c084d6b8175af44ccc37ec85b075573 | 50.935484 | 158 | 0.807453 | 5.227273 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/NewKotlinFileAction.kt | 1 | 12480 | // 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.actions
import com.intellij.ide.actions.*
import com.intellij.ide.fileTemplates.FileTemplate
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.actions.AttributesDefaults
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.InputValidatorEx
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.base.projectStructure.NewKotlinFileHook
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.toModuleGroup
import org.jetbrains.kotlin.idea.configuration.ConfigureKotlinStatus
import org.jetbrains.kotlin.idea.configuration.KotlinProjectConfigurator
import org.jetbrains.kotlin.idea.statistics.KotlinCreateFileFUSCollector
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.parsing.KotlinParserDefinition.Companion.STD_SCRIPT_SUFFIX
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import java.util.*
class NewKotlinFileAction : CreateFileFromTemplateAction(
KotlinBundle.message("action.new.file.text"),
KotlinBundle.message("action.new.file.description"),
KotlinFileType.INSTANCE.icon
), DumbAware {
override fun postProcess(createdElement: PsiFile, templateName: String?, customProperties: Map<String, String>?) {
super.postProcess(createdElement, templateName, customProperties)
val module = ModuleUtilCore.findModuleForPsiElement(createdElement)
if (createdElement is KtFile) {
if (module != null) {
for (hook in NewKotlinFileHook.EP_NAME.extensions) {
hook.postProcess(createdElement, module)
}
}
val ktClass = createdElement.declarations.singleOrNull() as? KtNamedDeclaration
if (ktClass != null) {
if (ktClass is KtClass && ktClass.isData()) {
val primaryConstructor = ktClass.primaryConstructor
if (primaryConstructor != null) {
createdElement.editor()?.caretModel?.moveToOffset(primaryConstructor.startOffset + 1)
return
}
}
CreateFromTemplateAction.moveCaretAfterNameIdentifier(ktClass)
} else {
val editor = createdElement.editor() ?: return
val lineCount = editor.document.lineCount
if (lineCount > 0) {
editor.caretModel.moveToLogicalPosition(LogicalPosition(lineCount - 1, 0))
}
}
}
}
private fun KtFile.editor() =
FileEditorManager.getInstance(this.project).selectedTextEditor?.takeIf { it.document == this.viewProvider.document }
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle(KotlinBundle.message("action.new.file.dialog.title"))
.addKind(
KotlinBundle.message("action.new.file.dialog.class.title"),
KotlinIcons.CLASS,
"Kotlin Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.file.title"),
KotlinFileType.INSTANCE.icon,
"Kotlin File"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.interface.title"),
KotlinIcons.INTERFACE,
"Kotlin Interface"
)
if (project.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) {
builder.addKind(
KotlinBundle.message("action.new.file.dialog.sealed.interface.title"),
KotlinIcons.INTERFACE,
"Kotlin Sealed Interface"
)
}
builder.addKind(
KotlinBundle.message("action.new.file.dialog.data.class.title"),
KotlinIcons.CLASS,
"Kotlin Data Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.enum.title"),
KotlinIcons.ENUM,
"Kotlin Enum"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.sealed.class.title"),
KotlinIcons.CLASS,
"Kotlin Sealed Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.annotation.title"),
KotlinIcons.ANNOTATION,
"Kotlin Annotation"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.object.title"),
KotlinIcons.OBJECT,
"Kotlin Object"
)
builder.setValidator(NameValidator)
}
override fun getActionName(directory: PsiDirectory, newName: String, templateName: String): String =
KotlinBundle.message("action.new.file.text")
override fun isAvailable(dataContext: DataContext): Boolean {
if (super.isAvailable(dataContext)) {
val ideView = LangDataKeys.IDE_VIEW.getData(dataContext)!!
val project = PlatformDataKeys.PROJECT.getData(dataContext)!!
val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
return ideView.directories.any {
projectFileIndex.isInSourceContent(it.virtualFile) ||
CreateTemplateInPackageAction.isInContentRoot(it.virtualFile, projectFileIndex)
}
}
return false
}
override fun hashCode(): Int = 0
override fun equals(other: Any?): Boolean = other is NewKotlinFileAction
override fun startInWriteAction() = false
override fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory) =
createFileFromTemplateWithStat(name, template, dir)
companion object {
private object NameValidator : InputValidatorEx {
override fun getErrorText(inputString: String): String? {
if (inputString.trim().isEmpty()) {
return KotlinBundle.message("action.new.file.error.empty.name")
}
val parts: List<String> = inputString.split(*FQNAME_SEPARATORS)
if (parts.any { it.trim().isEmpty() }) {
return KotlinBundle.message("action.new.file.error.empty.name.part")
}
return null
}
override fun checkInput(inputString: String): Boolean = true
override fun canClose(inputString: String): Boolean = getErrorText(inputString) == null
}
@get:TestOnly
val nameValidator: InputValidatorEx
get() = NameValidator
private fun findOrCreateTarget(dir: PsiDirectory, name: String, directorySeparators: CharArray): Pair<String, PsiDirectory> {
var className = removeKotlinExtensionIfPresent(name)
var targetDir = dir
for (splitChar in directorySeparators) {
if (splitChar in className) {
val names = className.trim().split(splitChar)
for (dirName in names.dropLast(1)) {
targetDir = targetDir.findSubdirectory(dirName) ?: runWriteAction {
targetDir.createSubdirectory(dirName)
}
}
className = names.last()
break
}
}
return Pair(className, targetDir)
}
private fun removeKotlinExtensionIfPresent(name: String): String = when {
name.endsWith(".$KOTLIN_WORKSHEET_EXTENSION") -> name.removeSuffix(".$KOTLIN_WORKSHEET_EXTENSION")
name.endsWith(".$STD_SCRIPT_SUFFIX") -> name.removeSuffix(".$STD_SCRIPT_SUFFIX")
name.endsWith(".${KotlinFileType.EXTENSION}") -> name.removeSuffix(".${KotlinFileType.EXTENSION}")
else -> name
}
private fun createFromTemplate(dir: PsiDirectory, className: String, template: FileTemplate): PsiFile? {
val project = dir.project
val defaultProperties = FileTemplateManager.getInstance(project).defaultProperties
val properties = Properties(defaultProperties)
val element = try {
CreateFromTemplateDialog(
project, dir, template,
AttributesDefaults(className).withFixedName(true),
properties
).create()
} catch (e: IncorrectOperationException) {
throw e
} catch (e: Exception) {
LOG.error(e)
return null
}
return element?.containingFile
}
private val FILE_SEPARATORS = charArrayOf('/', '\\')
private val FQNAME_SEPARATORS = charArrayOf('/', '\\', '.')
fun createFileFromTemplateWithStat(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? {
KotlinCreateFileFUSCollector.logFileTemplate(template.name)
return createFileFromTemplate(name, template, dir)
}
fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? {
val directorySeparators = when (template.name) {
"Kotlin File" -> FILE_SEPARATORS
else -> FQNAME_SEPARATORS
}
val (className, targetDir) = findOrCreateTarget(dir, name, directorySeparators)
val service = DumbService.getInstance(dir.project)
return service.computeWithAlternativeResolveEnabled<PsiFile?, Throwable> {
val adjustedDir = CreateTemplateInPackageAction.adjustDirectory(targetDir, JavaModuleSourceRootTypes.SOURCES)
val psiFile = createFromTemplate(adjustedDir, className, template)
if (psiFile is KtFile) {
val singleClass = psiFile.declarations.singleOrNull() as? KtClass
if (singleClass != null && !singleClass.isEnum() && !singleClass.isInterface() && name.contains("Abstract")) {
runWriteAction {
singleClass.addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
JavaCreateTemplateInPackageAction.setupJdk(adjustedDir, psiFile)
val module = ModuleUtil.findModuleForFile(psiFile)
val configurator = KotlinProjectConfigurator.EP_NAME.extensions.firstOrNull()
if (module != null && configurator != null) {
DumbService.getInstance(module.project).runWhenSmart {
if (configurator.getStatus(module.toModuleGroup()) == ConfigureKotlinStatus.CAN_BE_CONFIGURED) {
configurator.configure(module.project, emptyList())
}
}
}
return@computeWithAlternativeResolveEnabled psiFile
}
}
}
} | apache-2.0 | 35ae702a41f9b8344e0ec5611ae36fd2 | 43.102473 | 158 | 0.63742 | 5.411969 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/playalong/PlayalongToggleButton.kt | 2 | 2717 | package io.github.chrislo27.rhre3.editor.stage.playalong
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.editor.Tool
import io.github.chrislo27.rhre3.editor.stage.EditorStage
import io.github.chrislo27.rhre3.screen.EditorScreen
import io.github.chrislo27.rhre3.screen.PlayalongSettingsScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.ui.*
import io.github.chrislo27.toolboks.util.MathHelper
class PlayalongToggleButton(val editorStage: EditorStage, palette: UIPalette, parent: UIElement<EditorScreen>, stage: Stage<EditorScreen>)
: Button<EditorScreen>(palette, parent, stage) {
private val main: RHRE3Application get() = editorStage.main
private val label = TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = false
this.text = "\uE0E0"
this.textWrapping = false
this.textColor = Color(1f, 1f, 1f, 1f)
}
init {
this.addLabel(label)
}
override var tooltipText: String?
set(_) {}
get() = Localization["editor.playalong"]
override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
if (editorStage.playalongStage.visible) {
label.textColor?.fromHsv(MathHelper.getSawtoothWave(1.5f) * 360f, 0.3f, 0.75f)
} else {
label.textColor?.set(1f, 1f, 1f, 1f)
}
super.render(screen, batch, shapeRenderer)
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
val stage = editorStage
val visible = !stage.playalongStage.visible
val editor = stage.editor
stage.elements.filterIsInstance<Stage<*>>().forEach {
it.visible = !visible
}
stage.playalongStage.visible = visible
stage.subtitleStage.visible = true // Exception made for subtitles
stage.tapalongStage.visible = false
stage.presentationModeStage.visible = false
stage.paneLikeStages.forEach { it.visible = false }
stage.buttonBarStage.visible = true
stage.messageBarStage.visible = true
stage.centreAreaStage.visible = true
if (visible) {
editor.currentTool = Tool.SELECTION
}
stage.updateSelected()
editor.updateMessageLabel()
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
main.screen = PlayalongSettingsScreen(main, main.screen)
}
} | gpl-3.0 | 9d513a3a970c65473db767517a10d4c9 | 36.232877 | 138 | 0.697092 | 4.154434 | false | false | false | false |
muntasirsyed/intellij-community | platform/script-debugger/debugger-ui/src/util.kt | 1 | 1585 | /*
* 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 com.intellij.xdebugger.util
import com.intellij.xdebugger.XDebugSession
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.SuspendContext
import org.jetbrains.debugger.Vm
import org.jetbrains.rpc.CommandProcessor
import org.jetbrains.util.concurrency.AsyncPromise
// have to use package "com.intellij.xdebugger.util" to avoid package clash
public fun XDebugSession.rejectedErrorReporter(description: String? = null): (Throwable) -> Unit = {
Promise.logError(CommandProcessor.LOG, it)
if (it != AsyncPromise.OBSOLETE_ERROR) {
reportError("${if (description == null) "" else description + ": "}${it.getMessage()}")
}
}
public inline fun <T> contextDependentResultConsumer(context: SuspendContext, crossinline done: (result: T, vm: Vm) -> Unit) : (T) -> Unit {
return {
val vm = context.valueManager.vm
if (vm.attachStateManager.isAttached() && !vm.getSuspendContextManager().isContextObsolete(context)) {
done(it, vm)
}
}
} | apache-2.0 | 3b8625021786141f0f6f4b80a1ca4a0c | 38.65 | 140 | 0.74511 | 4.053708 | false | false | false | false |
ursjoss/sipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/paper/JooqPaperRepoTest.kt | 1 | 13207 | package ch.difty.scipamato.core.persistence.paper
import ch.difty.scipamato.common.persistence.paging.PaginationContext
import ch.difty.scipamato.common.persistence.paging.Sort
import ch.difty.scipamato.common.persistence.paging.Sort.Direction
import ch.difty.scipamato.core.db.tables.Paper.PAPER
import ch.difty.scipamato.core.db.tables.records.PaperRecord
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.entity.PaperAttachment
import ch.difty.scipamato.core.entity.search.PaperFilter
import ch.difty.scipamato.core.entity.search.SearchOrder
import ch.difty.scipamato.core.persistence.EntityRepository
import ch.difty.scipamato.core.persistence.JooqEntityRepoTest
import ch.difty.scipamato.core.persistence.paper.searchorder.PaperBackedSearchOrderRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldContainAll
import org.amshove.kluent.shouldContainSame
import org.jooq.DeleteConditionStep
import org.jooq.Record1
import org.jooq.SortField
import org.jooq.TableField
import org.junit.jupiter.api.Test
internal class JooqPaperRepoTest :
JooqEntityRepoTest<PaperRecord, Paper, Long, ch.difty.scipamato.core.db.tables.Paper,
PaperRecordMapper, PaperFilter>() {
override val unpersistedEntity = mockk<Paper>()
override val persistedEntity = mockk<Paper>()
override val persistedRecord = mockk<PaperRecord>()
override val unpersistedRecord = mockk<PaperRecord>()
override val mapper = mockk<PaperRecordMapper>()
override val filter = mockk<PaperFilter>()
private val searchOrderRepositoryMock = mockk<PaperBackedSearchOrderRepository>()
private val searchOrderMock = mockk<SearchOrder>()
private val paperMock = mockk<Paper>(relaxed = true)
private val paginationContextMock = mockk<PaginationContext>()
private val deleteConditionStepMock = mockk<DeleteConditionStep<PaperRecord>>(relaxed = true)
private val paperAttachmentMock = mockk<PaperAttachment>()
private val papers = listOf(paperMock, paperMock)
private val enrichedEntities = ArrayList<Paper?>()
override val sampleId: Long = SAMPLE_ID
override val table: ch.difty.scipamato.core.db.tables.Paper = PAPER
override val tableId: TableField<PaperRecord, Long> = PAPER.ID
override val recordVersion: TableField<PaperRecord, Int> = PAPER.VERSION
override val repo = JooqPaperRepo(
dsl, mapper, sortMapper, filterConditionMapper,
dateTimeService, insertSetStepSetter, updateSetStepSetter, searchOrderRepositoryMock,
applicationProperties
)
override fun makeRepoSavingReturning(returning: PaperRecord): EntityRepository<Paper, Long, PaperFilter> =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun doSave(entity: Paper, languageCode: String): PaperRecord = returning
}
override fun makeRepoFindingEntityById(entity: Paper): EntityRepository<Paper, Long, PaperFilter> =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun findById(id: Long, version: Int): Paper = entity
}
private fun makeRepoStubbingEnriching(): PaperRepository =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun enrichAssociatedEntitiesOf(entity: Paper?, language: String?) {
enrichedEntities.add(entity)
}
}
override fun expectEntityIdsWithValues() {
every { unpersistedEntity.id } returns SAMPLE_ID
every { unpersistedEntity.version } returns 0
every { persistedRecord.id } returns SAMPLE_ID
every { persistedRecord.version } returns 1
}
override fun expectUnpersistedEntityIdNull() {
every { unpersistedEntity.id } returns null
}
override fun verifyUnpersistedEntityId() {
verify { unpersistedEntity.id }
}
override fun verifyPersistedRecordId() {
verify { persistedRecord.id }
}
@Test
fun gettingTableId() {
repo.tableId shouldBeEqualTo tableId
}
@Test
fun gettingRecordVersion() {
repo.recordVersion shouldBeEqualTo PAPER.VERSION
}
@Test
fun gettingIdFromPaper() {
every { paperMock.id } returns 17L
repo.getIdFrom(paperMock) shouldBeEqualTo 17L
verify { paperMock.id }
}
@Test
fun gettingIdFromPaperRecord() {
every { persistedRecord.id } returns 17L
repo.getIdFrom(persistedRecord) shouldBeEqualTo 17L
verify { persistedRecord.id }
}
@Test
fun findingBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.findBySearchOrder(searchOrderMock) } returns papers
makeRepoStubbingEnriching().findBySearchOrder(searchOrderMock, LC) shouldContainSame listOf(
paperMock, paperMock
)
enrichedEntities shouldContainAll listOf(paperMock, paperMock)
verify { searchOrderRepositoryMock.findBySearchOrder(searchOrderMock) }
}
@Test
fun countingBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.countBySearchOrder(searchOrderMock) } returns 2
repo.countBySearchOrder(searchOrderMock) shouldBeEqualTo 2
verify { searchOrderRepositoryMock.countBySearchOrder(searchOrderMock) }
}
@Test
fun findingPageBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.findPageBySearchOrder(searchOrderMock, paginationContextMock) } returns papers
makeRepoStubbingEnriching().findPageBySearchOrder(
searchOrderMock, paginationContextMock, LC
) shouldContainSame listOf(paperMock, paperMock)
enrichedEntities shouldContainAll listOf(paperMock, paperMock)
verify { searchOrderRepositoryMock.findPageBySearchOrder(searchOrderMock, paginationContextMock) }
}
@Test
fun gettingPapersByPmIds_withNoPmIds_returnsEmptyList() {
repo.findByPmIds(ArrayList(), LC).shouldBeEmpty()
}
@Test
fun findingByNumbers_withNoNumbers_returnsEmptyList() {
repo.findByNumbers(ArrayList(), LC).shouldBeEmpty()
}
@Test
fun findingExistingPmIdsOutOf_withNoPmIds_returnsEmptyList() {
repo.findExistingPmIdsOutOf(ArrayList()).shouldBeEmpty()
}
@Test
fun findingPageByFilter() {
val sortFields = ArrayList<SortField<Paper>>()
val sort = Sort(Direction.DESC, "id")
every { paginationContextMock.sort } returns sort
every { paginationContextMock.pageSize } returns 20
every { paginationContextMock.offset } returns 0
every { filterConditionMapper.map(filter) } returns conditionMock
every { sortMapper.map(sort, table) } returns sortFields
every { dsl.selectFrom(table) } returns mockk() {
every { where(conditionMock) } returns mockk() {
every { orderBy(sortFields) } returns mockk() {
every { limit(20) } returns mockk() {
every { offset(0) } returns mockk() {
// don't want to go into the enrichment test fixture, thus returning empty list
every { fetch(mapper) } returns emptyList()
}
}
}
}
}
val papers = repo.findPageByFilter(filter, paginationContextMock, LC)
papers.shouldBeEmpty()
verify { filterConditionMapper.map(filter) }
verify { paginationContextMock.sort }
verify { paginationContextMock.pageSize }
verify { paginationContextMock.offset }
verify { sortMapper.map(sort, table) }
verify { dsl.selectFrom(table) }
}
@Test
fun findingPageByFilter_withNoExplicitLanguageCode() {
every { applicationProperties.defaultLocalization } returns LC
val sortFields = ArrayList<SortField<Paper>>()
val sort = Sort(Direction.DESC, "id")
every { paginationContextMock.sort } returns sort
every { paginationContextMock.pageSize } returns 20
every { paginationContextMock.offset } returns 0
every { filterConditionMapper.map(filter) } returns conditionMock
every { sortMapper.map(sort, table) } returns sortFields
every { dsl.selectFrom(table) } returns mockk() {
every { where(conditionMock) } returns mockk() {
every { orderBy(sortFields) } returns mockk() {
every { limit(20) } returns mockk() {
every { offset(0) } returns mockk() {
// don't want to go into the enrichment test fixture, thus returning empty list
every { fetch(mapper) } returns emptyList()
}
}
}
}
}
val papers = repo.findPageByFilter(filter, paginationContextMock)
papers.shouldBeEmpty()
verify { applicationProperties.defaultLocalization }
verify { filterConditionMapper.map(filter) }
verify { paginationContextMock.sort }
verify { paginationContextMock.pageSize }
verify { paginationContextMock.offset }
verify { sortMapper.map(sort, table) }
verify { dsl.selectFrom(table) }
}
@Test
fun findingPageOfIdsBySearchOrder() {
every {
searchOrderRepositoryMock.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock)
} returns listOf(17L, 3L, 5L)
repo.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock) shouldContainAll listOf(17L, 3L, 5L)
verify { searchOrderRepositoryMock.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock) }
}
@Test
fun deletingIds() {
val ids = listOf(3L, 5L, 7L)
every { dsl.deleteFrom(table) } returns deleteUsingStep
every { deleteUsingStep.where(PAPER.ID.`in`(ids)) } returns deleteConditionStepMock
repo.delete(ids)
verify { dsl.deleteFrom(table) }
verify { deleteUsingStep.where(PAPER.ID.`in`(ids)) }
verify { deleteConditionStepMock.execute() }
}
@Test
fun enrichingAssociatedEntitiesOf_withNullEntity_doesNothing() {
repo.enrichAssociatedEntitiesOf(null, "de")
}
@Test
fun enrichingAssociatedEntitiesOf_withNullLanguageCode_withNullPaperId_doesNotCallRepo() {
every { paperMock.id } returns null
val repo = makeRepoStubbingAttachmentEnriching()
repo.enrichAssociatedEntitiesOf(paperMock, null)
verify { paperMock.id }
verify(exactly = 0) { paperMock.attachments = any() }
}
@Test
fun enrichingAssociatedEntitiesOf_withNullLanguageCode_withPaperWithId_enrichesAttachments() {
every { paperMock.id } returns 17L
val repo = makeRepoStubbingAttachmentEnriching()
repo.enrichAssociatedEntitiesOf(paperMock, null)
verify { paperMock.id }
verify { paperMock.attachments = listOf(paperAttachmentMock) }
}
private fun makeRepoStubbingAttachmentEnriching(): JooqPaperRepo =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun loadSlimAttachment(paperId: Long): List<PaperAttachment> = listOf(paperAttachmentMock)
}
@Test
fun evaluatingNumbers_withNullRecord_returnsEmpty() {
repo.evaluateNumbers(null).isPresent.shouldBeFalse()
}
@Test
fun evaluatingNumbers_withRecordWithNullValue1_returnsEmpty() {
val numbers: Record1<Array<Long>> = mockk {
every { value1() } returns null
}
repo.evaluateNumbers(numbers).isPresent.shouldBeFalse()
}
@Test
fun evaluatingNumbers_withRecordWithEmptyValue1_returnsEmpty() {
val numbers: Record1<Array<Long>> = mockk {
every { value1() } returns arrayOf()
}
repo.evaluateNumbers(numbers).isPresent.shouldBeFalse()
}
companion object {
private const val SAMPLE_ID = 3L
private const val LC = "de"
}
}
| gpl-3.0 | 1744a3961d2edbbb40b75505de0a34f1 | 36.30791 | 120 | 0.673506 | 4.900557 | false | true | false | false |
neo4j-graphql/neo4j-graphql | src/test/java/org/neo4j/graphql/GraphSchemaTest.kt | 2 | 1710 | package org.neo4j.graphql
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.test.TestGraphDatabaseFactory
/**
* @author mh
* *
* @since 05.05.17
*/
class GraphSchemaTest {
private var db: GraphDatabaseService? = null
@Before
@Throws(Exception::class)
fun setUp() {
db = TestGraphDatabaseFactory().newImpermanentDatabase()
db!!.execute("CREATE (:Person {name:'Joe'})").close()
}
@After
@Throws(Exception::class)
fun tearDown() {
db!!.shutdown()
}
@Test
fun resetOnCreateProperty() {
val graphQL = GraphSchema.getGraphQL(db!!)
db!!.execute("CREATE (:Person {age:42})").close()
Assert.assertNotSame(graphQL, GraphSchema.getGraphQL(db!!))
}
@Test
fun resetOnCreateLabel() {
val graphQL = GraphSchema.getGraphQL(db!!)
db!!.execute("CREATE (:User {name:'Jane'})").close()
Assert.assertNotSame(graphQL, GraphSchema.getGraphQL(db!!))
}
@Test
fun cacheBetweenInvocations() {
val graphQL = GraphSchema.getGraphQL(db!!)
Assert.assertSame(graphQL, GraphSchema.getGraphQL(db!!))
}
@Test
fun noResetWithSameTokens() {
val graphQL = GraphSchema.getGraphQL(db!!)
db!!.execute("CREATE (:Person {name:'Jane'})").close()
Assert.assertSame(graphQL, GraphSchema.getGraphQL(db!!))
}
@Test
fun countSchemaElements() {
}
@Test
fun reset() {
val graphQL = GraphSchema.getGraphQL(db!!)
GraphSchema.reset()
Assert.assertNotSame(graphQL, GraphSchema.getGraphQL(db!!))
}
}
| apache-2.0 | 6d260ed5752a1755e0e3b1e50cb3846f | 23.428571 | 67 | 0.633918 | 4.042553 | false | true | false | false |
matrix-org/matrix-android-sdk | matrix-sdk/src/main/java/org/matrix/androidsdk/rest/model/pid/ThreePid.kt | 1 | 3503 | /*
* Copyright 2014 OpenMarket Ltd
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
* Copyright 2019 New Vector Ltd
*
* 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.matrix.androidsdk.rest.model.pid
import android.content.Context
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import org.matrix.androidsdk.R
import java.util.*
/**
* 3 pid
*/
@Parcelize
data class ThreePid(
/** Types of third party media. */
val medium: String,
/**
* When a client tries to add a phone number to their account, they first need to call /requestToken on the homeserver.
* The user will get a code sent via SMS and give it to the client.
* The code received by sms will be sent to this submit url
*/
var submitUrl: String? = null,
var emailAddress: String? = null,
/**
* The current client secret key used during email validation.
*/
var clientSecret : String = UUID.randomUUID().toString(),
/**
* The phone number of the user
* Used when MEDIUM_MSISDN
*/
var phoneNumber: String? = null,
var country: String? = null,
var sid: String? = null,
/**
* The number of attempts
*/
var sendAttempt: Int = 0,
/**
* Current validation state (AUTH_STATE_XXX)
*/
var state: State = State.TOKEN_UNKNOWN
) : Parcelable {
//TODO state is not really used, will be needed for resend mail?
enum class State {
TOKEN_UNKNOWN,
TOKEN_REQUESTED,
TOKEN_RECEIVED,
TOKEN_SUBMITTED,
TOKEN_AUTHENTIFICATED
}
// /**
// * Clear the validation parameters
// */
// private fun resetValidationParameters() {
// state = State.TOKEN_UNKNOWN
// clientSecret = UUID.randomUUID().toString()
// sendAttempt = 1
// sid = null
// }
companion object {
/**
* Types of third party media.
* The list is not exhaustive and depends on the Identity server capabilities.
*/
const val MEDIUM_EMAIL = "email"
const val MEDIUM_MSISDN = "msisdn"
fun fromEmail(email: String) = ThreePid(MEDIUM_EMAIL).apply {
this.emailAddress = email.toLowerCase()
}
fun fromPhoneNumber(msisdn: String, country: String? = null) = ThreePid(MEDIUM_MSISDN).apply {
this.phoneNumber = msisdn
this.country = country?.toUpperCase()
}
fun getMediumFriendlyName(medium: String, context: Context): String {
var mediumFriendlyName = ""
when (medium) {
MEDIUM_EMAIL -> mediumFriendlyName = context.getString(R.string.medium_email)
MEDIUM_MSISDN -> mediumFriendlyName = context.getString(R.string.medium_phone_number)
}
return mediumFriendlyName
}
}
}
| apache-2.0 | 29388ebd218cc8be6684ce51b264090a | 28.436975 | 127 | 0.618042 | 4.411839 | false | false | false | false |
zdary/intellij-community | plugins/git4idea/src/git4idea/checkin/GitAmendCommitService.kt | 5 | 1558 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.checkin
import com.intellij.dvcs.commit.AmendCommitService
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.config.GitVersionSpecialty
import org.jetbrains.annotations.NonNls
@Service
internal class GitAmendCommitService(project: Project) : AmendCommitService(project) {
override fun isAmendCommitSupported(): Boolean = true
@Throws(VcsException::class)
override fun getLastCommitMessage(root: VirtualFile): String? {
val h = GitLineHandler(project, root, GitCommand.LOG)
h.addParameters("--max-count=1")
h.addParameters("--encoding=UTF-8")
h.addParameters("--pretty=format:${getCommitMessageFormatPattern()}")
return Git.getInstance().runCommand(h).getOutputOrThrow()
}
private fun getCommitMessageFormatPattern(): @NonNls String =
if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) {
"%B"
}
else {
// only message: subject + body; "%-b" means that preceding line-feeds will be deleted if the body is empty
// %s strips newlines from subject; there is no way to work around it before 1.7.2 with %B (unless parsing some fixed format)
"%s%n%n%-b"
}
} | apache-2.0 | a402353a7b7b46e97dd4996098dc4cef | 41.135135 | 140 | 0.761232 | 4.067885 | false | false | false | false |
zdary/intellij-community | platform/util-ex/src/com/intellij/psi/util/psiTreeUtil.kt | 2 | 13133 | // 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.psi.util
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.util.containers.stopAfter
import org.jetbrains.annotations.ApiStatus
import java.util.*
import kotlin.reflect.KClass
// ----------- Walking children/siblings/parents -------------------------------------------------------------------------------------------
inline fun <reified T : PsiElement> PsiElement.parentOfType(withSelf: Boolean = false): T? {
return PsiTreeUtil.getParentOfType(this, T::class.java, !withSelf)
}
@Deprecated("Use parentOfTypes()", ReplaceWith("parentOfTypes(*classes)"))
fun <T : PsiElement> PsiElement.parentOfType(vararg classes: KClass<out T>): T? {
return parentOfTypes(*classes)
}
fun <T : PsiElement> PsiElement.parentOfTypes(vararg classes: KClass<out T>, withSelf: Boolean = false): T? {
val start = if (withSelf) this else this.parent
return PsiTreeUtil.getNonStrictParentOfType(start, *classes.map { it.java }.toTypedArray())
}
inline fun <reified T : PsiElement> PsiElement.parentsOfType(withSelf: Boolean = true): Sequence<T> = parentsOfType(T::class.java, withSelf)
@Deprecated("For binary compatibility with older API", level = DeprecationLevel.HIDDEN)
fun <T : PsiElement> PsiElement.parentsOfType(clazz: Class<out T>): Sequence<T> = parentsOfType(clazz, withSelf = true)
fun <T : PsiElement> PsiElement.parentsOfType(clazz: Class<out T>, withSelf: Boolean = true): Sequence<T> {
return parents(withSelf).filterIsInstance(clazz)
}
/**
* @param withSelf whether to include [this] element into the sequence
* @return a sequence of parents, starting with [this] (or parent, depending on [withSelf])
* and walking up to and including the containing file
*/
fun PsiElement.parents(withSelf: Boolean): Sequence<PsiElement> {
val seed = if (withSelf) this else parentWithoutWalkingDirectories(this)
return generateSequence(seed, ::parentWithoutWalkingDirectories)
}
private fun parentWithoutWalkingDirectories(element: PsiElement): PsiElement? {
return if (element is PsiFile) null else element.parent
}
@Deprecated("Use PsiElement.parents() function", ReplaceWith("parents(true)"))
fun PsiElement.parents(): Sequence<PsiElement> = parents(true)
@Deprecated("Use PsiElement.parents() function", ReplaceWith("parents(false)"))
fun PsiElement.strictParents(): Sequence<PsiElement> = parents(false)
@Deprecated("Use PsiElement.parents() function", ReplaceWith("parents(true)"))
val PsiElement.parentsWithSelf: Sequence<PsiElement>
get() = parents(true)
@Deprecated("Use PsiElement.parents() function", ReplaceWith("parents(false)"))
val PsiElement.parents: Sequence<PsiElement>
get() = parents(false)
fun PsiElement.siblings(forward: Boolean = true, withSelf: Boolean = true): Sequence<PsiElement> {
val seed = when {
withSelf -> this
forward -> nextSibling
else -> prevSibling
}
return generateSequence(seed) {
if (forward) it.nextSibling else it.prevSibling
}
}
@Deprecated("For binary compatibility with older API", level = DeprecationLevel.HIDDEN)
fun PsiElement.siblings(forward: Boolean = true): Sequence<PsiElement> {
return siblings(forward)
}
fun PsiElement?.isAncestor(element: PsiElement, strict: Boolean = false): Boolean {
return PsiTreeUtil.isAncestor(this, element, strict)
}
fun PsiElement.prevLeaf(skipEmptyElements: Boolean = false): PsiElement? = PsiTreeUtil.prevLeaf(this, skipEmptyElements)
fun PsiElement.nextLeaf(skipEmptyElements: Boolean = false): PsiElement? = PsiTreeUtil.nextLeaf(this, skipEmptyElements)
val PsiElement.prevLeafs: Sequence<PsiElement>
get() = generateSequence({ prevLeaf() }, { it.prevLeaf() })
val PsiElement.nextLeafs: Sequence<PsiElement>
get() = generateSequence({ nextLeaf() }, { it.nextLeaf() })
fun PsiElement.prevLeaf(filter: (PsiElement) -> Boolean): PsiElement? {
var leaf = prevLeaf()
while (leaf != null && !filter(leaf)) {
leaf = leaf.prevLeaf()
}
return leaf
}
fun PsiElement.nextLeaf(filter: (PsiElement) -> Boolean): PsiElement? {
var leaf = nextLeaf()
while (leaf != null && !filter(leaf)) {
leaf = leaf.nextLeaf()
}
return leaf
}
// -------------------- Recursive tree visiting --------------------------------------------------------------------------------------------
private val alwaysTrue: (Any?) -> Boolean = { true }
/**
* @param childrenFirst if `true` then traverse children before parent (postorder),
* if `false` then traverse parent before children (preorder)
* @param canGoInside a predicate which checks if children of an element should be traversed
* @return sequence of all children of [this] element (including this element)
*/
fun PsiElement.descendants(
childrenFirst: Boolean = false,
canGoInside: (PsiElement) -> Boolean = alwaysTrue
): Sequence<PsiElement> = sequence {
val root = this@descendants
if (childrenFirst) {
visitChildrenAndYield(root, canGoInside)
}
else {
yieldAndVisitChildren(root, canGoInside)
}
}
private suspend fun SequenceScope<PsiElement>.yieldAndVisitChildren(element: PsiElement, canGoInside: (PsiElement) -> Boolean) {
yield(element)
if (canGoInside(element)) {
var child = element.firstChild
while (child != null) {
yieldAndVisitChildren(child, canGoInside)
child = child.nextSibling
}
}
}
private suspend fun SequenceScope<PsiElement>.visitChildrenAndYield(element: PsiElement, canGoInside: (PsiElement) -> Boolean) {
if (canGoInside(element)) {
var child = element.firstChild
while (child != null) {
visitChildrenAndYield(child, canGoInside)
child = child.nextSibling
}
}
yield(element)
}
inline fun <reified T : PsiElement> PsiElement.descendantsOfType(childrenFirst: Boolean = false): Sequence<T> {
return descendants(childrenFirst).filterIsInstance<T>()
}
// -----------------------------------------------------------------------------------------------------------------------------------------
private typealias ElementAndOffset = Pair<PsiElement, Int>
/**
* Walks the tree up to (and including) the file level starting from [start].
*
* The method doesn't check if [offsetInStart] is within [start].
*
* @return returns pairs of (element, offset relative to element)
*/
@ApiStatus.Experimental
fun walkUp(start: PsiElement, offsetInStart: Int): Iterator<ElementAndOffset> {
return iterator {
elementsAtOffsetUp(start, offsetInStart)
}
}
/**
* Walks the tree up to (and including) the file level or [stopAfter] starting from [start].
*
* The method doesn't check if [offsetInStart] is within [start].
* The method doesn't check if [stopAfter] is an actual parent of [start].
*
* @return returns pairs of (element, offset relative to element)
*/
@ApiStatus.Experimental
fun walkUp(start: PsiElement, offsetInStart: Int, stopAfter: PsiElement): Iterator<ElementAndOffset> {
return walkUp(start, offsetInStart).stopAfter {
it.first === stopAfter
}
}
/**
* Walks the tree up to (and including) the file level starting from the leaf element at [offsetInFile].
* If [offsetInFile] is a boundary between two leafs
* then walks up from each leaf to the common parent of the leafs starting from the rightmost one
* and continues walking up to the file.
*
* **Example**: `foo.bar<caret>[42]`, leaf is `[` element.
* ```
* foo.bar[42]
* / \
* foo.bar [42]
* / | \ / | \
* foo . bar [ 42 ]
* ```
* Traversal order: `[`, `[42]`, `bar`, `foo.bar`, `foo.bar[42]`
*
* @return returns pairs of (element, offset relative to element)
* @see elementsAtOffsetUp
* @see leavesAroundOffset
*/
@ApiStatus.Experimental
fun PsiFile.elementsAroundOffsetUp(offsetInFile: Int): Iterator<ElementAndOffset> {
val leaf = findElementAt(offsetInFile) ?: return Collections.emptyIterator()
val offsetInLeaf = offsetInFile - leaf.textRange.startOffset
if (offsetInLeaf == 0) {
return elementsAroundOffsetUp(leaf)
}
else {
return walkUp(leaf, offsetInLeaf)
}
}
/**
* Walks the tree up to (and including) the file level starting from the leaf element at [offsetInFile].
*
* @return returns pairs of (element, offset relative to element)
* @see elementsAroundOffsetUp
*/
@ApiStatus.Experimental
fun PsiFile.elementsAtOffsetUp(offsetInFile: Int): Iterator<ElementAndOffset> {
val leaf = findElementAt(offsetInFile) ?: return Collections.emptyIterator()
val offsetInLeaf = offsetInFile - leaf.textRange.startOffset
return walkUp(leaf, offsetInLeaf)
}
private fun elementsAroundOffsetUp(leaf: PsiElement): Iterator<ElementAndOffset> = iterator {
// We want to still give preference to the elements to the right of the caret,
// since there may be references/declarations too.
val leftSubTree = walkUpToCommonParent(leaf) ?: return@iterator
// At this point elements to the right of the caret (`[` and `[42]`) are processed.
// The sibling on the left (`foo.bar`) might be a tree,
// so we should go up from the rightmost leaf of that tree (`bar`).
val rightMostChild = PsiTreeUtil.lastChild(leftSubTree)
// Since the subtree to the right of the caret was already processed,
// we don't stop at common parent and just go up to the top.
elementsAtOffsetUp(rightMostChild, rightMostChild.textLength)
}
private suspend fun SequenceScope<ElementAndOffset>.walkUpToCommonParent(leaf: PsiElement): PsiElement? {
var current = leaf
while (true) {
ProgressManager.checkCanceled()
yield(ElementAndOffset(current, 0))
if (current is PsiFile) {
return null
}
current.prevSibling?.let {
return it
}
current = current.parent ?: return null
}
}
private suspend fun SequenceScope<ElementAndOffset>.elementsAtOffsetUp(element: PsiElement, offsetInElement: Int) {
var currentElement = element
var currentOffset = offsetInElement
while (true) {
ProgressManager.checkCanceled()
yield(ElementAndOffset(currentElement, currentOffset))
if (currentElement is PsiFile) {
return
}
currentOffset += currentElement.startOffsetInParent
currentElement = currentElement.parent ?: return
}
}
/**
* @return iterable of elements without children at a given [offsetInFile].
* Returned elements are the same bottom elements from which walk up is started in [elementsAroundOffsetUp]
*/
@ApiStatus.Experimental
fun PsiFile.leavesAroundOffset(offsetInFile: Int): Iterable<ElementAndOffset> {
val leaf = findElementAt(offsetInFile) ?: return emptyList()
val offsetInLeaf = offsetInFile - leaf.textRange.startOffset
if (offsetInLeaf == 0) {
val prefLeaf = PsiTreeUtil.prevLeaf(leaf)
if (prefLeaf != null) {
return listOf(ElementAndOffset(leaf, 0), ElementAndOffset(prefLeaf, prefLeaf.textLength))
}
}
return listOf(ElementAndOffset(leaf, offsetInLeaf))
}
inline fun <reified T : PsiElement> PsiElement.contextOfType(withSelf: Boolean = false): T? {
return PsiTreeUtil.getContextOfType(this, T::class.java, !withSelf)
}
fun <T : PsiElement> PsiElement.contextOfType(vararg classes: KClass<out T>): T? {
return PsiTreeUtil.getContextOfType(this, *classes.map { it.java }.toTypedArray())
}
fun <T : PsiElement> Sequence<T>.skipTokens(tokens: TokenSet): Sequence<T> {
return filter { it.node.elementType !in tokens }
}
val PsiElement?.elementType: IElementType?
get() = PsiUtilCore.getElementType(this)
fun PsiFile.hasErrorElementInRange(range: TextRange): Boolean {
require(range.startOffset >= 0)
require(range.endOffset <= textLength)
var leaf = findElementAt(range.startOffset) ?: return false
var leafRange = leaf.textRange
if (leafRange.startOffset < range.startOffset) {
leaf = leaf.nextLeaf(skipEmptyElements = true) ?: return false
leafRange = leaf.textRange
}
check(leafRange.startOffset >= range.startOffset)
val stopAt = leaf.parents(false).first { range in it.textRange }
if (stopAt is PsiErrorElement) return true
if (leafRange.startOffset == range.startOffset) {
val prevLeaf = leaf.prevLeaf()
if (prevLeaf is PsiErrorElement && prevLeaf.textLength == 0) return true
}
if (leafRange.endOffset == range.endOffset) {
val nextLeaf = leaf.nextLeaf()
if (nextLeaf is PsiErrorElement && nextLeaf.textLength == 0) return true
}
fun PsiElement.isInsideErrorElement(): Boolean {
var element: PsiElement? = this
while (element != null && element != stopAt) {
if (element is PsiErrorElement) return true
element = element.parent
}
return false
}
var endOffset = leafRange.endOffset
while (endOffset <= range.endOffset) {
if (leaf.isInsideErrorElement()) return true
leaf = leaf.nextLeaf() ?: return false
endOffset += leaf.textLength
}
return false
}
| apache-2.0 | 371cb55a66c708f6a9f7f2df570d9b56 | 35.890449 | 140 | 0.709891 | 4.206598 | false | false | false | false |
leafclick/intellij-community | plugins/git4idea/src/git4idea/config/InlineErrorNotifier.kt | 1 | 5294 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.config
import com.intellij.ide.plugins.newui.TwoLineProgressIndicator
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.Alarm.ThreadToUse.SWING_THREAD
import com.intellij.util.SingleAlarm
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.Nls.Capitalization.Sentence
import org.jetbrains.annotations.Nls.Capitalization.Title
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.SwingConstants
internal interface InlineComponent {
fun showProgress(@Nls(capitalization = Title) text: String): ProgressIndicator
fun showError(@Nls(capitalization = Sentence) errorText: String, link: LinkLabel<*>? = null)
fun showMessage(@Nls(capitalization = Sentence) text: String)
fun hideProgress()
}
internal open class InlineErrorNotifier(private val inlineComponent: InlineComponent,
private val modalityState: ModalityState,
private val disposable: Disposable) : ErrorNotifier {
var isTaskInProgress: Boolean = false // Check from EDT only
private set
override fun showError(@Nls(capitalization = Sentence) text: String,
@Nls(capitalization = Sentence) description: String?, fixOption: ErrorNotifier.FixOption) {
invokeAndWaitIfNeeded(modalityState) {
val linkLabel = LinkLabel<Any>(fixOption.text, null) { _, _ ->
fixOption.fix()
}
val message = if (description == null) text else "$text\n$description"
inlineComponent.showError(message, linkLabel)
}
}
override fun showError(@Nls(capitalization = Sentence) text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showError(text)
}
}
@CalledInAwt
override fun executeTask(@Nls(capitalization = Title) title: String, cancellable: Boolean, action: () -> Unit) {
val pi = inlineComponent.showProgress(title)
isTaskInProgress = true
Disposer.register(disposable, Disposable { pi.cancel() })
ApplicationManager.getApplication().executeOnPooledThread {
try {
ProgressManager.getInstance().runProcess(Runnable {
action()
}, pi)
}
finally {
invokeAndWaitIfNeeded(modalityState) {
isTaskInProgress = false
}
}
}
}
override fun changeProgressTitle(@Nls(capitalization = Title) text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showProgress(text)
}
}
override fun showMessage(@Nls(capitalization = Sentence) text: String) {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.showMessage(text)
}
}
override fun hideProgress() {
invokeAndWaitIfNeeded(modalityState) {
inlineComponent.hideProgress()
}
}
}
class GitExecutableInlineComponent(private val container: BorderLayoutPanel,
private val modalityState: ModalityState,
private val panelToValidate: JPanel?) : InlineComponent {
private var progressShown = false
override fun showProgress(@Nls(capitalization = Title) text: String): ProgressIndicator {
container.removeAll()
val pi = TwoLineProgressIndicator(true).apply {
this.text = text
}
progressShown = true
SingleAlarm(Runnable {
if (progressShown) {
container.addToLeft(pi.component)
panelToValidate?.validate()
}
}, delay = DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS, threadToUse = SWING_THREAD).request(modalityState)
return pi
}
override fun showError(@Nls(capitalization = Sentence) errorText: String, link: LinkLabel<*>?) {
container.removeAll()
progressShown = false
val label = multilineLabel(errorText).apply {
foreground = DialogWrapper.ERROR_FOREGROUND_COLOR
}
container.addToCenter(label)
if (link != null) {
link.verticalAlignment = SwingConstants.TOP
container.addToRight(link)
}
panelToValidate?.validate()
}
override fun showMessage(@Nls(capitalization = Sentence) text: String) {
container.removeAll()
progressShown = false
container.addToLeft(JBLabel(text))
panelToValidate?.validate()
}
override fun hideProgress() {
container.removeAll()
progressShown = false
panelToValidate?.validate()
}
private fun multilineLabel(text: String): JComponent = JBLabel(text).apply {
setAllowAutoWrapping(true)
setCopyable(true)
}
}
| apache-2.0 | a5efd27fbb6f9ba748b11a24667acc19 | 33.154839 | 140 | 0.719872 | 4.861341 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/info/Folders.kt | 1 | 5980 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.info
import slatekit.common.ext.toId
import slatekit.common.io.Files
import java.io.File
/**
* Represents folder locations for an application
* Folders locations are organized by company/app and stored in the user home directory.
* e.g.
*
* - user ( e.g /usr/kreddy or c:/users/kreddy )
* - company ( ? name of company or name of root folder )
* - area ( ? parent folder for all apps for a certain area/department/group )
* - product1.console ( individual apps go here )
* - product2.shell
* - product3.server
* - conf
* - cache
* - logs
* - inputs
* - outputs
*
* @param home: location of where the folders reside ( e.g. ~/ ( user directory), /apps/, current directory )
* @param root : optional name of root folder or company name
* @param area : optional name of group folder that holds all apps
* @param app : name of the application folder for this app
* @param cache : name of cache folder for the application
* @param inputs : name of input folder for the application
* @param logs : name of logs folder for the application
* @param outputs : name of output folder for the application
*/
data class Folders private constructor(
@JvmField
val home: String,
@JvmField
val root: String,
@JvmField
val area: String,
@JvmField
val app: String,
@JvmField
val cache: String,
@JvmField
val inputs: String,
@JvmField
val logs: String,
@JvmField
val outputs: String,
@JvmField
val temp: String,
@JvmField
val conf: String
) : Meta {
override fun props(): List<Pair<String, String>> = listOf(
"root" to root,
"area" to area,
"app" to app,
"cache" to cache,
"inputs" to app,
"log" to logs,
"outputs" to outputs,
"temp" to temp
)
val pathToConf : String get() = this.pathToApp + File.separator + conf
val pathToCache : String get() = this.pathToApp + File.separator + cache
val pathToInputs : String get() = this.pathToApp + File.separator + inputs
val pathToLogs : String get() = this.pathToApp + File.separator + logs
val pathToOutputs: String get() = this.pathToApp + File.separator + outputs
val pathToTemp : String get() = this.pathToApp + File.separator + temp
fun buildPath(part: String): String {
val userHome = System.getProperty("user.home")
val path = userHome + File.separator +
root + File.separator +
area + File.separator +
part.replace(" ", "")
return path
}
val pathToApp: String
get() {
val sep = File.separator
val homePath = home
val rootPath = homePath + sep + root
val areaPath = rootPath + sep + area
val finalPath = areaPath + sep + app
return finalPath
}
fun create() {
val rootPath = Files.mkDir(home, root)
val areaPath = Files.mkDir(rootPath, area)
val appPath = Files.mkDir(areaPath, app)
Files.mkDir(appPath, cache)
Files.mkDir(appPath, conf)
Files.mkDir(appPath, inputs)
Files.mkDir(appPath, logs)
Files.mkDir(appPath, outputs)
Files.mkDir(appPath, temp)
}
companion object {
@JvmStatic
val none = Folders(
home = System.getProperty("user.dir"),
root = "slatekit",
area = "samples",
app = "app",
cache = "cache",
inputs = "input",
logs = "log",
outputs = "output",
temp = "temp",
conf = "conf"
)
@JvmStatic
val default = Folders(
home = System.getProperty("user.dir"),
root = "slatekit",
area = "samples",
app = "app",
cache = "cache",
inputs = "input",
logs = "log",
outputs = "output",
temp = "temp",
conf = "conf"
)
@JvmStatic
fun userDir(about:About) : Folders {
return create(System.getProperty("user.home"), about.company, about.area, about.name)
}
@JvmStatic
fun userDir(root: String, area: String, name: String) : Folders {
return create(System.getProperty("user.home"), root, area, name)
}
@JvmStatic
fun installDir(tool:String, about:About) : Folders {
return create("/usr/local/opt/$tool", about.company, about.area, about.name)
}
@JvmStatic
private fun create(home:String, root: String, area: String, app: String) : Folders {
// For user home directories ( ~/ ), the root always begins with "." as in ~/.slatekit
val finalRoot = "." + root.toId()
val finalArea = area.toId()
val finalApp = app.toId()
return Folders(
home = home,
root = finalRoot,
area = finalArea,
app = finalApp,
cache = "cache",
inputs = "input",
logs = "log",
outputs = "output",
temp = "temp",
conf = "conf"
)
}
}
}
| apache-2.0 | 23640bc23cbd4dbd01780772e60baea5 | 29.824742 | 109 | 0.534615 | 4.349091 | false | false | false | false |
leafclick/intellij-community | platform/object-serializer/src/xml/KotlinAwareBeanBinding.kt | 1 | 2686 | // 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.serialization.xml
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.diagnostic.logger
import com.intellij.serialization.BaseBeanBinding
import com.intellij.serialization.PropertyAccessor
import com.intellij.util.ObjectUtils
import com.intellij.util.containers.IntArrayList
import com.intellij.util.xmlb.BeanBinding
import com.intellij.util.xmlb.SerializationFilter
import org.jdom.Element
internal class KotlinAwareBeanBinding(beanClass: Class<*>) : BeanBinding(beanClass) {
private val beanBinding = BaseBeanBinding(beanClass)
// only for accessor, not field
private fun findBindingIndex(name: String): Int {
// accessors sorted by name
val index = ObjectUtils.binarySearch(0, myBindings.size) { index -> myBindings[index].accessor.name.compareTo(name) }
if (index >= 0) {
return index
}
for ((i, binding) in myBindings.withIndex()) {
val accessor = binding.accessor
if (accessor is PropertyAccessor && accessor.getterName == name) {
return i
}
}
return -1
}
override fun serializeInto(o: Any, element: Element?, filter: SerializationFilter?): Element? {
return when (o) {
is BaseState -> serializeBaseStateInto(o, element, filter)
else -> super.serializeInto(o, element, filter)
}
}
fun serializeBaseStateInto(o: BaseState, _element: Element?, filter: SerializationFilter?, excludedPropertyNames: Collection<String>? = null): Element? {
var element = _element
// order of bindings must be used, not order of properties
var bindingIndices: IntArrayList? = null
for (property in o.__getProperties()) {
val propertyName = property.name!!
if (property.isEqualToDefault() || (excludedPropertyNames != null && excludedPropertyNames.contains(propertyName))) {
continue
}
val propertyBindingIndex = findBindingIndex(propertyName)
if (propertyBindingIndex < 0) {
logger<BaseState>().debug("cannot find binding for property ${propertyName}")
continue
}
if (bindingIndices == null) {
bindingIndices = IntArrayList()
}
bindingIndices.add(propertyBindingIndex)
}
if (bindingIndices != null) {
bindingIndices.sort()
for (i in 0 until bindingIndices.size()) {
element = serializePropertyInto(myBindings[bindingIndices.getQuick(i)], o, element, filter, false)
}
}
return element
}
override fun newInstance(): Any {
return beanBinding.newInstance()
}
} | apache-2.0 | c998bedf06b99c1a1aed988636843737 | 33.896104 | 155 | 0.706627 | 4.560272 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/ranges/RangeTest/emptyEquals.kt | 2 | 881 | import kotlin.test.*
fun box() {
assertTrue(IntRange.EMPTY == IntRange.EMPTY)
assertEquals(IntRange.EMPTY, IntRange.EMPTY)
assertEquals(0L..42L, 0L..42L)
assertEquals(0L..4200000042000000L, 0L..4200000042000000L)
assertEquals(3 downTo 0, 3 downTo 0)
assertEquals(2..1, 1..0)
assertEquals(2L..1L, 1L..0L)
assertEquals(2.toShort()..1.toShort(), 1.toShort()..0.toShort())
assertEquals(2.toByte()..1.toByte(), 1.toByte()..0.toByte())
assertEquals(0f..-3.14f, 3.14f..0f)
assertEquals(-2.0..-3.0, 3.0..2.0)
assertEquals('b'..'a', 'c'..'b')
assertTrue(1 downTo 2 == 2 downTo 3)
assertTrue(-1L downTo 0L == -2L downTo -1L)
assertEquals('j'..'a' step 4, 'u'..'q' step 2)
assertFalse(0..1 == IntRange.EMPTY)
assertEquals("range".."progression", "hashcode".."equals")
assertFalse(("aa".."bb") == ("aaa".."bbb"))
}
| apache-2.0 | e7a975678cc4d01a62feb3c8d11092e1 | 31.62963 | 68 | 0.620885 | 3.135231 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/intrinsics/longRangeWithExplicitDot.kt | 5 | 150 | fun box(): String {
val l: Long = 1
val l2: Long = 2
val r = l.rangeTo(l2)
return if (r.start == l && r.endInclusive == l2) "OK" else "fail"
} | apache-2.0 | 4a2c82544494cd7baf13428d044d0ef1 | 24.166667 | 67 | 0.566667 | 2.631579 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/pointer/PointerInteropFilterAndroidViewHookupTest.kt | 3 | 17546 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.pointer
import android.content.Context
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_UP
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.gesture.PointerProperties
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.test.TestActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.viewinterop.AndroidView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
// Tests basic operations to make sure that pointerInputModifier(view: AndroidViewHolder) is
// hooked up to PointerInteropFilter correctly.
@MediumTest
@RunWith(AndroidJUnit4::class)
class PointerInteropFilterAndroidViewHookupTest {
private lateinit var root: View
private lateinit var child: CustomView2
private lateinit var captureRequestDisallow: CaptureRequestDisallow
private val motionEventLog = mutableListOf<MotionEvent?>()
private val eventStringLog = mutableListOf<String>()
private val siblingEvents = mutableListOf<PointerEventType>()
private val motionEventCallback: (MotionEvent?) -> Unit = {
motionEventLog.add(it)
eventStringLog.add("motionEvent")
}
@get:Rule
val rule = createAndroidComposeRule<TestActivity>()
@Before
fun setup() {
rule.activityRule.scenario.onActivity { activity ->
child = CustomView2(activity, motionEventCallback).apply {
layoutParams = ViewGroup.LayoutParams(100, 100)
}
val parent = ComposeView(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setContent {
Box(Modifier.fillMaxSize()) {
Box(Modifier.fillMaxSize()
.pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
siblingEvents += event.type
}
}
}
)
AndroidView(
{ child },
Modifier.spyGestureFilter { eventStringLog.add(it.name) }
)
}
}
}
captureRequestDisallow = CaptureRequestDisallow(activity)
captureRequestDisallow.addView(parent)
activity.setContentView(captureRequestDisallow)
root = activity.findViewById(android.R.id.content)
}
siblingEvents.clear()
}
@Test
fun ui_down_downMotionEventIsReceived() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
}
assertThat(motionEventLog).hasSize(1)
assertThat(motionEventLog[0]).isSameInstanceAs(down)
}
@Test
fun ui_downUp_upMotionEventIsReceived() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val up =
MotionEvent(
10,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
root.dispatchTouchEvent(up)
}
assertThat(motionEventLog).hasSize(2)
assertThat(motionEventLog[1]).isSameInstanceAs(up)
}
@Test
fun ui_downRetFalseUp_onlyDownIsReceived() {
child.retVal = false
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val up =
MotionEvent(
10,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
root.dispatchTouchEvent(up)
}
assertThat(motionEventLog).hasSize(1)
assertThat(motionEventLog[0]).isSameInstanceAs(down)
}
@Test
fun ui_downRetFalseUpMoveUp_onlyDownIsReceived() {
child.retVal = false
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val move =
MotionEvent(
10,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
val up =
MotionEvent(
20,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
root.dispatchTouchEvent(move)
root.dispatchTouchEvent(up)
}
assertThat(motionEventLog).hasSize(1)
assertThat(motionEventLog[0]).isSameInstanceAs(down)
}
@Test
fun ui_downRetFalseUpDown_2ndDownIsReceived() {
child.retVal = false
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val up =
MotionEvent(
10,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val down2 =
MotionEvent(
2,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
root.dispatchTouchEvent(up)
root.dispatchTouchEvent(down2)
}
assertThat(motionEventLog).hasSize(2)
assertThat(motionEventLog[1]).isSameInstanceAs(down2)
}
@Test
fun ui_downMove_moveIsDispatchedDuringFinal() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val move =
MotionEvent(
10,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
eventStringLog.clear()
root.dispatchTouchEvent(move)
}
assertThat(eventStringLog).hasSize(4)
assertThat(eventStringLog[0]).isEqualTo(PointerEventPass.Initial.toString())
assertThat(eventStringLog[1]).isEqualTo(PointerEventPass.Main.toString())
assertThat(eventStringLog[2]).isEqualTo(PointerEventPass.Final.toString())
assertThat(eventStringLog[3]).isEqualTo("motionEvent")
}
@Test
fun ui_downDisallowInterceptMove_moveIsDispatchedDuringInitial() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val move =
MotionEvent(
10,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
eventStringLog.clear()
child.requestDisallowInterceptTouchEvent(true)
root.dispatchTouchEvent(move)
}
assertThat(eventStringLog).hasSize(4)
assertThat(eventStringLog[0]).isEqualTo(PointerEventPass.Initial.toString())
assertThat(eventStringLog[1]).isEqualTo("motionEvent")
assertThat(eventStringLog[2]).isEqualTo(PointerEventPass.Main.toString())
assertThat(eventStringLog[3]).isEqualTo(PointerEventPass.Final.toString())
}
@Test
fun ui_downDisallowInterceptMoveAllowInterceptMove_2ndMoveIsDispatchedDuringFinal() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val move1 =
MotionEvent(
10,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
val move2 =
MotionEvent(
20,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(150f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
child.requestDisallowInterceptTouchEvent(true)
root.dispatchTouchEvent(move1)
eventStringLog.clear()
child.requestDisallowInterceptTouchEvent(false)
root.dispatchTouchEvent(move2)
}
assertThat(eventStringLog).hasSize(4)
assertThat(eventStringLog[0]).isEqualTo(PointerEventPass.Initial.toString())
assertThat(eventStringLog[1]).isEqualTo(PointerEventPass.Main.toString())
assertThat(eventStringLog[2]).isEqualTo(PointerEventPass.Final.toString())
assertThat(eventStringLog[3]).isEqualTo("motionEvent")
}
@Test
fun ui_downDisallowInterceptUpDownMove_2ndMoveIsDispatchedDuringFinal() {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val up =
MotionEvent(
10,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val downB =
MotionEvent(
20,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(50f, 50f)),
root
)
val moveB =
MotionEvent(
30,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(100f, 50f)),
root
)
rule.runOnIdle {
root.dispatchTouchEvent(down)
child.requestDisallowInterceptTouchEvent(true)
root.dispatchTouchEvent(up)
root.dispatchTouchEvent(downB)
eventStringLog.clear()
root.dispatchTouchEvent(moveB)
}
assertThat(eventStringLog).hasSize(4)
assertThat(eventStringLog[0]).isEqualTo(PointerEventPass.Initial.toString())
assertThat(eventStringLog[1]).isEqualTo(PointerEventPass.Main.toString())
assertThat(eventStringLog[2]).isEqualTo(PointerEventPass.Final.toString())
assertThat(eventStringLog[3]).isEqualTo("motionEvent")
}
@Test
fun disallowNotTriggeredWhenMovementInClickChild() {
var clicked = false
rule.runOnUiThread {
child.setOnClickListener { clicked = true }
}
rule.runOnIdle {
val outOfView = Offset(-50f, -50f)
root.dispatchTouchEvent(down())
root.dispatchTouchEvent(move(10, outOfView))
root.dispatchTouchEvent(up(20, outOfView))
}
assertThat(clicked).isFalse()
assertThat(captureRequestDisallow.disallowIntercept).isFalse()
}
@Test
fun disallowTriggeredWhenMovementInClickChildAfterRequestDisallow() {
var clicked = false
rule.runOnUiThread {
child.setOnClickListener { clicked = true }
}
rule.runOnIdle {
val outOfView = Offset(-50f, -50f)
root.dispatchTouchEvent(down())
child.requestDisallowInterceptTouchEvent(true)
root.dispatchTouchEvent(move(10, outOfView))
root.dispatchTouchEvent(up(20, outOfView))
}
assertThat(clicked).isFalse()
assertThat(captureRequestDisallow.disallowIntercept).isTrue()
}
@Test
fun overlappingChildAllowsEventsThrough() {
rule.runOnIdle {
val start = Offset(50f, 50f)
val middle = Offset(10f, 10f)
val end = Offset(51f, 50f)
root.dispatchTouchEvent(down(0, start))
root.dispatchTouchEvent(move(10, middle))
root.dispatchTouchEvent(move(20, end))
root.dispatchTouchEvent(up(30, end))
}
rule.runOnIdle {
assertThat(siblingEvents).hasSize(4)
assertThat(siblingEvents).containsExactly(
PointerEventType.Press,
PointerEventType.Move,
PointerEventType.Move,
PointerEventType.Release
)
}
}
fun down(eventTime: Int = 0, offset: Offset = Offset(50f, 50f)) =
MotionEvent(
eventTime,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(offset.x, offset.y)),
root
)
fun move(eventTime: Int, offset: Offset) =
MotionEvent(
eventTime,
ACTION_MOVE,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(offset.x, offset.y)),
root
)
fun up(eventTime: Int, offset: Offset = Offset(50f, 50f)) =
MotionEvent(
eventTime,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(0)),
arrayOf(PointerCoords(offset.x, offset.y)),
root
)
}
private class CustomView2(context: Context, val callBack: (MotionEvent?) -> Unit) : ViewGroup
(context) {
var retVal = true
override fun onTouchEvent(event: MotionEvent?): Boolean {
callBack(event)
return retVal
}
override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {}
}
private class CaptureRequestDisallow(context: Context) : FrameLayout(context) {
var disallowIntercept = false
override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
this.disallowIntercept = disallowIntercept
super.requestDisallowInterceptTouchEvent(disallowIntercept)
}
} | apache-2.0 | 99753ed3a361cdce88fbb3d0fe253620 | 29.569686 | 93 | 0.535336 | 5.283348 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/androidTest/java/com/owncloud/android/authentication/LoginActivityTest.kt | 1 | 27795 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
*
* Copyright (C) 2020 ownCloud GmbH.
*
* This program 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.
* <p>
* 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.
* <p>
* 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.owncloud.android.authentication
import android.accounts.AccountManager.KEY_ACCOUNT_NAME
import android.accounts.AccountManager.KEY_ACCOUNT_TYPE
import android.app.Activity
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.closeSoftKeyboard
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.Visibility
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.owncloud.android.R
import com.owncloud.android.domain.exceptions.NoNetworkConnectionException
import com.owncloud.android.domain.exceptions.OwncloudVersionNotSupportedException
import com.owncloud.android.domain.exceptions.ServerNotReachableException
import com.owncloud.android.domain.exceptions.UnauthorizedException
import com.owncloud.android.domain.server.model.AuthenticationMethod
import com.owncloud.android.domain.server.model.ServerInfo
import com.owncloud.android.domain.utils.Event
import com.owncloud.android.extensions.parseError
import com.owncloud.android.presentation.UIResult
import com.owncloud.android.presentation.ui.authentication.ACTION_UPDATE_EXPIRED_TOKEN
import com.owncloud.android.presentation.ui.authentication.ACTION_UPDATE_TOKEN
import com.owncloud.android.presentation.ui.authentication.BASIC_TOKEN_TYPE
import com.owncloud.android.presentation.ui.authentication.EXTRA_ACCOUNT
import com.owncloud.android.presentation.ui.authentication.EXTRA_ACTION
import com.owncloud.android.presentation.ui.authentication.KEY_AUTH_TOKEN_TYPE
import com.owncloud.android.presentation.ui.authentication.LoginActivity
import com.owncloud.android.presentation.ui.authentication.OAUTH_TOKEN_TYPE
import com.owncloud.android.presentation.ui.settings.SettingsActivity
import com.owncloud.android.presentation.viewmodels.authentication.OCAuthenticationViewModel
import com.owncloud.android.presentation.viewmodels.settings.SettingsViewModel
import com.owncloud.android.providers.ContextProvider
import com.owncloud.android.providers.MdmProvider
import com.owncloud.android.testutil.OC_ACCOUNT
import com.owncloud.android.testutil.OC_AUTH_TOKEN_TYPE
import com.owncloud.android.testutil.OC_BASIC_PASSWORD
import com.owncloud.android.testutil.OC_BASIC_USERNAME
import com.owncloud.android.testutil.OC_SERVER_INFO
import com.owncloud.android.testutil.annotation.FailsOnGithubAction
import com.owncloud.android.utils.CONFIGURATION_SERVER_URL
import com.owncloud.android.utils.CONFIGURATION_SERVER_URL_INPUT_VISIBILITY
import com.owncloud.android.utils.matchers.assertVisibility
import com.owncloud.android.utils.matchers.isDisplayed
import com.owncloud.android.utils.matchers.isEnabled
import com.owncloud.android.utils.matchers.isFocusable
import com.owncloud.android.utils.matchers.withText
import com.owncloud.android.utils.mockIntentToComponent
import com.owncloud.android.utils.replaceText
import com.owncloud.android.utils.scrollAndClick
import com.owncloud.android.utils.typeText
import io.mockk.every
import io.mockk.mockk
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
class LoginActivityTest {
private lateinit var activityScenario: ActivityScenario<LoginActivity>
private lateinit var ocAuthenticationViewModel: OCAuthenticationViewModel
private lateinit var settingsViewModel: SettingsViewModel
private lateinit var ocContextProvider: ContextProvider
private lateinit var mdmProvider: MdmProvider
private lateinit var context: Context
private lateinit var loginResultLiveData: MutableLiveData<Event<UIResult<String>>>
private lateinit var serverInfoLiveData: MutableLiveData<Event<UIResult<ServerInfo>>>
private lateinit var supportsOauth2LiveData: MutableLiveData<Event<UIResult<Boolean>>>
private lateinit var baseUrlLiveData: MutableLiveData<Event<UIResult<String>>>
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
ocAuthenticationViewModel = mockk(relaxed = true)
settingsViewModel = mockk(relaxUnitFun = true)
ocContextProvider = mockk(relaxed = true)
mdmProvider = mockk(relaxed = true)
loginResultLiveData = MutableLiveData()
serverInfoLiveData = MutableLiveData()
supportsOauth2LiveData = MutableLiveData()
baseUrlLiveData = MutableLiveData()
every { ocAuthenticationViewModel.loginResult } returns loginResultLiveData
every { ocAuthenticationViewModel.serverInfo } returns serverInfoLiveData
every { ocAuthenticationViewModel.supportsOAuth2 } returns supportsOauth2LiveData
every { ocAuthenticationViewModel.baseUrl } returns baseUrlLiveData
every { settingsViewModel.isThereAttachedAccount() } returns false
stopKoin()
startKoin {
context
allowOverride(override = true)
modules(
module {
viewModel {
ocAuthenticationViewModel
}
viewModel {
settingsViewModel
}
factory {
ocContextProvider
}
factory {
mdmProvider
}
}
)
}
}
@After
fun tearDown() {
unmockkAll()
}
private fun launchTest(
showServerUrlInput: Boolean = true,
serverUrl: String = "",
showLoginBackGroundImage: Boolean = true,
showWelcomeLink: Boolean = true,
accountType: String = "owncloud",
loginWelcomeText: String = "",
intent: Intent? = null
) {
every { mdmProvider.getBrandingBoolean(CONFIGURATION_SERVER_URL_INPUT_VISIBILITY, R.bool.show_server_url_input) } returns showServerUrlInput
every { mdmProvider.getBrandingString(CONFIGURATION_SERVER_URL, R.string.server_url) } returns serverUrl
every { ocContextProvider.getBoolean(R.bool.use_login_background_image) } returns showLoginBackGroundImage
every { ocContextProvider.getBoolean(R.bool.show_welcome_link) } returns showWelcomeLink
every { ocContextProvider.getString(R.string.account_type) } returns accountType
every { ocContextProvider.getString(R.string.login_welcome_text) } returns loginWelcomeText
every { ocContextProvider.getString(R.string.app_name) } returns BRANDED_APP_NAME
activityScenario = if (intent == null) {
ActivityScenario.launch(LoginActivity::class.java)
} else {
ActivityScenario.launch(intent)
}
}
@Test
fun initialViewStatus_notBrandedOptions() {
launchTest()
assertViewsDisplayed()
}
@Test
@FailsOnGithubAction
fun initialViewStatus_brandedOptions_serverInfoInSetup() {
launchTest(showServerUrlInput = false, serverUrl = OC_SERVER_INFO.baseUrl)
assertViewsDisplayed(
showHostUrlFrame = false,
showHostUrlInput = false,
showCenteredRefreshButton = true,
showEmbeddedCheckServerButton = false
)
verify(exactly = 1) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
}
@Test
fun initialViewStatus_brandedOptions_serverInfoInSetup_connectionFails() {
launchTest(showServerUrlInput = false, serverUrl = OC_SERVER_INFO.baseUrl)
serverInfoLiveData.postValue(Event(UIResult.Error(NoNetworkConnectionException())))
R.id.centeredRefreshButton.isDisplayed(true)
R.id.centeredRefreshButton.scrollAndClick()
verify(exactly = 2) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC.copy(isSecureConnection = true))))
R.id.centeredRefreshButton.isDisplayed(false)
}
@Test
fun initialViewStatus_brandedOptions_dontUseLoginBackgroundImage() {
launchTest(showLoginBackGroundImage = false)
assertViewsDisplayed(showLoginBackGroundImage = false)
}
@Test
fun initialViewStatus_brandedOptions_dontShowWelcomeLink() {
launchTest(showWelcomeLink = false)
assertViewsDisplayed(showWelcomeLink = false)
}
@Test
fun initialViewStatus_brandedOptions_customWelcomeText() {
launchTest(showWelcomeLink = true, loginWelcomeText = CUSTOM_WELCOME_TEXT)
assertViewsDisplayed(showWelcomeLink = true)
R.id.welcome_link.withText(CUSTOM_WELCOME_TEXT)
}
@Test
fun initialViewStatus_brandedOptions_defaultWelcomeText() {
launchTest(showWelcomeLink = true, loginWelcomeText = "")
assertViewsDisplayed(showWelcomeLink = true)
R.id.welcome_link.withText(String.format(ocContextProvider.getString(R.string.auth_register), BRANDED_APP_NAME))
}
@Test
fun checkServerInfo_clickButton_callGetServerInfo() {
launchTest()
R.id.hostUrlInput.typeText(OC_SERVER_INFO.baseUrl)
R.id.embeddedCheckServerButton.scrollAndClick()
verify(exactly = 1) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
}
@Test
fun checkServerInfo_clickLogo_callGetServerInfo() {
launchTest()
R.id.hostUrlInput.typeText(OC_SERVER_INFO.baseUrl)
R.id.thumbnail.scrollAndClick()
verify(exactly = 1) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
}
@Test
fun checkServerInfo_isLoading_show() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Loading()))
with(R.id.server_status_text) {
isDisplayed(true)
withText(R.string.auth_testing_connection)
}
}
@Test
fun checkServerInfo_isSuccess_updateUrlInput() {
launchTest()
R.id.hostUrlInput.typeText("demo.owncloud.com")
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC.copy(isSecureConnection = true))))
R.id.hostUrlInput.withText(SERVER_INFO_BASIC.baseUrl)
}
@Test
fun checkServerInfo_isSuccess_Secure() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC.copy(isSecureConnection = true))))
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.auth_secure_connection)
}
}
@Test
fun checkServerInfo_isSuccess_NotSecure() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC.copy(isSecureConnection = false))))
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.auth_connection_established)
}
}
@Test
fun checkServerInfo_isSuccess_Basic() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC)))
checkBasicFieldsVisibility(loginButtonShouldBeVisible = false)
}
@Test
fun checkServerInfo_isSuccess_Bearer() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BEARER)))
checkBearerFieldsVisibility()
}
@Test
fun checkServerInfo_isSuccess_None() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC.copy(authenticationMethod = AuthenticationMethod.NONE))))
assertNoneFieldsVisibility()
}
@Test
@FailsOnGithubAction
fun checkServerInfo_isSuccess_basicModifyUrlInput() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC)))
checkBasicFieldsVisibility()
R.id.account_username.typeText(OC_BASIC_USERNAME)
R.id.account_password.typeText(OC_BASIC_PASSWORD)
R.id.hostUrlInput.typeText("anything")
with(R.id.account_username) {
withText("")
assertVisibility(Visibility.GONE)
}
with(R.id.account_password) {
withText("")
assertVisibility(Visibility.GONE)
}
R.id.loginButton.assertVisibility(Visibility.GONE)
}
@Test
fun checkServerInfo_isSuccess_bearerModifyUrlInput() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BEARER)))
checkBearerFieldsVisibility()
R.id.hostUrlInput.typeText("anything")
R.id.loginButton.assertVisibility(Visibility.GONE)
}
@Test
@FailsOnGithubAction
fun checkServerInfo_isError_emptyUrl() {
launchTest()
R.id.hostUrlInput.typeText("")
R.id.embeddedCheckServerButton.scrollAndClick()
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.auth_can_not_auth_against_server)
}
verify(exactly = 0) { ocAuthenticationViewModel.getServerInfo(any()) }
}
@Test
fun checkServerInfo_isError_ownCloudVersionNotSupported() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Error(OwncloudVersionNotSupportedException())))
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.server_not_supported)
}
}
@Test
fun checkServerInfo_isError_noNetworkConnection() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Error(NoNetworkConnectionException())))
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.error_no_network_connection)
}
}
@Test
fun checkServerInfo_isError_otherExceptions() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Error(ServerNotReachableException())))
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.network_host_not_available)
}
}
@Test
@FailsOnGithubAction
fun loginBasic_callLoginBasic() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC)))
R.id.account_username.typeText(OC_BASIC_USERNAME)
R.id.account_password.typeText(OC_BASIC_PASSWORD)
with(R.id.loginButton) {
isDisplayed(true)
scrollAndClick()
}
verify(exactly = 1) { ocAuthenticationViewModel.loginBasic(OC_BASIC_USERNAME, OC_BASIC_PASSWORD, null) }
}
@Test
@FailsOnGithubAction
fun loginBasic_callLoginBasic_trimUsername() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC)))
R.id.account_username.typeText(" $OC_BASIC_USERNAME ")
R.id.account_password.typeText(OC_BASIC_PASSWORD)
with(R.id.loginButton) {
isDisplayed(true)
scrollAndClick()
}
verify(exactly = 1) { ocAuthenticationViewModel.loginBasic(OC_BASIC_USERNAME, OC_BASIC_PASSWORD, null) }
}
@Test
@FailsOnGithubAction
fun loginBasic_showOrHideFields() {
launchTest()
serverInfoLiveData.postValue(Event(UIResult.Success(SERVER_INFO_BASIC)))
R.id.account_username.typeText(OC_BASIC_USERNAME)
R.id.loginButton.isDisplayed(false)
R.id.account_password.typeText(OC_BASIC_PASSWORD)
R.id.loginButton.isDisplayed(true)
R.id.account_username.replaceText("")
R.id.loginButton.isDisplayed(false)
}
@Test
fun login_isLoading() {
launchTest()
loginResultLiveData.postValue(Event(UIResult.Loading()))
with(R.id.auth_status_text) {
withText(R.string.auth_trying_to_login)
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
}
}
@Test
fun login_isSuccess_finishResultCode() {
launchTest()
loginResultLiveData.postValue(Event(UIResult.Success(data = "Account_name")))
assertEquals(activityScenario.result.resultCode, Activity.RESULT_OK)
val accountName: String? = activityScenario.result?.resultData?.extras?.getString(KEY_ACCOUNT_NAME)
val accountType: String? = activityScenario.result?.resultData?.extras?.getString(KEY_ACCOUNT_TYPE)
assertNotNull(accountName)
assertNotNull(accountType)
assertEquals("Account_name", accountName)
assertEquals("owncloud", accountType)
}
@Test
fun login_isSuccess_finishResultCodeBrandedAccountType() {
launchTest(accountType = "notOwnCloud")
loginResultLiveData.postValue(Event(UIResult.Success(data = "Account_name")))
assertEquals(activityScenario.result.resultCode, Activity.RESULT_OK)
val accountName: String? = activityScenario.result?.resultData?.extras?.getString(KEY_ACCOUNT_NAME)
val accountType: String? = activityScenario.result?.resultData?.extras?.getString(KEY_ACCOUNT_TYPE)
assertNotNull(accountName)
assertNotNull(accountType)
assertEquals("Account_name", accountName)
assertEquals("notOwnCloud", accountType)
}
@Test
fun login_isError_NoNetworkConnectionException() {
launchTest()
loginResultLiveData.postValue(Event(UIResult.Error(NoNetworkConnectionException())))
R.id.server_status_text.withText(R.string.error_no_network_connection)
checkBasicFieldsVisibility(fieldsShouldBeVisible = false)
}
@Test
fun login_isError_ServerNotReachableException() {
launchTest()
loginResultLiveData.postValue(Event(UIResult.Error(ServerNotReachableException())))
R.id.server_status_text.withText(R.string.error_no_network_connection)
checkBasicFieldsVisibility(fieldsShouldBeVisible = false)
}
@Test
fun login_isError_OtherException() {
launchTest()
val exception = UnauthorizedException()
loginResultLiveData.postValue(Event(UIResult.Error(exception)))
R.id.auth_status_text.withText(exception.parseError("", context.resources, true) as String)
}
@Test
fun intent_withSavedAccount_viewModelCalls() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
}
launchTest(intent = intentWithAccount)
verify(exactly = 1) { ocAuthenticationViewModel.supportsOAuth2(OC_ACCOUNT.name) }
verify(exactly = 1) { ocAuthenticationViewModel.getBaseUrl(OC_ACCOUNT.name) }
}
@Test
fun supportsOAuth_isSuccess_actionUpdateExpiredTokenOAuth() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
putExtra(EXTRA_ACTION, ACTION_UPDATE_EXPIRED_TOKEN)
putExtra(KEY_AUTH_TOKEN_TYPE, OAUTH_TOKEN_TYPE)
}
launchTest(intent = intentWithAccount)
supportsOauth2LiveData.postValue(Event(UIResult.Success(true)))
with(R.id.instructions_message) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(context.getString(R.string.auth_expired_oauth_token_toast))
}
}
@Test
fun supportsOAuth_isSuccess_actionUpdateToken() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
putExtra(EXTRA_ACTION, ACTION_UPDATE_TOKEN)
putExtra(KEY_AUTH_TOKEN_TYPE, OC_AUTH_TOKEN_TYPE)
}
launchTest(intent = intentWithAccount)
supportsOauth2LiveData.postValue(Event(UIResult.Success(false)))
R.id.instructions_message.assertVisibility(Visibility.GONE)
}
@Test
fun supportsOAuth_isSuccess_actionUpdateExpiredTokenBasic() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
putExtra(EXTRA_ACTION, ACTION_UPDATE_EXPIRED_TOKEN)
putExtra(KEY_AUTH_TOKEN_TYPE, BASIC_TOKEN_TYPE)
}
launchTest(intent = intentWithAccount)
supportsOauth2LiveData.postValue(Event(UIResult.Success(false)))
with(R.id.instructions_message) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(context.getString(R.string.auth_expired_basic_auth_toast))
}
}
@Test
fun getBaseUrl_isSuccess_updatesBaseUrl() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
}
launchTest(intent = intentWithAccount)
baseUrlLiveData.postValue(Event(UIResult.Success(OC_SERVER_INFO.baseUrl)))
with(R.id.hostUrlInput) {
withText(OC_SERVER_INFO.baseUrl)
assertVisibility(Visibility.VISIBLE)
isDisplayed(true)
isEnabled(false)
isFocusable(false)
}
verify(exactly = 0) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
}
@Test
fun getBaseUrlAndActionNotCreate_isSuccess_updatesBaseUrl() {
val intentWithAccount = Intent(context, LoginActivity::class.java).apply {
putExtra(EXTRA_ACCOUNT, OC_ACCOUNT)
putExtra(EXTRA_ACTION, ACTION_UPDATE_EXPIRED_TOKEN)
}
launchTest(intent = intentWithAccount)
baseUrlLiveData.postValue(Event(UIResult.Success(OC_SERVER_INFO.baseUrl)))
with(R.id.hostUrlInput) {
withText(OC_SERVER_INFO.baseUrl)
assertVisibility(Visibility.VISIBLE)
isDisplayed(true)
isEnabled(false)
isFocusable(false)
}
verify(exactly = 1) { ocAuthenticationViewModel.getServerInfo(OC_SERVER_INFO.baseUrl) }
}
@Test
fun settingsLink() {
Intents.init()
launchTest()
closeSoftKeyboard()
mockIntentToComponent(RESULT_OK, SettingsActivity::class.java.name)
onView(withId(R.id.settings_link)).perform(click())
intended(hasComponent(SettingsActivity::class.java.name))
Intents.release()
}
private fun checkBasicFieldsVisibility(
fieldsShouldBeVisible: Boolean = true,
loginButtonShouldBeVisible: Boolean = false
) {
val visibilityMatcherFields = if (fieldsShouldBeVisible) Visibility.VISIBLE else Visibility.GONE
val visibilityMatcherLoginButton = if (loginButtonShouldBeVisible) Visibility.VISIBLE else Visibility.GONE
with(R.id.account_username) {
isDisplayed(fieldsShouldBeVisible)
assertVisibility(visibilityMatcherFields)
withText("")
}
with(R.id.account_password) {
isDisplayed(fieldsShouldBeVisible)
assertVisibility(visibilityMatcherFields)
withText("")
}
R.id.loginButton.assertVisibility(visibilityMatcherLoginButton)
R.id.auth_status_text.assertVisibility(visibilityMatcherLoginButton)
}
private fun checkBearerFieldsVisibility() {
R.id.account_username.assertVisibility(Visibility.GONE)
R.id.account_password.assertVisibility(Visibility.GONE)
R.id.auth_status_text.assertVisibility(Visibility.GONE)
with(R.id.loginButton) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
}
}
private fun assertNoneFieldsVisibility() {
with(R.id.server_status_text) {
isDisplayed(true)
assertVisibility(Visibility.VISIBLE)
withText(R.string.auth_unsupported_auth_method)
}
R.id.account_username.assertVisibility(Visibility.GONE)
R.id.account_password.assertVisibility(Visibility.GONE)
R.id.loginButton.assertVisibility(Visibility.GONE)
R.id.auth_status_text.assertVisibility(Visibility.GONE)
}
private fun assertViewsDisplayed(
showLoginBackGroundImage: Boolean = true,
showThumbnail: Boolean = true,
showCenteredRefreshButton: Boolean = false,
showInstructionsMessage: Boolean = false,
showHostUrlFrame: Boolean = true,
showHostUrlInput: Boolean = true,
showEmbeddedCheckServerButton: Boolean = true,
showEmbeddedRefreshButton: Boolean = false,
showServerStatusText: Boolean = false,
showAccountUsername: Boolean = false,
showAccountPassword: Boolean = false,
showAuthStatus: Boolean = false,
showLoginButton: Boolean = false,
showWelcomeLink: Boolean = true
) {
R.id.login_background_image.isDisplayed(displayed = showLoginBackGroundImage)
R.id.thumbnail.isDisplayed(displayed = showThumbnail)
R.id.centeredRefreshButton.isDisplayed(displayed = showCenteredRefreshButton)
R.id.instructions_message.isDisplayed(displayed = showInstructionsMessage)
R.id.hostUrlFrame.isDisplayed(displayed = showHostUrlFrame)
R.id.hostUrlInput.isDisplayed(displayed = showHostUrlInput)
R.id.embeddedCheckServerButton.isDisplayed(displayed = showEmbeddedCheckServerButton)
R.id.embeddedRefreshButton.isDisplayed(displayed = showEmbeddedRefreshButton)
R.id.server_status_text.isDisplayed(displayed = showServerStatusText)
R.id.account_username_container.isDisplayed(displayed = showAccountUsername)
R.id.account_username.isDisplayed(displayed = showAccountUsername)
R.id.account_password_container.isDisplayed(displayed = showAccountPassword)
R.id.account_password.isDisplayed(displayed = showAccountPassword)
R.id.auth_status_text.isDisplayed(displayed = showAuthStatus)
R.id.loginButton.isDisplayed(displayed = showLoginButton)
R.id.welcome_link.isDisplayed(displayed = showWelcomeLink)
}
companion object {
val SERVER_INFO_BASIC = OC_SERVER_INFO
val SERVER_INFO_BEARER = OC_SERVER_INFO.copy(authenticationMethod = AuthenticationMethod.BEARER_TOKEN)
private const val CUSTOM_WELCOME_TEXT = "Welcome to this test"
private const val BRANDED_APP_NAME = "BrandedAppName"
}
}
| gpl-2.0 | bc4c5161fd1faf65d0adcd4fba3c03b6 | 34.226869 | 148 | 0.701087 | 4.50324 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/ml-completion/src/org/jetbrains/kotlin/idea/mlCompletion/MlCompletionForKotlinFeature.kt | 6 | 1337 | // 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.mlCompletion
import com.intellij.completion.ml.settings.CompletionMLRankingSettings
import org.jetbrains.kotlin.idea.configuration.ExperimentalFeature
object MlCompletionForKotlinFeature : ExperimentalFeature() {
override val title: String
get() = KotlinMlCompletionBundle.message("experimental.ml.completion")
override fun shouldBeShown(): Boolean = MLCompletionForKotlin.isAvailable
override var isEnabled: Boolean
get() = MLCompletionForKotlin.isEnabled
set(value) {
MLCompletionForKotlin.isEnabled = value
}
}
internal object MLCompletionForKotlin {
const val isAvailable: Boolean = true
var isEnabled: Boolean
get() {
val settings = CompletionMLRankingSettings.getInstance()
return settings.isRankingEnabled && settings.isLanguageEnabled("Kotlin")
}
set(value) {
val settings = CompletionMLRankingSettings.getInstance()
if (value && !settings.isRankingEnabled) {
settings.isRankingEnabled = true
}
settings.setLanguageEnabled("Kotlin", value)
}
}
| apache-2.0 | da2670aa4478824e41292e86520b51f1 | 35.135135 | 158 | 0.700823 | 4.97026 | false | false | false | false |
android/compose-samples | JetNews/app/src/main/java/com/example/jetnews/ui/home/PostCards.kt | 1 | 7594 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui.home
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.posts.impl.post3
import com.example.jetnews.model.Post
import com.example.jetnews.ui.theme.JetnewsTheme
import com.example.jetnews.ui.utils.BookmarkButton
@Composable
fun AuthorAndReadTime(
post: Post,
modifier: Modifier = Modifier
) {
Row(modifier) {
Text(
text = stringResource(
id = R.string.home_post_min_read,
formatArgs = arrayOf(
post.metadata.author.name,
post.metadata.readTimeMinutes
)
),
style = MaterialTheme.typography.bodyMedium
)
}
}
@Composable
fun PostImage(post: Post, modifier: Modifier = Modifier) {
Image(
painter = painterResource(post.imageThumbId),
contentDescription = null, // decorative
modifier = modifier
.size(40.dp, 40.dp)
.clip(MaterialTheme.shapes.small)
)
}
@Composable
fun PostTitle(post: Post) {
Text(
text = post.title,
style = MaterialTheme.typography.titleMedium,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
@Composable
fun PostCardSimple(
post: Post,
navigateToArticle: (String) -> Unit,
isFavorite: Boolean,
onToggleFavorite: () -> Unit
) {
val bookmarkAction = stringResource(if (isFavorite) R.string.unbookmark else R.string.bookmark)
Row(
modifier = Modifier
.clickable(onClick = { navigateToArticle(post.id) })
.semantics {
// By defining a custom action, we tell accessibility services that this whole
// composable has an action attached to it. The accessibility service can choose
// how to best communicate this action to the user.
customActions = listOf(
CustomAccessibilityAction(
label = bookmarkAction,
action = { onToggleFavorite(); true }
)
)
}
) {
PostImage(post, Modifier.padding(16.dp))
Column(
modifier = Modifier
.weight(1f)
.padding(vertical = 10.dp)
) {
PostTitle(post)
AuthorAndReadTime(post)
}
BookmarkButton(
isBookmarked = isFavorite,
onClick = onToggleFavorite,
// Remove button semantics so action can be handled at row level
modifier = Modifier
.clearAndSetSemantics {}
.padding(vertical = 2.dp, horizontal = 6.dp)
)
}
}
@Composable
fun PostCardHistory(post: Post, navigateToArticle: (String) -> Unit) {
var openDialog by remember { mutableStateOf(false) }
Row(
Modifier
.clickable(onClick = { navigateToArticle(post.id) })
) {
PostImage(
post = post,
modifier = Modifier.padding(16.dp)
)
Column(
Modifier
.weight(1f)
.padding(vertical = 12.dp)
) {
Text(
text = stringResource(id = R.string.home_post_based_on_history),
style = MaterialTheme.typography.labelMedium
)
PostTitle(post = post)
AuthorAndReadTime(
post = post,
modifier = Modifier.padding(top = 4.dp)
)
}
IconButton(onClick = { openDialog = true }) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.cd_more_actions)
)
}
}
if (openDialog) {
AlertDialog(
modifier = Modifier.padding(20.dp),
onDismissRequest = { openDialog = false },
title = {
Text(
text = stringResource(id = R.string.fewer_stories),
style = MaterialTheme.typography.titleLarge
)
},
text = {
Text(
text = stringResource(id = R.string.fewer_stories_content),
style = MaterialTheme.typography.bodyLarge
)
},
confirmButton = {
Text(
text = stringResource(id = R.string.agree),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.padding(15.dp)
.clickable { openDialog = false }
)
}
)
}
}
@Preview("Bookmark Button")
@Composable
fun BookmarkButtonPreview() {
JetnewsTheme {
Surface {
BookmarkButton(isBookmarked = false, onClick = { })
}
}
}
@Preview("Bookmark Button Bookmarked")
@Composable
fun BookmarkButtonBookmarkedPreview() {
JetnewsTheme {
Surface {
BookmarkButton(isBookmarked = true, onClick = { })
}
}
}
@Preview("Simple post card")
@Preview("Simple post card (dark)", uiMode = UI_MODE_NIGHT_YES)
@Composable
fun SimplePostPreview() {
JetnewsTheme {
Surface {
PostCardSimple(post3, {}, false, {})
}
}
}
@Preview("Post History card")
@Composable
fun HistoryPostPreview() {
JetnewsTheme {
Surface {
PostCardHistory(post3, {})
}
}
}
| apache-2.0 | 5d791a6a2a0f7893170cca530116b1b4 | 30.380165 | 99 | 0.615354 | 4.681874 | false | false | false | false |
firebase/firebase-android-sdk | firebase-messaging/ktx/src/test/kotlin/com/google/firebase/messaging/ktx/MessagingTests.kt | 1 | 2908 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.messaging.ktx
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.ktx.Firebase
import com.google.firebase.ktx.app
import com.google.firebase.ktx.initialize
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.platforminfo.UserAgentPublisher
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
const val APP_ID = "APP_ID"
const val API_KEY = "API_KEY"
abstract class BaseTestCase {
@Before
fun setUp() {
Firebase.initialize(
ApplicationProvider.getApplicationContext(),
FirebaseOptions.Builder()
.setApplicationId(APP_ID)
.setApiKey(API_KEY)
.setProjectId("123")
.build()
)
}
@After
fun cleanUp() {
FirebaseApp.clearInstancesForTest()
}
}
@RunWith(RobolectricTestRunner::class)
class MessagingTests : BaseTestCase() {
@Test
fun `messaging should delegate to FirebaseMessaging#getInstance()`() {
assertThat(Firebase.messaging).isSameInstanceAs(FirebaseMessaging.getInstance())
}
@Test
fun `remoteMessage() should produce correct RemoteMessages`() {
val recipient = "recipient"
val expectedCollapseKey = "collapse"
val msgId = "id"
val msgType = "type"
val timeToLive = 100
val remoteMessage =
remoteMessage(recipient) {
collapseKey = expectedCollapseKey
messageId = msgId
messageType = msgType
ttl = timeToLive
addData("hello", "world")
}
assertThat(remoteMessage.to).isEqualTo(recipient)
assertThat(remoteMessage.collapseKey).isEqualTo(expectedCollapseKey)
assertThat(remoteMessage.messageId).isEqualTo(msgId)
assertThat(remoteMessage.messageType).isEqualTo(msgType)
assertThat(remoteMessage.data).isEqualTo(mapOf("hello" to "world"))
}
}
@RunWith(RobolectricTestRunner::class)
class LibraryVersionTest : BaseTestCase() {
@Test
fun `library version should be registered with runtime`() {
val publisher = Firebase.app.get(UserAgentPublisher::class.java)
assertThat(publisher.userAgent).contains(LIBRARY_NAME)
}
}
| apache-2.0 | a6930f7cd665470cf062681066226ea3 | 30.608696 | 84 | 0.742435 | 4.346786 | false | true | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/procedural/Table.kt | 1 | 2383 | package de.fabmax.kool.demo.procedural
import de.fabmax.kool.demo.DemoLoader
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.deferred.deferredPbrShader
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.MeshBuilder
import de.fabmax.kool.scene.geometry.simpleShape
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class Table : Mesh(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS, Attribute.TEXTURE_COORDS, Attribute.TANGENTS)) {
init {
isCastingShadow = false
generate {
makeGeometry()
geometry.removeDegeneratedTriangles()
geometry.generateNormals()
geometry.generateTangents()
}
shader = deferredPbrShader {
useAlbedoMap("${DemoLoader.materialPath}/granitesmooth1/granitesmooth1-albedo4.jpg")
useNormalMap("${DemoLoader.materialPath}/granitesmooth1/granitesmooth1-normal2.jpg")
useRoughnessMap("${DemoLoader.materialPath}/granitesmooth1/granitesmooth1-roughness3.jpg")
}
}
private fun MeshBuilder.makeGeometry() {
val tableR = 30f
val r = 1f
translate(0f, -r, 0f)
rotate(90f, Vec3f.X_AXIS)
profile {
val shape = simpleShape(true) {
for (a in 0..100) {
val rad = 2f * PI.toFloat() * a / 100
xy(cos(rad) * tableR, sin(rad) * tableR)
uv(0f, 0f)
}
}
for (i in 0..15) {
val p = i / 15f
withTransform {
val h = cos((1 - p) * PI.toFloat()) * r
val e = sin(p * PI.toFloat()) * r
val s = (tableR + e) / tableR
val uvS = (tableR + r * p * PI.toFloat()) * 0.04f
shape.texCoords.forEachIndexed { i, uv -> uv.set(shape.positions[i].x, shape.positions[i].y).norm().scale(uvS) }
translate(0f, 0f, h)
scale(s, s, 1f)
if (i == 0) {
sampleAndFillBottom()
} else {
sample()
}
}
}
fillTop()
}
}
} | apache-2.0 | b15bf8cb7cfd5fd88120941d4211aea7 | 33.057143 | 132 | 0.544692 | 3.951907 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt | 1 | 7238 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>(
ConvertToStringTemplateIntention::class,
ConvertToStringTemplateIntention::shouldSuggestToConvert,
problemText = KotlinBundle.message("convert.concatenation.to.template.before.text")
)
open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.template")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (!isApplicableToNoParentCheck(element)) return false
val parent = element.parent
if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val replacement = buildReplacement(element)
runWriteActionIfPhysical(element) {
element.replaced(replacement)
}
}
companion object {
fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean {
val entries = buildReplacement(expression).entries
return entries.none { it is KtBlockStringTemplateEntry }
&& !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry }
&& entries.count { it is KtLiteralStringTemplateEntry } >= 1
&& !expression.textContains('\n')
}
@JvmStatic
fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression {
val rightText = buildText(expression.right, false)
return fold(expression.left, rightText, KtPsiFactory(expression))
}
private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression {
val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart()
return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) {
val leftRight = buildText(left.right, forceBraces)
fold(left.left, leftRight + right, factory)
} else {
val leftText = buildText(left, forceBraces)
factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression
}
}
fun buildText(expr: KtExpression?, forceBraces: Boolean): String {
if (expr == null) return ""
val expression = KtPsiUtil.safeDeparenthesize(expr).let {
when {
(it as? KtDotQualifiedExpression)?.isToString() == true && it.receiverExpression !is KtSuperExpression ->
it.receiverExpression
it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr
else -> it
}
}
val expressionText = expression.text
when (expression) {
is KtConstantExpression -> {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(expression)!!
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext)
if (constant != null) {
val stringValue = constant.getValue(type).toString()
if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) {
return buildString {
StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this)
}
}
}
}
is KtStringTemplateExpression -> {
val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) {
val unquoted = expressionText.substring(3, expressionText.length - 3)
StringUtil.escapeStringCharacters(unquoted)
} else {
StringUtil.unquoteString(expressionText)
}
if (forceBraces) {
if (base.endsWith('$')) {
return base.dropLast(1) + "\\$"
} else {
val lastPart = expression.children.lastOrNull()
if (lastPart is KtSimpleNameStringTemplateEntry) {
return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}"
}
}
}
return base
}
is KtNameReferenceExpression ->
return "$" + (if (forceBraces) "{$expressionText}" else expressionText)
is KtThisExpression ->
return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText)
}
return "\${$expressionText}"
}
private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean {
if (expression.operationToken != KtTokens.PLUS) return false
val expressionType = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(expression)
if (!KotlinBuiltIns.isString(expressionType)) return false
return isSuitable(expression)
}
private fun isSuitable(expression: KtExpression): Boolean {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) {
return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false)
}
if (PsiUtilCore.hasErrorElementChild(expression)) return false
if (expression.textContains('\n')) return false
return true
}
}
}
| apache-2.0 | 74ccc40b39377daf8eb357f39d18c6ef | 47.253333 | 158 | 0.627383 | 5.986766 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/multi/Mangahere.kt | 1 | 4137 | /*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* TachiyomiEX 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 file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package eu.kanade.tachiyomi.data.source.online.multi
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
abstract class Mangahere() : ParsedOnlineSource() {
override fun supportsLatest() = true
override fun popularMangaInitialUrl() = "$baseUrl/directory/"
override fun latestUpdatesInitialUrl() = "$baseUrl/directory/?last_chapter_time.za"
override fun popularMangaSelector() = "div.directory_list > ul > li"
override fun popularMangaFromElement(element: Element, manga: Manga) {
element.select("div.title > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
}
override fun popularMangaNextPageSelector() = "div.next-page > a.next"
override fun searchMangaSelector() = "div.result_search > dl:has(dt)"
override fun searchMangaFromElement(element: Element, manga: Manga) {
element.select("dt > a.manga_info").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
}
override fun searchMangaNextPageSelector() = "div.directory_footer > div.next-page > a.next"
protected abstract fun parseStatus(status: String) : Int
override fun chapterListSelector() = "div.detail_list > ul > li"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("span.left > a")
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = element.select("span.right").first()?.text()?.let { parseChapterDate(it) } ?: 0
}
private fun parseChapterDate(date: String): Long {
return if ("Today" in date) {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else if ("Yesterday" in date) {
Calendar.getInstance().apply {
add(Calendar.DATE, -1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else {
try {
SimpleDateFormat("MMM dd, yyyy").parse(date).time
} catch (e: ParseException) {
0L
}
}
}
override fun pageListParse(document: Document, pages: MutableList<Page>) {
document.select("select.wid60").first()?.getElementsByTag("option")?.forEach {
pages.add(Page(pages.size, it.attr("value")))
}
pages.getOrNull(0)?.imageUrl = imageUrlParse(document)
}
override fun imageUrlParse(document: Document): String = document.getElementById("image").attr("src")
}
| gpl-3.0 | 651cba0b9ef0e51b9278b6d662c84deb | 37.663551 | 109 | 0.660382 | 4.345588 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaHelper.kt | 1 | 4516 | // 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.formatter.trailingComma
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespace
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.utils.addToStdlib.cast
object TrailingCommaHelper {
fun findInvalidCommas(commaOwner: KtElement): List<PsiElement> = commaOwner.firstChild
?.siblings(withItself = false)
?.filter { it.isComma }
?.filter {
it.prevLeaf(true)?.isLineBreak() == true || it.leafIgnoringWhitespace(false) != it.leafIgnoringWhitespaceAndComments(false)
}?.toList().orEmpty()
fun trailingCommaExistsOrCanExist(psiElement: PsiElement, settings: CodeStyleSettings): Boolean =
TrailingCommaContext.create(psiElement).commaExistsOrMayExist(settings.kotlinCustomSettings)
fun trailingCommaExists(commaOwner: KtElement): Boolean = when (commaOwner) {
is KtFunctionLiteral -> commaOwner.valueParameterList?.trailingComma != null
is KtWhenEntry -> commaOwner.trailingComma != null
is KtDestructuringDeclaration -> commaOwner.trailingComma != null
else -> trailingCommaOrLastElement(commaOwner)?.isComma == true
}
fun trailingCommaOrLastElement(commaOwner: KtElement): PsiElement? {
val lastChild = commaOwner.lastSignificantChild ?: return null
val withSelf = when (PsiUtil.getElementType(lastChild)) {
KtTokens.COMMA -> return lastChild
in RIGHT_BARRIERS -> false
else -> true
}
return lastChild.getPrevSiblingIgnoringWhitespaceAndComments(withSelf)?.takeIf {
PsiUtil.getElementType(it) !in LEFT_BARRIERS
}?.takeIfIsNotError()
}
/**
* @return true if [commaOwner] has a trailing comma and hasn't a line break before the first or after the last element
*/
fun lineBreakIsMissing(commaOwner: KtElement): Boolean {
if (!trailingCommaExists(commaOwner)) return false
val first = elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) return true
val last = elementAfterLastElement(commaOwner)
return last?.prevLeaf(true)?.isLineBreak() == false
}
fun elementBeforeFirstElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.lBrace else commaOwner.leftParenthesis
}
is KtWhenEntry -> commaOwner.parent.cast<KtWhenExpression>().openBrace
is KtDestructuringDeclaration -> commaOwner.lPar
else -> commaOwner.firstChild?.takeIfIsNotError()
}
fun elementAfterLastElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.arrow else commaOwner.rightParenthesis
}
is KtWhenEntry -> commaOwner.arrow
is KtDestructuringDeclaration -> commaOwner.rPar
else -> commaOwner.lastChild?.takeIfIsNotError()
}
private fun PsiElement.takeIfIsNotError(): PsiElement? = takeIf { it !is PsiErrorElement }
private val RIGHT_BARRIERS = TokenSet.create(KtTokens.RBRACKET, KtTokens.RPAR, KtTokens.RBRACE, KtTokens.GT, KtTokens.ARROW)
private val LEFT_BARRIERS = TokenSet.create(KtTokens.LBRACKET, KtTokens.LPAR, KtTokens.LBRACE, KtTokens.LT)
private val PsiElement.lastSignificantChild: PsiElement?
get() = when (this) {
is KtWhenEntry -> arrow
is KtDestructuringDeclaration -> rPar
else -> lastChild
}
} | apache-2.0 | 419d0f4f3d3d9e31a63abc5bf583c01f | 45.56701 | 158 | 0.728078 | 5.108597 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/searchUtil.kt | 1 | 11056 | // 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.search
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.cache.impl.id.IdIndex
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.search.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Processor
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.scriptDefinitionExists
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName
import org.jetbrains.kotlin.load.java.propertyNamesBySetMethodName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isTopLevelKtOrJavaMember
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName as getKotlinFqNameOriginal
infix fun SearchScope.and(otherScope: SearchScope): SearchScope = intersectWith(otherScope)
infix fun SearchScope.or(otherScope: SearchScope): SearchScope = union(otherScope)
infix fun GlobalSearchScope.or(otherScope: SearchScope): GlobalSearchScope = union(otherScope)
operator fun SearchScope.minus(otherScope: GlobalSearchScope): SearchScope = this and !otherScope
operator fun GlobalSearchScope.not(): GlobalSearchScope = GlobalSearchScope.notScope(this)
fun SearchScope.unionSafe(other: SearchScope): SearchScope {
if (this is LocalSearchScope && this.scope.isEmpty()) {
return other
}
if (other is LocalSearchScope && other.scope.isEmpty()) {
return this
}
return this.union(other)
}
fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this)
fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this)
fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this)
fun Project.containsKotlinFile(): Boolean = FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, projectScope())
fun GlobalSearchScope.restrictByFileType(fileType: FileType) = GlobalSearchScope.getScopeRestrictedByFileTypes(this, fileType)
fun SearchScope.restrictByFileType(fileType: FileType): SearchScope = when (this) {
is GlobalSearchScope -> restrictByFileType(fileType)
is LocalSearchScope -> {
val elements = scope.filter { it.containingFile.fileType == fileType }
when (elements.size) {
0 -> LocalSearchScope.EMPTY
scope.size -> this
else -> LocalSearchScope(elements.toTypedArray())
}
}
else -> this
}
fun GlobalSearchScope.restrictToKotlinSources() = restrictByFileType(KotlinFileType.INSTANCE)
fun SearchScope.restrictToKotlinSources() = restrictByFileType(KotlinFileType.INSTANCE)
fun SearchScope.excludeKotlinSources(project: Project): SearchScope = excludeFileTypes(project, KotlinFileType.INSTANCE)
fun Project.everythingScopeExcludeFileTypes(vararg fileTypes: FileType): GlobalSearchScope {
return GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.everythingScope(this), *fileTypes).not()
}
fun SearchScope.excludeFileTypes(project: Project, vararg fileTypes: FileType): SearchScope {
return if (this is GlobalSearchScope) {
this.intersectWith(project.everythingScopeExcludeFileTypes(*fileTypes))
} else {
this as LocalSearchScope
val filteredElements = scope.filter { it.containingFile.fileType !in fileTypes }
if (filteredElements.isNotEmpty())
LocalSearchScope(filteredElements.toTypedArray())
else
LocalSearchScope.EMPTY
}
}
/**
* `( *\\( *)` and `( *\\) *)` – to find parenthesis
* `( *, *(?![^\\[]*]))` – to find commas outside square brackets
*/
private val parenthesisRegex = Regex("( *\\( *)|( *\\) *)|( *, *(?![^\\[]*]))")
private inline fun CharSequence.ifNotEmpty(action: (CharSequence) -> Unit) {
takeIf(CharSequence::isNotBlank)?.let(action)
}
fun SearchScope.toHumanReadableString(): String = buildString {
val scopeText = [email protected]()
var currentIndent = 0
var lastIndex = 0
for (parenthesis in parenthesisRegex.findAll(scopeText)) {
val subSequence = scopeText.subSequence(lastIndex, parenthesis.range.first)
subSequence.ifNotEmpty {
append(" ".repeat(currentIndent))
appendLine(it)
}
val value = parenthesis.value
when {
"(" in value -> currentIndent += 2
")" in value -> currentIndent -= 2
}
lastIndex = parenthesis.range.last + 1
}
if (isEmpty()) append(scopeText)
}
// Copied from SearchParameters.getEffectiveSearchScope()
fun ReferencesSearch.SearchParameters.effectiveSearchScope(element: PsiElement): SearchScope {
if (element == elementToSearch) return effectiveSearchScope
if (isIgnoreAccessScope) return scopeDeterminedByUser
val accessScope = element.useScope()
return scopeDeterminedByUser.intersectWith(accessScope)
}
fun isOnlyKotlinSearch(searchScope: SearchScope): Boolean {
return searchScope is LocalSearchScope && searchScope.scope.all { it.containingFile is KtFile }
}
fun PsiElement.codeUsageScopeRestrictedToProject(): SearchScope = project.projectScope().intersectWith(codeUsageScope())
fun PsiElement.useScope(): SearchScope = PsiSearchHelper.getInstance(project).getUseScope(this)
fun PsiElement.codeUsageScope(): SearchScope = PsiSearchHelper.getInstance(project).getCodeUsageScope(this)
// TODO: improve scope calculations
fun PsiElement.codeUsageScopeRestrictedToKotlinSources(): SearchScope = codeUsageScope().restrictToKotlinSources()
fun PsiSearchHelper.isCheapEnoughToSearchConsideringOperators(
name: String,
scope: GlobalSearchScope,
fileToIgnoreOccurrencesIn: PsiFile?,
progress: ProgressIndicator?
): PsiSearchHelper.SearchCostResult {
if (OperatorConventions.isConventionName(Name.identifier(name))) {
return PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES
}
return isCheapEnoughToSearch(name, scope, fileToIgnoreOccurrencesIn, progress)
}
fun findScriptsWithUsages(declaration: KtNamedDeclaration, processor: (KtFile) -> Boolean): Boolean {
val project = declaration.project
val scope = declaration.useScope() as? GlobalSearchScope ?: return true
val name = declaration.name.takeIf { it?.isNotBlank() == true } ?: return true
val collector = Processor<VirtualFile> { file ->
val ktFile =
(PsiManager.getInstance(project).findFile(file) as? KtFile)?.takeIf { it.scriptDefinitionExists() } ?: return@Processor true
processor(ktFile)
}
return FileBasedIndex.getInstance().getFilesWithKey(
IdIndex.NAME,
setOf(IdIndexEntry(name, true)),
collector,
scope
)
}
data class ReceiverTypeSearcherInfo(
val psiClass: PsiClass?,
val containsTypeOrDerivedInside: ((KtDeclaration) -> Boolean)
)
fun PsiReference.isImportUsage(): Boolean =
element.getNonStrictParentOfType<KtImportDirective>() != null
// Used in the "mirai" plugin
@Deprecated(
"Use org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName()",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("getKotlinFqName()", "org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName")
)
fun PsiElement.getKotlinFqName(): FqName? = getKotlinFqNameOriginal()
fun PsiElement?.isPotentiallyOperator(): Boolean {
val namedFunction = safeAs<KtNamedFunction>() ?: return false
if (namedFunction.hasModifier(KtTokens.OPERATOR_KEYWORD)) return true
// operator modifier could be omitted for overriding function
if (!namedFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
val name = namedFunction.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) return false
// TODO: it's fast PSI-based check, a proper check requires call to resolveDeclarationWithParents() that is not frontend-independent
return true
}
private val PsiMethod.canBeGetter: Boolean
get() = JvmAbi.isGetterName(name) && parameters.isEmpty() && returnTypeElement?.textMatches("void") != true
private val PsiMethod.canBeSetter: Boolean
get() = JvmAbi.isSetterName(name) && parameters.size == 1 && returnTypeElement?.textMatches("void") != false
private val PsiMethod.probablyCanHaveSyntheticAccessors: Boolean
get() = canHaveOverride && !hasTypeParameters() && !isFinalProperty
private val PsiMethod.getterName: Name? get() = propertyNameByGetMethodName(Name.identifier(name))
private val PsiMethod.setterNames: Collection<Name>? get() = propertyNamesBySetMethodName(Name.identifier(name)).takeIf { it.isNotEmpty() }
private val PsiMethod.isFinalProperty: Boolean
get() {
val property = unwrapped as? KtProperty ?: return false
if (property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
val containingClassOrObject = property.containingClassOrObject ?: return true
return containingClassOrObject is KtObjectDeclaration
}
private val PsiMethod.isTopLevelDeclaration: Boolean get() = unwrapped?.isTopLevelKtOrJavaMember() == true
val PsiMethod.syntheticAccessors: Collection<Name>
get() {
if (!probablyCanHaveSyntheticAccessors) return emptyList()
return when {
canBeGetter -> listOfNotNull(getterName)
canBeSetter -> setterNames.orEmpty()
else -> emptyList()
}
}
val PsiMethod.canHaveSyntheticAccessors: Boolean get() = probablyCanHaveSyntheticAccessors && (canBeGetter || canBeSetter)
val PsiMethod.canHaveSyntheticGetter: Boolean get() = probablyCanHaveSyntheticAccessors && canBeGetter
val PsiMethod.canHaveSyntheticSetter: Boolean get() = probablyCanHaveSyntheticAccessors && canBeSetter
val PsiMethod.syntheticGetter: Name? get() = if (canHaveSyntheticGetter) getterName else null
val PsiMethod.syntheticSetters: Collection<Name>? get() = if (canHaveSyntheticSetter) setterNames else null
/**
* Attention: only language constructs are checked. For example: static member, constructor, top-level property
* @return `false` if constraints are found. Otherwise, `true`
*/
val PsiMethod.canHaveOverride: Boolean get() = !hasModifier(JvmModifier.STATIC) && !isConstructor && !isTopLevelDeclaration
| apache-2.0 | 8e0c2b92c3e8b5c7459de58093b390be | 42.341176 | 139 | 0.760224 | 4.864437 | false | false | false | false |
androidx/androidx | paging/paging-common/src/main/kotlin/androidx/paging/TransformablePage.kt | 3 | 4379 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
internal data class TransformablePage<T : Any>(
/**
* List of original (pre-transformation) page offsets the original page relative to initial = 0,
* that this [TransformablePage] depends on.
*
* This array is always sorted.
*/
val originalPageOffsets: IntArray,
/**
* Data to present (post-transformation)
*/
val data: List<T>,
/**
* Original (pre-transformation) page offset relative to initial = 0, that [hintOriginalIndices]
* are associated with.
*/
val hintOriginalPageOffset: Int,
/**
* Optional lookup table for page indices.
*
* If provided, this table provides a mapping from presentation index -> original,
* pre-transformation index.
*
* If null, the indices of [data] map directly to their original pre-transformation index.
*
* Note: [hintOriginalIndices] refers to indices of the original item which can be found in the
* loaded pages with pageOffset == [hintOriginalPageOffset].
*/
val hintOriginalIndices: List<Int>?
) {
/**
* Simple constructor for creating pre-transformation pages, which don't need an index lookup
* and only reference a single [originalPageOffset].
*/
constructor(
originalPageOffset: Int,
data: List<T>
) : this(intArrayOf(originalPageOffset), data, originalPageOffset, null)
init {
require(originalPageOffsets.isNotEmpty()) {
"originalPageOffsets cannot be empty when constructing TransformablePage"
}
require(hintOriginalIndices == null || hintOriginalIndices.size == data.size) {
"If originalIndices (size = ${hintOriginalIndices!!.size}) is provided," +
" it must be same length as data (size = ${data.size})"
}
}
fun viewportHintFor(
index: Int,
presentedItemsBefore: Int,
presentedItemsAfter: Int,
originalPageOffsetFirst: Int,
originalPageOffsetLast: Int
) = ViewportHint.Access(
pageOffset = hintOriginalPageOffset,
indexInPage = when {
hintOriginalIndices?.indices?.contains(index) == true -> hintOriginalIndices[index]
else -> index
},
presentedItemsBefore = presentedItemsBefore,
presentedItemsAfter = presentedItemsAfter,
originalPageOffsetFirst = originalPageOffsetFirst,
originalPageOffsetLast = originalPageOffsetLast
)
// Do not edit. Implementation generated by Studio, since data class uses referential equality
// for IntArray.
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TransformablePage<*>
if (!originalPageOffsets.contentEquals(other.originalPageOffsets)) return false
if (data != other.data) return false
if (hintOriginalPageOffset != other.hintOriginalPageOffset) return false
if (hintOriginalIndices != other.hintOriginalIndices) return false
return true
}
// Do not edit. Implementation generated by Studio, since data class uses referential equality
// for IntArray.
override fun hashCode(): Int {
var result = originalPageOffsets.contentHashCode()
result = 31 * result + data.hashCode()
result = 31 * result + hintOriginalPageOffset
result = 31 * result + (hintOriginalIndices?.hashCode() ?: 0)
return result
}
companion object {
@Suppress("UNCHECKED_CAST")
fun <T : Any> empty() = EMPTY_INITIAL_PAGE as TransformablePage<T>
val EMPTY_INITIAL_PAGE: TransformablePage<Any> = TransformablePage(0, emptyList())
}
}
| apache-2.0 | 3a5525b656f27d0e25f7fbb967ac94c4 | 35.190083 | 100 | 0.668417 | 4.876392 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/text/TextWithEllipsisTestCase.kt | 3 | 2380 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.benchmark.text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.ToggleableTestCase
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
/**
* The benchmark test case for [Text] with ellipsis.
*/
class TextWithEllipsisTestCase(
private val texts: List<String>,
private val width: Dp,
private val fontSize: TextUnit
) : LayeredComposeTestCase(), ToggleableTestCase {
private val align = mutableStateOf(TextAlign.Left)
@Composable
override fun MeasuredContent() {
val height = with(LocalDensity.current) { (fontSize * 3.5).toDp() }
for (text in texts) {
Text(
text = text,
textAlign = align.value,
fontSize = fontSize,
overflow = TextOverflow.Ellipsis,
softWrap = true,
modifier = Modifier.heightIn(max = height)
)
}
}
@Composable
override fun ContentWrappers(content: @Composable () -> Unit) {
Column(modifier = Modifier.width(width)) {
content()
}
}
override fun toggleState() {
align.value = if (align.value == TextAlign.Left) TextAlign.Right else TextAlign.Left
}
} | apache-2.0 | dd4b1b79ecac92a0d46baac7396e85a2 | 33.014286 | 92 | 0.707983 | 4.507576 | false | true | false | false |
GunoH/intellij-community | platform/platform-api/src/com/intellij/ui/jcef/JBCefBrowserJsCall.kt | 2 | 6180 | // 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.ui.jcef
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.CheckedDisposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import org.intellij.lang.annotations.Language
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
typealias JsExpression = String
typealias JsExpressionResult = String?
typealias JsExpressionResultPromise = AsyncPromise<JsExpressionResult>
/**
* Asynchronously runs JavaScript code in the JCEF browser.
*
* @param javaScriptExpression
* The passed JavaScript code should be either:
* * a valid single-line JavaScript expression
* * a valid multi-line function-body with at least one "return" statement
*
* Examples:
* ```Kotlin
* browser.executeJavaScriptAsync("2 + 2")
* .onSuccess { r -> r /* r is 4 */ }
*
* browser.executeJavaScriptAsync("return 2 + 2")
* .onSuccess { r -> r /* r is 4 */ }
*
* browser.executeJavaScriptAsync("""
* function sum(s1, s2) {
* return s1 + s2;
* };
*
* return sum(2,2);
* """.trimIndent())
* .onSuccess { r -> r /* r is 4 */ }
*
* ```
*
* @return The [Promise] that provides JS execution result or an error.
*/
fun JBCefBrowser.executeJavaScriptAsync(@Language("JavaScript") javaScriptExpression: JsExpression): Promise<JsExpressionResult> =
JBCefBrowserJsCall(javaScriptExpression, this)()
/**
* Encapsulates the [javaScriptExpression] which is executed in the provided [browser] by the [invoke] method.
* Handles JavaScript errors and submits them to the execution result.
* @param javaScriptExpression
* The passed JavaScript code should be either:
* * a valid single-line JavaScript expression
* * a valid multi-line function-body with at least one "return" statement
*
* @see [executeJavaScriptAsync]
*/
class JBCefBrowserJsCall(private val javaScriptExpression: JsExpression, val browser: JBCefBrowser) {
// TODO: Ensure the related JBCefClient has a sufficient number of slots in the pool
/**
* Performs [javaScriptExpression] in the JCEF [browser] asynchronously.
* @return The [Promise] that provides JS execution result or an error.
* @throws IllegalStateException if the related [browser] is not initialized (displayed).
* @throws IllegalStateException if the related [browser] is disposed.
* @see [com.intellij.ui.jcef.JBCefBrowserBase.isCefBrowserCreated]
*/
operator fun invoke(): Promise<JsExpressionResult> {
if (browser.isCefBrowserCreated.not())
throw IllegalStateException("Failed to execute the requested JS expression. The related JCEF browser in not initialized.")
/**
* The root [com.intellij.openapi.Disposable] object that indicates the lifetime of this call.
* Remains undisposed until the [javaScriptExpression] gets executed in the [browser] (either successfully or with an error).
*/
val executionLifetime: CheckedDisposable = Disposer.newCheckedDisposable().also { Disposer.register(browser, it) }
if (executionLifetime.isDisposed)
throw IllegalStateException(
"Failed to execute the requested JS expression. The related browser is disposed.")
val resultPromise = JsExpressionResultPromise().apply {
onProcessed {
Disposer.dispose(executionLifetime)
}
}
Disposer.register(executionLifetime) {
resultPromise.setError("The related browser is disposed during the call.")
}
val resultHandlerQuery: JBCefJSQuery = createResultHandlerQuery(executionLifetime, resultPromise)
val errorHandlerQuery: JBCefJSQuery = createErrorHandlerQuery(executionLifetime, resultPromise)
val jsToRun = javaScriptExpression.wrapWithErrorHandling(resultQuery = resultHandlerQuery, errorQuery = errorHandlerQuery)
try {
browser.cefBrowser.executeJavaScript(jsToRun, "", 0)
}
catch (ex: Exception) {
// In case something goes wrong with the browser interop
resultPromise.setError(ex)
}
return resultPromise
}
private fun createResultHandlerQuery(parentDisposable: Disposable, resultPromise: JsExpressionResultPromise) =
createQuery(parentDisposable).apply {
addHandler { result ->
resultPromise.setResult(result)
null
}
}
private fun createErrorHandlerQuery(parentDisposable: Disposable, resultPromise: JsExpressionResultPromise) =
createQuery(parentDisposable).apply {
addHandler { errorMessage ->
resultPromise.setError(errorMessage ?: "Unknown error")
null
}
}
private fun createQuery(parentDisposable: Disposable) = JBCefJSQuery.create(browser).also { Disposer.register(parentDisposable, it) }
private fun JsExpression.asFunctionBody(): JsExpression = let { expression ->
when {
StringUtil.containsLineBreak(expression) -> expression
StringUtil.startsWith(expression, "return") -> expression
else -> "return $expression"
}
}
@Suppress("JSVoidFunctionReturnValueUsed")
@Language("JavaScript")
private fun @receiver:Language("JavaScript") JsExpression.wrapWithErrorHandling(resultQuery: JBCefJSQuery, errorQuery: JBCefJSQuery) = """
function payload() {
${asFunctionBody()}
}
try {
let result = payload();
// call back the related JBCefJSQuery
window.${resultQuery.funcName}({
request: "" + result,
onSuccess: function (response) {
// do nothing
}, onFailure: function (error_code, error_message) {
// do nothing
}
});
} catch (e) {
// call back the related error handling JBCefJSQuery
window.${errorQuery.funcName}({
request: "" + e,
onSuccess: function (response) {
// do nothing
}, onFailure: function (error_code, error_message) {
// do nothing
}
});
}
""".trimIndent()
}
| apache-2.0 | 49ba8cadbaecd38c783ae64b97b68307 | 36.005988 | 140 | 0.692071 | 4.601638 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCodeInsightSettings.kt | 4 | 1452 | // 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.codeInsight
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StoragePathMacros.WORKSPACE_FILE
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.XmlSerializerUtil
@State(name = "KotlinCodeInsightWorkspaceSettings", storages = [Storage(WORKSPACE_FILE)])
class KotlinCodeInsightWorkspaceSettings : PersistentStateComponent<KotlinCodeInsightWorkspaceSettings> {
@JvmField
var optimizeImportsOnTheFly = false
override fun getState() = this
override fun loadState(state: KotlinCodeInsightWorkspaceSettings) = XmlSerializerUtil.copyBean(state, this)
companion object {
fun getInstance(project: Project): KotlinCodeInsightWorkspaceSettings = project.service()
}
}
@State(name = "KotlinCodeInsightSettings", storages = [Storage("editor.codeinsight.xml")], category = SettingsCategory.CODE)
class KotlinCodeInsightSettings : PersistentStateComponent<KotlinCodeInsightSettings> {
@JvmField
var addUnambiguousImportsOnTheFly = false
override fun getState() = this
override fun loadState(state: KotlinCodeInsightSettings) = XmlSerializerUtil.copyBean(state, this)
companion object {
fun getInstance(): KotlinCodeInsightSettings = service()
}
} | apache-2.0 | 1ec861ae304dca4da923f1c2413cf407 | 39.361111 | 158 | 0.787879 | 5.094737 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/GitStatisticsCollector.kt | 3 | 11810 | // 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 git4idea
import com.google.common.collect.HashMultiset
import com.intellij.dvcs.branch.DvcsSyncSettings.Value
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.beans.addBoolIfDiffers
import com.intellij.internal.statistic.beans.addIfDiffers
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EnumEventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.vcs.VcsException
import com.intellij.util.io.URLUtil
import com.intellij.util.io.exists
import com.intellij.util.io.isDirectory
import com.intellij.util.io.isFile
import com.intellij.vcs.log.impl.VcsLogApplicationSettings
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.VcsLogUiImpl
import git4idea.config.*
import git4idea.repo.GitCommitTemplateTracker
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY
import git4idea.ui.branch.dashboard.SHOW_GIT_BRANCHES_LOG_PROPERTY
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
class GitStatisticsCollector : ProjectUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(project: Project): MutableSet<MetricEvent> {
val set = HashSet<MetricEvent>()
val repositoryManager = GitUtil.getRepositoryManager(project)
val repositories = repositoryManager.repositories
val settings = GitVcsSettings.getInstance(project)
val defaultSettings = GitVcsSettings()
addIfDiffers(set, settings, defaultSettings, { it.syncSetting }, REPO_SYNC, REPO_SYNC_VALUE)
addIfDiffers(set, settings, defaultSettings, { it.updateMethod }, UPDATE_TYPE, UPDATE_TYPE_VALUE)
addIfDiffers(set, settings, defaultSettings, { it.saveChangesPolicy }, SAVE_POLICY, SAVE_POLICY_VALUE)
addBoolIfDiffers(set, settings, defaultSettings, { it.autoUpdateIfPushRejected() }, PUSH_AUTO_UPDATE)
addBoolIfDiffers(set, settings, defaultSettings, { it.warnAboutCrlf() }, WARN_CRLF)
addBoolIfDiffers(set, settings, defaultSettings, { it.warnAboutDetachedHead() }, WARN_DETACHED)
val appSettings = GitVcsApplicationSettings.getInstance()
val defaultAppSettings = GitVcsApplicationSettings()
addBoolIfDiffers(set, appSettings, defaultAppSettings, { it.isStagingAreaEnabled }, STAGING_AREA)
val version = GitVcs.getInstance(project).version
set.add(EXECUTABLE.metric(
EventFields.Version with version.presentation,
TYPE with version.type
))
for (repository in repositories) {
val branches = repository.branches
val repositoryMetric = REPOSITORY.metric(
LOCAL_BRANCHES with branches.localBranches.size,
REMOTE_BRANCHES with branches.remoteBranches.size,
REMOTES with repository.remotes.size,
WORKING_COPY_SIZE with repository.workingCopySize(),
IS_WORKTREE_USED with repository.isWorkTreeUsed(),
FS_MONITOR with repository.detectFsMonitor(),
)
val remoteTypes = HashMultiset.create(repository.remotes.mapNotNull { getRemoteServerType(it) })
for (remoteType in remoteTypes) {
repositoryMetric.data.addData("remote_$remoteType", remoteTypes.count(remoteType))
}
set.add(repositoryMetric)
}
addCommitTemplateMetrics(project, repositories, set)
addGitLogMetrics(project, set)
return set
}
private fun addCommitTemplateMetrics(project: Project, repositories: List<GitRepository>, set: java.util.HashSet<MetricEvent>) {
if (repositories.isEmpty()) return
val templatesCount = project.service<GitCommitTemplateTracker>().templatesCount()
if (templatesCount == 0) return
set.add(COMMIT_TEMPLATE.metric(
TEMPLATES_COUNT with templatesCount,
TEMPLATES_MULTIPLE_ROOTS with (repositories.size > 1)
))
}
private fun addGitLogMetrics(project: Project, metrics: MutableSet<MetricEvent>) {
val projectLog = project.serviceIfCreated<VcsProjectLog>() ?: return
val ui = projectLog.mainLogUi ?: return
addPropertyMetricIfDiffers(metrics, ui, SHOW_GIT_BRANCHES_LOG_PROPERTY, SHOW_GIT_BRANCHES_IN_LOG)
addPropertyMetricIfDiffers(metrics, ui, CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY, UPDATE_BRANCH_FILTERS_ON_SELECTION)
}
private fun addPropertyMetricIfDiffers(metrics: MutableSet<MetricEvent>,
ui: VcsLogUiImpl,
property: VcsLogUiProperties.VcsLogUiProperty<Boolean>,
eventId: VarargEventId) {
val defaultValue = (property as? VcsLogProjectTabsProperties.CustomBooleanTabProperty)?.defaultValue(ui.id)
?: (property as? VcsLogApplicationSettings.CustomBooleanProperty)?.defaultValue() ?: return
val properties = ui.properties
val value = if (properties.exists(property)) properties[property] else defaultValue
if (!Comparing.equal(value, defaultValue)) {
metrics.add(eventId.metric(EventFields.Enabled with value))
}
}
companion object {
private val GROUP = EventLogGroup("git.configuration", 10)
private val REPO_SYNC_VALUE: EnumEventField<Value> = EventFields.Enum("value", Value::class.java) { it.name.lowercase() }
private val REPO_SYNC: VarargEventId = GROUP.registerVarargEvent("repo.sync", REPO_SYNC_VALUE)
private val UPDATE_TYPE_VALUE = EventFields.Enum("value", UpdateMethod::class.java) { it.name.lowercase() }
private val UPDATE_TYPE = GROUP.registerVarargEvent("update.type", UPDATE_TYPE_VALUE)
private val SAVE_POLICY_VALUE = EventFields.Enum("value", GitSaveChangesPolicy::class.java) { it.name.lowercase() }
private val SAVE_POLICY = GROUP.registerVarargEvent("save.policy", SAVE_POLICY_VALUE)
private val PUSH_AUTO_UPDATE = GROUP.registerVarargEvent("push.autoupdate", EventFields.Enabled)
private val WARN_CRLF = GROUP.registerVarargEvent("warn.about.crlf", EventFields.Enabled)
private val WARN_DETACHED = GROUP.registerVarargEvent("warn.about.detached", EventFields.Enabled)
private val STAGING_AREA = GROUP.registerVarargEvent("staging.area.enabled", EventFields.Enabled)
private val TYPE = EventFields.Enum("type", GitVersion.Type::class.java) { it.name }
private val EXECUTABLE = GROUP.registerVarargEvent("executable", EventFields.Version, TYPE)
private val LOCAL_BRANCHES = EventFields.RoundedInt("local_branches")
private val REMOTE_BRANCHES = EventFields.RoundedInt("remote_branches")
private val REMOTES = EventFields.RoundedInt("remotes")
private val WORKING_COPY_SIZE = EventFields.RoundedLong("working_copy_size")
private val IS_WORKTREE_USED = EventFields.Boolean("is_worktree_used")
private val FS_MONITOR = EventFields.Enum<FsMonitor>("fs_monitor")
private val remoteTypes = setOf("github", "gitlab", "bitbucket",
"github_custom", "gitlab_custom", "bitbucket_custom")
private val remoteTypesEventIds = remoteTypes.map {
EventFields.Int("remote_$it")
}
private val REPOSITORY = GROUP.registerVarargEvent("repository",
LOCAL_BRANCHES,
REMOTE_BRANCHES,
REMOTES,
WORKING_COPY_SIZE,
IS_WORKTREE_USED,
FS_MONITOR,
*remoteTypesEventIds.toTypedArray()
)
private val TEMPLATES_COUNT = EventFields.Int("count")
private val TEMPLATES_MULTIPLE_ROOTS = EventFields.Boolean("multiple_root")
private val COMMIT_TEMPLATE = GROUP.registerVarargEvent("commit_template", TEMPLATES_COUNT, TEMPLATES_MULTIPLE_ROOTS)
private val SHOW_GIT_BRANCHES_IN_LOG = GROUP.registerVarargEvent("showGitBranchesInLog", EventFields.Enabled)
private val UPDATE_BRANCH_FILTERS_ON_SELECTION = GROUP.registerVarargEvent("updateBranchesFilterInLogOnSelection", EventFields.Enabled)
private fun getRemoteServerType(remote: GitRemote): String? {
val hosts = remote.urls.map(URLUtil::parseHostFromSshUrl).distinct()
if (hosts.contains("github.com")) return "github"
if (hosts.contains("gitlab.com")) return "gitlab"
if (hosts.contains("bitbucket.org")) return "bitbucket"
if (remote.urls.any { it.contains("github") }) return "github_custom"
if (remote.urls.any { it.contains("gitlab") }) return "gitlab_custom"
if (remote.urls.any { it.contains("bitbucket") }) return "bitbucket_custom"
return null
}
}
}
private const val MAX_SIZE: Long = 4L * 1024 * 1024 * 1024 // 4 GB
private const val MAX_TIME: Long = 5 * 1000 * 60 // 5 min
private fun Sequence<Long>.sumWithLimits(): Long {
var sum = 0L
val startTime = System.currentTimeMillis()
for (element in this) {
if (System.currentTimeMillis() - startTime > MAX_TIME)
return -1
sum += element
if (sum >= MAX_SIZE) return MAX_SIZE
}
return sum
}
/**
* Calculates size of work tree in given [GitRepository]
*
* @return size in bytes or -1 if some IO error occurs
*/
private fun GitRepository.workingCopySize(): Long = try {
val root = this.root.toNioPath().toFile()
root.walk()
.onEnter { it.name != GitUtil.DOT_GIT && !isInnerRepo(root, it) }
.filter { it.isFile }
.map { it.length() }
.sumWithLimits() // don't calculate working copy size over 4 gb to reduce CPU usage
}
catch (e: Exception) {
// if something goes wrong with file system operations
-1
}
private fun isInnerRepo(root: File, dir: File): Boolean {
if (root == dir) return false
return Path.of(dir.toString(), GitUtil.DOT_GIT).exists()
}
/**
* Checks that worktree is used in [GitRepository]
*
* worktree usage will be detected when:
* repo_root/.git is a file
* or repo_root/.git/worktrees is not empty
*/
private fun GitRepository.isWorkTreeUsed(): Boolean {
return try {
val rootPath = this.root.toNioPath()
val dotGit = Path.of(rootPath.toString(), GitUtil.DOT_GIT)
if (dotGit.isFile()) return true
val worktreesPath = repositoryFiles.worktreesDirFile.toPath()
if (!worktreesPath.exists()) return false
if (!worktreesPath.isDirectory()) return false
Files.list(worktreesPath).count() > 0
}
catch (e: Exception) {
false
}
}
enum class FsMonitor { NONE, BUILTIN, EXTERNAL_FS_MONITOR }
private fun GitRepository.detectFsMonitor(): FsMonitor {
try {
val useBuiltIn = GitConfigUtil.getBooleanValue(GitConfigUtil.getValue(project, root, "core.useBuiltinFSMonitor"))
?: false
if (useBuiltIn) return FsMonitor.BUILTIN
val fsMonitorHook = GitConfigUtil.getValue(project, root, "core.fsmonitor")
if (fsMonitorHook != null && GitConfigUtil.getBooleanValue(fsMonitorHook) != false) {
return FsMonitor.EXTERNAL_FS_MONITOR
}
}
catch (ignore: VcsException) {
}
return FsMonitor.NONE
}
| apache-2.0 | 589b374e544ca73f517a935451ca8cb9 | 41.635379 | 140 | 0.713548 | 4.338722 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/modifiers.kt | 8 | 4150 | // 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.nj2k.tree
import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
interface Modifier {
val text: String
}
@Suppress("unused")
enum class OtherModifier(override val text: String) : Modifier {
OVERRIDE("override"),
ACTUAL("actual"),
ANNOTATION("annotation"),
COMPANION("companion"),
CONST("const"),
CROSSINLINE("crossinline"),
DATA("data"),
EXPECT("expect"),
EXTERNAL("external"),
INFIX("infix"),
INLINE("inline"),
INNER("inner"),
LATEINIT("lateinit"),
NOINLINE("noinline"),
OPERATOR("operator"),
OUT("out"),
REIFIED("reified"),
SEALED("sealed"),
SUSPEND("suspend"),
TAILREC("tailrec"),
VARARG("vararg"),
FUN("fun"),
NATIVE("native"),
STATIC("static"),
STRICTFP("strictfp"),
SYNCHRONIZED("synchronized"),
TRANSIENT("transient"),
VOLATILE("volatile")
}
sealed class JKModifierElement : JKTreeElement()
interface JKOtherModifiersOwner : JKModifiersListOwner {
var otherModifierElements: List<JKOtherModifierElement>
}
class JKMutabilityModifierElement(var mutability: Mutability) : JKModifierElement() {
override fun accept(visitor: JKVisitor) = visitor.visitMutabilityModifierElement(this)
}
class JKModalityModifierElement(var modality: Modality) : JKModifierElement() {
override fun accept(visitor: JKVisitor) = visitor.visitModalityModifierElement(this)
}
class JKVisibilityModifierElement(var visibility: Visibility) : JKModifierElement() {
override fun accept(visitor: JKVisitor) = visitor.visitVisibilityModifierElement(this)
}
class JKOtherModifierElement(var otherModifier: OtherModifier) : JKModifierElement() {
override fun accept(visitor: JKVisitor) = visitor.visitOtherModifierElement(this)
}
interface JKVisibilityOwner : JKModifiersListOwner {
val visibilityElement: JKVisibilityModifierElement
}
enum class Visibility(override val text: String) : Modifier {
PUBLIC("public"),
INTERNAL("internal"),
PROTECTED("protected"),
PRIVATE("private")
}
interface JKModalityOwner : JKModifiersListOwner {
val modalityElement: JKModalityModifierElement
}
enum class Modality(override val text: String) : Modifier {
OPEN("open"),
FINAL("final"),
ABSTRACT("abstract"),
}
interface JKMutabilityOwner : JKModifiersListOwner {
val mutabilityElement: JKMutabilityModifierElement
}
enum class Mutability(override val text: String) : Modifier {
MUTABLE("var"),
IMMUTABLE("val"),
UNKNOWN("var")
}
interface JKModifiersListOwner : JKFormattingOwner
fun JKOtherModifiersOwner.elementByModifier(modifier: OtherModifier): JKOtherModifierElement? =
otherModifierElements.firstOrNull { it.otherModifier == modifier }
fun JKOtherModifiersOwner.hasOtherModifier(modifier: OtherModifier): Boolean =
otherModifierElements.any { it.otherModifier == modifier }
var JKVisibilityOwner.visibility: Visibility
get() = visibilityElement.visibility
set(value) {
visibilityElement.visibility = value
}
var JKMutabilityOwner.mutability: Mutability
get() = mutabilityElement.mutability
set(value) {
mutabilityElement.mutability = value
}
var JKModalityOwner.modality: Modality
get() = modalityElement.modality
set(value) {
modalityElement.modality = value
}
val JKModifierElement.modifier: Modifier
get() = when (this) {
is JKMutabilityModifierElement -> mutability
is JKModalityModifierElement -> modality
is JKVisibilityModifierElement -> visibility
is JKOtherModifierElement -> otherModifier
}
inline fun JKModifiersListOwner.forEachModifier(action: (JKModifierElement) -> Unit) {
safeAs<JKVisibilityOwner>()?.visibilityElement?.let(action)
safeAs<JKModalityOwner>()?.modalityElement?.let(action)
safeAs<JKOtherModifiersOwner>()?.otherModifierElements?.forEach(action)
safeAs<JKMutabilityOwner>()?.mutabilityElement?.let(action)
}
| apache-2.0 | 9fb307fc0ac94d2da885ff3c028ce19b | 28.225352 | 120 | 0.734458 | 4.525627 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/RefsTable.kt | 1 | 26902 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.util.containers.HashSetInterner
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType
import com.intellij.workspaceModel.storage.impl.containers.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import org.jetbrains.annotations.ApiStatus
import java.util.function.IntFunction
class ConnectionId private constructor(
val parentClass: Int,
val childClass: Int,
val connectionType: ConnectionType,
val isParentNullable: Boolean
) {
enum class ConnectionType {
ONE_TO_ONE,
ONE_TO_MANY,
ONE_TO_ABSTRACT_MANY,
ABSTRACT_ONE_TO_ONE
}
/**
* This function returns true if this connection allows removing parent of child.
*
* E.g. parent is optional (nullable) for child entity, so the parent can be safely removed.
*/
fun canRemoveParent(): Boolean = isParentNullable
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ConnectionId
if (parentClass != other.parentClass) return false
if (childClass != other.childClass) return false
if (connectionType != other.connectionType) return false
if (isParentNullable != other.isParentNullable) return false
return true
}
override fun hashCode(): Int {
var result = parentClass.hashCode()
result = 31 * result + childClass.hashCode()
result = 31 * result + connectionType.hashCode()
result = 31 * result + isParentNullable.hashCode()
return result
}
override fun toString(): String {
return "Connection(parent=${ClassToIntConverter.INSTANCE.getClassOrDie(parentClass).simpleName} " +
"child=${ClassToIntConverter.INSTANCE.getClassOrDie(childClass).simpleName} $connectionType)"
}
fun debugStr(): String = """
ConnectionId info:
- Parent class: ${this.parentClass.findEntityClass<WorkspaceEntity>()}
- Child class: ${this.childClass.findEntityClass<WorkspaceEntity>()}
- Connection type: $connectionType
- Parent of child is nullable: $isParentNullable
""".trimIndent()
companion object {
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> create(
parentClass: Class<Parent>,
childClass: Class<Child>,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass.toClassId(), childClass.toClassId(), connectionType, isParentNullable)
return interner.intern(connectionId)
}
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
@ApiStatus.Internal
fun create(
parentClass: Int,
childClass: Int,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass, childClass, connectionType, isParentNullable)
return interner.intern(connectionId)
}
private val interner = HashSetInterner<ConnectionId>()
}
}
/**
* [oneToManyContainer]: [ImmutableNonNegativeIntIntBiMap] - key - child, value - parent
*/
internal class RefsTable internal constructor(
override val oneToManyContainer: Map<ConnectionId, ImmutableNonNegativeIntIntBiMap>,
override val oneToOneContainer: Map<ConnectionId, ImmutableIntIntUniqueBiMap>,
override val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
constructor() : this(HashMap(), HashMap(), HashMap(), HashMap())
}
internal class MutableRefsTable(
override val oneToManyContainer: MutableMap<ConnectionId, NonNegativeIntIntBiMap>,
override val oneToOneContainer: MutableMap<ConnectionId, IntIntUniqueBiMap>,
override val oneToAbstractManyContainer: MutableMap<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: MutableMap<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
private val oneToAbstractManyCopiedToModify: MutableSet<ConnectionId> = HashSet()
private val abstractOneToOneCopiedToModify: MutableSet<ConnectionId> = HashSet()
private fun getOneToManyMutableMap(connectionId: ConnectionId): MutableNonNegativeIntIntBiMap {
val bimap = oneToManyContainer[connectionId] ?: run {
val empty = MutableNonNegativeIntIntBiMap()
oneToManyContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableNonNegativeIntIntBiMap -> bimap
is ImmutableNonNegativeIntIntBiMap -> {
val copy = bimap.toMutable()
oneToManyContainer[connectionId] = copy
copy
}
}
}
private fun getOneToAbstractManyMutableMap(connectionId: ConnectionId): LinkedBidirectionalMap<ChildEntityId, ParentEntityId> {
if (connectionId !in oneToAbstractManyContainer) {
oneToAbstractManyContainer[connectionId] = LinkedBidirectionalMap()
}
return if (connectionId in oneToAbstractManyCopiedToModify) {
oneToAbstractManyContainer[connectionId]!!
}
else {
val copy = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
val original = oneToAbstractManyContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
oneToAbstractManyContainer[connectionId] = copy
oneToAbstractManyCopiedToModify.add(connectionId)
copy
}
}
private fun getAbstractOneToOneMutableMap(connectionId: ConnectionId): BiMap<ChildEntityId, ParentEntityId> {
if (connectionId !in abstractOneToOneContainer) {
abstractOneToOneContainer[connectionId] = HashBiMap.create()
}
return if (connectionId in abstractOneToOneCopiedToModify) {
abstractOneToOneContainer[connectionId]!!
}
else {
val copy = HashBiMap.create<ChildEntityId, ParentEntityId>()
val original = abstractOneToOneContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
abstractOneToOneContainer[connectionId] = copy
abstractOneToOneCopiedToModify.add(connectionId)
copy
}
}
private fun getOneToOneMutableMap(connectionId: ConnectionId): MutableIntIntUniqueBiMap {
val bimap = oneToOneContainer[connectionId] ?: run {
val empty = MutableIntIntUniqueBiMap()
oneToOneContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableIntIntUniqueBiMap -> bimap
is ImmutableIntIntUniqueBiMap -> {
val copy = bimap.toMutable()
oneToOneContainer[connectionId] = copy
copy
}
}
}
fun removeRefsByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).removeValue(parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}.let { }
}
fun removeOneToOneRefByParent(connectionId: ConnectionId, parentId: Int) {
getOneToOneMutableMap(connectionId).removeValue(parentId)
}
fun removeOneToAbstractOneRefByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}
fun removeOneToAbstractOneRefByChild(connectionId: ConnectionId, childId: ChildEntityId) {
getAbstractOneToOneMutableMap(connectionId).remove(childId)
}
fun removeOneToOneRefByChild(connectionId: ConnectionId, childId: Int) {
getOneToOneMutableMap(connectionId).removeKey(childId)
}
fun removeOneToManyRefsByChild(connectionId: ConnectionId, childId: Int) {
getOneToManyMutableMap(connectionId).removeKey(childId)
}
fun removeOneToAbstractManyRefsByChild(connectionId: ConnectionId, childId: ChildEntityId) {
getOneToAbstractManyMutableMap(connectionId).remove(childId)
}
fun removeParentToChildRef(connectionId: ConnectionId, parentId: ParentEntityId, childId: ChildEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).remove(childId, parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).remove(childId, parentId)
}.let { }
}
internal fun updateChildrenOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childrenIds: Collection<ChildEntityId>) {
if (childrenIds !is Set<ChildEntityId> && childrenIds.size != childrenIds.toSet().size) error("Children have duplicates: $childrenIds")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId.id.arrayId)
val children = childrenIds.map { it.id.arrayId }.toIntArray()
copiedMap.putAll(children, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.putForce(childrenIds.single().id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
// In theory this removing can be avoided because keys will be replaced anyway, but without this cleanup we may get an
// incorrect ordering of the children
childrenIds.forEach { copiedMap.remove(it) }
childrenIds.forEach { copiedMap[it] = parentId }
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
}.let { }
}
fun updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: Int, childrenEntityIds: List<ChildEntityId>) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
val children = childrenEntityIds.mapToIntArray { it.id.arrayId }
copiedMap.putAll(children, parentId)
}
fun updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenEntityIds.forEach { copiedMap[it] = parentId }
}
fun updateOneToAbstractOneParentOfChild(
connectionId: ConnectionId,
childId: ChildEntityId,
parentId: ParentEntityId
) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.inverse().remove(parentId)
copiedMap[childId] = parentId
}
fun updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childEntityId: ChildEntityId) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
copiedMap[childEntityId.id.asChild()] = parentId
}
fun updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: Int, childEntityId: ChildEntityId) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeValue(parentId)
copiedMap.put(childEntityId.id.arrayId, parentId)
}
fun updateOneToOneParentOfChild(
connectionId: ConnectionId,
childId: Int,
parentId: EntityId
) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putForce(childId, parentId.arrayId)
}
internal fun updateParentOfChild(connectionId: ConnectionId, childId: ChildEntityId, parentId: ParentEntityId) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putAll(intArrayOf(childId.id.arrayId), parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putForce(childId.id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.forcePut(childId, parentId)
Unit
}
}.let { }
}
fun updateOneToManyParentOfChild(
connectionId: ConnectionId,
childId: Int,
parentId: ParentEntityId
) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putAll(intArrayOf(childId), parentId.id.arrayId)
}
fun updateOneToAbstractManyParentOfChild(
connectionId: ConnectionId,
childId: ChildEntityId,
parentId: ParentEntityId
) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.put(childId, parentId)
}
fun toImmutable(): RefsTable = RefsTable(
oneToManyContainer.mapValues { it.value.toImmutable() },
oneToOneContainer.mapValues { it.value.toImmutable() },
oneToAbstractManyContainer.mapValues {
it.value.let { value ->
val map = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
},
abstractOneToOneContainer.mapValues {
it.value.let { value ->
val map = HashBiMap.create<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
}
)
companion object {
fun from(other: RefsTable): MutableRefsTable = MutableRefsTable(
HashMap(other.oneToManyContainer), HashMap(other.oneToOneContainer),
HashMap(other.oneToAbstractManyContainer),
HashMap(other.abstractOneToOneContainer))
}
private fun <T> Sequence<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
private fun <T> List<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
}
internal sealed class AbstractRefsTable {
internal abstract val oneToManyContainer: Map<ConnectionId, NonNegativeIntIntBiMap>
internal abstract val oneToOneContainer: Map<ConnectionId, IntIntUniqueBiMap>
internal abstract val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>
internal abstract val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> findConnectionId(parentClass: Class<Parent>, childClass: Class<Child>): ConnectionId? {
val parentClassId = parentClass.toClassId()
val childClassId = childClass.toClassId()
return (oneToManyContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToOneContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToAbstractManyContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
}
?: abstractOneToOneContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
})
}
fun getParentRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToMany) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getParentOneToOneRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getChildrenRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, List<ChildEntityId>> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, List<ChildEntityId>>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToMany) {
val keys = bimap.getKeys(parentArrayId)
if (!keys.isEmpty()) {
val children = keys.map { createEntityId(it, connectionId.childClass) }.mapTo(ArrayList()) { it.asChild() }
val existingValue = res.putIfAbsent(connectionId, children)
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, listOf(createEntityId(key, connectionId.childClass).asChild()))
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
val keys = bimap.getKeysByValue(parentId) ?: continue
if (keys.isNotEmpty()) {
val existingValue = res.putIfAbsent(connectionId, keys.map { it })
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, listOf(key))
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getChildrenOneToOneRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, ChildEntityId> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ChildEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(key, connectionId.childClass).asChild())
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, key)
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getOneToManyChildren(connectionId: ConnectionId, parentId: Int): NonNegativeIntIntMultiMap.IntSequence? {
return oneToManyContainer[connectionId]?.getKeys(parentId)
}
fun getOneToAbstractManyChildren(connectionId: ConnectionId, parentId: ParentEntityId): List<ChildEntityId>? {
val map = oneToAbstractManyContainer[connectionId]
return map?.getKeysByValue(parentId)
}
fun getAbstractOneToOneChildren(connectionId: ConnectionId, parentId: ParentEntityId): ChildEntityId? {
val map = abstractOneToOneContainer[connectionId]
return map?.inverse()?.get(parentId)
}
fun getOneToAbstractOneParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
return abstractOneToOneContainer[connectionId]?.get(childId)
}
fun getOneToAbstractManyParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
val map = oneToAbstractManyContainer[connectionId]
return map?.get(childId)
}
fun getOneToOneChild(connectionId: ConnectionId, parentId: Int): Int? {
return oneToOneContainer[connectionId]?.getKey(parentId)
}
fun <Child : WorkspaceEntity> getOneToOneChild(connectionId: ConnectionId, parentId: Int, transformer: IntFunction<Child?>): Child? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsValue(parentId)) return null
return transformer.apply(bimap.getKey(parentId))
}
fun <Parent : WorkspaceEntity> getOneToOneParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
fun <Parent : WorkspaceEntity> getOneToManyParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToManyContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
}
// TODO: 25.05.2021 Make it value class
internal data class ChildEntityId(val id: EntityId) {
override fun toString(): String {
return "ChildEntityId(id=${id.asString()})"
}
}
internal data class ParentEntityId(val id: EntityId) {
override fun toString(): String {
return "ParentEntityId(id=${id.asString()})"
}
}
internal fun EntityId.asChild(): ChildEntityId = ChildEntityId(this)
internal fun EntityId.asParent(): ParentEntityId = ParentEntityId(this)
internal fun sameClass(fromConnectionId: Int, myClazz: Int, type: ConnectionType): Boolean {
return when (type) {
ConnectionType.ONE_TO_ONE, ConnectionType.ONE_TO_MANY -> fromConnectionId == myClazz
ConnectionType.ONE_TO_ABSTRACT_MANY, ConnectionType.ABSTRACT_ONE_TO_ONE -> {
fromConnectionId.findWorkspaceEntity().isAssignableFrom(myClazz.findWorkspaceEntity())
}
}
}
| apache-2.0 | 678e1a439bb254f7beb566bbf252f259 | 40.579598 | 145 | 0.731284 | 5.152653 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/facet/KotlinFacetType.kt | 1 | 1158 | // 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.facet
import com.intellij.facet.FacetType
import com.intellij.facet.FacetTypeId
import com.intellij.facet.FacetTypeRegistry
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.kotlin.idea.util.isRunningInCidrIde
import org.jetbrains.kotlin.idea.KotlinIcons
import javax.swing.Icon
abstract class KotlinFacetType<C : KotlinFacetConfiguration> :
FacetType<KotlinFacet, C>(TYPE_ID, ID, NAME) {
companion object {
const val ID = "kotlin-language"
val TYPE_ID = FacetTypeId<KotlinFacet>(ID)
@NlsSafe
const val NAME = "Kotlin"
val INSTANCE
get() = FacetTypeRegistry.getInstance().findFacetType(TYPE_ID)
}
override fun isSuitableModuleType(moduleType: ModuleType<*>) = if (isRunningInCidrIde) true else moduleType is JavaModuleType
override fun getIcon(): Icon = KotlinIcons.SMALL_LOGO
}
| apache-2.0 | 2b6676c7cfd3673723b1010794b61f29 | 37.6 | 158 | 0.759067 | 4.226277 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/ssh.kt | 2 | 3420 | // 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.intellij.build.io
import net.schmizz.sshj.xfer.LocalDestFile
import net.schmizz.sshj.xfer.LocalFileFilter
import net.schmizz.sshj.xfer.LocalSourceFile
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.concurrent.TimeUnit
internal class NioFileDestination(private val file: Path) : LocalDestFile {
override fun getOutputStream(): OutputStream = Files.newOutputStream(file)
override fun getChild(name: String?) = throw UnsupportedOperationException()
override fun getTargetFile(filename: String): LocalDestFile {
return this
}
override fun getTargetDirectory(dirname: String?): LocalDestFile {
return this
}
override fun setPermissions(perms: Int) {
Files.setPosixFilePermissions(file, fromOctalFileMode(perms))
}
override fun setLastAccessedTime(t: Long) {
// ignore
}
override fun setLastModifiedTime(t: Long) {
// ignore
}
}
internal class NioFileSource(private val file: Path, private val filePermission: Int = -1) : LocalSourceFile {
override fun getName() = file.fileName.toString()
override fun getLength() = Files.size(file)
override fun getInputStream(): InputStream = Files.newInputStream(file)
override fun getPermissions(): Int {
return if (filePermission == -1) toOctalFileMode(Files.getPosixFilePermissions(file)) else filePermission
}
override fun isFile() = true
override fun isDirectory() = false
override fun getChildren(filter: LocalFileFilter): Iterable<LocalSourceFile> = emptyList()
override fun providesAtimeMtime() = false
override fun getLastAccessTime() = System.currentTimeMillis() / 1000
override fun getLastModifiedTime() = TimeUnit.MILLISECONDS.toSeconds(Files.getLastModifiedTime(file).toMillis())
}
private fun toOctalFileMode(permissions: Set<PosixFilePermission?>): Int {
var result = 0
for (permissionBit in permissions) {
when (permissionBit) {
PosixFilePermission.OWNER_READ -> result = result or 256
PosixFilePermission.OWNER_WRITE -> result = result or 128
PosixFilePermission.OWNER_EXECUTE -> result = result or 64
PosixFilePermission.GROUP_READ -> result = result or 32
PosixFilePermission.GROUP_WRITE -> result = result or 16
PosixFilePermission.GROUP_EXECUTE -> result = result or 8
PosixFilePermission.OTHERS_READ -> result = result or 4
PosixFilePermission.OTHERS_WRITE -> result = result or 2
PosixFilePermission.OTHERS_EXECUTE -> result = result or 1
}
}
return result
}
private val decodeMap = arrayOf(
PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ,
PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ,
PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ
)
private fun fromOctalFileMode(mode: Int): Set<PosixFilePermission> {
var mask = 1
val perms = EnumSet.noneOf(PosixFilePermission::class.java)
for (flag in decodeMap) {
if (mask and mode != 0) {
perms.add(flag)
}
mask = mask shl 1
}
return perms
} | apache-2.0 | 19399a73eaac616490d6ccdb934b7fda | 33.555556 | 158 | 0.75614 | 4.458931 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-api/src/main/kotlin/org/craftsmenlabs/gareth/validator/model/ExperimentEnvironment.kt | 1 | 1640 | package org.craftsmenlabs.gareth.validator.model
import java.util.*
enum class ExecutionStatus {
PENDING,
/**
* return after successfully executing the baseline step
*/
RUNNING,
/**
* Returned after the assume step was evaluated successfully
*/
SUCCESS,
/**
* Returned after the assume step was evaluated with a failure
*/
FAILURE,
/**
* Returned when a non-recoverable error was encountered
*/
ERROR;
fun isCompleted() = this == SUCCESS || this == FAILURE || this == ERROR
}
enum class ItemType {
STRING, LONG, DOUBLE, BOOLEAN, LIST
}
enum class GlueLineType {
BASELINE, ASSUME, TIME, SUCCESS, FAILURE;
companion object {
@JvmStatic fun safeValueOf(key: String?): Optional<GlueLineType> {
try {
return if (key == null) Optional.empty() else Optional.of(GlueLineType.valueOf(key));
} catch (e: Exception) {
return Optional.empty();
}
}
}
}
data class Duration(val unit: String, val amount: Long)
data class DefinitionInfo(val glueline: String, val method: String, val className: String, val description: String? = null, val humanReadable: String? = null)
data class ExecutionRequest(val environment: ExperimentRunEnvironment, val glueLines: ValidatedGluelines)
data class ExecutionResult(val environment: ExperimentRunEnvironment, val status: ExecutionStatus)
data class EnvironmentItem(val key: String, val value: String, val itemType: ItemType)
data class ExperimentRunEnvironment(val items: List<EnvironmentItem> = listOf<EnvironmentItem>())
| gpl-2.0 | a9d54a61fbfe88bab755e14ea90343ea | 27.275862 | 158 | 0.678049 | 4.468665 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/propertyToIf/nestedIfs2.kt | 9 | 433 | // AFTER-WARNING: Parameter 'a' is never used
fun <T> doSomething(a: T) {}
fun test(n: Int): String? {
var res = <caret>if (n == 1) {
if (3 > 2) {
doSomething("***")
"one"
} else {
doSomething("***")
"???"
}
} else if (n == 2) {
doSomething("***")
null
} else {
doSomething("***")
"too many"
}
return res
}
| apache-2.0 | 64ab85d989d5eed33f691386fea353b6 | 18.681818 | 45 | 0.3903 | 3.900901 | false | false | false | false |
smmribeiro/intellij-community | platform/util/ui/src/com/intellij/ui/svg/SvgDocumentFactory.kt | 1 | 5768 | // 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.svg
import com.intellij.openapi.util.createXmlStreamReader
import org.apache.batik.anim.dom.SVG12DOMImplementation
import org.apache.batik.anim.dom.SVGDOMImplementation
import org.apache.batik.anim.dom.SVGOMDocument
import org.apache.batik.dom.GenericCDATASection
import org.apache.batik.dom.GenericText
import org.apache.batik.transcoder.TranscoderException
import org.apache.batik.util.ParsedURL
import org.codehaus.stax2.XMLStreamReader2
import org.jetbrains.annotations.ApiStatus
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.io.InputStream
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamException
import javax.xml.stream.XMLStreamReader
@ApiStatus.Internal
fun createSvgDocument(uri: String?, reader: InputStream) = createSvgDocument(uri, createXmlStreamReader(reader))
@ApiStatus.Internal
fun createSvgDocument(uri: String?, data: ByteArray) = createSvgDocument(uri, createXmlStreamReader(data))
private fun createSvgDocument(uri: String?, xmlStreamReader: XMLStreamReader2): Document {
val result = try {
buildDocument(xmlStreamReader)
}
catch (e: XMLStreamException) {
throw TranscoderException(e)
}
finally {
xmlStreamReader.close()
}
if (uri != null) {
result.parsedURL = ParsedURL(uri)
result.documentURI = uri
}
return result
}
private fun buildDocument(reader: XMLStreamReader): SVGOMDocument {
var state = reader.eventType
if (XMLStreamConstants.START_DOCUMENT != state) {
throw TranscoderException("Incorrect state: $state")
}
var document: SVGOMDocument? = null
while (state != XMLStreamConstants.END_DOCUMENT) {
when (state) {
XMLStreamConstants.START_DOCUMENT -> {
assert(document == null)
}
XMLStreamConstants.DTD, XMLStreamConstants.COMMENT, XMLStreamConstants.PROCESSING_INSTRUCTION, XMLStreamConstants.SPACE -> {
}
XMLStreamConstants.START_ELEMENT -> {
var version: String? = null
for (i in 0 until reader.attributeCount) {
val localName = reader.getAttributeLocalName(i)
val prefix = reader.getAttributePrefix(i)
if (prefix.isEmpty() && localName == "version") {
version = reader.getAttributeValue(i)
break
}
}
val implementation: SVGDOMImplementation = when {
version == null || version.isEmpty() || version == "1.0" || version == "1.1" -> SVGDOMImplementation.getDOMImplementation() as SVGDOMImplementation
version == "1.2" -> SVG12DOMImplementation.getDOMImplementation() as SVGDOMImplementation
else -> throw TranscoderException("Unsupported SVG version: $version")
}
val localName = reader.localName
document = implementation.createDocument(reader.namespaceURI, getRawName(reader.prefix, localName), null) as SVGOMDocument
val element = document.documentElement
readAttributes(element, reader)
if (localName != "svg") {
throw TranscoderException("Root element does not match that requested:\nRequested: svg\nFound: $localName")
}
processElementFragment(reader, document, implementation, element)
}
XMLStreamConstants.CHARACTERS -> {
val badContent = reader.text
if (!isAllXMLWhitespace(badContent)) {
throw TranscoderException("Unexpected XMLStream event at Document level: CHARACTERS ($badContent)")
}
}
else -> throw TranscoderException("Unexpected XMLStream event at Document level:$state")
}
state = if (reader.hasNext()) {
reader.next()
}
else {
throw TranscoderException("Unexpected end-of-XMLStreamReader")
}
}
return document!!
}
private fun processElementFragment(reader: XMLStreamReader, document: SVGOMDocument, factory: SVGDOMImplementation, parent: Element) {
var depth = 1
var current: Node = parent
while (depth > 0 && reader.hasNext()) {
when (reader.next()) {
XMLStreamConstants.START_ELEMENT -> {
val element = factory.createElementNS(document, reader.namespaceURI, reader.localName)
readAttributes(element, reader)
current.appendChild(element)
current = element
depth++
}
XMLStreamConstants.END_ELEMENT -> {
current = current.parentNode
depth--
}
XMLStreamConstants.CDATA -> current.appendChild(GenericCDATASection(reader.text, document))
XMLStreamConstants.SPACE, XMLStreamConstants.CHARACTERS -> {
if (!reader.isWhiteSpace) {
current.appendChild(GenericText(reader.text, document))
}
}
XMLStreamConstants.ENTITY_REFERENCE, XMLStreamConstants.COMMENT, XMLStreamConstants.PROCESSING_INSTRUCTION -> {
}
else -> throw TranscoderException("Unexpected XMLStream event: ${reader.eventType}")
}
}
}
private fun readAttributes(element: Element, reader: XMLStreamReader) {
for (i in 0 until reader.attributeCount) {
val localName = reader.getAttributeLocalName(i)
val prefix = reader.getAttributePrefix(i)
element.setAttributeNS(reader.getAttributeNamespace(i), getRawName(prefix, localName), reader.getAttributeValue(i))
}
}
private fun getRawName(prefix: String?, localName: String): String {
return if (prefix.isNullOrEmpty()) localName else "$prefix:$localName"
}
private fun isAllXMLWhitespace(value: String): Boolean {
var i = value.length
while (--i >= 0) {
val c = value[i]
if (c != ' ' && c != '\n' && c != '\t' && c != '\r') {
return false
}
}
return true
} | apache-2.0 | 86ae4fbb9115cc4457e6d2fc2ad71fe9 | 35.980769 | 158 | 0.705097 | 4.213294 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/testSrc/xml/ForbidSensitiveInformationTest.kt | 5 | 4281 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.xml
import com.intellij.configurationStore.JbXmlOutputter
import com.intellij.openapi.diagnostic.DefaultLogger
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.SystemProperties
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Tag
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.StringWriter
internal class ForbidSensitiveInformationTest {
@Rule
@JvmField
val disposableRule = DisposableRule()
@Before
fun before() {
DefaultLogger.disableStderrDumping(disposableRule.disposable);
}
@Test
fun `do not store password as attribute`() {
@Tag("bean")
class Bean {
@Attribute
var password: String? = null
@Attribute
var foo: String? = null
}
val bean = Bean()
bean.foo = "module"
bean.password = "ab"
// it is not part of XML bindings to ensure that even if you will use JDOM directly, you cannot output sensitive data
// so, testSerializer must not throw error
val element = assertSerializer(bean, "<bean password=\"ab\" foo=\"module\" />")
assertThatThrownBy {
val xmlWriter = JbXmlOutputter()
xmlWriter.output(element, StringWriter())
}.hasMessage("Attribute bean.@password probably contains sensitive information")
}
@Test
fun `do not store password as element`() {
@Tag("component")
class Bean {
var password: String? = null
@Attribute
var name: String? = null
}
val bean = Bean()
bean.name = "someComponent"
bean.password = "ab"
// it is not part of XML bindings to ensure that even if you will use JDOM directly, you cannot output sensitive data
// so, testSerializer must not throw error
val element = assertSerializer(bean, """
<component name="someComponent">
<option name="password" value="ab" />
</component>
""".trimIndent())
assertThatThrownBy {
val xmlWriter = JbXmlOutputter(
storageFilePathForDebugPurposes = "${FileUtilRt.toSystemIndependentName(SystemProperties.getUserHome())}/foo/bar.xml")
xmlWriter.output(element, StringWriter())
}.hasMessage("""Element [email protected].@name=password probably contains sensitive information (file: ~/foo/bar.xml)""")
}
@Test
fun `configuration name with password word`() {
@Tag("bean")
class Bean {
@OptionTag(tag = "configuration", valueAttribute = "bar")
var password: String? = null
// check that use or save password fields are ignored
var usePassword = false
var savePassword = false
var rememberPassword = false
@Attribute("keep-password")
var keepPassword = false
}
val bean = Bean()
bean.password = "ab"
bean.usePassword = true
bean.keepPassword = true
bean.rememberPassword = true
bean.savePassword = true
// it is not part of XML bindings to ensure that even if you will use JDOM directly, you cannot output sensitive data
// so, testSerializer must not throw error
val element = assertSerializer(bean, """
<bean keep-password="true">
<option name="rememberPassword" value="true" />
<option name="savePassword" value="true" />
<option name="usePassword" value="true" />
<configuration name="password" bar="ab" />
</bean>
""".trimIndent())
val xmlWriter = JbXmlOutputter()
val stringWriter = StringWriter()
xmlWriter.output(element, stringWriter)
assertThat(stringWriter.toString()).isEqualTo("""
<bean keep-password="true">
<option name="rememberPassword" value="true" />
<option name="savePassword" value="true" />
<option name="usePassword" value="true" />
<configuration name="password" bar="ab" />
</bean>
""".trimIndent())
}
} | apache-2.0 | 64692011bf57b29894cc00b473a616ee | 33.813008 | 140 | 0.686989 | 4.468685 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/smart/AfterNamedArgument.kt | 13 | 282 | fun foo(param1: String, param2: Int, param3: Char) { }
fun bar(pInt: Int, pString: String) {
foo(param2 = 1, <caret>)
}
// EXIST: { lookupString: "param1 =", itemText: "param1 =" }
// EXIST: { lookupString: "param3 =", itemText: "param3 =" }
// ABSENT: param2
// NOTHING_ELSE
| apache-2.0 | 7d0e89a1c8110c2320369cb799f8c141 | 27.2 | 60 | 0.620567 | 2.877551 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-repositories/src/main/kotlin/org/livingdoc/repositories/cache/CacheHelper.kt | 2 | 2121 | package org.livingdoc.repositories.cache
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/**
* The CacheHelper helps caching documents and retrieving the cached documents.
*
* The repositories that want to use caching can use this helper to implement
* the caching.
*/
object CacheHelper {
// Always update cache.
const val CACHE_ALWAYS = "cacheAlways"
// Cache if newer version is available. Can be used to reduce mobile data usage.
const val CACHE_ON_NEW_VERSION = "cacheOnNewVersion"
// Never use cache.
const val NO_CACHE = "noCache"
// Cache once and use this cache.
const val CACHE_ONCE = "cacheOnce"
/**
* Caches the given input stream to a file under the given path.
* The input stream is closed.
*
* @throws java.io.IOException
*/
fun cacheInputStream(inputStream: InputStream, path: Path) {
Files.createDirectories(path.parent)
inputStream.use { Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING) }
}
/**
* Gets the cached object from the path and returns the input stream.
*
* @throws java.io.IOException
*/
fun getCacheInputStream(path: Path): InputStream {
return Files.newInputStream(path)
}
/**
* Checks whether a file at the given path exists. Assumes the file is
* a cached document.
*
* @return true if there is a file. Otherwise false.
*/
fun isCached(path: Path): Boolean {
return Files.exists(path)
}
/**
* Checks whether an active connection to the given url exists.
*
* @return false if url is malformed or no connection is possible, true otherwise
*/
fun hasActiveNetwork(url: String): Boolean {
try {
val networkUrl = URL(url)
val connection: URLConnection = networkUrl.openConnection()
connection.connect()
} catch (e: Exception) {
return false
}
return true
}
}
| apache-2.0 | 1c1ceeed783f9c58342cd989c7e8826e | 28.458333 | 94 | 0.655823 | 4.373196 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/ExecuteShortcutAction.kt | 1 | 4839 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.framework.extensions.logInfo
import ch.rmy.android.framework.extensions.runIfNotNull
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.execute.ExecutionFactory
import ch.rmy.android.http_shortcuts.activities.execute.models.ExecutionParams
import ch.rmy.android.http_shortcuts.activities.execute.models.ExecutionStatus
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutNameOrId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import ch.rmy.android.http_shortcuts.scripting.ResponseObjectFactory
import ch.rmy.android.http_shortcuts.utils.ErrorFormatter
import ch.rmy.android.http_shortcuts.variables.VariableManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.lastOrNull
import kotlinx.coroutines.withContext
import org.liquidplayer.javascript.JSContext
import org.liquidplayer.javascript.JSObject
import javax.inject.Inject
class ExecuteShortcutAction(
private val shortcutNameOrId: ShortcutNameOrId?,
private val variableValues: Map<VariableKey, Any?>?,
) : BaseAction() {
@Inject
lateinit var executionFactory: ExecutionFactory
@Inject
lateinit var shortcutRepository: ShortcutRepository
@Inject
lateinit var errorFormatter: ErrorFormatter
@Inject
lateinit var responseObjectFactory: ResponseObjectFactory
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun execute(executionContext: ExecutionContext): JSObject {
logInfo("Preparing to execute shortcut ($shortcutNameOrId)")
if (executionContext.recursionDepth >= MAX_RECURSION_DEPTH) {
logInfo("Not executing shortcut, reached maximum recursion depth")
throw ActionException {
getString(R.string.action_type_trigger_shortcut_error_recursion_depth_reached)
}
}
val shortcut = try {
shortcutRepository.getShortcutByNameOrId(shortcutNameOrId ?: executionContext.shortcutId)
} catch (e: NoSuchElementException) {
logInfo("Not executing shortcut, not found")
throw ActionException {
getString(R.string.error_shortcut_not_found_for_triggering, shortcutNameOrId)
}
}
val execution = executionFactory.createExecution(
ExecutionParams(
shortcutId = shortcut.id,
variableValues = executionContext.variableManager.getVariableValuesByIds()
.runIfNotNull(variableValues) { overriddenVariableValues ->
plus(overriddenVariableValues.mapValues { it.value?.toString().orEmpty() })
},
recursionDepth = executionContext.recursionDepth + 1,
isNested = true,
)
)
val finalStatus = withContext(Dispatchers.Main) {
execution.execute()
}.lastOrNull()
(finalStatus as? ExecutionStatus.WithVariables)?.variableValues?.let {
executionContext.variableManager.storeVariableValues(it)
}
return createResult(
executionContext.jsContext,
status = when (finalStatus) {
is ExecutionStatus.CompletedSuccessfully -> "success"
is ExecutionStatus.CompletedWithError -> "failure"
else -> "unknown"
},
response = (finalStatus as? ExecutionStatus.WithResponse)
?.response
?.let { responseObjectFactory.create(executionContext.jsContext, it) },
error = (finalStatus as? ExecutionStatus.CompletedWithError)
?.error
?.message,
)
}
companion object {
private const val MAX_RECURSION_DEPTH = 3
private fun VariableManager.storeVariableValues(variableValues: Map<VariableId, String>) {
variableValues.forEach { (variableId, value) ->
setVariableValueByKeyOrId(variableId, value)
}
}
private fun createResult(jsContext: JSContext, status: String, response: JSObject? = null, error: String? = null) =
JSObject(jsContext).apply {
property("status", status)
property("response", response)
property("networkError", error)
}
}
}
| mit | b36fe6b8de7622ed540dc1da673dc64c | 40.358974 | 123 | 0.691465 | 5.040625 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/usecases/CheckHeadlessExecutionUseCase.kt | 1 | 1274 | package ch.rmy.android.http_shortcuts.activities.execute.usecases
import ch.rmy.android.http_shortcuts.data.models.ResponseHandlingModel.Companion.FAILURE_OUTPUT_NONE
import ch.rmy.android.http_shortcuts.data.models.ResponseHandlingModel.Companion.SUCCESS_OUTPUT_NONE
import ch.rmy.android.http_shortcuts.data.models.ResponseHandlingModel.Companion.UI_TYPE_TOAST
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.utils.PermissionManager
import javax.inject.Inject
class CheckHeadlessExecutionUseCase
@Inject
constructor(
private val permissionManager: PermissionManager,
) {
operator fun invoke(shortcut: ShortcutModel): Boolean {
val responseHandling = shortcut.responseHandling ?: return false
val usesNoOutput = responseHandling.successOutput == SUCCESS_OUTPUT_NONE && responseHandling.failureOutput == FAILURE_OUTPUT_NONE
val usesToastOutput = responseHandling.uiType == UI_TYPE_TOAST
val usesCodeAfterExecution = shortcut.codeOnSuccess.isNotEmpty() || shortcut.codeOnFailure.isNotEmpty()
return (usesNoOutput || (usesToastOutput && permissionManager.hasNotificationPermission())) &&
!usesCodeAfterExecution &&
!shortcut.isWaitForNetwork
}
}
| mit | 03d9b6e3bfb89f17096d0a4389d1edd4 | 52.083333 | 137 | 0.788854 | 4.439024 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt | 1 | 6910 | package eu.kanade.tachiyomi.data.track.anilist
import android.content.Context
import android.graphics.Color
import com.google.gson.Gson
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import rx.Completable
import rx.Observable
import uy.kohesive.injekt.injectLazy
class Anilist(private val context: Context, id: Int) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLANNING = 5
const val REPEATING = 6
const val DEFAULT_STATUS = READING
const val DEFAULT_SCORE = 0
const val POINT_100 = "POINT_100"
const val POINT_10 = "POINT_10"
const val POINT_10_DECIMAL = "POINT_10_DECIMAL"
const val POINT_5 = "POINT_5"
const val POINT_3 = "POINT_3"
}
override val name = "AniList"
private val gson: Gson by injectLazy()
private val interceptor by lazy { AnilistInterceptor(this, getPassword()) }
private val api by lazy { AnilistApi(client, interceptor) }
private val scorePreference = preferences.anilistScoreType()
init {
// If the preference is an int from APIv1, logout user to force using APIv2
try {
scorePreference.get()
} catch (e: ClassCastException) {
logout()
scorePreference.delete()
}
}
override fun getLogo() = R.drawable.al
override fun getLogoColor() = Color.rgb(18, 25, 35)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLANNING, REPEATING)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
PLANNING -> getString(R.string.plan_to_read)
REPEATING -> getString(R.string.repeating)
else -> ""
}
}
override fun getScoreList(): List<String> {
return when (scorePreference.getOrDefault()) {
// 10 point
POINT_10 -> IntRange(0, 10).map(Int::toString)
// 100 point
POINT_100 -> IntRange(0, 100).map(Int::toString)
// 5 stars
POINT_5 -> IntRange(0, 5).map { "$it ★" }
// Smiley
POINT_3 -> listOf("-", "😦", "😐", "😊")
// 10 point decimal
POINT_10_DECIMAL -> IntRange(0, 100).map { (it / 10f).toString() }
else -> throw Exception("Unknown score type")
}
}
override fun indexToScore(index: Int): Float {
return when (scorePreference.getOrDefault()) {
// 10 point
POINT_10 -> index * 10f
// 100 point
POINT_100 -> index.toFloat()
// 5 stars
POINT_5 -> when {
index == 0 -> 0f
else -> index * 20f - 10f
}
// Smiley
POINT_3 -> when {
index == 0 -> 0f
else -> index * 25f + 10f
}
// 10 point decimal
POINT_10_DECIMAL -> index.toFloat()
else -> throw Exception("Unknown score type")
}
}
override fun displayScore(track: Track): String {
val score = track.score
return when (scorePreference.getOrDefault()) {
POINT_5 -> when {
score == 0f -> "0 ★"
else -> "${((score + 10) / 20).toInt()} ★"
}
POINT_3 -> when {
score == 0f -> "0"
score <= 35 -> "😦"
score <= 60 -> "😐"
else -> "😊"
}
else -> track.toAnilistScore()
}
}
override fun add(track: Track): Observable<Track> {
return api.addLibManga(track)
}
override fun update(track: Track): Observable<Track> {
if (track.total_chapters != 0 && track.last_chapter_read == track.total_chapters) {
track.status = COMPLETED
}
// If user was using API v1 fetch library_id
if (track.library_id == null || track.library_id!! == 0L){
return api.findLibManga(track, getUsername().toInt()).flatMap {
if (it == null) {
throw Exception("$track not found on user library")
}
track.library_id = it.library_id
api.updateLibManga(track)
}
}
return api.updateLibManga(track)
}
override fun bind(track: Track): Observable<Track> {
return api.findLibManga(track, getUsername().toInt())
.flatMap { remoteTrack ->
if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.library_id = remoteTrack.library_id
update(track)
} else {
// Set default fields if it's not found in the list
track.score = DEFAULT_SCORE.toFloat()
track.status = DEFAULT_STATUS
add(track)
}
}
}
override fun search(query: String): Observable<List<TrackSearch>> {
return api.search(query)
}
override fun refresh(track: Track): Observable<Track> {
return api.getLibManga(track, getUsername().toInt())
.map { remoteTrack ->
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
track
}
}
override fun login(username: String, password: String) = login(password)
fun login(token: String): Completable {
val oauth = api.createOAuth(token)
interceptor.setAuth(oauth)
return api.getCurrentUser().map { (username, scoreType) ->
scorePreference.set(scoreType)
saveCredentials(username.toString(), oauth.access_token)
}.doOnError{
logout()
}.toCompletable()
}
override fun logout() {
super.logout()
preferences.trackToken(this).set(null)
interceptor.setAuth(null)
}
fun saveOAuth(oAuth: OAuth?) {
preferences.trackToken(this).set(gson.toJson(oAuth))
}
fun loadOAuth(): OAuth? {
return try {
gson.fromJson(preferences.trackToken(this).get(), OAuth::class.java)
} catch (e: Exception) {
null
}
}
}
| apache-2.0 | e0bdfb58c98ae190ada3daf2a5ce8b33 | 31.17757 | 91 | 0.542695 | 4.416934 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/fragments/roomwidgets/RoomWidgetPermissionViewModel.kt | 2 | 5986 | /*
* Copyright 2019 New Vector Ltd
*
* 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 im.vector.fragments.roomwidgets
import com.airbnb.mvrx.BaseMvRxViewModel
import com.airbnb.mvrx.MvRxState
import com.airbnb.mvrx.MvRxViewModelFactory
import com.airbnb.mvrx.ViewModelContext
import im.vector.Matrix
import im.vector.R
import im.vector.widgets.Widget
import im.vector.widgets.WidgetsManager
import im.vector.widgets.model.JitsiWidgetProperties
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.callback.SimpleApiCallback
import java.net.URL
data class RoomWidgetPermissionViewState(
val authorId: String = "",
val authorAvatarUrl: String? = null,
val authorName: String? = null,
val isWebviewWidget: Boolean = true,
val widgetDomain: String? = null,
//List of @StringRes
val permissionsList: List<Int>? = null
) : MvRxState
class RoomWidgetPermissionViewModel(val session: MXSession, val widget: Widget, initialState: RoomWidgetPermissionViewState)
: BaseMvRxViewModel<RoomWidgetPermissionViewState>(initialState, false) {
fun allowWidget(onFinished: (() -> Unit)? = null) = withState { state ->
if (state.isWebviewWidget) {
session.integrationManager.setWidgetAllowed(widget.widgetEvent?.eventId
?: "", true, object : SimpleApiCallback<Void?>() {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
})
} else {
session.integrationManager.setNativeWidgetDomainAllowed("jitsi", state.widgetDomain
?: "", true, object : SimpleApiCallback<Void?>() {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
})
}
}
fun blockWidget(onFinished: (() -> Unit)? = null) = withState { state ->
if (state.isWebviewWidget) {
session.integrationManager.setWidgetAllowed(widget.widgetEvent?.eventId
?: "", false, object : SimpleApiCallback<Void?>() {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
})
} else {
session.integrationManager.setNativeWidgetDomainAllowed("jitsi", state.widgetDomain
?: "", false, object : SimpleApiCallback<Void?>() {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
})
}
}
companion object : MvRxViewModelFactory<RoomWidgetPermissionViewModel, RoomWidgetPermissionViewState> {
val LOG_TAG = RoomWidgetPermissionViewModel::class.simpleName
override fun create(viewModelContext: ViewModelContext, state: RoomWidgetPermissionViewState): RoomWidgetPermissionViewModel? {
val args = viewModelContext.args<RoomWidgetPermissionBottomSheet.FragArgs>()
val session = Matrix.getMXSession(viewModelContext.activity, args.mxId)
return RoomWidgetPermissionViewModel(session, args.widget, state)
}
override fun initialState(viewModelContext: ViewModelContext): RoomWidgetPermissionViewState? {
val args = viewModelContext.args<RoomWidgetPermissionBottomSheet.FragArgs>()
val session = Matrix.getMXSession(viewModelContext.activity, args.mxId)
val widget = args.widget
val room = session.dataHandler.getRoom(widget.roomId)
val creator = room.getMember(widget.widgetEvent.sender)
var domain: String?
try {
domain = URL(widget.url).host
} catch (e: Throwable) {
domain = null
}
if (WidgetsManager.isJitsiWidget(widget)) {
val infoShared = listOf<Int>(
R.string.room_widget_permission_display_name,
R.string.room_widget_permission_avatar_url
)
return RoomWidgetPermissionViewState(
isWebviewWidget = false,
authorName = creator?.displayname,
authorId = widget.widgetEvent.sender,
authorAvatarUrl = creator?.getAvatarUrl(),
widgetDomain = JitsiWidgetProperties(widget.url).domain,
permissionsList = infoShared
)
} else {
//TODO check from widget urls the perms that should be shown?
//For now put all
val infoShared = listOf<Int>(
R.string.room_widget_permission_display_name,
R.string.room_widget_permission_avatar_url,
R.string.room_widget_permission_user_id,
R.string.room_widget_permission_theme,
R.string.room_widget_permission_widget_id,
R.string.room_widget_permission_room_id
)
return RoomWidgetPermissionViewState(
authorName = creator?.displayname,
authorId = widget.widgetEvent.sender,
authorAvatarUrl = creator?.getAvatarUrl(),
widgetDomain = domain,
permissionsList = infoShared
)
}
}
}
} | apache-2.0 | 80b9d7b0e41121252875ad72f61aa29a | 38.913333 | 135 | 0.603742 | 5.138197 | false | false | false | false |
dreampany/framework | frame/src/main/kotlin/com/dreampany/translation/data/source/firestore/FirestoreTranslationDataSource.kt | 1 | 5605 | package com.dreampany.translation.data.source.firestore
import com.dreampany.firebase.RxFirebaseFirestore
import com.dreampany.network.manager.NetworkManager
import com.dreampany.translation.data.misc.TextTranslationMapper
import com.dreampany.translation.data.model.TextTranslation
import com.dreampany.translation.data.source.api.TranslationDataSource
import com.dreampany.translation.misc.Constants
import io.reactivex.Maybe
import javax.inject.Singleton
/**
* Created by Roman-372 on 7/4/2019
* Copyright (c) 2019 bjit. All rights reserved.
* [email protected]
* Last modified $file.lastModified
*/
@Singleton
class FirestoreTranslationDataSource
constructor(
val network: NetworkManager,
val mapper: TextTranslationMapper,
val firestore: RxFirebaseFirestore
) : TranslationDataSource {
override fun isReady(target: String): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun ready(target: String) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private val TRANSLATIONS = Constants.FirebaseKey.TRANSLATIONS
override fun isExistsRx(source: String, target: String, input: String): Maybe<Boolean> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isExists(source: String, target: String, input: String): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItem(source: String, target: String, input: String): TextTranslation {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEmpty(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEmptyRx(): Maybe<Boolean> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCount(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCountRx(): Maybe<Int> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isExists(t: TextTranslation): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItem(id: String): TextTranslation {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemRx(
source: String,
target: String,
input: String
): Maybe<TextTranslation> {
return firestore.getItemRx(
TRANSLATIONS,
mapper.toId(source, target, input),
TextTranslation::class.java
)
}
override fun isExistsRx(t: TextTranslation): Maybe<Boolean> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun putItem(t: TextTranslation): Long {
val id = mapper.toId(t)
val error = firestore.setItemRx(TRANSLATIONS, id, t).blockingGet()
return if (error == null) {
0L
} else -1L
}
override fun putItemRx(t: TextTranslation): Maybe<Long> {
return Maybe.fromCallable { putItem(t) }
}
override fun putItems(ts: List<TextTranslation>): List<Long> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun putItemsRx(ts: List<TextTranslation>): Maybe<List<Long>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun delete(t: TextTranslation): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun deleteRx(t: TextTranslation): Maybe<Int> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun delete(ts: List<TextTranslation>): List<Long> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun deleteRx(ts: List<TextTranslation>): Maybe<List<Long>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemRx(id: String): Maybe<TextTranslation> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItems(): MutableList<TextTranslation> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemsRx(): Maybe<List<TextTranslation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItems(limit: Int): List<TextTranslation> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemsRx(limit: Int): Maybe<List<TextTranslation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | apache-2.0 | ffa6a83f78ea3a3b7b209733fac5d01c | 38.202797 | 107 | 0.690277 | 4.556911 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/vedit/HttlVisualEditorFilter.kt | 1 | 2486 | package com.softmotions.ncms.vedit
import httl.spi.filters.AbstractFilter
import net.htmlparser.jericho.OutputDocument
import net.htmlparser.jericho.Source
import org.slf4j.LoggerFactory
/**
* Visual editor HTTL filter.
*
* Filter concept is based on [httl.spi.filters.AttributeSyntaxFilter]
*
* @author Adamansky Anton ([email protected])
*/
class HttlVisualEditorFilter : AbstractFilter() {
private val log = LoggerFactory.getLogger(javaClass)
override fun filter(key: String?, value: String?): String {
val source = Source(value)
val document = OutputDocument(source)
process(source, document)
if (log.isDebugEnabled) {
log.debug("Source: {} \n\nTransformed: {}", value, document)
}
return document.toString();
}
private fun process(source: Source, document: OutputDocument) {
var metaInjected = false;
val allElements = source.allElements
allElements.find {
it.getAttributeValue("ncms-block") != null
} ?: return
for (el in allElements) {
val blockAttr = el.attributes?.get("ncms-block") ?: continue
if (!metaInjected) {
metaInjected = true
document.insert(el.begin, "\n$!{ncmsVEStyles()}\n$!{ncmsVEScripts()}\n")
document.insert(el.attributes.end, " $!{ncmsDocumentVEMeta()}");
}
val attr2 = el.attributes.get("class")
if (attr2 == null) {
document.insert(el.startTag.end - 1, " class=\"ncms-block\"")
} else {
document.remove(attr2.valueSegment)
document.insert(attr2.valueSegment.begin, attr2.value + " ncms-block")
}
document.replace(blockAttr, "data-ncms-block=\"$!{ncmsVEBlockId('${blockAttr.value}')}\"")
if (el.endTag == null) {
// val st = el.startTag.toString()
// if (st.length > 2) {
// document.replace(el.startTag.end - 2, el.startTag.end,
// ">#if(ncmsVEBlockExists('${blockAttr.value}'))$!{ncmsVEBlock('${blockAttr.value}')}#end</${el.name}>"
// )
// }
} else {
document.insert(el.content.begin, "#if(ncmsVEBlockExists('${blockAttr.value}'))$!{ncmsVEBlock('${blockAttr.value}')}#else ")
document.insert(el.content.end, " #end")
}
}
}
} | apache-2.0 | 064b4221bf0a59844ab27f2221b666d2 | 37.261538 | 140 | 0.572808 | 3.952305 | false | false | false | false |
artem-zinnatullin/RxUi | rxui-sample-kotlin/src/test/kotlin/com/artemzin/rxui/sample/kotlin/MainPresenterTest.kt | 1 | 3817 | @file:Suppress("IllegalIdentifier")
package com.artemzin.rxui.sample.kotlin
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Failure
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Success
import io.reactivex.schedulers.Schedulers
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.*
class MainPresenterTest {
val authService = spy(TestAuthService())
val ioScheduler = Schedulers.trampoline()
val view = TestMainView()
val presenter = MainPresenter(authService, ioScheduler)
@Before
fun beforeEachTest() {
// GIVEN presenter is bound to view
presenter.bind(view)
// THEN sign in should be disabled by default
verify(view.signInDisableAction).accept(Unit)
verifyZeroInteractions(view.signInEnableAction)
// Reset counter for tests.
reset(view.signInDisableAction)
}
@Test
fun `should enable sign in if both login and password are not empty`() {
// GIVEN login is not empty
view.login.onNext("a")
// AND password is not empty
view.password.onNext("1")
// THEN sign in should be enabled
verify(view.signInEnableAction).accept(Unit)
verifyZeroInteractions(view.signInDisableAction)
}
@Test
fun `should not enable sign in if login is not empty but password is empty`() {
// WHEN login is not empty
view.login.onNext("a")
// AND password is empty
view.password.onNext("")
// THEN sign in should be disabled
verify(view.signInDisableAction).accept(Unit)
verifyZeroInteractions(view.signInEnableAction)
}
@Test
fun `should not enable sign in if login is empty but password is not empty`() {
// WHEN login is empty
view.login.onNext("")
// AND password is not empty
view.password.onNext("a")
// THEN sign in should be disabled
verify(view.signInDisableAction).accept(Unit)
verifyZeroInteractions(view.signInEnableAction)
}
@Test
fun `should send request to auth service`() {
// WHEN login is not empty (typing simulation)
view.login.onNext("@art")
view.login.onNext("@artem_zin")
// AND password is not empty (typing simulation)
view.password.onNext("123")
view.password.onNext("123456")
// AND click on sign in happens
view.signInClicks.onNext(Unit)
// THEN should call signIn service with correct credentials (not intermediate ones)
verify(authService).signIn("@artem_zin", "123456")
verifyNoMoreInteractions(authService)
}
@Test
fun `should send success sign in result to view`() {
// WHEN login is not empty
view.login.onNext("abc")
// AND password is not empty
view.password.onNext("213")
// AND click on sign in happens
view.signInClicks.onNext(Unit)
// AND signIn response arrives
authService.signIn.onNext(Success)
// THEN should send signIn result to view
verify(view.signInSuccessAction).accept(Success)
verifyZeroInteractions(view.signInFailureAction)
}
@Test
fun `should send failure sign in result to view`() {
// WHEN login is not empty
view.login.onNext("abc")
// AND password is not empty
view.password.onNext("213")
// AND click on sign in happens
view.signInClicks.onNext(Unit)
// AND signIn response arrives
val failure = Failure(RuntimeException("test"))
authService.signIn.onNext(failure)
// THEN should send signIn result to view
verify(view.signInFailureAction).accept(failure)
verifyZeroInteractions(view.signInSuccessAction)
}
}
| mit | 851ada367d85073709ee75c21ed49722 | 28.820313 | 91 | 0.655227 | 4.604343 | false | true | false | false |
android/fit-samples | BasicHistoryApiKotlin/app/src/main/java/com/google/android/gms/fit/samples/basichistoryapikotlin/MainActivity.kt | 1 | 19109 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.fit.samples.basichistoryapikotlin
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.TextViewCompat
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.fit.samples.common.logger.Log
import com.google.android.gms.fit.samples.common.logger.LogView
import com.google.android.gms.fit.samples.common.logger.LogWrapper
import com.google.android.gms.fit.samples.common.logger.MessageOnlyLogFilter
import com.google.android.gms.fitness.Fitness
import com.google.android.gms.fitness.FitnessOptions
import com.google.android.gms.fitness.data.DataPoint
import com.google.android.gms.fitness.data.DataSet
import com.google.android.gms.fitness.data.DataSource
import com.google.android.gms.fitness.data.DataType
import com.google.android.gms.fitness.data.Field
import com.google.android.gms.fitness.request.DataDeleteRequest
import com.google.android.gms.fitness.request.DataReadRequest
import com.google.android.gms.fitness.request.DataUpdateRequest
import com.google.android.gms.fitness.result.DataReadResponse
import com.google.android.gms.tasks.Task
import java.text.DateFormat
import java.util.Calendar
import java.util.Date
import java.util.TimeZone
import java.util.concurrent.TimeUnit
const val TAG = "BasicHistoryApi"
/**
* This enum is used to define actions that can be performed after a successful sign in to Fit.
* One of these values is passed to the Fit sign-in, and returned in a successful callback, allowing
* subsequent execution of the desired action.
*/
enum class FitActionRequestCode {
INSERT_AND_READ_DATA,
UPDATE_AND_READ_DATA,
DELETE_DATA
}
/**
* This sample demonstrates how to use the History API of the Google Fit platform to insert data,
* query against existing data, and remove data. It also demonstrates how to authenticate a user
* with Google Play Services and how to properly represent data in a {@link DataSet}.
*/
class MainActivity : AppCompatActivity() {
private val dateFormat = DateFormat.getDateInstance()
private val fitnessOptions: FitnessOptions by lazy {
FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_WRITE)
.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeLogging()
fitSignIn(FitActionRequestCode.INSERT_AND_READ_DATA)
}
/**
* Checks that the user is signed in, and if so, executes the specified function. If the user is
* not signed in, initiates the sign in flow, specifying the post-sign in function to execute.
*
* @param requestCode The request code corresponding to the action to perform after sign in.
*/
private fun fitSignIn(requestCode: FitActionRequestCode) {
if (oAuthPermissionsApproved()) {
performActionForRequestCode(requestCode)
} else {
requestCode.let {
GoogleSignIn.requestPermissions(
this,
requestCode.ordinal,
getGoogleAccount(), fitnessOptions)
}
}
}
/**
* Handles the callback from the OAuth sign in flow, executing the post sign in function
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (resultCode) {
RESULT_OK -> {
val postSignInAction = FitActionRequestCode.values()[requestCode]
postSignInAction.let {
performActionForRequestCode(postSignInAction)
}
}
else -> oAuthErrorMsg(requestCode, resultCode)
}
}
/**
* Runs the desired method, based on the specified request code. The request code is typically
* passed to the Fit sign-in flow, and returned with the success callback. This allows the
* caller to specify which method, post-sign-in, should be called.
*
* @param requestCode The code corresponding to the action to perform.
*/
private fun performActionForRequestCode(requestCode: FitActionRequestCode) = when (requestCode) {
FitActionRequestCode.INSERT_AND_READ_DATA -> insertAndReadData()
FitActionRequestCode.UPDATE_AND_READ_DATA -> updateAndReadData()
FitActionRequestCode.DELETE_DATA -> deleteData()
}
private fun oAuthErrorMsg(requestCode: Int, resultCode: Int) {
val message = """
There was an error signing into Fit. Check the troubleshooting section of the README
for potential issues.
Request code was: $requestCode
Result code was: $resultCode
""".trimIndent()
Log.e(TAG, message)
}
private fun oAuthPermissionsApproved() = GoogleSignIn.hasPermissions(getGoogleAccount(), fitnessOptions)
/**
* Gets a Google account for use in creating the Fitness client. This is achieved by either
* using the last signed-in account, or if necessary, prompting the user to sign in.
* `getAccountForExtension` is recommended over `getLastSignedInAccount` as the latter can
* return `null` if there has been no sign in before.
*/
private fun getGoogleAccount() = GoogleSignIn.getAccountForExtension(this, fitnessOptions)
/**
* Inserts and reads data by chaining {@link Task} from {@link #insertData()} and {@link
* #readHistoryData()}.
*/
private fun insertAndReadData() = insertData().continueWith { readHistoryData() }
/** Creates a {@link DataSet} and inserts it into user's Google Fit history. */
private fun insertData(): Task<Void> {
// Create a new dataset and insertion request.
val dataSet = insertFitnessData()
// Then, invoke the History API to insert the data.
Log.i(TAG, "Inserting the dataset in the History API.")
return Fitness.getHistoryClient(this, getGoogleAccount())
.insertData(dataSet)
.addOnSuccessListener { Log.i(TAG, "Data insert was successful!") }
.addOnFailureListener { exception ->
Log.e(TAG, "There was a problem inserting the dataset.", exception)
}
}
/**
* Asynchronous task to read the history data. When the task succeeds, it will print out the
* data.
*/
private fun readHistoryData(): Task<DataReadResponse> {
// Begin by creating the query.
val readRequest = queryFitnessData()
// Invoke the History API to fetch the data with the query
return Fitness.getHistoryClient(this, getGoogleAccount())
.readData(readRequest)
.addOnSuccessListener { dataReadResponse ->
// For the sake of the sample, we'll print the data so we can see what we just
// added. In general, logging fitness information should be avoided for privacy
// reasons.
printData(dataReadResponse)
}
.addOnFailureListener { e ->
Log.e(TAG, "There was a problem reading the data.", e)
}
}
/**
* Creates and returns a {@link DataSet} of step count data for insertion using the History API.
*/
private fun insertFitnessData(): DataSet {
Log.i(TAG, "Creating a new data insert request.")
// [START build_insert_data_request]
// Set a start and end time for our data, using a start time of 1 hour before this moment.
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
val now = Date()
calendar.time = now
val endTime = calendar.timeInMillis
calendar.add(Calendar.HOUR_OF_DAY, -1)
val startTime = calendar.timeInMillis
// Create a data source
val dataSource = DataSource.Builder()
.setAppPackageName(this)
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setStreamName("$TAG - step count")
.setType(DataSource.TYPE_RAW)
.build()
// Create a data set
val stepCountDelta = 950
return DataSet.builder(dataSource)
.add(DataPoint.builder(dataSource)
.setField(Field.FIELD_STEPS, stepCountDelta)
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
).build()
// [END build_insert_data_request]
}
/** Returns a [DataReadRequest] for all step count changes in the past week. */
private fun queryFitnessData(): DataReadRequest {
// [START build_read_data_request]
// Setting a start and end date using a range of 1 week before this moment.
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
val now = Date()
calendar.time = now
val endTime = calendar.timeInMillis
calendar.add(Calendar.WEEK_OF_YEAR, -1)
val startTime = calendar.timeInMillis
Log.i(TAG, "Range Start: ${dateFormat.format(startTime)}")
Log.i(TAG, "Range End: ${dateFormat.format(endTime)}")
return DataReadRequest.Builder()
// The data request can specify multiple data types to return, effectively
// combining multiple data queries into one call.
// In this example, it's very unlikely that the request is for several hundred
// datapoints each consisting of a few steps and a timestamp. The more likely
// scenario is wanting to see how many steps were walked per day, for 7 days.
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
// Analogous to a "Group By" in SQL, defines how data should be aggregated.
// bucketByTime allows for a time span, whereas bucketBySession would allow
// bucketing by "sessions", which would need to be defined in code.
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
}
/**
* Logs a record of the query result. It's possible to get more constrained data sets by
* specifying a data source or data type, but for demonstrative purposes here's how one would
* dump all the data. In this sample, logging also prints to the device screen, so we can see
* what the query returns, but your app should not log fitness information as a privacy
* consideration. A better option would be to dump the data you receive to a local data
* directory to avoid exposing it to other applications.
*/
private fun printData(dataReadResult: DataReadResponse) {
// [START parse_read_data_result]
// If the DataReadRequest object specified aggregated data, dataReadResult will be returned
// as buckets containing DataSets, instead of just DataSets.
if (dataReadResult.buckets.isNotEmpty()) {
Log.i(TAG, "Number of returned buckets of DataSets is: " + dataReadResult.buckets.size)
for (bucket in dataReadResult.buckets) {
bucket.dataSets.forEach { dumpDataSet(it) }
}
} else if (dataReadResult.dataSets.isNotEmpty()) {
Log.i(TAG, "Number of returned DataSets is: " + dataReadResult.dataSets.size)
dataReadResult.dataSets.forEach { dumpDataSet(it) }
}
// [END parse_read_data_result]
}
// [START parse_dataset]
private fun dumpDataSet(dataSet: DataSet) {
Log.i(TAG, "Data returned for Data type: ${dataSet.dataType.name}")
for (dp in dataSet.dataPoints) {
Log.i(TAG, "Data point:")
Log.i(TAG, "\tType: ${dp.dataType.name}")
Log.i(TAG, "\tStart: ${dp.getStartTimeString()}")
Log.i(TAG, "\tEnd: ${dp.getEndTimeString()}")
dp.dataType.fields.forEach {
Log.i(TAG, "\tField: ${it.name} Value: ${dp.getValue(it)}")
}
}
}
// [END parse_dataset]
/**
* Deletes a [DataSet] from the History API. In this example, we delete all step count data
* for the past 24 hours.
*/
private fun deleteData() {
Log.i(TAG, "Deleting today's step count data.")
// [START delete_dataset]
// Set a start and end time for our data, using a start time of 1 day before this moment.
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
val now = Date()
calendar.time = now
val endTime = calendar.timeInMillis
calendar.add(Calendar.DAY_OF_YEAR, -1)
val startTime = calendar.timeInMillis
// Create a delete request object, providing a data type and a time interval
val request = DataDeleteRequest.Builder()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.addDataType(DataType.TYPE_STEP_COUNT_DELTA)
.build()
// Invoke the History API with the HistoryClient object and delete request, and then
// specify a callback that will check the result.
Fitness.getHistoryClient(this, getGoogleAccount())
.deleteData(request)
.addOnSuccessListener {
Log.i(TAG, "Successfully deleted today's step count data.")
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to delete today's step count data.", e)
}
}
/**
* Updates and reads data by chaining [Task] from [.updateData] and [ ][.readHistoryData].
*/
private fun updateAndReadData() = updateData().continueWithTask { readHistoryData() }
/**
* Creates a [DataSet],then makes a [DataUpdateRequest] to update step data. Then
* invokes the History API with the HistoryClient object and update request.
*/
private fun updateData(): Task<Void> {
// Create a new dataset and update request.
val dataSet = updateFitnessData()
val startTime = dataSet.dataPoints[0].getStartTime(TimeUnit.MILLISECONDS)
val endTime = dataSet.dataPoints[0].getEndTime(TimeUnit.MILLISECONDS)
// [START update_data_request]
Log.i(TAG, "Updating the dataset in the History API.")
val request = DataUpdateRequest.Builder()
.setDataSet(dataSet)
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
// Invoke the History API to update data.
return Fitness.getHistoryClient(this, getGoogleAccount())
.updateData(request)
.addOnSuccessListener { Log.i(TAG, "Data update was successful.") }
.addOnFailureListener { e ->
Log.e(TAG, "There was a problem updating the dataset.", e)
}
}
/** Creates and returns a {@link DataSet} of step count data to update. */
private fun updateFitnessData(): DataSet {
Log.i(TAG, "Creating a new data update request.")
// [START build_update_data_request]
// Set a start and end time for the data that fits within the time range
// of the original insertion.
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
val now = Date()
calendar.time = now
val endTime = calendar.timeInMillis
calendar.add(Calendar.MINUTE, -50)
val startTime = calendar.timeInMillis
// Create a data source
val dataSource = DataSource.Builder()
.setAppPackageName(this)
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setStreamName("$TAG - step count")
.setType(DataSource.TYPE_RAW)
.build()
// Create a data set
val stepCountDelta = 1000
// For each data point, specify a start time, end time, and the data value -- in this case,
// the number of new steps.
return DataSet.builder(dataSource)
.add(DataPoint.builder(dataSource)
.setField(Field.FIELD_STEPS, stepCountDelta)
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
).build()
// [END build_update_data_request]
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_delete_data -> {
fitSignIn(FitActionRequestCode.DELETE_DATA)
true
}
R.id.action_update_data -> {
clearLogView()
fitSignIn(FitActionRequestCode.UPDATE_AND_READ_DATA)
true
}
else -> super.onOptionsItemSelected(item)
}
}
/** Clears all the logging message in the LogView. */
private fun clearLogView() {
val logView = findViewById<LogView>(R.id.sample_logview)
logView.text = ""
}
/** Initializes a custom log class that outputs both to in-app targets and logcat. */
private fun initializeLogging() {
// Wraps Android's native log framework.
val logWrapper = LogWrapper()
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper)
// Filter strips out everything except the message text.
val msgFilter = MessageOnlyLogFilter()
logWrapper.next = msgFilter
// On screen logging via a customized TextView.
val logView = findViewById<LogView>(R.id.sample_logview)
TextViewCompat.setTextAppearance(logView, R.style.Log)
logView.setBackgroundColor(Color.WHITE)
msgFilter.next = logView
Log.i(TAG, "Ready.")
}
}
| apache-2.0 | 9ff40ecc14190b64d76f93ea8724120d | 42.038288 | 108 | 0.642315 | 4.619048 | false | false | false | false |
mniami/android.kotlin.benchmark | app/src/main/java/guideme/volunteers/databases/actions/GetUser.kt | 2 | 1538 | package guideme.volunteers.databases.actions
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import guideme.volunteers.domain.User
import guideme.volunteers.log.createLog
import io.reactivex.Single
import io.reactivex.SingleEmitter
class GetUser(private val database: FirebaseDatabase) {
private val log = createLog(this)
fun execute(user: User) : Single<User> {
return Single.create { emitter ->
loadUser(user, emitter)
}
}
private fun loadUser(user: User, emitter: SingleEmitter<User>) {
val ref = database.reference.child(DatabaseTables.USERS).child(user.id)
val eventListener = object : ValueEventListener {
override fun onDataChange(var1: DataSnapshot) {
val u = var1.getValue(User::class.java)
if (u != null) {
log.d { "User found '${u.person.name}'" }
emitter.onSuccess(u)
} else {
log.d { "User not found" }
ref.removeEventListener(this)
AddUser(database).update(user, emitter)
}
}
override fun onCancelled(var1: DatabaseError) {
log.d { "Loading user canceled" }
ref.removeEventListener(this)
}
}
ref.addValueEventListener(eventListener)
}
} | apache-2.0 | a73d95bd817da065bb25621fbfd4f6fc | 34.790698 | 79 | 0.620936 | 4.703364 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/settings/AppSettings.kt | 1 | 3501 | package com.battlelancer.seriesguide.settings
import android.content.Context
import android.content.pm.PackageManager
import android.text.format.DateUtils
import androidx.preference.PreferenceManager
import com.battlelancer.seriesguide.BuildConfig
import com.battlelancer.seriesguide.util.Errors
import timber.log.Timber
object AppSettings {
const val KEY_VERSION = "oldversioncode"
@Deprecated("")
const val KEY_GOOGLEANALYTICS = "enableGAnalytics"
@Deprecated("")
const val KEY_HAS_SEEN_NAV_DRAWER = "hasSeenNavDrawer"
const val KEY_ASKED_FOR_FEEDBACK = "askedForFeedback"
const val KEY_SEND_ERROR_REPORTS = "com.battlelancer.seriesguide.sendErrorReports"
const val KEY_USER_DEBUG_MODE_ENBALED = "com.battlelancer.seriesguide.userDebugModeEnabled"
/**
* Returns the version code of the previously installed version. Is the current version on fresh
* installs.
*/
@JvmStatic
fun getLastVersionCode(context: Context): Int {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
var lastVersionCode = prefs.getInt(KEY_VERSION, -1)
if (lastVersionCode == -1) {
// set current version as default value
lastVersionCode = BuildConfig.VERSION_CODE
prefs.edit().putInt(KEY_VERSION, lastVersionCode).apply()
}
return lastVersionCode
}
@JvmStatic
fun shouldAskForFeedback(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
if (prefs.getBoolean(KEY_ASKED_FOR_FEEDBACK, false)) {
return false // already asked for feedback
}
try {
val ourPackageInfo = context.packageManager
.getPackageInfo(context.packageName, 0)
val installedRecently = System.currentTimeMillis() <
ourPackageInfo.firstInstallTime + 30 * DateUtils.DAY_IN_MILLIS
if (installedRecently) {
return false // was only installed recently
}
} catch (e: PackageManager.NameNotFoundException) {
Timber.e(e, "Failed to find our package info.")
return false // failed to find our package
}
return true
}
@JvmStatic
fun setAskedForFeedback(context: Context) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_ASKED_FOR_FEEDBACK, true)
.apply()
}
fun isSendErrorReports(context: Context): Boolean {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_SEND_ERROR_REPORTS, true)
}
fun setSendErrorReports(context: Context, isEnabled: Boolean, save: Boolean) {
if (save) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_SEND_ERROR_REPORTS, isEnabled)
.apply()
}
Timber.d("Turning error reporting %s", if (isEnabled) "ON" else "OFF")
Errors.getReporter()?.setCrashlyticsCollectionEnabled(isEnabled)
}
/**
* Returns if user-visible debug components should be enabled
* (e.g. logging to logcat, debug views). Always true for debug builds.
*/
fun isUserDebugModeEnabled(context: Context): Boolean {
return BuildConfig.DEBUG || PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_USER_DEBUG_MODE_ENBALED, false)
}
} | apache-2.0 | f5f1a12dcfadcf634567dc421d89e5eb | 36.655914 | 100 | 0.668095 | 4.822314 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/history/SgActivityHelper.kt | 1 | 4427 | package com.battlelancer.seriesguide.shows.history
import android.content.Context
import android.text.format.DateUtils
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import timber.log.Timber
/**
* Helper methods for adding or removing local episode watch activity.
*/
@Dao
interface SgActivityHelper {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertActivity(activity: SgActivity)
@Query("DELETE FROM activity WHERE activity_time < :deleteOlderThanMs")
fun deleteOldActivity(deleteOlderThanMs: Long): Int
@Query("DELETE FROM activity WHERE activity_episode = :episodeStableId AND activity_type = :type")
fun deleteActivity(episodeStableId: String, type: Int): Int
@Query("SELECT * FROM activity ORDER BY activity_time DESC")
fun getActivityByLatest(): List<SgActivity>
companion object {
private const val HISTORY_THRESHOLD = 30 * DateUtils.DAY_IN_MILLIS
/**
* Adds an activity entry for the given episode with the current time as timestamp.
* If an entry already exists it is replaced.
*
* Also cleans up old entries.
*/
@JvmStatic
fun addActivity(context: Context, episodeId: Long, showId: Long) {
// Need to use global IDs (in case a show is removed and added again).
val database = SgRoomDatabase.getInstance(context)
// Try using TMDB ID
var type = ActivityType.TMDB_ID
var showStableIdOrZero = database.sgShow2Helper().getShowTmdbId(showId)
var episodeStableIdOrZero = database.sgEpisode2Helper().getEpisodeTmdbId(episodeId)
// Fall back to TVDB ID
if (showStableIdOrZero == 0 || episodeStableIdOrZero == 0) {
type = ActivityType.TVDB_ID
showStableIdOrZero = database.sgShow2Helper().getShowTvdbId(showId)
episodeStableIdOrZero = database.sgEpisode2Helper().getEpisodeTvdbId(episodeId)
if (showStableIdOrZero == 0 || episodeStableIdOrZero == 0) {
// Should never happen: have neither TMDB or TVDB ID.
Timber.e(
"Failed to add activity, no TMDB or TVDB ID for show %d episode %d",
showId,
episodeId
)
return
}
}
val timeMonthAgo = System.currentTimeMillis() - HISTORY_THRESHOLD
val helper = database.sgActivityHelper()
// delete all entries older than 30 days
val deleted = helper.deleteOldActivity(timeMonthAgo)
Timber.d("addActivity: removed %d outdated activities", deleted)
// add new entry
val currentTime = System.currentTimeMillis()
val activity = SgActivity(
null,
episodeStableIdOrZero.toString(),
showStableIdOrZero.toString(),
currentTime,
type
)
helper.insertActivity(activity)
Timber.d("addActivity: episode: %d timestamp: %d", episodeId, currentTime)
}
/**
* Tries to remove any activity with the given episode id.
*/
@JvmStatic
fun removeActivity(context: Context, episodeId: Long) {
// Need to use global IDs (in case a show is removed and added again).
val database = SgRoomDatabase.getInstance(context)
// Try removal using TMDB ID.
var deleted = 0
val episodeTmdbIdOrZero = database.sgEpisode2Helper().getEpisodeTmdbId(episodeId)
if (episodeTmdbIdOrZero != 0) {
deleted += database.sgActivityHelper()
.deleteActivity(episodeTmdbIdOrZero.toString(), ActivityType.TMDB_ID)
}
// Try removal using TVDB ID.
val episodeTvdbIdOrZero = database.sgEpisode2Helper().getEpisodeTvdbId(episodeId)
if (episodeTvdbIdOrZero != 0) {
deleted += database.sgActivityHelper()
.deleteActivity(episodeTvdbIdOrZero.toString(), ActivityType.TVDB_ID)
}
Timber.d("removeActivity: deleted %d activity entries", deleted)
}
}
} | apache-2.0 | ff491d682c998248127b0af4305910f0 | 39.254545 | 102 | 0.619155 | 5.171729 | false | false | false | false |
kishmakov/Kitchen | server/src/io/magnaura/server/v1/V1Frontend.kt | 1 | 2822 | package io.magnaura.server.v1
import io.ktor.locations.*
import io.magnaura.protocol.v1.V1RootPath
import io.magnaura.server.Frontend
import io.magnaura.server.v1.handles.CommandHandler
import io.magnaura.server.v1.handles.ContextHandler
import io.magnaura.server.v1.handles.CompileHandler
object V1Frontend : Frontend(
V1RootPath,
listOf(
CommandHandler,
CompileHandler,
ContextHandler
)
)
//{
// override fun Route.setupRoutes() {
// get("/") {
// call.respondText(text(), contentType = ContentType.Text.Plain)
// }
// post("/compiler") {
// val project = call.receive<Project>()
//
// val analyser = ErrorAnalyzer(project.files.map { kotlinFile(it.name, it.text) })
//
// with (analyser.messageCollector) {
// if (hasErrors()) {
// call.respond(CompilationResult(errors = errors(), warnings = warnings()))
// return@post
// }
// }
//
// val compilation = KotlinCompiler(analyser).compile()
//
// val compiledClasses = ArrayList<CompiledClass>()
//
// for ((name, bytes) in compilation.files) {
// val index = Storage.registerClass(bytes)
// compiledClasses.add(CompiledClass(name, index))
// }
// for ((name, index) in libraryIds) {
// compiledClasses.add(CompiledClass(name, index))
// }
// call.respond(CompilationResult(
// compiledClasses,
// warnings = analyser.messageCollector.warnings()))
// }
// post(CompileCommandHandle.handlePath) {
// val (hash, context, command) = call.receive<CompileCommandHandle.Request>()
// val result = compileCommand(hash, context, command).toProtocolResponse()
// call.response.status(HttpStatusCode.Accepted)
// call.respond(result)
// }
//
// // Static feature. Try to access `/static/ktor_logo.svg`
// static("/static") {
// resources("static")
// }
//
// get<ClassRequest> {
// val message = ByteArrayContent(Storage.getClassBytes(it.index), ContentType.Application.OctetStream)
// call.respond(message)
// }
// // Register nested routes
// get<Type.Edit> {
// call.respondText("Inside $it")
// }
// get<Type.List> {
// call.respondText("Inside $it")
// }
// }
//}
@Location("/file/{index}")
data class ClassRequest(val index: Int)
@Location("/type/{name}") data class Type(val name: String) {
@Location("/edit")
data class Edit(val type: Type)
@Location("/list/{page}")
data class List(val type: Type, val page: Int)
}
| gpl-3.0 | 2d39a65e3cd81c72c71be90e47b45d08 | 29.673913 | 114 | 0.570163 | 3.930362 | false | false | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/ValidationInfo.kt | 1 | 981 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api.data
import de.fhg.aisec.ids.api.router.CounterExample
class ValidationInfo {
var valid = false
var counterExamples: List<CounterExample>? = null
}
| apache-2.0 | e3d503fb777ea2bf3278c3fa805ad991 | 35.333333 | 75 | 0.643221 | 4.399103 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/BlockPlaceListener.kt | 1 | 2695 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.blocklog.bukkit.listener
import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit
import com.rpkit.blocklog.bukkit.block.RPKBlockChangeImpl
import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryService
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.bukkit.location.toRPKBlockLocation
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.MONITOR
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockPlaceEvent
import java.time.LocalDateTime
class BlockPlaceListener(private val plugin: RPKBlockLoggingBukkit) : Listener {
@EventHandler(priority = MONITOR)
fun onBlockPlace(event: BlockPlaceEvent) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val blockHistoryService = Services[RPKBlockHistoryService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player)
val profile = minecraftProfile?.profile as? RPKProfile
val character = if (minecraftProfile == null) null else characterService.getPreloadedActiveCharacter(minecraftProfile)
blockHistoryService.getBlockHistory(event.block.toRPKBlockLocation()).thenAccept { blockHistory ->
val blockChange = RPKBlockChangeImpl(
blockHistory = blockHistory,
time = LocalDateTime.now(),
profile = profile,
minecraftProfile = minecraftProfile,
character = character,
from = event.blockReplacedState.type,
to = event.block.type,
reason = "PLACE"
)
plugin.server.scheduler.runTask(plugin, Runnable {
blockHistoryService.addBlockChange(blockChange)
})
}
}
} | apache-2.0 | 07b8470e3b1789edb38a61027fa85070 | 43.196721 | 126 | 0.734323 | 4.821109 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentKickCommand.kt | 1 | 5663 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit.command.payment
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.notifications.bukkit.notification.RPKNotificationService
import com.rpkit.payments.bukkit.RPKPaymentsBukkit
import com.rpkit.payments.bukkit.group.RPKPaymentGroupName
import com.rpkit.payments.bukkit.group.RPKPaymentGroupService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.concurrent.CompletableFuture
/**
* Payment kick command.
* Kicks a character from a payment group.
*/
class PaymentKickCommand(private val plugin: RPKPaymentsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.payments.command.payment.kick")) {
sender.sendMessage(plugin.messages.noPermissionPaymentKick)
return true
}
if (args.size <= 1) {
sender.sendMessage(plugin.messages.paymentKickUsage)
return true
}
val paymentGroupService = Services[RPKPaymentGroupService::class.java]
if (paymentGroupService == null) {
sender.sendMessage(plugin.messages.noPaymentGroupService)
return true
}
paymentGroupService.getPaymentGroup(RPKPaymentGroupName(args.dropLast(1).joinToString(" ")))
.thenAccept getPaymentGroup@{ paymentGroup ->
if (paymentGroup == null) {
sender.sendMessage(plugin.messages.paymentKickInvalidGroup)
return@getPaymentGroup
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages.noMinecraftProfileService)
return@getPaymentGroup
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages.noCharacterService)
return@getPaymentGroup
}
val bukkitPlayer = plugin.server.getPlayer(args.last())
if (bukkitPlayer == null) {
sender.sendMessage(plugin.messages.paymentKickInvalidPlayer)
return@getPaymentGroup
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages.noMinecraftProfile)
return@getPaymentGroup
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages.paymentKickInvalidCharacter)
return@getPaymentGroup
}
CompletableFuture.allOf(
paymentGroup.removeInvite(character),
paymentGroup.removeMember(character)
).thenRun {
sender.sendMessage(plugin.messages.paymentKickValid)
val notificationService = Services[RPKNotificationService::class.java]
if (notificationService == null) {
sender.sendMessage(plugin.messages.noNotificationService)
return@thenRun
}
val now = LocalDateTime.now()
val notificationTitle = plugin.messages.paymentNotificationKickTitle.withParameters(
member = character,
group = paymentGroup,
date = now.atZone(ZoneId.systemDefault())
)
val notificationMessage = plugin.messages.paymentNotificationKick.withParameters(
member = character,
group = paymentGroup,
date = now.atZone(ZoneId.systemDefault())
)
if (!minecraftProfile.isOnline) { // If offline
val profile = character.profile
if (profile != null) {
notificationService.createNotification(
recipient = profile,
title = notificationTitle,
content = notificationMessage
)
}
} else { // If online
minecraftProfile.sendMessage(notificationMessage)
}
}
}
return true
}
} | apache-2.0 | efec8b6076843218cdc07f50011801dd | 46.2 | 118 | 0.606216 | 5.826132 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut09/ambientLighting.kt | 2 | 8010 | package glNext.tut09
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.f
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.destroy
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.mousePole.*
/**
* Created by GBarbieri on 23.03.2017.
*/
fun main(args: Array<String>) {
AmbientLighting_Next().setup("Tutorial 09 - Ambient Lighting")
}
class AmbientLighting_Next : Framework() {
lateinit var whiteDiffuseColor: ProgramData
lateinit var vertexDiffuseColor: ProgramData
lateinit var whiteAmbDiffuseColor: ProgramData
lateinit var vertexAmbDiffuseColor: ProgramData
lateinit var cylinder: Mesh
lateinit var plane: Mesh
val projectionUniformBuffer = intBufferBig(1)
val lightDirection = Vec4(0.866f, 0.5f, 0.0f, 0.0f)
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
var drawColoredCyl = true
var showAmbient = false
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
cylinder = Mesh(gl, javaClass, "tut09/UnitCylinder.xml")
plane = Mesh(gl, javaClass, "tut09/LargePlane.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
clamp = true
}
initUniformBuffer(projectionUniformBuffer) {
data(Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE)
}
}
fun initializeProgram(gl: GL3) {
whiteDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PN.vert", "color-passthrough.frag")
vertexDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PCN.vert", "color-passthrough.frag")
whiteAmbDiffuseColor = ProgramData(gl, "dir-amb-vertex-lighting-PN.vert", "color-passthrough.frag")
vertexAmbDiffuseColor = ProgramData(gl, "dir-amb-vertex-lighting-PCN.vert", "color-passthrough.frag")
}
override fun display(gl: GL3) = with(gl) {
clear {
color(0)
depth()
}
val modelMatrix = MatrixStack().setMatrix(viewPole.calcMatrix())
val lightDirCameraSpace = modelMatrix.top() * lightDirection
val whiteDiffuse = if (showAmbient) whiteAmbDiffuseColor else whiteDiffuseColor
val vertexDiffuse = if (showAmbient) vertexAmbDiffuseColor else vertexDiffuseColor
usingProgram {
if (showAmbient) {
name = whiteDiffuse.theProgram
glUniform4f(whiteDiffuse.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(whiteDiffuse.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
name = vertexDiffuse.theProgram
glUniform4f(vertexDiffuse.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(vertexDiffuse.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
} else {
name = whiteDiffuse.theProgram
glUniform4f(whiteDiffuse.lightIntensityUnif, 1.0f)
name = vertexDiffuse.theProgram
glUniform4f(vertexDiffuse.lightIntensityUnif, 1.0f)
}
name = whiteDiffuse.theProgram
glUniform3f(whiteDiffuse.dirToLightUnif, lightDirCameraSpace)
name = vertexDiffuse.theProgram
glUniform3f(vertexDiffuse.dirToLightUnif, lightDirCameraSpace)
modelMatrix run {
//Render the ground plane.
run {
name = whiteDiffuse.theProgram
whiteDiffuse.modelToCameraMatrixUnif.mat4 = top()
val normMatrix = top().toMat3()
whiteDiffuse.normalModelToCameraMatrixUnif.mat3 = normMatrix
plane.render(gl)
}
//Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (drawColoredCyl) {
name = vertexDiffuse.theProgram
vertexDiffuse.modelToCameraMatrixUnif.mat4 = top()
val normMatrix = top().toMat3()
vertexDiffuse.normalModelToCameraMatrixUnif.mat3 = normMatrix
cylinder.render(gl, "lit-color")
} else {
name = whiteDiffuse.theProgram
whiteDiffuse.modelToCameraMatrixUnif.mat4 = top()
val normMatrix = top().toMat3()
whiteDiffuse.normalModelToCameraMatrixUnif.mat3 = normMatrix
cylinder.render(gl, "lit")
}
}
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
perspMatrix.perspective(45.0f, w.f / h, zNear, zFar)
withUniformBuffer(projectionUniformBuffer) { subData(perspMatrix.top()) }
glViewport(w, h)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl
KeyEvent.VK_T -> {
showAmbient = !showAmbient
println("Ambient Lighting " + if (showAmbient) "On." else "Off.")
}
}
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(vertexDiffuseColor.theProgram, whiteDiffuseColor.theProgram, vertexAmbDiffuseColor.theProgram, whiteAmbDiffuseColor.theProgram)
glDeleteBuffer(projectionUniformBuffer)
cylinder.dispose(gl)
plane.dispose(gl)
projectionUniformBuffer.destroy()
}
inner class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut09", vertex, fragment)
val dirToLightUnif = gl.glGetUniformLocation(theProgram, "dirToLight")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
} | mit | 6c80ad9a14c5bc1b6bcf0db4464099f5 | 30.53937 | 152 | 0.608489 | 4.213572 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/lyricFinder/NowPlaying.kt | 1 | 2474 | package com.itachi1706.cheesecakeutilities.modules.lyricFinder
import android.content.Intent
import android.graphics.Bitmap
/**
* Created by Kenneth on 25/12/2017.
* for com.itachi1706.cheesecakeutilities.modules.LyricFinder in CheesecakeUtilities
*/
class NowPlaying {
private var album: String? = null
private var title: String? = null
private var artist: String? = null
var albumart: Bitmap? = null
var state: Int = 0
val stateString: String
get() {
return when (state) {
PLAY -> "Playing"
PAUSE -> "Paused"
STOP -> "Stopped/Unknown"
else -> "Stopped/Unknown"
}
}
constructor() {
album = "Unknown Album"
title = "Unknown Title"
artist = "Unknown Artist"
state = STOP
}
constructor(intent: Intent) {
album = intent.getStringExtra(LYRIC_ALBUM)
artist = intent.getStringExtra(LYRIC_ARTIST)
title = intent.getStringExtra(LYRIC_TITLE)
state = intent.getIntExtra(LYRIC_STATE, STOP)
}
fun generateIntent(): Intent {
val intent = Intent(LYRIC_DATA)
intent.putExtra(LYRIC_ALBUM, album)
intent.putExtra(LYRIC_ARTIST, artist)
intent.putExtra(LYRIC_TITLE, title)
intent.putExtra(LYRIC_STATE, state)
return intent
}
fun getAlbum(): String? {
return album
}
fun setAlbum(album: String?) {
if (album == null)
this.album = "Unknown Album"
else
this.album = album
}
fun getTitle(): String? {
return title
}
fun setTitle(title: String?) {
if (title == null)
this.title = "Unknown Title"
else
this.title = title
}
fun getArtist(): String? {
return artist
}
fun setArtist(artist: String?) {
if (artist == null)
this.artist = "Unknown Artist"
else
this.artist = artist
}
companion object {
val PLAY = 0
val PAUSE = 1
val STOP = 2
val LYRIC_TITLE = "title"
val LYRIC_ARTIST = "artist"
val LYRIC_ALBUM = "album"
val LYRIC_STATE = "state"
val LYRIC_ALBUMART = "album_art"
val LYRIC_UPDATE = "com.itachi1706.cheesecakeutilities.LYRIC_UPDATE_BROADCAST"
val LYRIC_DATA = "com.itachi1706.cheesecakeutilities.LYRIC_DATA_BROADCAST"
}
}
| mit | 09dbe3ad61f9933365a71467d5ba02da | 23.74 | 86 | 0.574373 | 4.172007 | false | false | false | false |
talent-bearers/Slimefusion | src/main/java/talent/bearers/slimefusion/common/block/ModBlocks.kt | 1 | 1135 | package talent.bearers.slimefusion.common.block
import talent.bearers.slimefusion.common.lib.LibNames
/**
* @author WireSegal
* Created at 11:00 PM on 12/23/16.
*/
object ModBlocks {
val MARK: BlockMark
val COLORFUL_LOG: BlockLogColorful
val DARK_LOG: BlockLogDark
val PLANKS: BlockPlanks
val QUARTZITE: BlockStone
val OPAL_QUARTZITE: BlockStone
val SCORCHED_QUARTZITE: BlockStone
val BLUEDUST: BlockZeleniDirt
val SHALEDUST: BlockZeleniDirt
val FLOWER: BlockZeleniFlower
val ORE: BlockPolestoneOre
val METAL_ORE: BlockMoonshard
init {
MARK = BlockMark()
COLORFUL_LOG = BlockLogColorful()
DARK_LOG = BlockLogDark()
PLANKS = BlockPlanks()
QUARTZITE = BlockStone(LibNames.QUARTZITE)
OPAL_QUARTZITE = BlockStone(LibNames.OPAL_QUARTZITE)
SCORCHED_QUARTZITE = BlockStone(LibNames.SCORCHED_QUARTZITE)
BLUEDUST = BlockZeleniDirt(LibNames.BLUEDUST)
SHALEDUST = BlockZeleniDirt(LibNames.SHALEDUST)
FLOWER = BlockZeleniFlower()
ORE = BlockPolestoneOre()
METAL_ORE = BlockMoonshard()
}
}
| mit | 2a229fc09243fc9a0fc3b145ce40f43a | 29.675676 | 68 | 0.697797 | 3.170391 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/declarations/BrokerCommand.kt | 1 | 2022 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerBuyStockExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerInfoExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerPortfolioExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerSellStockExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerStockInfoExecutor
class BrokerCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Broker
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.ECONOMY, I18N_PREFIX.Description) {
subcommand(I18N_PREFIX.Info.Label, I18N_PREFIX.Info.Description) {
executor = { BrokerInfoExecutor(it) }
}
subcommand(I18N_PREFIX.Portfolio.Label, I18N_PREFIX.Portfolio.Description) {
executor = { BrokerPortfolioExecutor(it) }
}
subcommand(I18N_PREFIX.Stock.Label, I18N_PREFIX.Stock.Description) {
executor = { BrokerStockInfoExecutor(it) }
}
subcommand(I18N_PREFIX.Buy.Label, I18N_PREFIX.Buy.Description) {
executor = { BrokerBuyStockExecutor(it) }
}
subcommand(I18N_PREFIX.Sell.Label, I18N_PREFIX.Sell.Description) {
executor = { BrokerSellStockExecutor(it) }
}
}
} | agpl-3.0 | c88dd6deb4582158dbbaff74eea76366 | 49.575 | 116 | 0.778437 | 4.311301 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/dashboard/configure/ConfigureAutoroleRoute.kt | 1 | 2211 | package net.perfectdreams.loritta.morenitta.website.routes.dashboard.configure
import net.perfectdreams.loritta.morenitta.dao.ServerConfig
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.website.evaluate
import io.ktor.server.application.ApplicationCall
import net.dv8tion.jda.api.entities.Guild
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.website.routes.dashboard.RequiresGuildAuthLocalizedRoute
import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession
import net.perfectdreams.loritta.morenitta.website.utils.extensions.legacyVariables
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondHtml
import net.perfectdreams.temmiediscordauth.TemmieDiscordAuth
class ConfigureAutoroleRoute(loritta: LorittaBot) : RequiresGuildAuthLocalizedRoute(loritta, "/configure/autorole") {
override suspend fun onGuildAuthenticatedRequest(call: ApplicationCall, locale: BaseLocale, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification, guild: Guild, serverConfig: ServerConfig) {
loritta as LorittaBot
val autoroleConfig = loritta.newSuspendedTransaction {
serverConfig.autoroleConfig
}
val variables = call.legacyVariables(loritta, locale)
variables["saveType"] = "autorole"
variables["serverConfig"] = FakeServerConfig(
FakeServerConfig.FakeAutoroleConfig(
autoroleConfig?.enabled ?: false,
autoroleConfig?.giveOnlyAfterMessageWasSent ?: false,
autoroleConfig?.giveRolesAfter ?: 0
)
)
val validEnabledRoles = autoroleConfig?.roles?.filter {
try {
guild.getRoleById(it) != null
} catch (e: Exception) {
false
}
} ?: listOf()
variables["currentAutoroles"] = validEnabledRoles.joinToString(separator = ";")
call.respondHtml(evaluate("autorole.html", variables))
}
/**
* Fake Server Config for Pebble, in the future this will be removed
*/
private class FakeServerConfig(val autoroleConfig: FakeAutoroleConfig) {
class FakeAutoroleConfig(
val isEnabled: Boolean,
val giveOnlyAfterMessageWasSent: Boolean,
val giveRolesAfter: Long
)
}
} | agpl-3.0 | 46cacd22724a93cbd309e08f781db678 | 38.5 | 230 | 0.800543 | 4.360947 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.