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
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/features/settings/SettingsScreenPresenter.kt
1
6501
/* * 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.features.settings import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.util.Patterns import com.stfalcon.mvphelper.Presenter import com.stfalcon.new_uaroads_android.R import com.stfalcon.new_uaroads_android.common.analytics.AnalyticsManager import com.stfalcon.new_uaroads_android.common.data.preferences.Settings import com.stfalcon.new_uaroads_android.common.injection.InjectionConsts import com.stfalcon.new_uaroads_android.features.autostart.AutoStartJobScheduler import com.stfalcon.new_uaroads_android.features.tracks.autoupload.AutoUploaderJobScheduler import com.stfalcon.new_uaroads_android.repos.tracks.TracksRepo import io.reactivex.android.schedulers.AndroidSchedulers import org.jetbrains.anko.toast import javax.inject.Inject import javax.inject.Named /* * Created by troy379 on 12.04.17. */ class SettingsScreenPresenter @Inject constructor( val context: Context, @Named(InjectionConsts.NAME_USER_ID) val userId: String, @Named(InjectionConsts.NAME_APP_VERSION) val appVersion: String, @Named(InjectionConsts.NAME_ACCOUNT_EMAIL) val accountEmail: String, @Named(InjectionConsts.NAME_SENSOR_INFO) val sensorInfo: String, val settings: Settings, val tracksRepo: TracksRepo, val autoUploaderJobScheduler: AutoUploaderJobScheduler, val autoStartJobScheduler: AutoStartJobScheduler, val analyticsManager: AnalyticsManager) : Presenter<SettingsScreenContract.View>(), SettingsScreenContract.Presenter { private var developerCounter = 0 override fun onViewAttached(view: SettingsScreenContract.View, created: Boolean) { super.onViewAttached(view, created) view.showSettings( settings.isAuthorized(), settings.getUserEmail() ?: accountEmail, settings.isWifiOnlyEnabled(), settings.isSendRoutesAutomatically(), settings.isAutostartEnabled(), settings.isNotificationEnabled(), settings.isPitSoundEnabled(), settings.isAutostartSoundEnabled(), settings.isDevModeEnabled(), appVersion, userId) view.onAuthorizationChanged(settings.isAuthorized(), settings.getUserEmail() ?: accountEmail) analyticsManager.sendScreen("SettingActivity") } override fun onLoginButtonClicked(email: String) { if (checkIsEmailValid(email)) { if (!settings.isAuthorized()) disposables.add(tracksRepo.sendDeviceInfo(email, sensorInfo, userId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { settings.setUserEmail(email) settings.setAuthorized(true) view?.onAuthorizationChanged(true, email) }, { it.message?.let { view?.showError(it) } } )) else { settings.setUserEmail(null) settings.setAuthorized(false) view?.onAuthorizationChanged(false, email) } } else { context.toast(R.string.settings_error_email) } } override fun onSendViaWiFiClicked(isChecked: Boolean) { settings.enableWifiOnlyMode(isChecked) analyticsManager.sendSettingSendingOnlyWIfi(isChecked) } override fun onPitSoundClicked(isChecked: Boolean) { settings.enablePitSound(isChecked) analyticsManager.sendSettingPitSound(isChecked) } override fun onAutostartSoundClicked(isChecked: Boolean) { settings.enableAutostartSound(isChecked) analyticsManager.sendSettingAutoStartSound(isChecked) } override fun onSendRoutesAutomaticallyClicked(isChecked: Boolean) { settings.sendRoutesAutomatically(isChecked) if (isChecked) { autoUploaderJobScheduler.scheduleAutoUploadingService() } else { autoUploaderJobScheduler.cancelAll() } analyticsManager.sendSettingAutoSending(isChecked) } override fun onAutoStartClicked(isChecked: Boolean) { settings.enableAutostart(isChecked) if (isChecked) { autoStartJobScheduler.scheduleAutoStartService() } else { autoStartJobScheduler.cancelAll() } analyticsManager.sendSettingAutoRecord(isChecked) } override fun onShowNotificationClicked(isChecked: Boolean) { settings.enableNotification(isChecked) } override fun onAppVersionClicked() { developerCounter++ if (settings.isDevModeEnabled() && developerCounter == 3) { developerCounter = 0 context.toast(R.string.settings_dev_mode_disabled) settings.enableDevMode(false) view?.onDevModeChanged(false) } else if (developerCounter == 7) { developerCounter = 0 context.toast(R.string.settings_dev_mode_enabled) settings.enableDevMode(true) view?.onDevModeChanged(true) } } override fun onCopyUserIdClicked() { copyToClipboard(userId) context.toast(R.string.settings_user_id_copied) } private fun copyToClipboard(text: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(text, text) clipboard.primaryClip = clip } private fun checkIsEmailValid(email: String?) = Patterns.EMAIL_ADDRESS.matcher(email).matches() }
apache-2.0
9ec09183a909b190b194561a34126851
38.406061
101
0.66036
4.95881
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/EventCard.kt
1
3111
package de.tum.`in`.tumcampusapp.component.ui.ticket import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.navigation.NavDestination import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder import de.tum.`in`.tumcampusapp.component.ui.ticket.activity.EventDetailsActivity import de.tum.`in`.tumcampusapp.component.ui.ticket.adapter.EventsAdapter import de.tum.`in`.tumcampusapp.component.ui.ticket.model.Event import de.tum.`in`.tumcampusapp.component.ui.ticket.repository.EventsLocalRepository import de.tum.`in`.tumcampusapp.component.ui.ticket.repository.TicketsLocalRepository import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoActivity import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.utils.Const class EventCard(context: Context) : Card(CardManager.CARD_EVENT, context, "card_event") { var event: Event? = null // TODO(thellmund) Inject this private val eventCardsProvider = EventCardsProvider(context, EventsLocalRepository(TcaDb.getInstance(context))) private val localRepo = TicketsLocalRepository(TcaDb.getInstance(context)) override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) { super.updateViewHolder(viewHolder) val eventViewHolder = viewHolder as? EventsAdapter.EventViewHolder ?: return val event = this.event if (event != null) { val ticketCount = event.let { localRepo.getTicketCount(it) } ?: 0 eventViewHolder.bind(event, ticketCount) } } override fun getNavigationDestination(): NavDestination? { val event = this.event if (event != null && event.kino != -1) { val args = Bundle().apply { putInt(Const.KINO_ID, event.kino) } return NavDestination.Activity(KinoActivity::class.java, args) } val args = Bundle().apply { putParcelable(Const.KEY_EVENT, event) } return NavDestination.Activity(EventDetailsActivity::class.java, args) } override fun shouldShow(prefs: SharedPreferences): Boolean { return event?.dismissed == 0 } override fun discard(editor: SharedPreferences.Editor) { event?.let { eventCardsProvider.setDismissed(it.id) } } companion object { @JvmStatic fun inflateViewHolder( parent: ViewGroup, interactionListener: CardInteractionListener ): CardViewHolder { val card = LayoutInflater.from(parent.context) .inflate(R.layout.card_events_item, parent, false) return EventsAdapter.EventViewHolder(card, interactionListener, true) } } }
gpl-3.0
1b68869c14f7206bbb64d2b5c46d99d6
39.934211
115
0.724204
4.363254
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/GroupSerialization.kt
1
6532
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.google.gson.reflect.TypeToken import com.habitrpg.android.habitica.models.inventory.Quest import com.habitrpg.android.habitica.models.inventory.QuestRageStrike import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.models.social.Group import com.habitrpg.android.habitica.models.social.GroupCategory import com.habitrpg.shared.habitica.models.tasks.TasksOrder import io.realm.Realm import io.realm.RealmList import java.lang.reflect.Type class GroupSerialization : JsonDeserializer<Group>, JsonSerializer<Group> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Group { val group = Group() val obj = json.asJsonObject group.id = obj.get("_id").asString group.name = obj.get("name").asString if (obj.has("description") && !obj.get("description").isJsonNull) { group.description = obj.get("description").asString } if (obj.has("summary") && !obj.get("summary").isJsonNull) { group.summary = obj.get("summary").asString } if (obj.has("leaderMessage") && !obj.get("leaderMessage").isJsonNull) { group.leaderMessage = obj.get("leaderMessage").asString } if (obj.has("privacy")) { group.privacy = obj.get("privacy").asString } if (obj.has("memberCount")) { group.memberCount = obj.get("memberCount").asInt } if (obj.has("balance")) { group.balance = obj.get("balance").asDouble } if (obj.has("logo") && !obj.get("logo").isJsonNull) { group.logo = obj.get("logo").asString } if (obj.has("type")) { group.type = obj.get("type").asString } if (obj.has("leader")) { if (obj.get("leader").isJsonPrimitive) { group.leaderID = obj.get("leader").asString } else { val leader = obj.get("leader").asJsonObject group.leaderID = leader.get("_id").asString if (leader.has("profile") && !leader.get("profile").isJsonNull) { if (leader.get("profile").asJsonObject.has("name")) { group.leaderName = leader.get("profile").asJsonObject.get("name").asString } } } } if (obj.has("quest")) { group.quest = context.deserialize(obj.get("quest"), object : TypeToken<Quest>() {}.type) group.quest?.id = group.id val questObject = obj.getAsJsonObject("quest") if (questObject.has("members")) { val members = obj.getAsJsonObject("quest").getAsJsonObject("members") val realm = Realm.getDefaultInstance() val dbMembers = realm.copyFromRealm(realm.where(Member::class.java).equalTo("party.id", group.id).findAll()) realm.close() dbMembers.forEach { member -> if (members.has(member.id)) { val value = members.get(member.id) if (value.isJsonNull) { member.participatesInQuest = null } else { member.participatesInQuest = value.asBoolean } } else { member.participatesInQuest = null } members.remove(member.id) } members.entrySet().forEach { (key, value) -> val member = Member() member.id = key if (!value.isJsonNull) { member.participatesInQuest = value.asBoolean } dbMembers.add(member) } val newMembers = RealmList<Member>() newMembers.addAll(dbMembers) group.quest?.participants = newMembers } if (questObject.has("extra") && questObject["extra"].asJsonObject.has("worldDmg")) { val worldDamageObject = questObject.getAsJsonObject("extra").getAsJsonObject("worldDmg") worldDamageObject.entrySet().forEach { (key, value) -> val rageStrike = QuestRageStrike(key, value.asBoolean) group.quest?.addRageStrike(rageStrike) } } } if (obj.has("leaderOnly")) { val leaderOnly = obj.getAsJsonObject("leaderOnly") if (leaderOnly.has("challenges")) { group.leaderOnlyChallenges = leaderOnly.get("challenges").asBoolean } if (leaderOnly.has("getGems")) { group.leaderOnlyGetGems = leaderOnly.get("getGems").asBoolean } } if (obj.has("tasksOrder")) { group.tasksOrder = context.deserialize(obj.get("tasksOrder"), TasksOrder::class.java) } if (obj.has("categories")) { group.categories = RealmList() obj.getAsJsonArray("categories").forEach { group.categories?.add(context.deserialize(it, GroupCategory::class.java)) } } return group } override fun serialize(src: Group, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val obj = JsonObject() obj.addProperty("name", src.name) obj.addProperty("description", src.description) obj.addProperty("summary", src.summary) obj.addProperty("logo", src.logo) obj.addProperty("type", src.type) obj.addProperty("type", src.type) obj.addProperty("leader", src.leaderID) val leaderOnly = JsonObject() leaderOnly.addProperty("challenges", src.leaderOnlyChallenges) leaderOnly.addProperty("getGems", src.leaderOnlyGetGems) obj.add("leaderOnly", leaderOnly) return obj } }
gpl-3.0
5ff06f57f541f7c9d9ddb6e2aacf674e
42.135135
124
0.56384
4.750545
false
false
false
false
da1z/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ParameterNullityInference.kt
4
9372
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.dataFlow import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaTokenType import com.intellij.psi.impl.source.JavaLightTreeUtil import com.intellij.psi.impl.source.tree.ElementType import com.intellij.psi.impl.source.tree.JavaElementType.* import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.tree.TokenSet import java.util.* fun inferNotNullParameters(tree: LighterAST, method: LighterASTNode, statements: List<LighterASTNode>): BitSet { val parameterNames = getParameterNames(tree, method) return inferNotNullParameters(tree, parameterNames, statements) } private fun inferNotNullParameters(tree: LighterAST, parameterNames: List<String?>, statements: List<LighterASTNode>): BitSet { val canBeNulls = parameterNames.filterNotNullTo(HashSet()) if (canBeNulls.isEmpty()) return BitSet() val notNulls = HashSet<String>() val queue = ArrayDeque<LighterASTNode>(statements) while (queue.isNotEmpty() && canBeNulls.isNotEmpty()) { val element = queue.removeFirst() val type = element.tokenType when (type) { CONDITIONAL_EXPRESSION, EXPRESSION_STATEMENT -> JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst) RETURN_STATEMENT -> { queue.clear() JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst) } FOR_STATEMENT -> { val condition = JavaLightTreeUtil.findExpressionChild(tree, element) queue.clear() if (condition != null) { queue.addFirst(condition) LightTreeUtil.firstChildOfType(tree, element, ElementType.JAVA_STATEMENT_BIT_SET)?.let(queue::addFirst) } else { // no condition == endless loop: we may analyze body (at least until break/return/if/etc.) tree.getChildren(element).asReversed().forEach(queue::addFirst) } } WHILE_STATEMENT -> { queue.clear() val expression = JavaLightTreeUtil.findExpressionChild(tree, element) if (expression?.tokenType == LITERAL_EXPRESSION && LightTreeUtil.firstChildOfType(tree, expression, JavaTokenType.TRUE_KEYWORD) != null) { // while(true) == endless loop: we may analyze body (at least until break/return/if/etc.) tree.getChildren(element).asReversed().forEach(queue::addFirst) } else { dereference(tree, expression, canBeNulls, notNulls, queue) } } FOREACH_STATEMENT, SWITCH_STATEMENT, IF_STATEMENT, THROW_STATEMENT -> { queue.clear() val expression = JavaLightTreeUtil.findExpressionChild(tree, element) dereference(tree, expression, canBeNulls, notNulls, queue) } BINARY_EXPRESSION, POLYADIC_EXPRESSION -> { if (LightTreeUtil.firstChildOfType(tree, element, TokenSet.create(JavaTokenType.ANDAND, JavaTokenType.OROR)) != null) { JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst) } else { tree.getChildren(element).asReversed().forEach(queue::addFirst) } } EMPTY_STATEMENT, ASSERT_STATEMENT, DO_WHILE_STATEMENT, DECLARATION_STATEMENT, BLOCK_STATEMENT -> { tree.getChildren(element).asReversed().forEach(queue::addFirst) } SYNCHRONIZED_STATEMENT -> { val sync = JavaLightTreeUtil.findExpressionChild(tree, element) dereference(tree, sync, canBeNulls, notNulls, queue) LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst) } FIELD, PARAMETER, LOCAL_VARIABLE -> { canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, element)) JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst) } EXPRESSION_LIST -> { val children = JavaLightTreeUtil.getExpressionChildren(tree, element) // When parameter is passed to another method, that method may have "null -> fail" contract, // so without knowing this we cannot continue inference for the parameter children.forEach { ignore(tree, it, canBeNulls) } children.asReversed().forEach(queue::addFirst) } ASSIGNMENT_EXPRESSION -> { val lvalue = JavaLightTreeUtil.findExpressionChild(tree, element) ignore(tree, lvalue, canBeNulls) tree.getChildren(element).asReversed().forEach(queue::addFirst) } ARRAY_ACCESS_EXPRESSION -> JavaLightTreeUtil.getExpressionChildren(tree, element).forEach { dereference(tree, it, canBeNulls, notNulls, queue) } METHOD_REF_EXPRESSION, REFERENCE_EXPRESSION -> { val qualifier = JavaLightTreeUtil.findExpressionChild(tree, element) dereference(tree, qualifier, canBeNulls, notNulls, queue) } CLASS, METHOD, LAMBDA_EXPRESSION -> { // Ignore classes, methods and lambda expression bodies as it's not known whether they will be instantiated/executed. // For anonymous classes argument list, field initializers and instance initialization sections are checked. } TRY_STATEMENT -> { queue.clear() val canCatchNpe = LightTreeUtil.getChildrenOfType(tree, element, CATCH_SECTION) .asSequence() .map { LightTreeUtil.firstChildOfType(tree, it, PARAMETER) } .filterNotNull() .map { parameter -> LightTreeUtil.firstChildOfType(tree, parameter, TYPE) } .any { canCatchNpe(tree, it) } if (!canCatchNpe) { LightTreeUtil.getChildrenOfType(tree, element, RESOURCE_LIST).forEach(queue::addFirst) LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst) // stop analysis after first try as we are not sure how execution goes further: // whether or not it visit catch blocks, etc. } } else -> { if (ElementType.JAVA_STATEMENT_BIT_SET.contains(type)) { // Unknown/unprocessed statement: just stop processing the rest of the method queue.clear() } else { tree.getChildren(element).asReversed().forEach(queue::addFirst) } } } } val notNullParameters = BitSet() parameterNames.forEachIndexed { index, s -> if (notNulls.contains(s)) notNullParameters.set(index) } return notNullParameters } private val NPE_CATCHERS = setOf("Throwable", "Exception", "RuntimeException", "NullPointerException", CommonClassNames.JAVA_LANG_THROWABLE, CommonClassNames.JAVA_LANG_EXCEPTION, CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, CommonClassNames.JAVA_LANG_NULL_POINTER_EXCEPTION) fun canCatchNpe(tree: LighterAST, type: LighterASTNode?): Boolean { if (type == null) return false val codeRef = LightTreeUtil.firstChildOfType(tree, type, JAVA_CODE_REFERENCE) val name = JavaLightTreeUtil.getNameIdentifierText(tree, codeRef) if (name == null) { // Multicatch return LightTreeUtil.getChildrenOfType(tree, type, TYPE).any { canCatchNpe(tree, it) } } return NPE_CATCHERS.contains(name) } private fun ignore(tree: LighterAST, expression: LighterASTNode?, canBeNulls: HashSet<String>) { if (expression != null && expression.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, expression) == null) { canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, expression)) } } private fun dereference(tree: LighterAST, expression: LighterASTNode?, canBeNulls: HashSet<String>, notNulls: HashSet<String>, queue: ArrayDeque<LighterASTNode>) { if (expression == null) return if (expression.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, expression) == null) { JavaLightTreeUtil.getNameIdentifierText(tree, expression)?.takeIf(canBeNulls::remove)?.let(notNulls::add) } else { queue.addFirst(expression) } } /** * Returns list of parameter names. A null in returned list means that either parameter name * is absent in the source or it's a primitive type (thus nullity inference does not apply). */ private fun getParameterNames(tree: LighterAST, method: LighterASTNode): List<String?> { val parameterList = LightTreeUtil.firstChildOfType(tree, method, PARAMETER_LIST) ?: return emptyList() val parameters = LightTreeUtil.getChildrenOfType(tree, parameterList, PARAMETER) return parameters.map { if (LightTreeUtil.firstChildOfType(tree, it, ElementType.PRIMITIVE_TYPE_BIT_SET) != null) null else JavaLightTreeUtil.getNameIdentifierText(tree, it) } }
apache-2.0
710ecf4129f45de6addd9f18d79f8405
46.095477
129
0.695903
4.781633
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/components/Pill.kt
1
1453
package eu.kanade.presentation.components import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp @Composable fun Pill( text: String, modifier: Modifier = Modifier, color: Color = MaterialTheme.colorScheme.background, contentColor: Color = MaterialTheme.colorScheme.onBackground, elevation: Dp = 1.dp, fontSize: TextUnit = LocalTextStyle.current.fontSize, ) { androidx.compose.material3.Surface( modifier = modifier .requiredWidth(IntrinsicSize.Max) .padding(start = 4.dp) .clip(RoundedCornerShape(100)), color = color, contentColor = contentColor, tonalElevation = elevation, ) { Text( text = text, modifier = Modifier.padding(6.dp, 1.dp), fontSize = fontSize, maxLines = 1, softWrap = false, ) } }
apache-2.0
995bb1d8d133906418567fa66f63ff48
32.022727
65
0.718513
4.484568
false
false
false
false
kronenpj/iqtimesheet
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/ActionBarListActivity.kt
1
918
package com.github.kronenpj.iqtimesheet.IQTimeSheet import android.support.v7.app.AppCompatActivity import android.widget.HeaderViewListAdapter import android.widget.ListAdapter import android.widget.ListView /** * Created by kronenpj on 7/9/16. */ abstract class ActionBarListActivity : AppCompatActivity() { private var mListView: ListView? = null protected val listView: ListView get() { if (mListView == null) { mListView = findViewById(android.R.id.list) } return mListView as ListView } protected var listAdapter: ListAdapter get() { val adapter = listView.adapter return if (adapter is HeaderViewListAdapter) { adapter.wrappedAdapter } else { adapter } } set(adapter) { listView.adapter = adapter } }
apache-2.0
b3a3e83fca19f003cf124b2b875fa940
25.257143
60
0.610022
4.857143
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/platform/windows/Windows.kt
2
2837
package failchat.platform.windows import com.sun.jna.Native import com.sun.jna.Pointer import com.sun.jna.platform.win32.User32 import com.sun.jna.platform.win32.WinDef.HWND import failchat.exception.NativeCallException import failchat.util.binary import javafx.stage.Stage import mu.KotlinLogging object Windows { private val logger = KotlinLogging.logger {} /** @throws [NativeCallException] */ fun makeWindowClickTransparent(windowHandle: HWND) { changeWindowStyle(windowHandle) { currentStyle -> currentStyle or User32.WS_EX_LAYERED or User32.WS_EX_TRANSPARENT } } /** @throws [NativeCallException] */ fun makeWindowClickOpaque(windowHandle: HWND, removeLayeredStyle: Boolean) { changeWindowStyle(windowHandle) { currentStyle -> val notTransparentStyle = currentStyle and User32.WS_EX_TRANSPARENT.inv() if (removeLayeredStyle) { notTransparentStyle and User32.WS_EX_LAYERED.inv() } else { notTransparentStyle } } } /** @throws [NativeCallException] */ private fun changeWindowStyle(windowHandle: HWND, changeOperation: (Int) -> Int) { val currentStyle = User32.INSTANCE.GetWindowLong(windowHandle, User32.GWL_EXSTYLE) .ifError { errorCode -> throw NativeCallException("Failed to get window style, error code: $errorCode, handle: $windowHandle") } val newStyle = changeOperation.invoke(currentStyle) logger.debug { "Changing window style, current: ${currentStyle.binary()}, new: ${newStyle.binary()}; window: $windowHandle" } User32.INSTANCE.SetWindowLong(windowHandle, User32.GWL_EXSTYLE, newStyle) .ifError { errorCode -> throw NativeCallException("Failed to set window style, error code: $errorCode, handle: $windowHandle") } } private inline fun Int.ifError(operation: (errorCode: Int) -> Nothing): Int { if (this != 0) return this val errorCode = Native.getLastError() operation(errorCode) } fun getWindowHandle(stage: Stage): HWND { val peerField = stage.javaClass.superclass.getDeclaredField("peer") peerField.isAccessible = true val windowStage = peerField.get(stage) val platformWindowField = windowStage.javaClass.getDeclaredField("platformWindow") platformWindowField.isAccessible = true val platformWindow = platformWindowField.get(windowStage) val getNativeHandleMethod = platformWindow.javaClass.superclass.getDeclaredMethod("getNativeHandle") getNativeHandleMethod.isAccessible = true val handle = getNativeHandleMethod.invoke(platformWindow) as Long return HWND(Pointer(handle)) } }
gpl-3.0
b00d088364cd5ae48c8a269c3b99df93
37.337838
133
0.678181
4.517516
false
false
false
false
javaslang/javaslang-circuitbreaker
resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/circuitbreaker/CircuitBreaker.kt
1
2124
/* * * Copyright 2019: Guido Pio Mariotti, Brad Newman * * 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 io.github.resilience4j.kotlin.circuitbreaker import io.github.resilience4j.circuitbreaker.CircuitBreaker import io.github.resilience4j.kotlin.isCancellation import java.util.concurrent.TimeUnit import kotlin.coroutines.coroutineContext /** * Decorates and executes the given suspend function [block]. */ suspend fun <T> CircuitBreaker.executeSuspendFunction(block: suspend () -> T): T { acquirePermission() val start = System.nanoTime() try { val result = block() val durationInNanos = System.nanoTime() - start onSuccess(durationInNanos, TimeUnit.NANOSECONDS) return result } catch (exception: Throwable) { if (isCancellation(coroutineContext, exception)) { releasePermission() } else { val durationInNanos = System.nanoTime() - start onError(durationInNanos, TimeUnit.NANOSECONDS, exception) } throw exception } } /** * Decorates the given *suspend* function [block] and returns it. */ fun <T> CircuitBreaker.decorateSuspendFunction(block: suspend () -> T): suspend () -> T = { executeSuspendFunction(block) } /** * Decorates and executes the given function [block]. */ fun <T> CircuitBreaker.executeFunction(block: () -> T): T { return this.decorateCallable(block).call() } /** * Decorates the given function [block] and returns it. */ fun <T> CircuitBreaker.decorateFunction(block: () -> T): () -> T = { executeFunction(block) }
apache-2.0
48e678ae4069bcabdd7a5c56d5f964d4
30.701493
91
0.693032
4.148438
false
false
false
false
chengpo/number-speller
app/src/main/java/com/monkeyapp/numbers/MainFragment.kt
1
8357
/* MIT License Copyright (c) 2017 - 2021 Po Cheng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.monkeyapp.numbers import android.app.Activity import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.util.DisplayMetrics import android.util.Log import android.view.* import android.widget.Button import android.widget.FrameLayout import android.widget.TextView import androidx.core.os.bundleOf import androidx.core.view.children import androidx.core.view.doOnLayout import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.navigation.ui.onNavDestinationSelected import arrow.core.Either import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import com.google.firebase.analytics.FirebaseAnalytics import com.monkeyapp.numbers.apphelpers.* import com.monkeyapp.numbers.translators.SpellerError class MainFragment : Fragment() { private lateinit var adView: AdView private val mainViewModel: MainViewModel by viewModels { MainViewModel.Factory() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onResume() { super.onResume() adView.resume() } override fun onPause() { super.onPause() adView.pause() } override fun onDestroyView() { super.onDestroyView() adView.destroy() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.content_main, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adView = AdView(requireContext()).apply(::setupAdView) val omniButtonView: OmniButton = view.findViewById(R.id.omniButtonView) val digitPadView: ViewGroup = view.findViewById(R.id.digitPadView) val wordsTextView: TextView = view.findViewById(R.id.wordsTextView) val numberTextView: TextView = view.findViewById(R.id.numberTextView) omniButtonView.setOnClickListener { when ((it as OmniButton).state) { OmniButton.State.Clean -> mainViewModel.reset() OmniButton.State.Camera -> startActivityForResult(requireContext().ocrIntent, REQUEST_CODE_OCR_CAPTURE) } } digitPadView.children .first { it.id == R.id.btnDel } .apply { // long click to reset number setOnLongClickListener { mainViewModel.reset() return@setOnLongClickListener true } // delete last digit setOnClickListener { mainViewModel.backspace() } } digitPadView.children .filter { it is Button && (it.text[0] == '.' || it.text[0] in '0'..'9') } .forEach { child -> child.setOnClickListener { mainViewModel.append((it as Button).text[0]) } } wordsTextView.setOnClickListener { try { val wordsText = wordsTextView.text.toString() if (wordsText.isNotBlank()) { val action = MainFragmentDirections.actionMainToFullScreen(wordsText) findNavController().navigate(action) } } catch (e: IllegalArgumentException) { Log.e("MainFragment", "navigation failed", e) } } mainViewModel.formattedNumberText.observe(viewLifecycleOwner, Observer { numberTextView.text = it omniButtonView.state = if (it.isEmpty()) { OmniButton.State.Camera } else { OmniButton.State.Clean } }) mainViewModel.numberWordsText.observe(viewLifecycleOwner, Observer { when (it) { is Either.Right -> wordsTextView.text = it.b is Either.Left -> { when (it.a) { SpellerError.NUMBER_IS_TOO_LARGE -> { digitPadView.snackbar(R.string.too_large_to_spell) { icon(R.drawable.ic_error, R.color.accent) } } } } } }) // attach rating prompter RatingPrompter(context = requireContext(), anchorView = digitPadView).run { bind(viewLifecycleOwner) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_OCR_CAPTURE && resultCode == Activity.RESULT_OK) { val number = data?.getStringExtra("number") ?: "" if (number.isNotBlank()) { mainViewModel.reset() number.forEach { digit -> mainViewModel.append(digit) } } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.main, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return item.onNavDestinationSelected(findNavController()) || super.onOptionsItemSelected(item) } private companion object { const val REQUEST_CODE_OCR_CAPTURE = 1000 } } private fun MainFragment.setupAdView(adView: AdView) { val adContainerView = requireView().findViewById<FrameLayout>(R.id.adViewContainer) fun adaptiveAdSize(): AdSize { val display = requireActivity().windowManager.defaultDisplay val outMetrics = DisplayMetrics() display.getMetrics(outMetrics) val density = outMetrics.density var adWidthPixels = adContainerView.width.toFloat() if (adWidthPixels == 0.0f) { adWidthPixels = outMetrics.widthPixels.toFloat() if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { adWidthPixels /= 2 } } val adWidth = (adWidthPixels / density).toInt() return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), adWidth) } adContainerView.doOnLayout { adView.apply { adSize = adaptiveAdSize() adUnitId = resources.getString(R.string.ad_unit_id) adListener = object : AdListener() { override fun onAdFailedToLoad(errorCode: Int) { FirebaseAnalytics.getInstance(requireContext()) .logEvent("AdLoadingFailed", bundleOf("ErrorCode" to errorCode.toString())) } } } adContainerView.addView(adView) adView.loadAd(AdRequest.Builder().build()) } }
mit
da3f6656c73ea52a15923cd0bc3cf347
34.871245
116
0.630968
5.013197
false
false
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/database/feed/model/FeedEntity.kt
4
1547
package org.schabi.newpipe.database.feed.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import org.schabi.newpipe.database.feed.model.FeedEntity.Companion.FEED_TABLE import org.schabi.newpipe.database.feed.model.FeedEntity.Companion.STREAM_ID import org.schabi.newpipe.database.feed.model.FeedEntity.Companion.SUBSCRIPTION_ID import org.schabi.newpipe.database.stream.model.StreamEntity import org.schabi.newpipe.database.subscription.SubscriptionEntity @Entity( tableName = FEED_TABLE, primaryKeys = [STREAM_ID, SUBSCRIPTION_ID], indices = [Index(SUBSCRIPTION_ID)], foreignKeys = [ ForeignKey( entity = StreamEntity::class, parentColumns = [StreamEntity.STREAM_ID], childColumns = [STREAM_ID], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE, deferred = true ), ForeignKey( entity = SubscriptionEntity::class, parentColumns = [SubscriptionEntity.SUBSCRIPTION_UID], childColumns = [SUBSCRIPTION_ID], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE, deferred = true ) ] ) data class FeedEntity( @ColumnInfo(name = STREAM_ID) var streamId: Long, @ColumnInfo(name = SUBSCRIPTION_ID) var subscriptionId: Long ) { companion object { const val FEED_TABLE = "feed" const val STREAM_ID = "stream_id" const val SUBSCRIPTION_ID = "subscription_id" } }
gpl-3.0
b16e6ef3f608c97b8d7c3a8c63f44d75
32.630435
89
0.696186
4.345506
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/suica/SuicaTrip.kt
1
8620
/* * SuicaTrip.kt * * Copyright 2011 Kazzz * Copyright 2014-2015 Eric Butler <[email protected]> * Copyright 2016-2018 Michael Farrell <[email protected]> * Copyright 2018 Google Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.suica import au.id.micolous.metrodroid.card.felica.FelicaBlock import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.Trip import au.id.micolous.metrodroid.util.NumberUtils import kotlin.text.Regex @Parcelize class SuicaTrip (val balance: Int, val consoleTypeInt: Int, private val mProcessType: Int, val fareRaw: Int, override var startTimestamp: Timestamp?, override var endTimestamp: Timestamp?, override val startStation: Station?, override val endStation: Station?, val startStationId: Int, val endStationId: Int, val dateRaw: Int): Trip() { override val routeName: FormattedString? get() { if (startStation == null) return FormattedString("$consoleType $processType") val routeName = super.routeName ?: return null // SUICA HACK: // If there's something that looks like "#2" at the start, then mark // that as the default language. val m = LINE_NUMBER.matchEntire(routeName.unformatted)?.groups ?: return routeName // There is a line number //Log.d(TAG, String.format("num = %s, line = %s", m.group(1), m.group(2))); val sep = m[1]?.value?.length ?: return routeName return FormattedString.defaultLanguage(routeName.unformatted.substring(0, sep)) + routeName.substring(sep) } override val humanReadableRouteID: String? get() = if (startStation != null) super.humanReadableRouteID else NumberUtils.intToHex(consoleTypeInt) + " " + NumberUtils.intToHex(mProcessType) override val fare: TransitCurrency? get() = TransitCurrency.JPY(fareRaw) override val mode: Trip.Mode get() { val consoleType = consoleTypeInt and 0xFF return when { isTVM -> Trip.Mode.TICKET_MACHINE consoleType == 0xc8 -> Trip.Mode.VENDING_MACHINE consoleType == 0xc7 -> Trip.Mode.POS consoleTypeInt == CONSOLE_BUS.toByte().toInt() -> Trip.Mode.BUS else -> Trip.Mode.METRO } } private val consoleType: String get() = SuicaUtil.getConsoleTypeName(consoleTypeInt) private val processType: String get() = SuicaUtil.getProcessTypeName(mProcessType) private val isTVM: Boolean get() = isTVM(consoleTypeInt) override fun getAgencyName(isShort: Boolean) = startStation?.companyName /* public boolean isBus() { return mIsBus; } public boolean isProductSale() { return mIsProductSale; } public boolean isCharge() { return mIsCharge; } public int getBusLineCode() { return mBusLineCode; } public int getBusStopCode() { return mBusStopCode; } */ fun setEndTime(hour: Int, min: Int) { endTimestamp = endTimestamp?.toDaystamp()?.promote(SuicaUtil.TZ, hour, min) } fun setStartTime(hour: Int, min: Int) { startTimestamp = startTimestamp?.toDaystamp()?.promote(SuicaUtil.TZ, hour, min) } companion object { private const val CONSOLE_BUS = 0x05 private const val CONSOLE_CHARGE = 0x02 /** * Used when localisePlaces=true to ensure route and line numbers are still read out in the * user's language. * * eg: * - "#7 Eastern Line" -> (local)#7 (foreign)Eastern Line * - "300 West" -> (local)300 (foreign)West * - "North Ferry" -> (foreign)North Ferry */ private val LINE_NUMBER = Regex("(#?\\d+)?(\\D.+)") private fun isTVM(consoleTypeInt: Int): Boolean { val consoleType = consoleTypeInt and 0xFF val tvmConsoleTypes = intArrayOf(0x03, 0x07, 0x08, 0x12, 0x13, 0x14, 0x15) return consoleType in tvmConsoleTypes } fun parse(block: FelicaBlock, previousBalance: Int): SuicaTrip { val data = block.data // 00000080000000000000000000000000 // 00 00 - console type // 01 00 - process type // 02 00 - ?? // 03 80 - ?? // 04 00 - date // 05 00 - date // 06 00 - enter line code // 07 00 // 08 00 // 09 00 // 10 00 // 11 00 // 12 00 // 13 00 // 14 00 // 15 00 val consoleTypeInt = data[0].toInt() val mProcessType = data[1].toInt() val isProductSale = consoleTypeInt == 0xc7.toByte().toInt() || consoleTypeInt == 0xc8.toByte().toInt() val dateRaw = data.byteArrayToInt(4, 2) val startTimestamp = SuicaUtil.extractDate(isProductSale, data) @Suppress("UnnecessaryVariable") val endTimestamp = startTimestamp // Balance is little-endian val balance = data.byteArrayToIntReversed(10, 2) val regionCode = data[15].toInt() and 0xFF val fareRaw = if (previousBalance >= 0) { previousBalance - balance } else { // Can't get amount for first record. 0 } val startStation: Station? val endStation: Station? // Unused block (new card) if (startTimestamp == null) { startStation = null endStation = null } else if (isProductSale || mProcessType == CONSOLE_CHARGE.toByte().toInt()) { startStation = null endStation = null } else if (consoleTypeInt == CONSOLE_BUS.toByte().toInt()) { val busLineCode = data.byteArrayToInt(6, 2) val busStopCode = data.byteArrayToInt(8, 2) startStation = SuicaDBUtil.getBusStop(regionCode, busLineCode, busStopCode) endStation = null } else if (isTVM(consoleTypeInt)) { val railEntranceLineCode = data[6].toInt() and 0xFF val railEntranceStationCode = data[7].toInt() and 0xFF startStation = SuicaDBUtil.getRailStation(regionCode, railEntranceLineCode, railEntranceStationCode) endStation = null } else { val railEntranceLineCode = data[6].toInt() and 0xFF val railEntranceStationCode = data[7].toInt() and 0xFF val railExitLineCode = data[8].toInt() and 0xFF val railExitStationCode = data[9].toInt() and 0xFF startStation = SuicaDBUtil.getRailStation(regionCode, railEntranceLineCode, railEntranceStationCode) endStation = SuicaDBUtil.getRailStation(regionCode, railExitLineCode, railExitStationCode) } return SuicaTrip(balance = balance, consoleTypeInt = consoleTypeInt, mProcessType = mProcessType, fareRaw = fareRaw, startTimestamp = startTimestamp, endTimestamp = endTimestamp, startStation = startStation, endStation = endStation, dateRaw = dateRaw, startStationId = data.byteArrayToInt(6, 2), endStationId = data.byteArrayToInt(8, 2)) } } }
gpl-3.0
6edeb06d3bd5312aad343a2911cfb1f3
37.141593
114
0.594084
4.338198
false
false
false
false
VTUZ-12IE1bzud/TruckMonitor-Android
app/src/main/kotlin/ru/annin/truckmonitor/presentation/ui/activity/MainActivity.kt
1
7146
package ru.annin.truckmonitor.presentation.ui.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.support.design.widget.TabLayout import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.support.v4.view.GravityCompat import android.support.v4.view.ViewPager import android.support.v4.widget.DrawerLayout import android.support.v7.widget.Toolbar import android.view.View import com.arellomobile.mvp.MvpAppCompatActivity import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.PresenterType import com.arellomobile.mvp.presenter.ProvidePresenter import ru.annin.truckmonitor.R import ru.annin.truckmonitor.data.repository.KeyStoreRepository import ru.annin.truckmonitor.data.repository.RestApiRepository import ru.annin.truckmonitor.data.repository.SettingsRepository import ru.annin.truckmonitor.domain.model.CurrentCarriageResponse import ru.annin.truckmonitor.domain.value.NavigationMenuItem import ru.annin.truckmonitor.presentation.common.BaseViewDelegate import ru.annin.truckmonitor.presentation.presenter.MainPresenter import ru.annin.truckmonitor.presentation.ui.adapter.CurrentCarriagePagerAdapter import ru.annin.truckmonitor.presentation.ui.alert.ErrorAlert import ru.annin.truckmonitor.presentation.ui.view.MainView import ru.annin.truckmonitor.utils.visible /** * Главный экран. * * @author Pavel Annin. */ class MainActivity : MvpAppCompatActivity(), MainView { companion object { private const val REQUEST_CODE_QR_SCANNER = 1 @JvmStatic fun start(context: Context) { val intent = Intent(context, MainActivity::class.java) context.startActivity(intent) } } // Component's @InjectPresenter(type = PresenterType.LOCAL) lateinit var presenter: MainPresenter private lateinit var viewDelegate: ViewDelegate @ProvidePresenter(type = PresenterType.LOCAL) fun providePresenter() = MainPresenter(RestApiRepository, KeyStoreRepository, SettingsRepository) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewDelegate = ViewDelegate(findViewById(R.id.root), supportFragmentManager).apply { onItemClick = { when (it) { NavigationMenuItem.HOME -> { /** Текущий экран. */ } NavigationMenuItem.HISTORY -> presenter.onHistoryOpen() NavigationMenuItem.USER_INFO -> presenter.onUserInfoOpen() NavigationMenuItem.ABOUT -> TODO() NavigationMenuItem.LOG_OUT -> presenter.onLogOut() } } } } override fun navigate2Me() = MeActivity.start(this) override fun navigate2History() = HistoryActivity.start(this) override fun navigate2Login() { LoginActivity.start(this) finish() } override fun navigate2QrScanner() = QrScannerActivity.start(this, REQUEST_CODE_QR_SCANNER) override fun toggleLoad(isLoad: Boolean) = viewDelegate.run { this.isLoad = isLoad } override fun error(err: Throwable) { var fragment = supportFragmentManager.findFragmentByTag(ErrorAlert.TAG) if (fragment == null) { fragment = ErrorAlert.newInstance(err) (fragment as DialogFragment).show(supportFragmentManager, ErrorAlert.TAG) } } override fun showCarriage(data: CurrentCarriageResponse) = viewDelegate.run { currentCarriage = data } /** * View Delegate главного экрана. * * @property isNavigationOpen Состояние навигационного меню. * @property isLoad Индикатор загрузки. * @property onItemClick Событие, выбран пнукт навигации. */ private class ViewDelegate(vRoot: View, private val fm: FragmentManager) : BaseViewDelegate(vRoot) { // View's private val vLoad by findView<View>(R.id.v_load_indicator) private val vDrawer by findView<DrawerLayout>(R.id.root) private val vNavigation by findView<NavigationView>(R.id.v_navigation) private val vToolbar by findView<Toolbar>(R.id.v_toolbar) private val vTab by findView<TabLayout>(R.id.v_tab) private val cntPages by findView<ViewPager>(R.id.cnt_pager) // Adapter's private val carriageAdapter by lazy { CurrentCarriagePagerAdapter(fm, resource) } // Data's private var tempSelectItem: NavigationMenuItem? = null // Properties var isNavigationOpen: Boolean get() = vDrawer.isDrawerVisible(GravityCompat.START) set(value) = vDrawer.run { if (isNavigationOpen != value) { if (value) vDrawer.openDrawer(GravityCompat.START) else vDrawer.closeDrawer(GravityCompat.START) } } var isLoad: Boolean get() = vLoad.visible() set(value) = vLoad.visible(value) var currentCarriage: CurrentCarriageResponse? = null set(value) = carriageAdapter.run { currentCarriage = value notifyDataSetChanged() } // Listener's var onItemClick: ((NavigationMenuItem) -> Unit)? = null init { vTab.setupWithViewPager(cntPages) cntPages.run { adapter = carriageAdapter } // Listener's vDrawer.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerStateChanged(newState: Int) { /** Empty */ } override fun onDrawerSlide(drawerView: View?, slideOffset: Float) { /** Empty */ } override fun onDrawerOpened(drawerView: View?) { /** Empty */ } override fun onDrawerClosed(drawerView: View?) { tempSelectItem?.let { onItemClick?.invoke(it) } tempSelectItem = null } }) vNavigation.setNavigationItemSelectedListener { tempSelectItem = when (it.itemId) { R.id.action_home -> NavigationMenuItem.HOME R.id.action_history -> NavigationMenuItem.HISTORY R.id.action_user_info -> NavigationMenuItem.USER_INFO R.id.action_about -> NavigationMenuItem.ABOUT R.id.action_log_out -> NavigationMenuItem.LOG_OUT else -> return@setNavigationItemSelectedListener false } isNavigationOpen = false return@setNavigationItemSelectedListener true } vToolbar.setNavigationOnClickListener { isNavigationOpen = true } } } }
apache-2.0
87d55371a272f15fafd0bae21fc7ed78
37.459016
116
0.652977
4.770847
false
false
false
false
darkoverlordofdata/entitas-kotlin
entitas/src/main/java/com/darkoverlordofdata/entitas/Group.kt
1
4020
package com.darkoverlordofdata.entitas import java.util.* /** * * Use pool.GetGroup(matcher) to get a group of _entities which match the specified matcher. * Calling pool.GetGroup(matcher) with the same matcher will always return the same instance of the group. * The created group is managed by the pool and will always be up to date. * It will automatically add _entities that match the matcher or remove _entities as soon as they don't match the matcher anymore. */ class Group(matcher: IMatcher) { val count:Int get() = _entities.size val onEntityAdded = Event<GroupChangedArgs>() val onEntityRemoved = Event<GroupChangedArgs>() val onEntityUpdated = Event<GroupUpdatedArgs>() internal val matcher = matcher private var _entities: HashSet<Entity> = hashSetOf() private var _toStringCache = "" private var _entitiesCache: Array<Entity> = arrayOf() private var _singleEntityCache: Entity? = null /** * Custom Sort for Groups * * group.setSort({entities: Array<Entity> -> * entities.sortBy { e:Entity -> e.layer.ordinal } * }) * */ private var _sortEntities: ((entities: Array<Entity>) -> Unit) = {} val entities:Array<Entity> get() { if (_entitiesCache.size == 0) { _entitiesCache = _entities.toTypedArray() _sortEntities(_entitiesCache) } return _entitiesCache } val singleEntity: Entity? get() = entities.singleOrNull() fun createObserver(eventType: GroupEventType): GroupObserver { return GroupObserver(arrayOf(this), arrayOf(eventType)) } fun setSort(sorter: (entities: Array<Entity>)-> Unit) { _sortEntities = sorter } fun handleEntitySilently(entity: Entity) { if (matcher.matches(entity)) addEntitySilently(entity) else removeEntitySilently(entity) } fun handleEntity(entity: Entity, index:Int, component: IComponent) { if (matcher.matches(entity)) addEntity(entity, index, component) else removeEntity(entity, index, component) } fun updateEntity(entity: Entity, index:Int, previousComponent: IComponent, newComponent: IComponent?) { if (entity in _entities) { onEntityRemoved(GroupChangedArgs(this, entity, index, previousComponent)) onEntityAdded(GroupChangedArgs(this, entity, index, newComponent)) onEntityUpdated(GroupUpdatedArgs(this, entity, index, previousComponent, newComponent)) } } fun addEntitySilently(entity: Entity) { if (entity !in _entities) { _entities.add(entity) _entitiesCache = arrayOf() _toStringCache = "" entity.retain() } } fun addEntity(entity: Entity, index:Int, component: IComponent) { if (entity !in _entities) { _entities.add(entity) _entitiesCache = arrayOf() _toStringCache = "" entity.retain() onEntityAdded(GroupChangedArgs(this, entity, index, component)) } } fun removeEntitySilently(entity: Entity) { if (entity in _entities) { _entities.remove(entity) _entitiesCache = arrayOf() _singleEntityCache = null entity.release() } } fun removeEntity(entity: Entity, index:Int, component: IComponent) { if (entity in _entities) { _entities.remove(entity) _entitiesCache = arrayOf() _singleEntityCache = null onEntityRemoved(GroupChangedArgs(this, entity, index, component)) entity.release() } } fun containsEntity(entity: Entity):Boolean { return entity in _entities } override fun toString():String { if (_toStringCache == "") { _toStringCache = "Group(${matcher.toString()})" } return _toStringCache } }
mit
28279605215be8cdd96bf18af4bad3b6
30.661417
130
0.614179
4.562997
false
false
false
false
mobilesolutionworks/works-controller-android
test-app/src/androidTest/kotlin/com/mobilesolutionworks/android/controller/test/nested/NestedWorksFragmentTest.kt
1
5266
package com.mobilesolutionworks.android.controller.test.nested import android.support.test.espresso.Espresso.onView import android.support.test.espresso.Espresso.pressBack import android.support.test.espresso.UiController import android.support.test.espresso.action.ViewActions import android.support.test.espresso.matcher.ViewMatchers import android.support.test.espresso.matcher.ViewMatchers.isRoot import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import android.support.test.runner.lifecycle.Stage import android.view.Surface import android.view.View import com.linkedin.android.testbutler.TestButler import com.mobilesolutionworks.android.app.controller.WorksController import com.mobilesolutionworks.android.controller.test.R import com.mobilesolutionworks.android.controller.test.base.RotationTest import com.mobilesolutionworks.android.controller.test.util.HostAndController import com.mobilesolutionworks.android.controller.test.util.PerformRootAction import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.lang.ref.WeakReference import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Overview * <p> * As per support lib 25.1.0, {@link Fragment#setRetainInstance(boolean)} is now working on nested * fragment, however if the nested fragment is moved to back stack along with the parent after certain * configuration changes the nested fragment will be destroyed. * <p> * <p> * <ul> * <li>Test whether the behavior as per premise above is correct</li> * </ul> * Created by yunarta on 9/3/17. */ @RunWith(AndroidJUnit4::class) class NestedWorksFragmentTest : RotationTest() { @Rule @JvmField var mActivityTestRule = ActivityTestRule(RetainWorksControllerActivity::class.java) @Test @Throws(Exception::class) fun testControllerRetainBehavior() { // Context of the app under test. val activityHash = AtomicReference<Int>() val fragmentCheck = HostAndController<WorksController>() val nestedFragmentCheck = HostAndController<WorksController>() onView(isRoot()).perform(object : PerformRootAction() { override fun perform(uiController: UiController, view: View) { val resumedActivities = ArrayList(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) val activity = resumedActivities[0] as RetainWorksControllerActivity activityHash.set(System.identityHashCode(activity)) val root = activity.supportFragmentManager.findFragmentById(R.id.fragment_container) as EmptyWorksFragment fragmentCheck.set(root) val nested = root.childFragmentManager.findFragmentByTag("child") as EmptyWorksFragment nestedFragmentCheck.set(nested) } }) val addedFragmentWorksController = AtomicReference<WeakReference<WorksController>>() onView(ViewMatchers.withId(R.id.button)).perform(ViewActions.click()) onView(isRoot()).perform(object : PerformRootAction() { override fun perform(uiController: UiController, view: View) { val resumedActivities = ArrayList(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) val activity = resumedActivities[0] as RetainWorksControllerActivity assertNotSame("Could not change orientation", activityHash.get(), System.identityHashCode(activity)) val rootFragment = activity.supportFragmentManager.findFragmentById(R.id.fragment_container) as EmptyWorksFragment val controller = rootFragment.controller addedFragmentWorksController.set(WeakReference<WorksController>(controller)) } }) TestButler.setRotation(Surface.ROTATION_90) mLatch!!.await() TestButler.setRotation(Surface.ROTATION_0) mLatch!!.await() pressBack() TestButler.setRotation(Surface.ROTATION_90) mLatch!!.await() TestButler.setRotation(Surface.ROTATION_0) mLatch!!.await() Runtime.getRuntime().gc() assertNull(addedFragmentWorksController.get().get()) onView(isRoot()).perform(object : PerformRootAction() { override fun perform(uiController: UiController, view: View) { val resumedActivities = ArrayList(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) val activity = resumedActivities[0] as RetainWorksControllerActivity assertNotSame("Could not change orientation", activityHash.get(), System.identityHashCode(activity)) val root = activity.supportFragmentManager.findFragmentById(R.id.fragment_container) as EmptyWorksFragment fragmentCheck.validate(root) val nested = root.childFragmentManager.findFragmentByTag("child") as EmptyWorksFragment nestedFragmentCheck.validate(nested) } }) } }
apache-2.0
a1339f2402347cd2f59e1b545d652006
41.813008
133
0.733194
5.024809
false
true
false
false
square/picasso
picasso/src/main/java/com/squareup/picasso3/Dispatcher.kt
1
17541
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.picasso3 import android.Manifest.permission.ACCESS_NETWORK_STATE import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.Intent.ACTION_AIRPLANE_MODE_CHANGED import android.content.IntentFilter import android.net.ConnectivityManager import android.net.ConnectivityManager.CONNECTIVITY_ACTION import android.net.NetworkInfo import android.os.Handler import android.os.HandlerThread import android.os.Looper import android.os.Message import android.os.Process.THREAD_PRIORITY_BACKGROUND import android.util.Log import androidx.core.content.ContextCompat import com.squareup.picasso3.BitmapHunter.Companion.forRequest import com.squareup.picasso3.MemoryPolicy.Companion.shouldWriteToMemoryCache import com.squareup.picasso3.NetworkPolicy.NO_CACHE import com.squareup.picasso3.NetworkRequestHandler.ContentLengthException import com.squareup.picasso3.Picasso.Priority.HIGH import com.squareup.picasso3.RequestHandler.Result.Bitmap import com.squareup.picasso3.Utils.OWNER_DISPATCHER import com.squareup.picasso3.Utils.VERB_CANCELED import com.squareup.picasso3.Utils.VERB_DELIVERED import com.squareup.picasso3.Utils.VERB_ENQUEUED import com.squareup.picasso3.Utils.VERB_IGNORED import com.squareup.picasso3.Utils.VERB_PAUSED import com.squareup.picasso3.Utils.VERB_REPLAYING import com.squareup.picasso3.Utils.VERB_RETRYING import com.squareup.picasso3.Utils.flushStackLocalLeaks import com.squareup.picasso3.Utils.getLogIdsForHunter import com.squareup.picasso3.Utils.hasPermission import com.squareup.picasso3.Utils.isAirplaneModeOn import com.squareup.picasso3.Utils.log import java.util.WeakHashMap import java.util.concurrent.ExecutorService internal class Dispatcher internal constructor( private val context: Context, @get:JvmName("-service") internal val service: ExecutorService, private val mainThreadHandler: Handler, private val cache: PlatformLruCache ) { @get:JvmName("-hunterMap") internal val hunterMap = mutableMapOf<String, BitmapHunter>() @get:JvmName("-failedActions") internal val failedActions = WeakHashMap<Any, Action>() @get:JvmName("-pausedActions") internal val pausedActions = WeakHashMap<Any, Action>() @get:JvmName("-pausedTags") internal val pausedTags = mutableSetOf<Any>() @get:JvmName("-receiver") internal val receiver: NetworkBroadcastReceiver @get:JvmName("-airplaneMode") @set:JvmName("-airplaneMode") internal var airplaneMode = isAirplaneModeOn(context) private val dispatcherThread: DispatcherThread private val handler: Handler private val scansNetworkChanges: Boolean init { dispatcherThread = DispatcherThread() dispatcherThread.start() val dispatcherThreadLooper = dispatcherThread.looper flushStackLocalLeaks(dispatcherThreadLooper) handler = DispatcherHandler(dispatcherThreadLooper, this) scansNetworkChanges = hasPermission(context, ACCESS_NETWORK_STATE) receiver = NetworkBroadcastReceiver(this) receiver.register() } fun shutdown() { // Shutdown the thread pool only if it is the one created by Picasso. (service as? PicassoExecutorService)?.shutdown() dispatcherThread.quit() // Unregister network broadcast receiver on the main thread. Picasso.HANDLER.post { receiver.unregister() } } fun dispatchSubmit(action: Action) { handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action)) } fun dispatchCancel(action: Action) { handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL, action)) } fun dispatchPauseTag(tag: Any) { handler.sendMessage(handler.obtainMessage(TAG_PAUSE, tag)) } fun dispatchResumeTag(tag: Any) { handler.sendMessage(handler.obtainMessage(TAG_RESUME, tag)) } fun dispatchComplete(hunter: BitmapHunter) { handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter)) } fun dispatchRetry(hunter: BitmapHunter) { handler.sendMessageDelayed(handler.obtainMessage(HUNTER_RETRY, hunter), RETRY_DELAY) } fun dispatchFailed(hunter: BitmapHunter) { handler.sendMessage(handler.obtainMessage(HUNTER_DECODE_FAILED, hunter)) } fun dispatchNetworkStateChange(info: NetworkInfo) { handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info)) } fun dispatchAirplaneModeChange(airplaneMode: Boolean) { handler.sendMessage( handler.obtainMessage( AIRPLANE_MODE_CHANGE, if (airplaneMode) AIRPLANE_MODE_ON else AIRPLANE_MODE_OFF, 0 ) ) } fun performSubmit(action: Action, dismissFailed: Boolean = true) { if (action.tag in pausedTags) { pausedActions[action.getTarget()] = action if (action.picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_PAUSED, logId = action.request.logId(), extras = "because tag '${action.tag}' is paused" ) } return } var hunter = hunterMap[action.request.key] if (hunter != null) { hunter.attach(action) return } if (service.isShutdown) { if (action.picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_IGNORED, logId = action.request.logId(), extras = "because shut down" ) } return } hunter = forRequest(action.picasso, this, cache, action) hunter.future = service.submit(hunter) hunterMap[action.request.key] = hunter if (dismissFailed) { failedActions.remove(action.getTarget()) } if (action.picasso.isLoggingEnabled) { log(owner = OWNER_DISPATCHER, verb = VERB_ENQUEUED, logId = action.request.logId()) } } fun performCancel(action: Action) { val key = action.request.key val hunter = hunterMap[key] if (hunter != null) { hunter.detach(action) if (hunter.cancel()) { hunterMap.remove(key) if (action.picasso.isLoggingEnabled) { log(OWNER_DISPATCHER, VERB_CANCELED, action.request.logId()) } } } if (action.tag in pausedTags) { pausedActions.remove(action.getTarget()) if (action.picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_CANCELED, logId = action.request.logId(), extras = "because paused request got canceled" ) } } val remove = failedActions.remove(action.getTarget()) if (remove != null && remove.picasso.isLoggingEnabled) { log(OWNER_DISPATCHER, VERB_CANCELED, remove.request.logId(), "from replaying") } } fun performPauseTag(tag: Any) { // Trying to pause a tag that is already paused. if (!pausedTags.add(tag)) { return } // Go through all active hunters and detach/pause the requests // that have the paused tag. val iterator = hunterMap.values.iterator() while (iterator.hasNext()) { val hunter = iterator.next() val loggingEnabled = hunter.picasso.isLoggingEnabled val single = hunter.action val joined = hunter.actions val hasMultiple = !joined.isNullOrEmpty() // Hunter has no requests, bail early. if (single == null && !hasMultiple) { continue } if (single != null && single.tag == tag) { hunter.detach(single) pausedActions[single.getTarget()] = single if (loggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_PAUSED, logId = single.request.logId(), extras = "because tag '$tag' was paused" ) } } if (joined != null) { for (i in joined.indices.reversed()) { val action = joined[i] if (action.tag != tag) { continue } hunter.detach(action) pausedActions[action.getTarget()] = action if (loggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_PAUSED, logId = action.request.logId(), extras = "because tag '$tag' was paused" ) } } } // Check if the hunter can be cancelled in case all its requests // had the tag being paused here. if (hunter.cancel()) { iterator.remove() if (loggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_CANCELED, logId = getLogIdsForHunter(hunter), extras = "all actions paused" ) } } } } fun performResumeTag(tag: Any) { // Trying to resume a tag that is not paused. if (!pausedTags.remove(tag)) { return } val batch = mutableListOf<Action>() val iterator = pausedActions.values.iterator() while (iterator.hasNext()) { val action = iterator.next() if (action.tag == tag) { batch += action iterator.remove() } } if (batch.isNotEmpty()) { mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(REQUEST_BATCH_RESUME, batch)) } } @SuppressLint("MissingPermission") fun performRetry(hunter: BitmapHunter) { if (hunter.isCancelled) return if (service.isShutdown) { performError(hunter) return } var networkInfo: NetworkInfo? = null if (scansNetworkChanges) { val connectivityManager = ContextCompat.getSystemService(context, ConnectivityManager::class.java) if (connectivityManager != null) { networkInfo = connectivityManager.activeNetworkInfo } } if (hunter.shouldRetry(airplaneMode, networkInfo)) { if (hunter.picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_RETRYING, logId = getLogIdsForHunter(hunter) ) } if (hunter.exception is ContentLengthException) { hunter.data = hunter.data.newBuilder().networkPolicy(NO_CACHE).build() } hunter.future = service.submit(hunter) } else { performError(hunter) // Mark for replay only if we observe network info changes and support replay. if (scansNetworkChanges && hunter.supportsReplay()) { markForReplay(hunter) } } } fun performComplete(hunter: BitmapHunter) { if (shouldWriteToMemoryCache(hunter.data.memoryPolicy)) { val result = hunter.result if (result != null) { if (result is Bitmap) { val bitmap = result.bitmap cache[hunter.key] = bitmap } } } hunterMap.remove(hunter.key) deliver(hunter) } fun performError(hunter: BitmapHunter) { hunterMap.remove(hunter.key) deliver(hunter) } fun performAirplaneModeChange(airplaneMode: Boolean) { this.airplaneMode = airplaneMode } fun performNetworkStateChange(info: NetworkInfo?) { // Intentionally check only if isConnected() here before we flush out failed actions. if (info != null && info.isConnected) { flushFailedActions() } } private fun flushFailedActions() { if (failedActions.isNotEmpty()) { val iterator = failedActions.values.iterator() while (iterator.hasNext()) { val action = iterator.next() iterator.remove() if (action.picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_REPLAYING, logId = action.request.logId() ) } performSubmit(action, false) } } } private fun markForReplay(hunter: BitmapHunter) { val action = hunter.action action?.let { markForReplay(it) } val joined = hunter.actions if (joined != null) { for (i in joined.indices) { markForReplay(joined[i]) } } } private fun markForReplay(action: Action) { val target = action.getTarget() action.willReplay = true failedActions[target] = action } private fun deliver(hunter: BitmapHunter) { if (hunter.isCancelled) { return } val result = hunter.result if (result != null) { if (result is Bitmap) { val bitmap = result.bitmap bitmap.prepareToDraw() } } val message = mainThreadHandler.obtainMessage(HUNTER_COMPLETE, hunter) if (hunter.priority == HIGH) { mainThreadHandler.sendMessageAtFrontOfQueue(message) } else { mainThreadHandler.sendMessage(message) } logDelivery(hunter) } private fun logDelivery(bitmapHunter: BitmapHunter) { val picasso = bitmapHunter.picasso if (picasso.isLoggingEnabled) { log( owner = OWNER_DISPATCHER, verb = VERB_DELIVERED, logId = getLogIdsForHunter(bitmapHunter) ) } } private class DispatcherHandler( looper: Looper, private val dispatcher: Dispatcher ) : Handler(looper) { override fun handleMessage(msg: Message) { when (msg.what) { REQUEST_SUBMIT -> { val action = msg.obj as Action dispatcher.performSubmit(action) } REQUEST_CANCEL -> { val action = msg.obj as Action dispatcher.performCancel(action) } TAG_PAUSE -> { val tag = msg.obj dispatcher.performPauseTag(tag) } TAG_RESUME -> { val tag = msg.obj dispatcher.performResumeTag(tag) } HUNTER_COMPLETE -> { val hunter = msg.obj as BitmapHunter dispatcher.performComplete(hunter) } HUNTER_RETRY -> { val hunter = msg.obj as BitmapHunter dispatcher.performRetry(hunter) } HUNTER_DECODE_FAILED -> { val hunter = msg.obj as BitmapHunter dispatcher.performError(hunter) } NETWORK_STATE_CHANGE -> { val info = msg.obj as NetworkInfo dispatcher.performNetworkStateChange(info) } AIRPLANE_MODE_CHANGE -> { dispatcher.performAirplaneModeChange(msg.arg1 == AIRPLANE_MODE_ON) } else -> { Picasso.HANDLER.post { throw AssertionError("Unknown handler message received: ${msg.what}") } } } } } internal class DispatcherThread : HandlerThread( Utils.THREAD_PREFIX + DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND ) internal class NetworkBroadcastReceiver( private val dispatcher: Dispatcher ) : BroadcastReceiver() { fun register() { val filter = IntentFilter() filter.addAction(ACTION_AIRPLANE_MODE_CHANGED) if (dispatcher.scansNetworkChanges) { filter.addAction(CONNECTIVITY_ACTION) } dispatcher.context.registerReceiver(this, filter) } fun unregister() { dispatcher.context.unregisterReceiver(this) } @SuppressLint("MissingPermission") override fun onReceive(context: Context, intent: Intent?) { // On some versions of Android this may be called with a null Intent, // also without extras (getExtras() == null), in such case we use defaults. if (intent == null) { return } when (intent.action) { ACTION_AIRPLANE_MODE_CHANGED -> { if (!intent.hasExtra(EXTRA_AIRPLANE_STATE)) { return // No airplane state, ignore it. Should we query Utils.isAirplaneModeOn? } dispatcher.dispatchAirplaneModeChange(intent.getBooleanExtra(EXTRA_AIRPLANE_STATE, false)) } CONNECTIVITY_ACTION -> { val connectivityManager = ContextCompat.getSystemService(context, ConnectivityManager::class.java) val networkInfo = try { connectivityManager!!.activeNetworkInfo } catch (re: RuntimeException) { Log.w(TAG, "System UI crashed, ignoring attempt to change network state.") return } if (networkInfo == null) { Log.w( TAG, "No default network is currently active, ignoring attempt to change network state." ) return } dispatcher.dispatchNetworkStateChange(networkInfo) } } } internal companion object { const val EXTRA_AIRPLANE_STATE = "state" } } internal companion object { private const val RETRY_DELAY = 500L private const val AIRPLANE_MODE_ON = 1 private const val AIRPLANE_MODE_OFF = 0 private const val REQUEST_SUBMIT = 1 private const val REQUEST_CANCEL = 2 const val HUNTER_COMPLETE = 4 private const val HUNTER_RETRY = 5 private const val HUNTER_DECODE_FAILED = 6 const val NETWORK_STATE_CHANGE = 9 private const val AIRPLANE_MODE_CHANGE = 10 private const val TAG_PAUSE = 11 private const val TAG_RESUME = 12 const val REQUEST_BATCH_RESUME = 13 private const val DISPATCHER_THREAD_NAME = "Dispatcher" } }
apache-2.0
2c1e87d54e603d502fd8221d7d129fed
29.453125
100
0.655094
4.324704
false
false
false
false
GunoH/intellij-community
platform/util/src/com/intellij/util/io/writeAheadLog.kt
4
18875
// 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.util.io import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.io.ByteArraySequence import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.CompressionUtil import com.intellij.util.ConcurrencyUtil import com.intellij.util.indexing.impl.IndexStorageUtil import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet import it.unimi.dsi.fastutil.ints.IntSet import org.apache.commons.compress.utils.IOUtils import java.io.* import java.nio.file.FileAlreadyExistsException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.concurrent.ExecutorService import java.util.function.Function import java.util.zip.CRC32 import java.util.zip.CheckedInputStream import java.util.zip.CheckedOutputStream import java.util.zip.Checksum private const val VERSION = 0 internal enum class WalOpCode(internal val code: Int) { PUT(0), REMOVE(1), APPEND(2); companion object { val size = values().size } } private val checksumGen = { CRC32() } @Volatile var debugWalRecords = false private val log = logger<WalRecord>() private class CorruptionException(val reason: String): IOException(reason) private class EndOfLog: IOException() internal class PersistentEnumeratorWal<Data> @Throws(IOException::class) @JvmOverloads constructor(dataDescriptor: KeyDescriptor<Data>, useCompression: Boolean, file: Path, walIoExecutor: ExecutorService, compact: Boolean = false) : Closeable { private val underlying = PersistentMapWal(dataDescriptor, integerExternalizer, useCompression, file, walIoExecutor, compact) fun enumerate(data: Data, id: Int) = underlying.put(data, id) fun flush() = underlying.flush() override fun close() = underlying.close() } internal class PersistentMapWal<K, V> @Throws(IOException::class) @JvmOverloads constructor(private val keyDescriptor: KeyDescriptor<K>, private val valueExternalizer: DataExternalizer<V>, private val useCompression: Boolean, private val file: Path, private val walIoExecutor: ExecutorService /*todo ensure sequential*/, compact: Boolean = false) : Closeable { private val out: DataOutputStream val version: Int = VERSION init { if (compact) { tryCompact(file, keyDescriptor, valueExternalizer)?.let { compactedWal -> FileUtil.deleteWithRenaming(file) FileUtil.rename(compactedWal.toFile(), file.toFile()) } } ensureCompatible(version, useCompression, file) out = DataOutputStream(Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND).buffered()) } @Throws(IOException::class) private fun ensureCompatible(expectedVersion: Int, useCompression: Boolean, file: Path) { if (!Files.exists(file)) { Files.createDirectories(file.parent) DataOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)).use { DataInputOutputUtil.writeINT(it, expectedVersion) it.writeBoolean(useCompression) } return } val (actualVersion, actualUsesCompression) = DataInputStream(Files.newInputStream(file, StandardOpenOption.READ)).use { DataInputOutputUtil.readINT(it) to it.readBoolean() } if (actualVersion != expectedVersion) { throw VersionUpdatedException(file, expectedVersion, actualVersion) } if (actualUsesCompression != useCompression) { throw VersionUpdatedException(file, useCompression, actualUsesCompression) } } private fun ByteArray.write(outputStream: DataOutputStream) { if (useCompression) { CompressionUtil.writeCompressed(outputStream, this, 0, size) } else { outputStream.writeInt(size) outputStream.write(this) } } private fun AppendablePersistentMap.ValueDataAppender.writeToByteArray(): ByteArray { val baos = UnsyncByteArrayOutputStream() append(DataOutputStream(baos)) return baos.toByteArray() } private fun appendRecord(key: K, appender: AppendablePersistentMap.ValueDataAppender) = WalRecord.writeRecord(WalOpCode.APPEND) { keyDescriptor.save(it, key) appender.writeToByteArray().write(it) } private fun putRecord(key: K, value: V) = WalRecord.writeRecord(WalOpCode.PUT) { keyDescriptor.save(it, key) writeData(value, valueExternalizer).write(it) } private fun removeRecord(key: K) = WalRecord.writeRecord(WalOpCode.REMOVE) { keyDescriptor.save(it, key) } private fun WalRecord.submitWrite() { walIoExecutor.submit { if (debugWalRecords) { println("write: $this") } this.write(out) } } @Throws(IOException::class) fun appendData(key: K, appender: AppendablePersistentMap.ValueDataAppender) { appendRecord(key, appender).submitWrite() } @Throws(IOException::class) fun put(key: K, value: V) { putRecord(key, value).submitWrite() } @Throws(IOException::class) fun remove(key: K) { removeRecord(key).submitWrite() } @Throws(IOException::class) // todo rethrow io exception fun flush() { walIoExecutor.submit { out.flush() }.get() } // todo rethrow io exception @Throws(IOException::class) override fun close() { walIoExecutor.submit { out.close() }.get() } @Throws(IOException::class) fun closeAndDelete() { close() FileUtil.deleteWithRenaming(file) } } private val integerExternalizer: EnumeratorIntegerDescriptor get() = EnumeratorIntegerDescriptor.INSTANCE sealed class WalEvent<K, V> { abstract val key: K data class PutEvent<K, V>(override val key: K, val value: V): WalEvent<K, V>() data class RemoveEvent<K, V>(override val key: K): WalEvent<K, V>() data class AppendEvent<K, V>(override val key: K, val data: ByteArray): WalEvent<K, V>() { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AppendEvent<*, *> if (key != other.key) return false if (!data.contentEquals(other.data)) return false return true } override fun hashCode(): Int { var result = key?.hashCode() ?: 0 result = 31 * result + data.contentHashCode() return result } } object CorruptionEvent: WalEvent<Nothing, Nothing>() { override val key: Nothing get() = throw UnsupportedOperationException() } } @Throws(IOException::class) fun <Data> restoreMemoryEnumeratorFromWal(walFile: Path, dataDescriptor: KeyDescriptor<Data>): List<Data> { return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, List<Data>> { val result = arrayListOf<Data>() override fun get(key: Data): Int = error("get not supported") override fun remove(key: Data) = error("remove not supported") override fun put(key: Data, value: Int) { assert(result.size == value) result.add(key) } override fun result(): List<Data> = result }).toList() } @Throws(IOException::class) fun <Data> restorePersistentEnumeratorFromWal(walFile: Path, outputMapFile: Path, dataDescriptor: KeyDescriptor<Data>): PersistentEnumerator<Data> { if (Files.exists(outputMapFile)) { throw FileAlreadyExistsException(outputMapFile.toString()) } return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, PersistentEnumerator<Data>> { val result = PersistentEnumerator(outputMapFile, dataDescriptor, 1024) override fun get(key: Data): Int = error("get not supported") override fun remove(key: Data) = error("remove not supported") override fun put(key: Data, value: Int) = assert(result.enumerate(key) == value) override fun result(): PersistentEnumerator<Data> = result }) } @Throws(IOException::class) fun <K, V> restorePersistentMapFromWal(walFile: Path, outputMapFile: Path, keyDescriptor: KeyDescriptor<K>, valueExternalizer: DataExternalizer<V>): PersistentMap<K, V> { if (Files.exists(outputMapFile)) { throw FileAlreadyExistsException(outputMapFile.toString()) } return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, PersistentMap<K, V>> { val result = PersistentHashMap(outputMapFile, keyDescriptor, valueExternalizer) override fun get(key: K): V? = result.get(key) override fun remove(key: K) = result.remove(key) override fun put(key: K, value: V) = result.put(key, value) override fun result(): PersistentMap<K, V> = result }) } @Throws(IOException::class) fun <K, V> restoreHashMapFromWal(walFile: Path, keyDescriptor: KeyDescriptor<K>, valueExternalizer: DataExternalizer<V>): Map<K, V> { return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, Map<K, V>> { private val map = linkedMapOf<K, V>() override fun get(key: K): V? = map.get(key) override fun remove(key: K) { map.remove(key) } override fun put(key: K, value: V) { map.put(key, value) } override fun result(): Map<K, V> = map }) } private fun <K, V> tryCompact(walFile: Path, keyDescriptor: KeyDescriptor<K>, valueExternalizer: DataExternalizer<V>): Path? { if (!Files.exists(walFile)) { return null } val keyToLastEvent = IndexStorageUtil.createKeyDescriptorHashedMap<K, IntSet>(keyDescriptor) val shouldCompact = PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { var eventCount = 0 for (walEvent in it.readWal()) { when (walEvent) { is WalEvent.AppendEvent -> keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount) is WalEvent.PutEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet().also{ set -> set.add(eventCount) }) is WalEvent.RemoveEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet()) is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted") } keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount) eventCount++ } keyToLastEvent.size * 2 < eventCount } if (!shouldCompact) return null val compactedWalFile = walFile.resolveSibling("${walFile.fileName}_compacted") PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { walPlayer -> PersistentMapWal(keyDescriptor, valueExternalizer, walPlayer.useCompression, compactedWalFile, ConcurrencyUtil.newSameThreadExecutorService()).use { compactedWal -> walPlayer.readWal().forEachIndexed{index, walEvent -> val key = walEvent.key val events = keyToLastEvent.get(key) ?: throw IOException("No events found for key = $key") if (events.contains(index)) { when (walEvent) { is WalEvent.AppendEvent -> compactedWal.appendData(key, AppendablePersistentMap.ValueDataAppender { out -> out.write(walEvent.data) }) is WalEvent.PutEvent -> compactedWal.put(key, walEvent.value) is WalEvent.RemoveEvent -> {/*do nothing*/} is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted") } } } } } return compactedWalFile } private class ChecksumOutputStream(delegate: OutputStream, checksumGen: () -> Checksum): CheckedOutputStream(delegate, checksumGen()) { fun checksum() = checksum.value } private class ChecksumInputStream(delegate: InputStream, checksumGen: () -> Checksum): CheckedInputStream(delegate, checksumGen()) { fun checksum() = checksum.value } /** * +-------------+---------------+---------------------+---------+ * | OpCode (1b) | Checksum (8b) | Payload Length (4b) | Payload | * +-------------+---------------+---------------------+---------+ * * TODO it makes sense to add header for each record */ private class WalRecord(val opCode: WalOpCode, private val checksum: Long, val payload: ByteArraySequence) { override fun toString(): String { return "record($opCode, checksum = $checksum, len = ${payload.length()}, payload = ${StringUtil.toHexString(payload.toBytes())})" } @Throws(IOException::class) fun write(target: DataOutputStream) { target.writeByte(opCode.code) DataInputOutputUtil.writeLONG(target, checksum) DataInputOutputUtil.writeINT(target, payload.length) target.write(payload.internalBuffer, payload.offset, payload.length) } companion object { @Throws(IOException::class) fun writeRecord(opCode: WalOpCode, writer: (DataOutputStream) -> Unit): WalRecord { val baos = UnsyncByteArrayOutputStream() val cos = ChecksumOutputStream(baos, checksumGen) DataOutputStream(cos).use { writer(it) } return WalRecord(opCode, cos.checksum(), baos.toByteArraySequence()) } @Throws(IOException::class) fun read(input: DataInputStream): WalRecord { val code: Int try { code = input.readByte().toInt() } catch (e: EOFException) { throw EndOfLog() } if (code >= WalOpCode.size) { throw CorruptionException("no opcode present for code $code") } val checksum = DataInputOutputUtil.readLONG(input) val payloadLength = DataInputOutputUtil.readINT(input) val cis = ChecksumInputStream(input, checksumGen) val data = IOUtils.readRange(cis, payloadLength) val actualChecksum = cis.checksum() if (actualChecksum != checksum) { throw CorruptionException("checksum is wrong for log record: expected = $checksum but actual = $actualChecksum") } return WalRecord(WalOpCode.values()[code], checksum, ByteArraySequence(data)) } } } private fun <V> readData(array: ByteArray, valueExternalizer: DataExternalizer<V>): V { return valueExternalizer.read(DataInputStream(ByteArrayInputStream(array))) } private fun <V> writeData(value: V, valueExternalizer: DataExternalizer<V>): ByteArray { val baos = UnsyncByteArrayOutputStream() valueExternalizer.save(DataOutputStream(baos), value) return baos.toByteArray() } private interface Accumulator<K, V, R> { fun get(key: K): V? fun remove(key: K) fun put(key: K, value: V) fun result(): R } private fun <K, V, R> restoreFromWal(walFile: Path, keyDescriptor: KeyDescriptor<K>, valueExternalizer: DataExternalizer<V>, accumulator: Accumulator<K, V, R>): R { return PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { for (walEvent in it.readWal()) { when (walEvent) { is WalEvent.AppendEvent -> { val previous = accumulator.get(walEvent.key) val currentData = if (previous == null) walEvent.data else writeData(previous, valueExternalizer) + walEvent.data accumulator.put(walEvent.key, readData(currentData, valueExternalizer)) } is WalEvent.PutEvent -> accumulator.put(walEvent.key, walEvent.value) is WalEvent.RemoveEvent -> accumulator.remove(walEvent.key) is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted") } } accumulator.result() } } class PersistentMapWalPlayer<K, V> @Throws(IOException::class) constructor(private val keyDescriptor: KeyDescriptor<K>, private val valueExternalizer: DataExternalizer<V>, file: Path) : Closeable { private val input: DataInputStream internal val useCompression: Boolean val version: Int = VERSION init { if (!Files.exists(file)) { throw FileNotFoundException(file.toString()) } input = DataInputStream(Files.newInputStream(file).buffered()) ensureCompatible(version, input, file) useCompression = input.readBoolean() } @Throws(IOException::class) private fun ensureCompatible(expectedVersion: Int, input: DataInputStream, file: Path) { val actualVersion = DataInputOutputUtil.readINT(input) if (actualVersion != expectedVersion) { throw VersionUpdatedException(file, expectedVersion, actualVersion) } } fun readWal(): Sequence<WalEvent<K, V>> = generateSequence { readNextEvent() } @Throws(IOException::class) override fun close() = input.close() @Throws(IOException::class) private fun readNextEvent(): WalEvent<K, V>? { val record: WalRecord try { record = WalRecord.read(input) } catch (e: EndOfLog) { return null } catch (e: IOException) { return WalEvent.CorruptionEvent as WalEvent<K, V> } if (debugWalRecords) { println("read: $record") } val recordStream = record.payload.toInputStream() return when (record.opCode) { WalOpCode.PUT -> WalEvent.PutEvent(keyDescriptor.read(recordStream), readData(readByteArray(recordStream), valueExternalizer)) WalOpCode.REMOVE -> WalEvent.RemoveEvent(keyDescriptor.read(recordStream)) WalOpCode.APPEND -> WalEvent.AppendEvent(keyDescriptor.read(recordStream), readByteArray(recordStream)) } } private fun readByteArray(inputStream: DataInputStream): ByteArray { if (useCompression) { return CompressionUtil.readCompressed(inputStream) } else { return ByteArray(inputStream.readInt()).also { inputStream.readFully(it) } } } }
apache-2.0
4e9698b525dd87d8a70c806384a56847
35.723735
168
0.651762
4.831072
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/StorageIndexes.kt
2
13461
// 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.HashBiMap import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.indices.EntityStorageInternalIndex import com.intellij.workspaceModel.storage.impl.indices.MultimapStorageIndex import com.intellij.workspaceModel.storage.impl.indices.SymbolicIdInternalIndex import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY internal open class StorageIndexes( // List of IDs of entities that use this particular persistent id internal open val softLinks: MultimapStorageIndex, internal open val virtualFileIndex: VirtualFileIndex, internal open val entitySourceIndex: EntityStorageInternalIndex<EntitySource>, internal open val symbolicIdIndex: SymbolicIdInternalIndex, internal open val externalMappings: Map<String, ExternalEntityMappingImpl<*>> ) { constructor(softLinks: MultimapStorageIndex, virtualFileIndex: VirtualFileIndex, entitySourceIndex: EntityStorageInternalIndex<EntitySource>, symbolicIdIndex: SymbolicIdInternalIndex ) : this(softLinks, virtualFileIndex, entitySourceIndex, symbolicIdIndex, emptyMap()) companion object { val EMPTY = StorageIndexes(MultimapStorageIndex(), VirtualFileIndex(), EntityStorageInternalIndex(false), SymbolicIdInternalIndex(), HashMap()) } fun toMutable(): MutableStorageIndexes { val copiedSoftLinks = MultimapStorageIndex.MutableMultimapStorageIndex.from(softLinks) val copiedVirtualFileIndex = VirtualFileIndex.MutableVirtualFileIndex.from(virtualFileIndex) val copiedEntitySourceIndex = EntityStorageInternalIndex.MutableEntityStorageInternalIndex.from(entitySourceIndex) val copiedSymbolicIdIndex = SymbolicIdInternalIndex.MutableSymbolicIdInternalIndex.from(symbolicIdIndex) val copiedExternalMappings = MutableExternalEntityMappingImpl.fromMap(externalMappings) return MutableStorageIndexes(copiedSoftLinks, copiedVirtualFileIndex, copiedEntitySourceIndex, copiedSymbolicIdIndex, copiedExternalMappings) } fun assertConsistency(storage: AbstractEntityStorage) { assertEntitySourceIndex(storage) assertSymbolicIdIndex(storage) // TODO Should we get this back? // assertSoftLinksIndex(storage) virtualFileIndex.assertConsistency() // Assert external mappings for ((_, mappings) in externalMappings) { for ((id, _) in mappings.index) { assert(storage.entityDataById(id) != null) { "Missing entity by id: $id" } } } } /* private fun assertSoftLinksIndex(storage: AbstractEntityStorage) { // XXX skipped size check storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed if (family.entities.firstOrNull { it != null } !is SoftLinkable) return@forEachIndexed var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedLinks = softLinks.getEntriesById(mutableId) if (data is ModuleEntityData) { assertModuleSoftLinks(data, expectedLinks) } else { val actualLinks = (data as SoftLinkable).getLinks() assert(expectedLinks.size == actualLinks.size) { "Different sizes: $expectedLinks, $actualLinks" } assert(expectedLinks.all { it in actualLinks }) { "Different sets: $expectedLinks, $actualLinks" } } } } } */ // XXX: Hack to speed up module links assertion /* private fun assertModuleSoftLinks(entityData: ModuleEntityData, expectedLinks: Set<PersistentEntityId<*>>) { val actualRefs = HashSet<Any>(entityData.dependencies.size) entityData.dependencies.forEach { dependency -> when (dependency) { is ModuleDependencyItem.Exportable.ModuleDependency -> { assert(dependency.module in expectedLinks) actualRefs += dependency.module } is ModuleDependencyItem.Exportable.LibraryDependency -> { assert(dependency.library in expectedLinks) actualRefs += dependency.library } else -> Unit } } assert(actualRefs.size == expectedLinks.size) } */ private fun assertSymbolicIdIndex(storage: AbstractEntityStorage) { var expectedSize = 0 storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed if (family.entities.firstOrNull { it != null }?.symbolicId() == null) return@forEachIndexed var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedSymbolicId = symbolicIdIndex.getEntryById(mutableId) assert(expectedSymbolicId == data.symbolicId()) { "Entity $data isn't found in persistent id index. SymbolicId: ${data.symbolicId()}, Id: $mutableId. Expected entity source: $expectedSymbolicId" } expectedSize++ } } assert(expectedSize == symbolicIdIndex.index.size) { "Incorrect size of symbolic id index. Expected: $expectedSize, actual: ${symbolicIdIndex.index.size}" } } private fun assertEntitySourceIndex(storage: AbstractEntityStorage) { var expectedSize = 0 storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed // Optimization to skip useless conversion of classes var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedEntitySource = entitySourceIndex.getEntryById(mutableId) assert(expectedEntitySource == data.entitySource) { "Entity $data isn't found in entity source index. Entity source: ${data.entitySource}, Id: $mutableId. Expected entity source: $expectedEntitySource" } expectedSize++ } } assert(expectedSize == entitySourceIndex.index.size) { "Incorrect size of entity source index. Expected: $expectedSize, actual: ${entitySourceIndex.index.size}" } } } internal class MutableStorageIndexes( override val softLinks: MultimapStorageIndex.MutableMultimapStorageIndex, override val virtualFileIndex: VirtualFileIndex.MutableVirtualFileIndex, override val entitySourceIndex: EntityStorageInternalIndex.MutableEntityStorageInternalIndex<EntitySource>, override val symbolicIdIndex: SymbolicIdInternalIndex.MutableSymbolicIdInternalIndex, override val externalMappings: MutableMap<String, MutableExternalEntityMappingImpl<*>> ) : StorageIndexes(softLinks, virtualFileIndex, entitySourceIndex, symbolicIdIndex, externalMappings) { fun <T : WorkspaceEntity> entityAdded(entityData: WorkspaceEntityData<T>) { val pid = entityData.createEntityId() // Update soft links index if (entityData is SoftLinkable) { entityData.index(softLinks) } val entitySource = entityData.entitySource entitySourceIndex.index(pid, entitySource) entityData.symbolicId()?.let { symbolicId -> symbolicIdIndex.index(pid, symbolicId) } entitySource.virtualFileUrl?.let { virtualFileIndex.index(pid, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) } } fun entityRemoved(entityId: EntityId) { entitySourceIndex.index(entityId) symbolicIdIndex.index(entityId) virtualFileIndex.removeRecordsByEntityId(entityId) externalMappings.values.forEach { it.remove(entityId) } } fun updateSoftLinksIndex(softLinkable: SoftLinkable) { softLinkable.index(softLinks) } fun removeFromSoftLinksIndex(softLinkable: SoftLinkable) { val pid = (softLinkable as WorkspaceEntityData<*>).createEntityId() for (link in softLinkable.getLinks()) { softLinks.remove(pid, link) } } fun updateIndices(oldEntityId: EntityId, newEntityData: WorkspaceEntityData<*>, builder: AbstractEntityStorage) { val newEntityId = newEntityData.createEntityId() virtualFileIndex.updateIndex(oldEntityId, newEntityId, builder.indexes.virtualFileIndex) entitySourceIndex.index(newEntityId, newEntityData.entitySource) builder.indexes.symbolicIdIndex.getEntryById(oldEntityId)?.also { symbolicIdIndex.index(newEntityId, it) } } private fun <T : WorkspaceEntity> simpleUpdateSoftReferences(copiedData: WorkspaceEntityData<T>, modifiableEntity: ModifiableWorkspaceEntityBase<*, *>?) { val pid = copiedData.createEntityId() if (copiedData is SoftLinkable) { // if (modifiableEntity is ModifiableModuleEntity && !modifiableEntity.dependencyChanged) return // if (modifiableEntity is ModifiableModuleEntity) return copiedData.updateLinksIndex(this.softLinks.getEntriesById(pid), this.softLinks) } } fun applyExternalMappingChanges(diff: MutableEntityStorageImpl, replaceMap: HashBiMap<NotThisEntityId, ThisEntityId>, target: MutableEntityStorageImpl) { diff.indexes.externalMappings.keys.asSequence().filterNot { it in externalMappings.keys }.forEach { externalMappings[it] = MutableExternalEntityMappingImpl<Any>() } diff.indexes.externalMappings.forEach { (identifier, index) -> val mapping = externalMappings[identifier] if (mapping != null) { mapping.applyChanges(index, replaceMap, target) if (mapping.index.isEmpty()) { externalMappings.remove(identifier) } } } } @Suppress("UNCHECKED_CAST") fun updateExternalMappingForEntityId(replaceWithEntityId: EntityId, targetEntityId: EntityId, replaceWithIndexes: StorageIndexes) { replaceWithIndexes.externalMappings.forEach { (mappingId, mapping) -> val data = mapping.index[replaceWithEntityId] ?: return@forEach val externalMapping = externalMappings[mappingId] if (externalMapping == null) { val newMapping = MutableExternalEntityMappingImpl<Any>() newMapping.add(targetEntityId, data) externalMappings[mappingId] = newMapping } else { externalMapping as MutableExternalEntityMappingImpl<Any> externalMapping.add(targetEntityId, data) } } } fun <T : WorkspaceEntity> updateSymbolicIdIndexes(builder: MutableEntityStorageImpl, updatedEntity: WorkspaceEntity, beforeSymbolicId: SymbolicEntityId<*>?, copiedData: WorkspaceEntityData<T>, modifiableEntity: ModifiableWorkspaceEntityBase<*, *>? = null) { val entityId = (updatedEntity as WorkspaceEntityBase).id if (updatedEntity is WorkspaceEntityWithSymbolicId) { val newSymbolicId = updatedEntity.symbolicId if (beforeSymbolicId != null && beforeSymbolicId != newSymbolicId) { symbolicIdIndex.index(entityId, newSymbolicId) updateComposedIds(builder, beforeSymbolicId, newSymbolicId) } } simpleUpdateSoftReferences(copiedData, modifiableEntity) } private fun updateComposedIds(builder: MutableEntityStorageImpl, beforeSymbolicId: SymbolicEntityId<*>, newSymbolicId: SymbolicEntityId<*>) { val idsWithSoftRef = HashSet(this.softLinks.getIdsByEntry(beforeSymbolicId)) for (entityId in idsWithSoftRef) { val originalEntityData = builder.getOriginalEntityData(entityId) as WorkspaceEntityData<WorkspaceEntity> val originalParentsData = builder.getOriginalParents(entityId.asChild()) val entity = builder.entitiesByType.getEntityDataForModification(entityId) as WorkspaceEntityData<WorkspaceEntity> val editingBeforeSymbolicId = entity.symbolicId() (entity as SoftLinkable).updateLink(beforeSymbolicId, newSymbolicId) // Add an entry to changelog builder.changeLog.addReplaceEvent(entityId, entity, originalEntityData, originalParentsData, emptyList(), emptySet(), emptyMap()) // TODO :: Avoid updating of all soft links for the dependent entity builder.indexes.updateSymbolicIdIndexes(builder, entity.createEntity(builder), editingBeforeSymbolicId, entity) } } fun removeExternalMapping(identifier: String) { externalMappings[identifier]?.clearMapping() } fun toImmutable(): StorageIndexes { val copiedLinks = this.softLinks.toImmutable() val newVirtualFileIndex = virtualFileIndex.toImmutable() val newEntitySourceIndex = entitySourceIndex.toImmutable() val newSymbolicIdIndex = symbolicIdIndex.toImmutable() val newExternalMappings = MutableExternalEntityMappingImpl.toImmutable(externalMappings) return StorageIndexes(copiedLinks, newVirtualFileIndex, newEntitySourceIndex, newSymbolicIdIndex, newExternalMappings) } }
apache-2.0
b666bcdeba51025a6455ddd33cd66fa8
45.417241
211
0.731446
5.421265
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/permissions/PermissionsSettingsViewModel.kt
2
2911
package org.thoughtcrime.securesms.components.settings.conversation.permissions import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.thoughtcrime.securesms.groups.GroupAccessControl import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.groups.LiveGroup import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.livedata.Store class PermissionsSettingsViewModel( private val groupId: GroupId, private val repository: PermissionsSettingsRepository ) : ViewModel() { private val store = Store(PermissionsSettingsState()) private val liveGroup = LiveGroup(groupId) private val internalEvents = SingleLiveEvent<PermissionsSettingsEvents>() val state: LiveData<PermissionsSettingsState> = store.stateLiveData val events: LiveData<PermissionsSettingsEvents> = internalEvents init { store.update(liveGroup.isSelfAdmin) { isSelfAdmin, state -> state.copy(selfCanEditSettings = isSelfAdmin) } store.update(liveGroup.membershipAdditionAccessControl) { membershipAdditionAccessControl, state -> state.copy(nonAdminCanAddMembers = membershipAdditionAccessControl == GroupAccessControl.ALL_MEMBERS) } store.update(liveGroup.attributesAccessControl) { attributesAccessControl, state -> state.copy(nonAdminCanEditGroupInfo = attributesAccessControl == GroupAccessControl.ALL_MEMBERS) } store.update(liveGroup.isAnnouncementGroup) { isAnnouncementGroup, state -> state.copy(announcementGroup = isAnnouncementGroup) } } fun setNonAdminCanAddMembers(nonAdminCanAddMembers: Boolean) { repository.applyMembershipRightsChange(groupId, nonAdminCanAddMembers.asGroupAccessControl()) { reason -> internalEvents.postValue(PermissionsSettingsEvents.GroupChangeError(reason)) } } fun setNonAdminCanEditGroupInfo(nonAdminCanEditGroupInfo: Boolean) { repository.applyAttributesRightsChange(groupId, nonAdminCanEditGroupInfo.asGroupAccessControl()) { reason -> internalEvents.postValue(PermissionsSettingsEvents.GroupChangeError(reason)) } } fun setAnnouncementGroup(announcementGroup: Boolean) { repository.applyAnnouncementGroupChange(groupId, announcementGroup) { reason -> internalEvents.postValue(PermissionsSettingsEvents.GroupChangeError(reason)) } } private fun Boolean.asGroupAccessControl(): GroupAccessControl { return if (this) { GroupAccessControl.ALL_MEMBERS } else { GroupAccessControl.ONLY_ADMINS } } class Factory( private val groupId: GroupId, private val repository: PermissionsSettingsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return requireNotNull(modelClass.cast(PermissionsSettingsViewModel(groupId, repository))) } } }
gpl-3.0
562cf9f1d56d9ecf3e6644b71f9e2f74
37.302632
112
0.789763
4.65016
false
false
false
false
jimandreas/BottomNavigationView-plus-LeakCanary
app/src/main/java/com/jimandreas/android/designlibdemo/StateChangeHandler.kt
2
1988
package com.jimandreas.android.designlibdemo import android.app.Activity import android.content.Intent import android.os.Handler import android.os.HandlerThread import android.view.MenuItem import androidx.os.postDelayed fun handleStateChange(activity: Activity, item: MenuItem) { val handlerThread = HandlerThread("handler-test") lateinit var handler: Handler handlerThread.start() handler = Handler(handlerThread.looper) lateinit var intent: Intent handler.postDelayed(200) { val id = item.itemId with(activity) { when (id) { R.id.action_info -> { intent = Intent(activity, MainActivityKotlin::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } R.id.action_leak1 -> { intent = Intent(activity, Leak1TestActivity::class.java) intent.putExtra(Leak1TestActivity.EXTRA_NAME, "Leak1") intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } R.id.action_leak2 -> { intent = Intent(activity, Leak2TestActivity::class.java) intent.putExtra(Leak2TestActivity.EXTRA_NAME, "Leak2") intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } R.id.action_cheeses -> { intent = Intent(activity, CheesesActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } R.id.action_settings -> { intent = Intent(activity, SettingsActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } } } } }
apache-2.0
b3e628fbc0c70b1167f9be8a327233d7
37.230769
77
0.56338
4.884521
false
true
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/data/status/retrofit/StatusConverterFactory.kt
1
1321
package org.dvbviewer.controller.data.status.retrofit import com.google.gson.reflect.TypeToken import okhttp3.RequestBody import okhttp3.ResponseBody import org.dvbviewer.controller.data.entities.Status import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type class StatusConverterFactory private constructor() : Converter.Factory() { private val statusType: Type init { val typeToken = TypeToken.get(Status::class.java) statusType = typeToken.type } override fun responseBodyConverter(type: Type, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, Status>? { return if (type == statusType) { StatusPresetResponseBodyConverter() } else null } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>?, methodAnnotations: Array<Annotation>?, retrofit: Retrofit?): Converter<Status, RequestBody>? { return if (type == statusType) { StatusRequestBodyConverter() } else null } companion object { /** Create an instance conversion. */ fun create(): StatusConverterFactory { return StatusConverterFactory() } } }
apache-2.0
2587a0c0322220a0d09aa383b33ae213
29.744186
174
0.663134
5.242063
false
false
false
false
linkedin/LiTr
litr/src/main/java/com/linkedin/android/litr/render/GlTexture.kt
1
2921
/* * MIT License * * Copyright (c) 2019 Mattia Iavarone * Copyright (c) 2021 LinkedIn Corporation * * 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. */ // modified from: https://github.com/natario1/Egloo package com.linkedin.android.litr.render import android.opengl.GLES20 class GlTexture @JvmOverloads constructor( val unit: Int = GLES20.GL_TEXTURE0, val target: Int = GLES20.GL_TEXTURE_2D, id: Int? = null, val width: Int = 0, val height: Int = 0 ) { val texName: Int = if (id == null) { val textures = IntArray(1) GLES20.glGenTextures(1, textures, 0) textures[0] } else { id } init { GLES20.glBindTexture(target, texName) GlRenderUtils.checkGlError("glBindTexture GlTexture") if (width > 0 && height > 0) { GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null) GlRenderUtils.checkGlError("glTexImage2D GlTexture") } GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) GlRenderUtils.checkGlError("glTexParameter GlTexture") GLES20.glBindTexture(target, 0) } fun bind() { GLES20.glActiveTexture(unit) GLES20.glBindTexture(target, texName) GlRenderUtils.checkGlError("glBindTexture GlTexture") } fun unbind() { GLES20.glBindTexture(target, 0) GLES20.glActiveTexture(GLES20.GL_TEXTURE0) } fun delete() { GLES20.glDeleteTextures(1, intArrayOf(texName), 0) } }
bsd-2-clause
829e51695eed5d5d7dd55abc2c7c0cd3
36.448718
137
0.705238
3.702155
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/player/GaplessExoPlayerWrapper.kt
1
12896
package io.casey.musikcube.remote.service.playback.impl.player import android.content.Context import android.content.SharedPreferences import android.net.Uri import com.danikula.videocache.CacheListener import com.google.android.exoplayer2.* import com.google.android.exoplayer2.source.ConcatenatingMediaSource import com.google.android.exoplayer2.source.MediaSource import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.source.TrackGroupArray import com.google.android.exoplayer2.trackselection.TrackSelectionArray import com.google.android.exoplayer2.upstream.DataSource import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory import com.google.android.exoplayer2.util.Util import io.casey.musikcube.remote.Application import io.casey.musikcube.remote.service.playback.PlayerWrapper import io.casey.musikcube.remote.service.websocket.model.ITrack import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.util.Preconditions import java.io.File import kotlin.math.max import kotlin.math.min class GaplessExoPlayerWrapper : PlayerWrapper() { private var sourceFactory: DataSource.Factory private var source: MediaSource? = null private var metadata: ITrack? = null private var prefetch: Boolean = false private var lastPosition: Long = -1 private var percentAvailable = 0 private var originalUri: String? = null private var proxyUri: String? = null private val transcoding: Boolean private var initialOffsetMs: Int = 0 init { val userAgent = Util.getUserAgent(context, "musikdroid") val httpFactory: DataSource.Factory = DefaultHttpDataSourceFactory( userAgent, null, TIMEOUT, TIMEOUT, true) this.sourceFactory = DefaultDataSourceFactory(context, null, httpFactory) this.transcoding = prefs.getInt(Prefs.Key.TRANSCODER_BITRATE_INDEX, 0) != 0 } override fun play(uri: String, metadata: ITrack, offsetMs: Int) { Preconditions.throwIfNotOnMainThread() if (!dead()) { removeAllAndReset() this.metadata = metadata this.originalUri = uri this.proxyUri = streamProxy.getProxyUrl(uri) this.initialOffsetMs = offsetMs addCacheListener() this.source = ProgressiveMediaSource .Factory(sourceFactory) .createMediaSource(Uri.parse(proxyUri)) addPlayer(this, this.source!!) state = State.Preparing } } override fun prefetch(uri: String, metadata: ITrack) { Preconditions.throwIfNotOnMainThread() if (!dead()) { removePending() this.metadata = metadata this.originalUri = uri this.proxyUri = streamProxy.getProxyUrl(uri) this.prefetch = true this.source = ProgressiveMediaSource .Factory(sourceFactory) .createMediaSource(Uri.parse(proxyUri)) addCacheListener() addPlayer(this, source!!) state = State.Prepared } } override fun pause() { Preconditions.throwIfNotOnMainThread() this.prefetch = true if (this.state == State.Playing) { gaplessPlayer?.playWhenReady = false state = State.Paused } } override fun resume() { Preconditions.throwIfNotOnMainThread() prefetch = false when (state) { State.Paused, State.Prepared -> { gaplessPlayer?.playWhenReady = true state = State.Playing } State.Error -> { gaplessPlayer?.playWhenReady = lastPosition == -1L source?.let { gaplessPlayer?.prepare(it) state = State.Preparing } ?: run { state = State.Error } } else -> { } } } override val uri get() = originalUri ?: "" override var position: Int get(): Int { Preconditions.throwIfNotOnMainThread() return gaplessPlayer?.currentPosition?.toInt() ?: 0 } set(millis) { Preconditions.throwIfNotOnMainThread() this.lastPosition = -1 if (gaplessPlayer?.playbackState != Player.STATE_IDLE) { if (gaplessPlayer?.isCurrentWindowSeekable == true) { var offset = millis.toLong() val isInitialSeek = initialOffsetMs > 0 && (millis == initialOffsetMs) /* if we're transcoding we don't want to seek arbitrarily because it may put a lot of pressure on the backend. just allow seeking up to what we currently have buffered! one exception: if we transfer playback context from the backend to here, we want to wait until we are able to pickup where we left off. */ if (!isInitialSeek && transcoding && percentAvailable != 100) { /* give ourselves 2% wiggle room! */ val percent = max(0, percentAvailable - 2).toFloat() / 100.0f val totalMs = gaplessPlayer?.duration val available = (totalMs!!.toFloat() * percent).toLong() offset = min(millis.toLong(), available) } initialOffsetMs = 0 gaplessPlayer?.seekTo(offset) } } } override val duration: Int get() { Preconditions.throwIfNotOnMainThread() return gaplessPlayer?.duration?.toInt() ?: 0 } override val bufferedPercent: Int get() = if (transcoding) percentAvailable else 100 override fun updateVolume() { Preconditions.throwIfNotOnMainThread() gaplessPlayer?.volume = getVolume() } override fun setNextMediaPlayer(wrapper: PlayerWrapper?) { Preconditions.throwIfNotOnMainThread() } override fun dispose() { Preconditions.throwIfNotOnMainThread() if (!dead()) { state = State.Killing removePlayer(this) removeCacheListener() state = State.Disposed } } private fun dead(): Boolean { val state = state return state == State.Killing || state == State.Disposed } private fun addCacheListener() { if (streamProxy.isCached(this.originalUri!!)) { percentAvailable = 100 if (originalUri != null && metadata != null) { storeOffline(originalUri!!, metadata!!) } } else { streamProxy.registerCacheListener(this.cacheListener, this.originalUri!!) } } private fun removeCacheListener() { streamProxy.unregisterCacheListener(this.cacheListener) } private val cacheListener = CacheListener { _: File, _: String, percent: Int -> percentAvailable = percent if (percentAvailable >= 100) { if (originalUri != null && metadata != null) { storeOffline(originalUri!!, metadata!!) } } } private var eventListener = object : Player.EventListener { override fun onTimelineChanged(timeline: Timeline, manifest: Any?, reason: Int) { } override fun onTracksChanged(trackGroups: TrackGroupArray, trackSelections: TrackSelectionArray) { } override fun onLoadingChanged(isLoading: Boolean) { } override fun onSeekProcessed() { } override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) { } override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { Preconditions.throwIfNotOnMainThread() if (playbackState == Player.STATE_BUFFERING) { state = State.Buffering } else if (playbackState == Player.STATE_READY) { if (dead()) { dispose() } else { state = State.Prepared gaplessPlayer!!.volume = getVolume() if (lastPosition != -1L) { gaplessPlayer?.seekTo(lastPosition) lastPosition = -1 } else if (initialOffsetMs > 0) { position = initialOffsetMs } if (!prefetch) { gaplessPlayer?.playWhenReady = true state = State.Playing } else { state = State.Paused } } } else if (playbackState == Player.STATE_ENDED) { state = State.Finished dispose() } } override fun onPlayerError(error: ExoPlaybackException) { Preconditions.throwIfNotOnMainThread() lastPosition = gaplessPlayer?.currentPosition ?: 0 when (state) { State.Preparing, State.Prepared, State.Playing, State.Paused -> state = State.Error else -> { } } } override fun onPositionDiscontinuity(type: Int) { /* window index corresponds to the position of the current song in the queue. the current song should always be 0! if it's not, then that means we advanced to the next one... */ if (gaplessPlayer?.currentWindowIndex ?: 0 != 0) { promoteNext() state = State.Finished } } override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters) { } override fun onRepeatModeChanged(repeatMode: Int) { } } companion object { const val TIMEOUT = 1000 * 60 * 2 /* 2 minutes; makes seeking an incomplete transcode work most of the time */ private val prefs: SharedPreferences by lazy { Application.instance.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) } private val context: Context by lazy { Application.instance } private var all = mutableListOf<GaplessExoPlayerWrapper>() private lateinit var dcms: ConcatenatingMediaSource private var gaplessPlayer: SimpleExoPlayer? = null private fun promoteNext() { if (all.size > 0) { removePlayer(all[0]) if (all.size > 0) { val next = all[0] gaplessPlayer?.addListener(next.eventListener) next.state = when(gaplessPlayer?.playbackState) { Player.STATE_READY -> State.Playing else -> State.Buffering } } } } private fun removeAllAndReset() { all.forEach { gaplessPlayer?.removeListener(it.eventListener) } all.clear() gaplessPlayer?.stop() gaplessPlayer?.release() gaplessPlayer = SimpleExoPlayer.Builder(context) .setBandwidthMeter(DefaultBandwidthMeter.Builder(context).build()) .build() dcms = ConcatenatingMediaSource() } private fun removePending() { if (all.size > 0) { (1 until dcms.size).forEach { _ -> dcms.removeMediaSource(1) } val remain = all.removeAt(0) all.forEach { gaplessPlayer?.removeListener(it.eventListener) } all = mutableListOf(remain) } } private fun addPlayer(wrapper: GaplessExoPlayerWrapper, source: MediaSource) { addActivePlayer(wrapper) if (all.size == 0) { gaplessPlayer?.addListener(wrapper.eventListener) } dcms.addMediaSource(source) all.add(wrapper) if (dcms.size == 1) { gaplessPlayer?.prepare(dcms) } } private fun removePlayer(wrapper: GaplessExoPlayerWrapper) { val index = all.indexOf(wrapper) if (index >= 0) { dcms.removeMediaSource(index) gaplessPlayer?.removeListener(all[index].eventListener) all.removeAt(index) } removeActivePlayer(wrapper) } } }
bsd-3-clause
c27fe2134d6272253c72561e819d0421
33.026385
132
0.573356
5.227402
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ViewerNavigation.kt
2
1815
package eu.kanade.tachiyomi.ui.reader.viewer import android.graphics.PointF import android.graphics.RectF import androidx.annotation.StringRes import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferenceValues import eu.kanade.tachiyomi.util.lang.invert abstract class ViewerNavigation { sealed class NavigationRegion(@StringRes val nameRes: Int, val colorRes: Int) { object MENU : NavigationRegion(R.string.action_menu, R.color.navigation_menu) object PREV : NavigationRegion(R.string.nav_zone_prev, R.color.navigation_prev) object NEXT : NavigationRegion(R.string.nav_zone_next, R.color.navigation_next) object LEFT : NavigationRegion(R.string.nav_zone_left, R.color.navigation_left) object RIGHT : NavigationRegion(R.string.nav_zone_right, R.color.navigation_right) } data class Region( val rectF: RectF, val type: NavigationRegion ) { fun invert(invertMode: PreferenceValues.TappingInvertMode): Region { if (invertMode == PreferenceValues.TappingInvertMode.NONE) return this return this.copy( rectF = this.rectF.invert(invertMode) ) } } private var constantMenuRegion: RectF = RectF(0f, 0f, 1f, 0.05f) abstract var regions: List<Region> var invertMode: PreferenceValues.TappingInvertMode = PreferenceValues.TappingInvertMode.NONE fun getAction(pos: PointF): NavigationRegion { val x = pos.x val y = pos.y val region = regions.map { it.invert(invertMode) } .find { it.rectF.contains(x, y) } return when { region != null -> region.type constantMenuRegion.contains(x, y) -> NavigationRegion.MENU else -> NavigationRegion.MENU } } }
apache-2.0
b83a7bb9daf088ad240ad3b0c3015719
36.040816
96
0.680992
4.033333
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/volumes/CroppingExample.kt
1
7364
package graphics.scenery.tests.examples.volumes import bdv.util.AxisOrder import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.utils.extensions.minus import graphics.scenery.utils.extensions.plus import graphics.scenery.utils.extensions.times import graphics.scenery.volumes.SlicingPlane import graphics.scenery.volumes.TransferFunction import graphics.scenery.volumes.Volume import ij.IJ import ij.ImagePlus import net.imglib2.img.Img import net.imglib2.img.display.imagej.ImageJFunctions import net.imglib2.type.numeric.integer.UnsignedShortType import org.joml.Quaternionf import org.joml.Vector3f import org.scijava.ui.behaviour.ClickBehaviour import tpietzsch.example2.VolumeViewerOptions import kotlin.concurrent.thread import graphics.scenery.numerics.Random import graphics.scenery.attribute.material.Material import graphics.scenery.attribute.spatial.Spatial /** * Volume Cropping Example using the "BDV Rendering Example loading a RAII" * * Press "R" to add a moving slicing plane and "T" to remove one. * * The four volumes in the background present the different slicingModes. * * @author Jan Tiemann <[email protected]> */ class CroppingExample : SceneryBase("Volume Cropping example", 1280, 720) { lateinit var volume: Volume lateinit var volume2: Volume var slicingPlanes = mapOf<SlicingPlane,Animator>() val additionalVolumes = true var additionalAnimators = emptyList<Animator>() override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam: Camera = DetachedHeadCamera() with(cam) { perspectiveCamera(50.0f, windowWidth, windowHeight) spatial { position = Vector3f(0.0f, 0.0f, 5.0f) } scene.addChild(this) } val shell = Box(Vector3f(10.0f, 10.0f, 10.0f), insideNormals = true) shell.material { cullingMode = Material.CullingMode.None diffuse = Vector3f(0.2f, 0.2f, 0.2f) specular = Vector3f(0.0f) ambient = Vector3f(0.0f) } scene.addChild(shell) Light.createLightTetrahedron<PointLight>(spread = 4.0f, radius = 15.0f, intensity = 0.5f) .forEach { scene.addChild(it) } val origin = Box(Vector3f(0.1f, 0.1f, 0.1f)) origin.material().diffuse = Vector3f(0.8f, 0.0f, 0.0f) scene.addChild(origin) val imp: ImagePlus = IJ.openImage("https://imagej.nih.gov/ij/images/t1-head.zip") val img: Img<UnsignedShortType> = ImageJFunctions.wrapShort(imp) volume = Volume.fromRAI(img, UnsignedShortType(), AxisOrder.DEFAULT, "T1 head", hub, VolumeViewerOptions()) volume.transferFunction = TransferFunction.ramp(0.001f, 0.5f, 0.3f) scene.addChild(volume) volume.slicingMode = Volume.SlicingMode.Cropping addAnimatedSlicingPlane() if (additionalVolumes) { fun addAdditionalVolume(base: Vector3f): Volume { val vol2Pivot = RichNode() scene.addChild(vol2Pivot) vol2Pivot.spatial { position += base scale = Vector3f(0.5f) } volume2 = Volume.fromRAI(img, UnsignedShortType(), AxisOrder.DEFAULT, "T1 head", hub, VolumeViewerOptions()) volume2.transferFunction = TransferFunction.ramp(0.001f, 0.5f, 0.3f) vol2Pivot.addChild(volume2) val slicingPlane2 = createSlicingPlane() scene.removeChild(slicingPlane2) vol2Pivot.addChild(slicingPlane2) slicingPlane2.addTargetVolume(volume2) val animator2 = Animator(slicingPlane2.spatial()) additionalAnimators = additionalAnimators + animator2 return volume2 } addAdditionalVolume(Vector3f(2f,2f,-2f)).slicingMode = Volume.SlicingMode.Slicing addAdditionalVolume(Vector3f(-2f,2f,-2f)).slicingMode = Volume.SlicingMode.Cropping addAdditionalVolume(Vector3f(2f,-2f,-2f)).slicingMode = Volume.SlicingMode.Both addAdditionalVolume(Vector3f(-2f,-2f,-2f)) } thread { while (running) { slicingPlanes.entries.forEach { it.value.animate() } additionalAnimators.forEach { it.animate() } Thread.sleep(20) } } } class Animator(val spatial: Spatial) { private var moveDir = Random.random3DVectorFromRange(-1.0f, 1.0f) - spatial.position private var rotationStart = Quaternionf(spatial.rotation) private var rotationTarget = Random.randomQuaternion() private var startTime = System.currentTimeMillis() fun animate() { val relDelta = (System.currentTimeMillis() - startTime) / 5000f val scaledMov = moveDir * (20f / 5000f) spatial.position += scaledMov rotationStart.nlerp(rotationTarget, relDelta, spatial.rotation) spatial.needsUpdate = true if (startTime + 5000 < System.currentTimeMillis()) { moveDir = Random.random3DVectorFromRange(-1.0f, 1.0f) - spatial.position rotationStart = Quaternionf(spatial.rotation) rotationTarget = Random.randomQuaternion() startTime = System.currentTimeMillis() } } } private fun addAnimatedSlicingPlane(){ val slicingPlane = createSlicingPlane() slicingPlane.addTargetVolume(volume) val animator = Animator(slicingPlane.spatial()) slicingPlanes = slicingPlanes + (slicingPlane to animator) } private fun removeAnimatedSlicingPlane(){ if (slicingPlanes.isEmpty()) return val (plane,_) = slicingPlanes.entries.first() scene.removeChild(plane) plane.removeTargetVolume(volume) slicingPlanes = slicingPlanes.toMutableMap().let { it.remove(plane); it} } private fun createSlicingPlane(): SlicingPlane { val slicingPlaneFunctionality = SlicingPlane() scene.addChild(slicingPlaneFunctionality) val slicingPlaneVisual: Node slicingPlaneVisual = Box(Vector3f(1f, 0.01f, 1f)) slicingPlaneVisual.material { diffuse = Vector3f(0.0f, 0.8f, 0.0f) } slicingPlaneFunctionality.addChild(slicingPlaneVisual) val nose = Box(Vector3f(0.1f, 0.1f, 0.1f)) nose.material { diffuse = Vector3f(0.8f, 0.0f, 0.0f) } nose.spatial { position = Vector3f(0f, 0.05f, 0f) } slicingPlaneVisual.addChild(nose) return slicingPlaneFunctionality } override fun inputSetup() { setupCameraModeSwitching() inputHandler?.addBehaviour("addPlane", ClickBehaviour { _, _ -> addAnimatedSlicingPlane() }) inputHandler?.addKeyBinding("addPlane", "R") inputHandler?.addBehaviour("removePlane", ClickBehaviour { _, _ -> removeAnimatedSlicingPlane() }) inputHandler?.addKeyBinding("removePlane", "T") } companion object { @JvmStatic fun main(args: Array<String>) { CroppingExample().main() } } }
lgpl-3.0
0a927af7764b39a70c3894b0da7db9c1
36.005025
118
0.64598
4.12318
false
false
false
false
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/ui/admin/customer/ManageCustomerFragment.kt
1
6017
package rynkbit.tk.coffeelist.ui.admin.customer import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.manage_customer_fragment.* import rynkbit.tk.coffeelist.R import rynkbit.tk.coffeelist.db.facade.CustomerFacade import rynkbit.tk.coffeelist.db.facade.InvoiceFacade import rynkbit.tk.coffeelist.db.facade.ItemFacade import rynkbit.tk.coffeelist.ui.admin.customer.add.AddCustomerDialog import rynkbit.tk.coffeelist.ui.entity.UICustomer import rynkbit.tk.coffeelist.ui.facade.UICustomerFacade class ManageCustomerFragment : Fragment() { private lateinit var viewModel: ManageCustomerViewModel private lateinit var adapter: ManageCustomerAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.manage_customer_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(ManageCustomerViewModel::class.java) adapter = ManageCustomerAdapter() adapter.onClearBalance = onClearBalance() adapter.onRemoveCustomer = onRemoveCustomer() adapter.onUpdateCustomer = onUpdateCustomer() listEditItems.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) listEditItems.adapter = adapter fabAddCustomer.setOnClickListener { AddCustomerDialog { dialogInterface, name -> onAddCustomer(dialogInterface, name) }.show(parentFragmentManager, null) } } private fun onAddCustomer(dialogInterface: DialogInterface, name: String) { CustomerFacade() .insert(UICustomer( 0, name, 0.0 )) .observe(this, Observer { dialogInterface.dismiss() updateCustomers() }) } override fun onResume() { super.onResume() updateCustomers() } private fun updateCustomers() { val liveData = viewModel.updateAll(this) liveData.observe(this, Observer { finishedUpdating -> if (finishedUpdating.all { it }) { liveData.removeObservers(this) val uiCustomers = mutableListOf<UICustomer>() for (customer in viewModel.customers) { val invoices = viewModel.invoice.filter { it.customerId == customer.id } var balance = 0.0 for (invoice in invoices) { balance += viewModel.items.find { it.id == invoice.itemId }?.price ?: 0.0 } uiCustomers.add(UICustomer( customer.id, customer.name, balance )) } adapter.updateCustomers(uiCustomers) } }) } private fun onUpdateCustomer(): (customer: UICustomer) -> Unit = { customer -> viewModel .customerFacade .update(customer) .observe(this, Observer { }) } private fun onRemoveCustomer(): (customer: UICustomer) -> Unit = { customer -> val dialogBuilder = AlertDialog.Builder(context) dialogBuilder .setTitle(R.string.remove) .setMessage(getString(R.string.remove_customer_confirmation, customer.name)) .setPositiveButton(R.string.confirm_label) { dialogInterface: DialogInterface, i: Int -> InvoiceFacade() .deleteByCustomer(customer.id) .observe(this, Observer { dialogInterface.dismiss() CustomerFacade() .delete(customer) .observe(this, Observer { updateCustomers() }) }) } .setNegativeButton(R.string.cancel) { dialogInterface: DialogInterface, i: Int -> dialogInterface.dismiss() } .create() .show() } private fun onClearBalance(): (customer: UICustomer) -> Unit = { customer -> val dialogBuilder = AlertDialog.Builder(context) dialogBuilder .setTitle(R.string.clear_balance) .setMessage(getString(R.string.confirm_clear_balance, customer.name)) .setPositiveButton(R.string.confirm_label) { dialogInterface: DialogInterface, i: Int -> dialogInterface.dismiss() InvoiceFacade() .clearCustomer(customer) .observe(this, Observer { UICustomerFacade() .findCustomersWithBalance(this, activity!!) .observe(this, Observer { customers -> adapter.updateCustomers(customers.sortedBy { it.id }) }) }) } .setNegativeButton(R.string.cancel) { dialogInterface: DialogInterface, i: Int -> dialogInterface.dismiss() } .create() .show() } }
mit
6768f49db018d8d84336888b3365743b
36.141975
104
0.559249
5.692526
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/util/ShareUtil.kt
1
8819
package org.wikipedia.util import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.LabeledIntent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Parcelable import android.os.TransactionTooLargeException import android.widget.Toast import androidx.core.content.FileProvider import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.BuildConfig import org.wikipedia.R import org.wikipedia.page.PageTitle import org.wikipedia.util.DateUtil.getFeedCardDateString import org.wikipedia.util.log.L import java.io.File import java.util.* object ShareUtil { private const val APP_PACKAGE_REGEX = "org\\.wikipedia.*" private const val FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".fileprovider" private const val FILE_PREFIX = "file://" private fun shareText(context: Context, subject: String, text: String) { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject) shareIntent.putExtra(Intent.EXTRA_TEXT, text) shareIntent.type = "text/plain" try { val chooserIntent = getIntentChooser(context, shareIntent, context.getString(R.string.share_via)) if (chooserIntent == null) { showUnresolvableIntentMessage(context) } else { context.startActivity(chooserIntent) } } catch (e: TransactionTooLargeException) { L.logRemoteErrorIfProd(RuntimeException("Transaction too large for share intent.")) } } @JvmStatic fun shareText(context: Context, title: PageTitle) { shareText(context, StringUtil.fromHtml(title.displayText).toString(), UriUtil.getUrlWithProvenance(context, title, R.string.prov_share_link)) } fun shareText(context: Context, title: PageTitle, newId: Long, oldId: Long) { shareText(context, StringUtil.fromHtml(title.displayText).toString(), title.getWebApiUrl("diff=$newId&oldid=$oldId&variant=${title.wikiSite.languageCode()}")) } @JvmStatic fun shareImage(context: Context, bmp: Bitmap, imageFileName: String, subject: String, text: String) { Observable.fromCallable { getUriFromFile(context, processBitmapForSharing(context, bmp, imageFileName)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ uri: Uri? -> if (uri == null) { displayShareErrorMessage(context) return@subscribe } val chooserIntent = buildImageShareChooserIntent(context, subject, text, uri) context.startActivity(chooserIntent) }) { caught: Throwable -> displayOnCatchMessage(caught, context) } } @JvmStatic fun getFeaturedImageShareSubject(context: Context, age: Int): String { return context.getString(R.string.feed_featured_image_share_subject) + " | " + getFeedCardDateString(age) } private fun buildImageShareChooserIntent(context: Context, subject: String, text: String, uri: Uri): Intent? { val shareIntent = createImageShareIntent(subject, text, uri) return getIntentChooser(context, shareIntent, context.resources.getString(R.string.image_share_via)) } private fun getUriFromFile(context: Context, file: File?): Uri? { if (file == null) { return null } return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, file) else Uri.parse(FILE_PREFIX + file.absolutePath) } private fun processBitmapForSharing(context: Context, bmp: Bitmap, imageFileName: String): File? { val shareFolder = getClearShareFolder(context) ?: return null shareFolder.mkdirs() val bytes = FileUtil.compressBmpToJpg(bmp) return FileUtil.writeToFile(bytes, File(shareFolder, cleanFileName(imageFileName))) } private fun createImageShareIntent(subject: String, text: String, uri: Uri): Intent { return Intent(Intent.ACTION_SEND) .putExtra(Intent.EXTRA_SUBJECT, subject) .putExtra(Intent.EXTRA_TEXT, text) .putExtra(Intent.EXTRA_STREAM, uri) .setType("image/jpeg") } private fun displayOnCatchMessage(caught: Throwable, context: Context) { Toast.makeText(context, context.getString(R.string.gallery_share_error, caught.localizedMessage), Toast.LENGTH_SHORT).show() } private fun displayShareErrorMessage(context: Context) { Toast.makeText(context, context.getString(R.string.gallery_share_error, context.getString(R.string.err_cannot_save_file)), Toast.LENGTH_SHORT).show() } @JvmStatic fun showUnresolvableIntentMessage(context: Context?) { Toast.makeText(context, R.string.error_can_not_process_link, Toast.LENGTH_LONG).show() } private fun getClearShareFolder(context: Context): File? { try { val dir = File(getShareFolder(context), "share") FileUtil.deleteRecursively(dir) return dir } catch (caught: Throwable) { L.e("Caught " + caught.message, caught) } return null } private fun getShareFolder(context: Context): File { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) context.cacheDir else context.getExternalFilesDir(null)!! } private fun cleanFileName(fileName: String): String { // Google+ doesn't like file names that have characters %28, %29, %2C var fileNameStr = fileName fileNameStr = fileNameStr.replace("%2[0-9A-F]".toRegex(), "_") .replace("[^0-9a-zA-Z-_.]".toRegex(), "_") .replace("_+".toRegex(), "_") // ensure file name ends with .jpg if (!fileNameStr.endsWith(".jpg")) { fileNameStr = "$fileNameStr.jpg" } return fileNameStr } fun getIntentChooser(context: Context, intent: Intent, chooserTitle: CharSequence? = null): Intent? { val infoList = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) val excludedComponents = HashSet<ComponentName>() infoList.forEach { val activityInfo = it.activityInfo val componentName = ComponentName(activityInfo.packageName, activityInfo.name) if (isSelfComponentName(componentName)) excludedComponents.add(componentName) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Intent.createChooser(intent, chooserTitle) .putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, excludedComponents.toTypedArray()) } if (infoList.isEmpty()) { return null } val targetIntents = ArrayList<Intent>() for (info in infoList) { val activityInfo = info.activityInfo if (excludedComponents.contains(ComponentName(activityInfo.packageName, activityInfo.name))) continue val targetIntent = Intent(intent) .setPackage(activityInfo.packageName) .setComponent(ComponentName(activityInfo.packageName, activityInfo.name)) targetIntents.add(LabeledIntent(targetIntent, activityInfo.packageName, info.labelRes, info.icon)) } val chooserIntent = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Intent.createChooser(Intent(), chooserTitle) } else { Intent.createChooser(targetIntents.removeAt(0), chooserTitle) }) ?: return null chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toTypedArray<Parcelable>()) return chooserIntent } @JvmStatic fun canOpenUrlInApp(context: Context, url: String): Boolean { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) return context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .any { it.activityInfo.packageName.matches(APP_PACKAGE_REGEX.toRegex()) } } private fun isSelfComponentName(componentName: ComponentName): Boolean { return componentName.packageName.matches(APP_PACKAGE_REGEX.toRegex()) } }
apache-2.0
49d6777d786f25772c599f9567194187
41.603865
113
0.654609
4.680998
false
false
false
false
CrystalLord/plounge-quoter
src/main/kotlin/org/crystal/struct/IntMatrix.kt
1
2195
package org.crystal.struct /** * Library class to help represent Int Matrices. */ open class IntMatrix { private var internalList: IntArray val width: Int val height: Int private val defaultVal: Int constructor(width: Int, height: Int) : this(width, height, 0) constructor(width: Int, height: Int, defaultVal: Int) { this.width = width this.height = height this.defaultVal = defaultVal val size: Int = this.width * this.height this.internalList = IntArray(size) for (i: Int in 0 until size) { this.internalList[i] = defaultVal } } /** * Get the element at a specified row/column. */ fun getXY(x: Int, y: Int): Int { if (x < 0 || y < 0 || y >= this.height || x >= this.width) { throw IllegalArgumentException("Out of index for IntMatrix") } val index: Int = y * this.width + x return this.internalList[index] } /** * Set the element at a specified row/column. */ fun setXY(x: Int, y: Int, value: Int) { if (x < 0 || y < 0 || y >= this.height || x >= this.width) { throw IllegalArgumentException("Out of index for IntMatrix") } val index: Int = y * this.width + x this.internalList[index] = value } /** * Is the given xy position within the bounds of the matrix? * @param[x] X position. * @param[y] Y position. * @return Returns a boolean indicating whether the xy position is within * bounds. */ fun inMatrix(x: Int, y: Int): Boolean { return ( (0 <= x && x < this.width) && (0 <= y && y < this.height) ) } /** * Return a new Matrix object with the same contents. */ fun clone(): IntMatrix { var newMatrix: IntMatrix = IntMatrix( this.width, this.height, this.defaultVal ) var newList: IntArray = IntArray( this.internalList.size, {x -> this.internalList[x]} ) newMatrix.internalList = newList return newMatrix } }
apache-2.0
b3a8600264729152e099fac9ac238727
27.506494
77
0.540774
4.064815
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt
3
2476
// 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.util import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsContexts import com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.idea.KotlinFileType import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel open class DialogWithEditor( val project: Project, @NlsContexts.DialogTitle title: String, val initialText: String ) : DialogWrapper(project, true) { val editor: Editor = createEditor() init { init() setTitle(title) } final override fun init() { super.init() } private fun createEditor(): Editor { val editorFactory = EditorFactory.getInstance()!! val virtualFile = LightVirtualFile("dummy.kt", KotlinFileType.INSTANCE, initialText) val document = FileDocumentManager.getInstance().getDocument(virtualFile)!! val editor = editorFactory.createEditor(document, project, KotlinFileType.INSTANCE, false) val settings = editor.settings settings.isVirtualSpace = false settings.isLineMarkerAreaShown = false settings.isFoldingOutlineShown = false settings.isRightMarginShown = false settings.isAdditionalPageAtBottom = false settings.additionalLinesCount = 2 settings.additionalColumnsCount = 12 assert(editor is EditorEx) (editor as EditorEx).isEmbeddedIntoDialogWrapper = true editor.getColorsScheme().setColor(EditorColors.CARET_ROW_COLOR, editor.getColorsScheme().defaultBackground) return editor } override fun createCenterPanel(): JComponent { val panel = JPanel(BorderLayout()) panel.add(editor.component, BorderLayout.CENTER) return panel } override fun getPreferredFocusedComponent(): JComponent { return editor.contentComponent } override fun dispose() { super.dispose() EditorFactory.getInstance()!!.releaseEditor(editor) } }
apache-2.0
e8f123d976f0014c7db0cd04a6350cfc
33.388889
158
0.732633
4.922465
false
false
false
false
Killian-LeClainche/Java-Base-Application-Engine
tests/polaris/okapi/tests/teamdefense/world/terrain/Grasslands.kt
1
7265
package polaris.okapi.tests.teamdefense.world.terrain import org.joml.Vector2d import org.lwjgl.system.rpmalloc.RPmalloc import polaris.okapi.tests.teamdefense.world.Tile import polaris.okapi.tests.teamdefense.world.Tree import polaris.okapi.util.FastNoise import polaris.okapi.util.* import java.lang.Math.abs import java.nio.ByteBuffer /** * Created by Killian Le Clainche on 4/25/2018. */ class Grasslands(size : Int, seed : Int) : Generator(size, seed) { override fun generate(worldMap: Array<Array<Tile>>) : ByteBuffer? { val bitmap = size * PIXELS_PER_TILE; val terrain = RPmalloc.rpmalloc((bitmap * bitmap * 3).toLong()) if(terrain != null) { val heatNoise = FastNoise(seed) val terrainNoise = FastNoise(seed + 1) val heightNoise = FastNoise(seed + 2) val shaderNoise = FastNoise(seed + 3) heatNoise.frequency = 0.001f heatNoise.noiseType = FastNoise.NoiseType.SimplexFractal terrainNoise.noiseType = FastNoise.NoiseType.SimplexFractal terrainNoise.fractalType = FastNoise.FractalType.FBM terrainNoise.octaves = 6 terrainNoise.gain = .75f heightNoise.frequency = .01f heightNoise.noiseType = FastNoise.NoiseType.ValueFractal heightNoise.octaves = 6 heightNoise.gain = .4f shaderNoise.frequency = .5f shaderNoise.noiseType = FastNoise.NoiseType.SimplexFractal shaderNoise.fractalType = FastNoise.FractalType.FBM shaderNoise.octaves = 6 shaderNoise.gain = 1f var x = 0f var y = 0f var heatValue = 0f var terrainValue = 0f var heightValue = 0f var shaderValue = 0f var red = 0 var green = 0 var blue = 0 for (i in 0 until bitmap) { for (j in 0 until bitmap) { x = i / PIXELS_PER_TILE.toFloat() y = j / PIXELS_PER_TILE.toFloat() heatValue = (heatNoise.getNoise(x, y) + 1) terrainValue = terrainNoise.getNoise(x, y) + 1 heightValue = heightNoise.getNoise(x, y) shaderValue = shaderNoise.getNoise(x, y) if(heightValue < -.25) { heightValue = 1.0f//clamp(0.0, 1.0, (abs(heightValue) - .25) / .03).toFloat() red = clamp(0, 255, (Terrain.DESERT.red * (1 - heightValue) + (Terrain.SEA.red) * heightValue).toInt()) green = clamp(0, 255, (Terrain.DESERT.green * (1 - heightValue) + (Terrain.SEA.green) * heightValue).toInt()) blue = clamp(0, 255, (Terrain.DESERT.blue * (1 - heightValue) + (Terrain.SEA.blue) * heightValue).toInt()) } else { if(heightValue < -.23) { red = Terrain.GRASSLANDS.red green = Terrain.GRASSLANDS.green blue = Terrain.GRASSLANDS.blue if(shaderValue < (abs(heightValue) - .24) / .01) { red = Terrain.DESERT.red green = Terrain.DESERT.green blue = Terrain.DESERT.blue } } else { red = Terrain.GRASSLANDS.red green = Terrain.GRASSLANDS.green blue = Terrain.GRASSLANDS.blue } } red = clamp(0, 255, red + random(-red * .1, red * .1).toInt()) green = clamp(0, 255, green + random(-green * .1, green * .1).toInt()) blue = clamp(0, 255, blue + random(-blue * .1, blue * .1).toInt()) /*var offset = 1 + simplexNoise.getNoise(i.toFloat() / PIXELS_PER_TILE.toFloat(), j.toFloat() / PIXELS_PER_TILE.toFloat()) / 3.0 var red = (clamp(0, 255, Terrain.GRASSLANDS.red)).toByte() var green = (clamp(0, 255, Terrain.GRASSLANDS.green)).toByte() var blue = (clamp(0, 255, Terrain.GRASSLANDS.blue)).toByte() offset = waterNoise.getNoise(i.toFloat() / PIXELS_PER_TILE.toFloat(), j.toFloat() / PIXELS_PER_TILE.toFloat()).toDouble() //System.out.println(offset) if (offset < -.28) { offset = 1 - min(1.0, (abs(offset) - .28) / .3) //offset = 1 - getExpDistance(0.15, offset, .35) //System.out.println(offset) red = (clamp(0.0, 255.0, (red - 0.0) * offset)).toByte() green = (clamp(0.0, 255.0, Terrain.SEA.green + (green - Terrain.SEA.green) * offset)).toByte() blue = (clamp(0.0, 255.0, Terrain.SEA.blue + (blue - Terrain.SEA.blue) * offset)).toByte() red = clamp(0.0, 255.0, red + random(-10.0 * offset, 10.0 * offset)).toByte() green = clamp(0.0, 255.0, green + random(-10.0 * offset, 10.0 * offset)).toByte() blue = clamp(0.0, 255.0, blue + random(-10.0 * offset, 10.0 * offset)).toByte() if (offset <= .7) worldMap[i / PIXELS_PER_TILE][j / PIXELS_PER_TILE].water += offset } else { red = clamp(0.0, 255.0, red + random(-10.0, 10.0)).toByte() green = clamp(0.0, 255.0, green + random(-10.0, 10.0)).toByte() blue = clamp(0.0, 255.0, blue + random(-10.0, 10.0)).toByte() }*/ terrain.put(red.toByte()) terrain.put(green.toByte()) terrain.put(blue.toByte()) } } terrain.flip() worldMap.forEach { it.forEach { it.water /= PIXELS_PER_TILE * PIXELS_PER_TILE.toDouble() } } /*for(i in 0 until size * 2) { for(j in 0 until size * 2) { val spot = terrainNoise.getNoise(i.toFloat(), j.toFloat()) val tile = worldMap[i / 2][j / 2] if(spot < -.2 && tile.water <= .05) { val treeVector = Vector2d(i / 2.0 + random(.5), j / 2.0 + random(.5)) if(random(2) == 0) tile.trees.add(Tree(Trees.GRASSLAND_TREE_1, Vector2d(treeVector.x, treeVector.y))) else if(random(1) == 0) tile.trees.add(Tree(Trees.GRASSLAND_TREE_2, Vector2d(treeVector.x, treeVector.y))) else tile.trees.add(Tree(Trees.GRASSLAND_TREE_3, Vector2d(treeVector.x, treeVector.y))) } } }*/ } else System.err.println("Could not generate terrain!") return terrain } }
gpl-2.0
1c9f2b8f13e0c551b941125cebc6750b
40.758621
148
0.483276
3.939805
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/iam/src/main/kotlin/com/kotlin/iam/CreateAccountAlias.kt
1
1687
// snippet-sourcedescription:[CreateAccountAlias.kt demonstrates how to create an alias for an AWS account.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Identity and Access Management (IAM)] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.iam // snippet-start:[iam.kotlin.create_account_alias.import] import aws.sdk.kotlin.services.iam.IamClient import aws.sdk.kotlin.services.iam.model.CreateAccountAliasRequest import kotlin.system.exitProcess // snippet-end:[iam.kotlin.create_account_alias.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <alias> Where: alias - The account alias to create (for example, myawsaccount). """ if (args.size != 1) { println(usage) exitProcess(0) } val alias = args[0] createIAMAccountAlias(alias) } // snippet-start:[iam.kotlin.create_account_alias.main] suspend fun createIAMAccountAlias(alias: String) { val request = CreateAccountAliasRequest { accountAlias = alias } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.createAccountAlias(request) println("Successfully created account alias named $alias") } } // snippet-end:[iam.kotlin.create_account_alias.main]
apache-2.0
a613812a67f58f645f6fe5c3ec3c971c
27.596491
108
0.682276
3.95082
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/ui/adapter/FeedsPagerAdapter.kt
1
3264
/* * Copyright 2019 Eduard Scarlat * * 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 ro.edi.novelty.ui.adapter import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.adapter.FragmentStateAdapter import ro.edi.novelty.ui.FeedFragment import ro.edi.novelty.ui.MyFeedsFragment import ro.edi.novelty.ui.MyNewsFragment import ro.edi.novelty.ui.viewmodel.FeedsViewModel class FeedsPagerAdapter(fa: FragmentActivity, private val feedsModel: FeedsViewModel) : FragmentStateAdapter(fa) { override fun getItemId(page: Int): Long { return when (page) { 0 -> 0L 1 -> 1L else -> feedsModel.getFeed(page - 2)?.id?.toLong() ?: RecyclerView.NO_ID } } override fun containsItem(itemId: Long): Boolean { return when (itemId) { 0L, 1L -> true else -> feedsModel.feeds.value?.find { it.id.toLong() == itemId } != null } } override fun getItemCount(): Int { return feedsModel.feeds.value?.size?.plus(2) ?: 2 } override fun createFragment(page: Int): Fragment { return when (page) { 0 -> MyNewsFragment.newInstance() 1 -> MyFeedsFragment.newInstance() else -> { // val feedState = mFeedState[feed.title] // if (feedState == null) { // mFeedState[feed.title] = FEED_STATE_NEEDS_REFRESH // } feedsModel.getFeed(page - 2)?.let { return FeedFragment.newInstance(it.id) } return MyNewsFragment.newInstance() // should never happen } } } // companion object { // private const val FEED_STATE_NEEDS_REFRESH = 0 // private const val FEED_STATE_REFRESHED = 1 // } // fun refreshFeed(position: Int) { // logi("refresh: %d", position) // // if (position <= 0) { // return // } // // val f = getFragment(position) as FeedFragment // if (f == null || f.arguments == null) { // logi("refresh denied: %d", position) // return // } // // val feedTitle = f.arguments!!.getString("feedId") // // val feedState = mFeedState[feedTitle] // logi("refresh: %d: state %d", position, feedState) // // if (feedState != null && feedState == FEED_STATE_NEEDS_REFRESH) { // logi(TAG, "refresh: %d: %s", position, feedTitle) // f.refresh() // mFeedState[feedTitle] = FEED_STATE_REFRESHED // } // } }
apache-2.0
0f64febbbbcbce5f7789813add850a0a
32.020833
87
0.588542
3.871886
false
false
false
false
syncloud/android
syncloud/src/main/java/org/syncloud/android/discovery/DiscoveryManager.kt
1
1675
package org.syncloud.android.discovery import android.net.nsd.NsdManager import android.net.wifi.WifiManager import kotlinx.coroutines.delay import org.apache.log4j.Logger import org.syncloud.android.discovery.nsd.NsdDiscovery class DiscoveryManager(wifi: WifiManager, private val manager: NsdManager) { private val lock: MulticastLock = MulticastLock(wifi) private var discovery: Discovery? = null private var canceled = false suspend fun run(timeoutSeconds: Int, added: suspend (device: String) -> Unit ) { canceled = false logger.info("starting discovery") if (discovery == null) { lock.acquire() discovery = NsdDiscovery(manager, added, "syncloud") (discovery as NsdDiscovery).start() try { logger.info("waiting for $timeoutSeconds seconds") var count = 0 while (count < timeoutSeconds && !canceled) { delay(1000) count++ } } catch (e: InterruptedException) { logger.error("sleep interrupted", e) } stop() } } fun cancel() { canceled = true } private fun stop() { logger.info("stopping discovery") if (discovery != null) { try { discovery?.stop() discovery = null } catch (e: Exception) { logger.error("failed to stop discovery", e) } lock.release() } } companion object { private val logger = Logger.getLogger(DiscoveryManager::class.java.name) } }
gpl-3.0
48cecfe2063be36860f9bab0bd6d38f1
29.472727
84
0.56597
4.827089
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/widget/HistoryWidgetProvider.kt
1
1297
package com.mgaetan89.showsrage.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.net.Uri import com.mgaetan89.showsrage.Constants import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.activity.MainActivity class HistoryWidgetProvider : ListWidgetProvider() { override fun getListAdapterIntent(context: Context?, widgetId: Int): Intent { if (context == null) { return Intent() } val intent = Intent(context, HistoryWidgetService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) return intent } override fun getTitlePendingIntent(context: Context?, widgetId: Int): PendingIntent { val intent = Intent(context, MainActivity::class.java) intent.action = Constants.Intents.ACTION_DISPLAY_HISTORY intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK) return PendingIntent.getActivity(context, widgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT) } override fun getWidgetEmptyText(context: Context?) = context?.getString(R.string.no_history) override fun getWidgetTitle(context: Context?) = context?.getString(R.string.history) }
apache-2.0
bcc8f587e3f89988585fbb1535862598
35.027778
96
0.797995
3.954268
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/tests/git4idea/rebase/GitRewordTest.kt
9
4514
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.rebase import com.intellij.openapi.util.text.StringUtil import git4idea.config.GitVersionSpecialty import git4idea.test.* import org.junit.Assume.assumeTrue class GitRewordTest : GitSingleRepoTest() { fun `test reword latest commit`() { val commit = file("a").create("initial").addCommit("Wrong message").details() val newMessage = "Correct message" GitRewordOperation(repo, commit, newMessage).execute() assertLastMessage(newMessage, "Message reworded incorrectly") } fun `test reword via amend doesn't touch the local changes`() { val commit = file("a").create("initial").addCommit("Wrong message").details() file("b").create("b").add() val newMessage = "Correct message" GitRewordOperation(repo, commit, newMessage).execute() assertLastMessage(newMessage, "Message reworded incorrectly") repo.assertStagedChanges { added("b") } repo.assertCommitted { added("a") } } fun `test reword previous commit`() { val file = file("a").create("initial") val commit = file.addCommit("Wrong message").details() file.append("b").addCommit("Second message") val newMessage = "Correct message" GitRewordOperation(repo, commit, newMessage).execute() assertMessage(newMessage, repo.message("HEAD^"), "Message reworded incorrectly") } fun `test undo reword`() { val commit = file("a").create("initial").addCommit("Wrong message").details() val operation = GitRewordOperation(repo, commit, "Correct message") operation.execute() operation.undo() assertLastMessage("Wrong message", "Message reworded incorrectly") } fun `test undo is not possible if HEAD moved`() { val commit = file("a").create("initial").addCommit("Wrong message").details() val operation = GitRewordOperation(repo, commit, "Correct message") operation.execute() file("b").create().addCommit("New commit") operation.undo() repo.assertLatestHistory( "New commit", "Correct message" ) assertErrorNotification("Can't Undo Reword", "Repository has already been changed") } fun `test undo is not possible if commit was pushed`() { git("remote add origin http://example.git") val file = file("a").create("initial") file.append("First commit\n").addCommit("First commit") val commit = file.append("To reword\n").addCommit("Wrong message").details() file.append("Third commit").addCommit("Third commit") val operation = GitRewordOperation(repo, commit, "Correct message") operation.execute() git("update-ref refs/remotes/origin/master HEAD") operation.undo() repo.assertLatestHistory( "Third commit", "Correct message", "First commit" ) assertErrorNotification("Can't Undo Reword", "Commit has already been pushed to origin/master") } // IDEA-175002 fun `test reword with trailing spaces`() { val commit = file("a").create("initial").addCommit("Wrong message").details() val newMessage = "Subject with trailing spaces \n\nBody \nwith \nspaces." GitRewordOperation(repo, commit, newMessage).execute() assertLastMessage(newMessage) } // IDEA-175443 fun `test reword with hash symbol`() { assumeTrue("Not testing: not possible to fix in Git prior to 1.8.2: ${vcs.version}", GitVersionSpecialty.KNOWS_CORE_COMMENT_CHAR.existsIn(vcs.version)) // IDEA-182044 val commit = file("a").create("initial").addCommit("Wrong message").details() val newMessage = """ Subject #body starting with a hash """.trimIndent() GitRewordOperation(repo, commit, newMessage).execute() val actualMessage = git("log HEAD --no-walk --pretty=%B") assertTrue("Message reworded incorrectly. Expected:\n[$newMessage] Actual:\n[$actualMessage]", StringUtil.equalsIgnoreWhitespaces(newMessage, actualMessage)) } }
apache-2.0
fc6902281bd1f6df1b5b9e8d6b9ded93
31.717391
99
0.692069
4.234522
false
true
false
false
google/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnit3SuperTearDownInspection.kt
5
2755
// 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.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInspection.AbstractBaseUastLocalInspectionTool import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.registerUProblem import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.InheritanceUtil import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.junit.JUnitCommonClassNames import org.jetbrains.uast.* import org.jetbrains.uast.util.isInFinallyBlock import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor import org.jetbrains.uast.visitor.AbstractUastVisitor class JUnit3SuperTearDownInspection : AbstractBaseUastLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = UastHintedVisitorAdapter.create( holder.file.language, SuperTearDownInFinallyVisitor(holder), arrayOf(UCallExpression::class.java), directOnly = true ) } private class SuperTearDownInFinallyVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { if (node.receiver !is USuperExpression || node.methodName != "tearDown") return true val parentMethod = node.getParentOfType( UMethod::class.java, strict = true, terminators = arrayOf(ULambdaExpression::class.java, UDeclaration::class.java) ) ?: return true if (parentMethod.name != "tearDown") return true val containingClass = node.getContainingUClass()?.javaPsi ?: return true if (!InheritanceUtil.isInheritor(containingClass, JUnitCommonClassNames.JUNIT_FRAMEWORK_TEST_CASE)) return true if (node.isInFinallyBlock()) return true if (!hasNonTrivialActivity(parentMethod, node)) return true val message = JvmAnalysisBundle.message("jvm.inspections.junit3.super.teardown.problem.descriptor") holder.registerUProblem(node, message) return true } private fun hasNonTrivialActivity(parentMethod: UElement, node: UCallExpression): Boolean { val visitor = NonTrivialActivityVisitor(node) parentMethod.accept(visitor) return visitor.hasNonTrivialActivity } private class NonTrivialActivityVisitor(private val ignore: UCallExpression) : AbstractUastVisitor() { var hasNonTrivialActivity = false override fun visitCallExpression(node: UCallExpression): Boolean { if (node == ignore) return true hasNonTrivialActivity = true return true } } }
apache-2.0
b2402d1d720163d8376cd27cf0075c4c
45.711864
130
0.795644
4.955036
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/completionUtilsNoResolve.kt
1
6607
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.lookup.AutoCompletionPolicy import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.ui.JBColor import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.javaToKotlinNameMap 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.isAncestor import org.jetbrains.kotlin.renderer.render @ApiStatus.Internal val KOTLIN_CAST_REQUIRED_COLOR = JBColor(0x4E4040, 0x969696) val PsiElement.isInsideKtTypeReference: Boolean get() = getNonStrictParentOfType<KtTypeReference>() != null fun createKeywordElement( keyword: String, tail: String = "", lookupObject: KeywordLookupObject = KeywordLookupObject() ): LookupElementBuilder { var element = LookupElementBuilder.create(lookupObject, keyword + tail) element = element.withPresentableText(keyword) element = element.withBoldness(true) if (tail.isNotEmpty()) { element = element.withTailText(tail, false) } return element } fun createKeywordElementWithSpace( keyword: String, tail: String = "", addSpaceAfter: Boolean = false, lookupObject: KeywordLookupObject = KeywordLookupObject() ): LookupElement { val element = createKeywordElement(keyword, tail, lookupObject) return if (addSpaceAfter) { element.withInsertHandler(WithTailInsertHandler.SPACE.asPostInsertHandler) } else { element } } fun Name?.labelNameToTail(): String = if (this != null) "@" + render() else "" enum class ItemPriority { SUPER_METHOD_WITH_ARGUMENTS, FROM_UNRESOLVED_NAME_SUGGESTION, GET_OPERATOR, DEFAULT, IMPLEMENT, OVERRIDE, STATIC_MEMBER_FROM_IMPORTS, STATIC_MEMBER } /** * Checks whether user likely expects completion at the given position to offer a return statement. */ fun isLikelyInPositionForReturn(position: KtElement, parent: KtDeclarationWithBody, parentReturnUnit: Boolean): Boolean { val isInTopLevelInUnitFunction = parentReturnUnit && position.parent?.parent === parent val isInsideLambda = position.getNonStrictParentOfType<KtFunctionLiteral>()?.let { parent.isAncestor(it) } == true return when { isInsideLambda -> false // for now we do not want to alter completion inside lambda bodies position.inReturnExpression() -> false position.isRightOperandInElvis() -> true position.isLastOrSingleStatement() && !position.isDirectlyInLoopBody() && !isInTopLevelInUnitFunction -> true else -> false } } private fun KtElement.inReturnExpression(): Boolean = findReturnExpression(this) != null fun KtElement.isRightOperandInElvis(): Boolean { val elvisParent = parent as? KtBinaryExpression ?: return false return elvisParent.operationToken == KtTokens.ELVIS && elvisParent.right === this } /** * Checks if expression is either last expression in a block, or a single expression in position where single * expressions are allowed (`when` entries, `for` and `while` loops, and `if`s). */ private fun PsiElement.isLastOrSingleStatement(): Boolean = when (val containingExpression = parent) { is KtBlockExpression -> containingExpression.statements.lastOrNull() === this is KtWhenEntry, is KtContainerNodeForControlStructureBody -> true else -> false } private fun KtElement.isDirectlyInLoopBody(): Boolean { val loopContainer = when (val blockOrContainer = parent) { is KtBlockExpression -> blockOrContainer.parent as? KtContainerNodeForControlStructureBody is KtContainerNodeForControlStructureBody -> blockOrContainer else -> null } return loopContainer?.parent is KtLoopExpression } /** * If [expression] is directly relates to the return expression already, this return expression will be found. * * Examples: * * ```kotlin * return 10 // 10 is in return * return if (true) 10 else 20 // 10 and 20 are in return * return 10 ?: 20 // 10 and 20 are in return * return when { true -> 10 ; else -> { 20; 30 } } // 10 and 30 are in return, but 20 is not * ``` */ private tailrec fun findReturnExpression(expression: PsiElement?): KtReturnExpression? = when (val parent = expression?.parent) { is KtReturnExpression -> parent is KtBinaryExpression -> if (parent.operationToken == KtTokens.ELVIS) findReturnExpression(parent) else null is KtContainerNodeForControlStructureBody, is KtIfExpression -> findReturnExpression(parent) is KtBlockExpression -> if (expression.isLastOrSingleStatement()) findReturnExpression(parent) else null is KtWhenEntry -> findReturnExpression(parent.parent) else -> null } var LookupElement.priority by UserDataProperty(Key<ItemPriority>("ITEM_PRIORITY_KEY")) fun LookupElement.suppressAutoInsertion() = AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(this) fun referenceScope(declaration: KtNamedDeclaration): KtElement? = when (val parent = declaration.parent) { is KtParameterList -> parent.parent as KtElement is KtClassBody -> { val classOrObject = parent.parent as KtClassOrObject if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) { classOrObject.containingClassOrObject } else { classOrObject } } is KtFile -> parent is KtBlockExpression -> parent else -> null } fun FqName.isJavaClassNotToBeUsedInKotlin(): Boolean = JavaToKotlinClassMap.isJavaPlatformClass(this) || javaToKotlinNameMap[this] != null fun findValueArgument(expression: KtExpression): KtValueArgument? { // Search for value argument among parent and grandparent to avoid parsing errors like KTIJ-18231 return expression.parent as? KtValueArgument ?: expression.parent.parent as? KtValueArgument }
apache-2.0
a1cd543d2462a9311c36b80899bf000a
39.539877
158
0.735735
4.801599
false
false
false
false
StephaneBg/ScoreIt
core/src/main/kotlin/com/sbgapps/scoreit/core/utils/RecyclerViewSwipeDecorator.kt
1
10906
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.core.utils import android.graphics.Canvas import android.graphics.drawable.ColorDrawable import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.sbgapps.scoreit.core.ext.dip import timber.log.Timber /** * A simple utility class to add a background and/or an icon while swiping a RecyclerView item left or right. */ class RecyclerViewSwipeDecorator private constructor( private val canvas: Canvas, private val recyclerView: RecyclerView, private val viewHolder: RecyclerView.ViewHolder, private val dX: Float, private val actionState: Int ) { private var swipeLeftBackgroundColor: Int = 0 private var swipeLeftActionIconId: Int = 0 private var swipeLeftActionIconTint: Int? = null private var swipeRightBackgroundColor: Int = 0 private var swipeRightActionIconId: Int = 0 private var swipeRightActionIconTint: Int? = null init { swipeLeftBackgroundColor = 0 swipeRightBackgroundColor = 0 swipeLeftActionIconId = 0 swipeRightActionIconId = 0 swipeLeftActionIconTint = null swipeRightActionIconTint = null } /** * Set the background color for left swipe direction * * @param swipeLeftBackgroundColor The resource id of the background color to be set */ private fun setSwipeLeftBackgroundColor(swipeLeftBackgroundColor: Int) { this.swipeLeftBackgroundColor = swipeLeftBackgroundColor } /** * Set the action icon for left swipe direction * * @param swipeLeftActionIconId The resource id of the icon to be set */ private fun setSwipeLeftActionIconId(swipeLeftActionIconId: Int) { this.swipeLeftActionIconId = swipeLeftActionIconId } /** * Set the tint color for action icon drawn while swiping left * * @param color a color in ARGB format (e.g. 0xFF0000FF for blue) */ private fun setSwipeLeftActionIconTint(color: Int) { swipeLeftActionIconTint = color } /** * Set the background color for right swipe direction * * @param swipeRightBackgroundColor The resource id of the background color to be set */ private fun setSwipeRightBackgroundColor(swipeRightBackgroundColor: Int) { this.swipeRightBackgroundColor = swipeRightBackgroundColor } /** * Set the action icon for right swipe direction * * @param swipeRightActionIconId The resource id of the icon to be set */ private fun setSwipeRightActionIconId(swipeRightActionIconId: Int) { this.swipeRightActionIconId = swipeRightActionIconId } /** * Set the tint color for action icon drawn while swiping right * * @param color a color in ARGB format (e.g. 0xFF0000FF for blue) */ private fun setSwipeRightActionIconTint(color: Int) { swipeRightActionIconTint = color } /** * Decorate the RecyclerView item with the chosen backgrounds and icons */ fun decorate() { try { val iconHorizontalMargin = recyclerView.context.dip(16) val iconVisibilityDx = recyclerView.context.dip(16 + 24) if (actionState != ItemTouchHelper.ACTION_STATE_SWIPE) return if (dX > 0) { // Swiping Right if (swipeRightBackgroundColor != 0) { val background = ColorDrawable(swipeRightBackgroundColor) background.setBounds( viewHolder.itemView.left, viewHolder.itemView.top, viewHolder.itemView.left + dX.toInt(), viewHolder.itemView.bottom ) background.draw(canvas) } if (swipeRightActionIconId != 0 && dX > iconVisibilityDx) { val icon = ContextCompat.getDrawable(recyclerView.context, swipeRightActionIconId) if (icon != null) { val iconSize = icon.intrinsicHeight val halfIcon = iconSize / 2 val top = viewHolder.itemView.top + ((viewHolder.itemView.bottom - viewHolder.itemView.top) / 2 - halfIcon) icon.setBounds( viewHolder.itemView.left + iconHorizontalMargin, top, viewHolder.itemView.left + iconHorizontalMargin + icon.intrinsicWidth, top + icon.intrinsicHeight ) swipeRightActionIconTint?.let { DrawableCompat.setTint(icon, it) } icon.draw(canvas) } } } else if (dX < 0) { // Swiping Left if (swipeLeftBackgroundColor != 0) { val background = ColorDrawable(swipeLeftBackgroundColor) background.setBounds( viewHolder.itemView.right + dX.toInt(), viewHolder.itemView.top, viewHolder.itemView.right, viewHolder.itemView.bottom ) background.draw(canvas) } if (swipeLeftActionIconId != 0 && dX < -iconVisibilityDx) { val icon = ContextCompat.getDrawable(recyclerView.context, swipeLeftActionIconId) if (icon != null) { val iconSize = icon.intrinsicHeight val halfIcon = iconSize / 2 val top = viewHolder.itemView.top + ((viewHolder.itemView.bottom - viewHolder.itemView.top) / 2 - halfIcon) icon.setBounds( viewHolder.itemView.right - iconHorizontalMargin - halfIcon * 2, top, viewHolder.itemView.right - iconHorizontalMargin, top + icon.intrinsicHeight ) swipeLeftActionIconTint?.let { DrawableCompat.setTint(icon, it) } icon.draw(canvas) } } } } catch (e: Exception) { Timber.e(e) } } /** * A Builder for the RecyclerViewSwipeDecorator class */ class Builder /** * Create a builder for a RecyclerViewsSwipeDecorator * * @param canvas The canvas which RecyclerView is drawing its children * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to * @param viewHolder The ViewHolder which is being interacted by the User or it was interacted and simply animating to its original position * @param dX The amount of horizontal displacement caused by user's action * @param actionState The type of interaction on the View. Is either ACTION_STATE_DRAG or ACTION_STATE_SWIPE. */ ( canvas: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, actionState: Int ) { private val mDecorator: RecyclerViewSwipeDecorator = RecyclerViewSwipeDecorator( canvas, recyclerView, viewHolder, dX, actionState ) /** * Add a background color while swiping right * * @param color A single color value in the form 0xAARRGGBB * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun addSwipeRightBackgroundColor(color: Int): Builder { mDecorator.setSwipeRightBackgroundColor(color) return this } /** * Add an action icon while swiping right * * @param drawableId The resource id of the icon to be set * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun addSwipeRightActionIcon(drawableId: Int): Builder { mDecorator.setSwipeRightActionIconId(drawableId) return this } /** * Set the tint color for action icon shown while swiping right * * @param color a color in ARGB format (e.g. 0xFF0000FF for blue) * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun setSwipeRightActionIconTint(color: Int): Builder { mDecorator.setSwipeRightActionIconTint(color) return this } /** * Adds a background color while swiping left * * @param color A single color value in the form 0xAARRGGBB * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun addSwipeLeftBackgroundColor(color: Int): Builder { mDecorator.setSwipeLeftBackgroundColor(color) return this } /** * Add an action icon while swiping left * * @param drawableId The resource id of the icon to be set * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun addSwipeLeftActionIcon(drawableId: Int): Builder { mDecorator.setSwipeLeftActionIconId(drawableId) return this } /** * Set the tint color for action icon shown while swiping left * * @param color a color in ARGB format (e.g. 0xFF0000FF for blue) * @return This instance of @RecyclerViewSwipeDecorator.Builder */ fun setSwipeLeftActionIconTint(color: Int): Builder { mDecorator.setSwipeLeftActionIconTint(color) return this } /** * Create a RecyclerViewSwipeDecorator * * @return The created @RecyclerViewSwipeDecorator */ fun create(): RecyclerViewSwipeDecorator { return mDecorator } } }
apache-2.0
5ae4dee3d1a51e2baefafd49b54cbbb5
36.095238
151
0.594131
5.309153
false
false
false
false
forkhubs/android
app/src/main/java/com/github/pockethub/android/ui/item/news/ReleaseEventItem.kt
5
1552
package com.github.pockethub.android.ui.item.news import android.text.TextUtils import android.view.View import androidx.core.text.buildSpannedString import com.github.pockethub.android.ui.view.OcticonTextView import com.github.pockethub.android.util.AvatarLoader import com.meisolsson.githubsdk.model.GitHubEvent import com.meisolsson.githubsdk.model.Release import com.meisolsson.githubsdk.model.payload.ReleasePayload import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.news_item.* class ReleaseEventItem( avatarLoader: AvatarLoader, gitHubEvent: GitHubEvent ) : NewsItem(avatarLoader, gitHubEvent) { override fun bind(holder: ViewHolder, position: Int) { super.bind(holder, position) holder.tv_event_icon.text = OcticonTextView.ICON_UPLOAD holder.tv_event.text = buildSpannedString { val context = holder.root.context boldActor(context, this, gitHubEvent) append(" uploaded a file to ") boldRepo(context, this, gitHubEvent) } val details = buildSpannedString { val payload = gitHubEvent.payload() as ReleasePayload? val download: Release? = payload?.release() appendText(this, download?.name()) } if (TextUtils.isEmpty(details)) { holder.tv_event_details.visibility = View.GONE } else { holder.tv_event_details.visibility = View.VISIBLE holder.tv_event_details.text = details } } }
apache-2.0
2519c0c49d95a9fe6048bb9c9664858f
36.853659
66
0.697809
4.511628
false
false
false
false
leafclick/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/util.kt
1
2432
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.impl.VcsLogManager import git4idea.GitCommit import git4idea.GitVcs import git4idea.history.GitCommitRequirements import git4idea.history.GitCommitRequirements.DiffInMergeCommits import git4idea.history.GitCommitRequirements.DiffRenameLimit import git4idea.history.GitLogUtil fun getGitRootFiles(project: Project, files: Collection<FilePath>): Map<VirtualFile, Collection<FilePath>> { val rootFiles = HashMap<VirtualFile, HashSet<FilePath>>() val projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project) files.forEach { filePath -> val fileVcs = projectLevelVcsManager.getVcsRootObjectFor(filePath) if (fileVcs != null && fileVcs.vcs is GitVcs) { rootFiles.getOrPut(fileVcs.path) { HashSet() }.add(filePath) } } return rootFiles } fun processCommitsFromHashes(project: Project, root: VirtualFile, hashes: List<String>, commitConsumer: (GitCommit) -> Unit) { val requirements = GitCommitRequirements(diffRenameLimit = DiffRenameLimit.NO_RENAMES, diffInMergeCommits = DiffInMergeCommits.NO_DIFF) GitLogUtil.readFullDetailsForHashes(project, root, hashes.toList(), requirements, Consumer<GitCommit> { commitConsumer(it) }) } fun <T> measureSupplierTimeMillis(supplier: () -> T): Pair<Long, T> { val startTime = System.currentTimeMillis() val result = supplier() val executionTime = System.currentTimeMillis() - startTime return Pair(executionTime, result) } fun <T, K> MutableMap<T, K>.retainAll(keys: Collection<T>) = this.keys.subtract(keys).forEach { this.remove(it) } internal fun Project.getGitRoots() = ProjectLevelVcsManager.getInstance(this).allVcsRoots.filter { it.vcs is GitVcs } internal fun Project.anyGitRootsForIndexing(): Boolean { val gitRoots = this.getGitRoots() val rootsForIndex = VcsLogPersistentIndex.getRootsForIndexing(VcsLogManager.findLogProviders(gitRoots, this)) return rootsForIndex.isNotEmpty() }
apache-2.0
bf44030ba42b3a88fdea1dfe8f32466f
40.948276
140
0.778372
4.229565
false
false
false
false
AndroidX/androidx
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/StartupProfiles.kt
3
2002
/* * 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. */ @file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) package androidx.benchmark.macro import androidx.annotation.RestrictTo private val PROFILE_RULE_REGEX = "(H?S?P?)L([^$;]*)(.*)".toRegex() /** * Builds a startup profile for a given baseline profile. * * This startup profile can be used for dex layout optimizations. */ fun startupProfile(profile: String, includeStartupOnly: Boolean = false): String { val rules = profile.lines().mapNotNull { rule -> when (val result = PROFILE_RULE_REGEX.find(rule)) { null -> null else -> { val (flags, classPrefix, _) = result.destructured // Empty flags are indicative that the class needs to be aggressively preloaded // Therefore the class belongs in the primary dex. val isStartup = flags.isEmpty() || flags.contains("S") if (includeStartupOnly && !isStartup) { null } else { "SL$classPrefix;" } } } } val ruleSet = mutableSetOf<String>() val startupRules = mutableListOf<String>() // Try and keep the same order rules.forEach { rule -> if (!ruleSet.contains(rule)) { ruleSet += rule startupRules += rule } } return startupRules.joinToString(separator = "\n") }
apache-2.0
e7754af18ce0a79d524672a728c6982f
34.122807
95
0.629371
4.448889
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizeActionGroupPanel.kt
1
9113
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.ui.customization import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.* import com.intellij.ui.components.JBList import com.intellij.ui.components.dialog import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.speedSearch.SpeedSearchUtil import com.intellij.util.Function import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.Nls import java.awt.Component import java.awt.Dimension import java.awt.event.KeyEvent import java.util.function.Supplier import javax.swing.Icon import javax.swing.JComponent import javax.swing.JList /** * An actions list with search field and control buttons: add, remove, move and reset. * * @param [groupId] id of group that is used to show actions * @param [addActionGroupIds] ids of groups that are shown when Add action is called. * If empty all actions are shown by default. * Use [addActionHandler] to override default dialog. * * @see showDialog */ class CustomizeActionGroupPanel( val groupId: String, val addActionGroupIds: List<String> = emptyList(), ) : BorderLayoutPanel() { private val list: JBList<Any> /** * Handles Add action event for adding new actions. Returns a list of objects. * * @see CustomizationUtil.acceptObjectIconAndText */ var addActionHandler: () -> List<Any>? = { ActionGroupPanel.showDialog( IdeBundle.message("group.customizations.add.action.group"), *addActionGroupIds.toTypedArray() ) } init { list = JBList<Any>().apply { model = CollectionListModel(collectActions(groupId, CustomActionsSchema.getInstance())) cellRenderer = MyListCellRender() } preferredSize = Dimension(420, 300) addToTop(BorderLayoutPanel().apply { addToRight(createActionToolbar()) addToCenter(createSearchComponent()) }) addToCenter(createCentralPanel(list)) } private fun collectActions(groupId: String, schema: CustomActionsSchema): List<Any> { return ActionGroupPanel.getActions(listOf(groupId), schema).first().children } fun getActions(): List<Any> = (list.model as CollectionListModel).toList() private fun createActionToolbar(): JComponent { val group = DefaultActionGroup().apply { val addActionGroup = DefaultActionGroup().apply { templatePresentation.text = IdeBundle.message("group.customizations.add.action.group") templatePresentation.icon = AllIcons.General.Add isPopup = true } addActionGroup.addAll( AddAction(IdeBundle.messagePointer("button.add.action")) { selected, model -> addActionHandler()?.let { result -> result.forEachIndexed { i, value -> model.add(selected + i + 1, value) } list.selectedIndices = IntArray(result.size) { i -> selected + i + 1 } } }, AddAction(IdeBundle.messagePointer("button.add.separator")) { selected, model -> model.add(selected + 1, Separator.create()) list.selectedIndex = selected + 1 } ) add(addActionGroup) add(RemoveAction(IdeBundle.messagePointer("button.remove"), AllIcons.General.Remove)) add(MoveAction(Direction.UP, IdeBundle.messagePointer("button.move.up"), AllIcons.Actions.MoveUp)) add(MoveAction(Direction.DOWN, IdeBundle.messagePointer("button.move.down"), AllIcons.Actions.MoveDown)) add(RestoreAction(IdeBundle.messagePointer("button.restore.all"), AllIcons.Actions.Rollback)) } return ActionManager.getInstance().createActionToolbar("CustomizeActionGroupPanel", group, true).apply { targetComponent = list setReservePlaceAutoPopupIcon(false) }.component } private fun createSearchComponent(): Component { val speedSearch = object : ListSpeedSearch<Any>(list, Function { when (it) { is String -> ActionManager.getInstance().getAction(it).templateText else -> null } }) { override fun isPopupActive() = true override fun showPopup(searchText: String?) {} override fun isSpeedSearchEnabled() = false override fun showPopup() {} } val filterComponent = object : FilterComponent("CUSTOMIZE_ACTIONS", 5) { override fun filter() { speedSearch.findAndSelectElement(filter) speedSearch.component.repaint() } } for (keyCode in intArrayOf(KeyEvent.VK_HOME, KeyEvent.VK_END, KeyEvent.VK_UP, KeyEvent.VK_DOWN)) { object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val filter: String = filterComponent.filter if (!StringUtil.isEmpty(filter)) { speedSearch.adjustSelection(keyCode, filter) } } }.registerCustomShortcutSet(keyCode, 0, filterComponent.textEditor) } return filterComponent } private fun createCentralPanel(list: JBList<Any>): Component { return Wrapper(ScrollPaneFactory.createScrollPane(list)).apply { border = JBUI.Borders.empty(3) } } companion object { fun showDialog(groupId: String, sourceGroupIds: List<String>, @Nls title: String, customize: CustomizeActionGroupPanel.() -> Unit = {}): List<Any>? { val panel = CustomizeActionGroupPanel(groupId, sourceGroupIds) panel.preferredSize = Dimension(480, 360) panel.customize() val dialog = dialog( title = title, panel = panel, resizable = true, focusedComponent = panel.list ) return if (dialog.showAndGet()) panel.getActions() else null } } private inner class AddAction( text: Supplier<String>, val block: (selected: Int, model: CollectionListModel<Any>) -> Unit ) : DumbAwareAction(text, Presentation.NULL_STRING, null) { override fun actionPerformed(e: AnActionEvent) { val selected = list.selectedIndices?.lastOrNull() ?: (list.model.size - 1) val model = (list.model as CollectionListModel) block(selected, model) } } private inner class MoveAction( val direction: Direction, text: Supplier<String>, icon: Icon ) : DumbAwareAction(text, Presentation.NULL_STRING, icon) { init { registerCustomShortcutSet(direction.shortcut, list) } override fun actionPerformed(e: AnActionEvent) { val model = list.model as CollectionListModel val indices = list.selectedIndices for (i in indices.indices) { val index = indices[i] model.exchangeRows(index, index + direction.sign) indices[i] = index + direction.sign } list.selectedIndices = indices list.scrollRectToVisible(list.getCellBounds(indices.first(), indices.last())) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = direction.test(list.selectedIndices, list.model.size) } } private inner class RemoveAction( text: Supplier<String>, icon: Icon ) : DumbAwareAction(text, Presentation.NULL_STRING, icon) { init { registerCustomShortcutSet(CommonShortcuts.getDelete(), list) } override fun actionPerformed(e: AnActionEvent) { val model = list.model as CollectionListModel val selectedIndices = list.selectedIndices selectedIndices.reversedArray().forEach(model::remove) selectedIndices.firstOrNull()?.let { list.selectedIndex = it.coerceAtMost(model.size - 1) } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = list.selectedIndices.isNotEmpty() } } private inner class RestoreAction( text: Supplier<String>, icon: Icon ) : DumbAwareAction(text, Presentation.NULL_STRING, icon) { private val defaultActions = collectActions(groupId, CustomActionsSchema()) override fun actionPerformed(e: AnActionEvent) { list.model = CollectionListModel(defaultActions) } override fun update(e: AnActionEvent) { val current = (list.model as CollectionListModel).items e.presentation.isEnabled = defaultActions != current } } enum class Direction(val sign: Int, val shortcut: ShortcutSet, val test: (index: IntArray, size: Int) -> Boolean) { UP(-1, CommonShortcuts.MOVE_UP, { index, _ -> index.isNotEmpty() && index.first() >= 1 }), DOWN(1, CommonShortcuts.MOVE_DOWN, { index, size -> index.isNotEmpty() && index.last() < size - 1 }); } private class MyListCellRender : ColoredListCellRenderer<Any>() { override fun customizeCellRenderer(list: JList<out Any>, value: Any?, index: Int, selected: Boolean, hasFocus: Boolean) { CustomizationUtil.acceptObjectIconAndText(value) { t, i -> SpeedSearchUtil.appendFragmentsForSpeedSearch(list, t, SimpleTextAttributes.REGULAR_ATTRIBUTES, selected, this) icon = i } } } }
apache-2.0
02a41d9d8ce6920dbb3308b9f0754ae7
35.166667
158
0.696697
4.513621
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/redundantSuspendModifier/operators.kt
9
1127
// WITH_STDLIB class A(val x: Int) { // Redundant suspend operator fun plus(a: A): A { return A(x + a.x) } } // Not redundant suspend fun foo(a1: A, a2: A): A { return a1 + a2 } // Not redundant suspend fun bar(a1: A, a2: A): A { var result = a1 result += a2 return result } class B(var x: Int) { // Redundant suspend operator fun minusAssign(b: B) { x -= b.x } } // Not redundant suspend fun foo(b1: B, b2: B): B { val result = b1 result -= b2 return result } class C(val x: Int, val y: Int) { // Redundant suspend operator fun invoke() = x + y } // Not redundant suspend fun bar(): Int { return C(1, 2)() } // Not redundant suspend fun foo(c1: C, c2: C): Int { return c1() + c2() } interface C { // Not redundant suspend fun foo() } class D : C { // Not redundant override suspend fun foo() { } } open class E { // Not redundant open suspend fun bar() { } // Not redundant abstract suspend fun baz() } // Not redundant suspend fun foo(): Int { return someFunctionThatDoesntResolve() }
apache-2.0
770d8a0ca641ee9f2da7322d701c3f67
14.243243
44
0.565217
3.11326
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/GizmoTest.kt
1
9220
package de.fabmax.kool.demo import de.fabmax.kool.KoolContext import de.fabmax.kool.demo.menu.DemoMenu import de.fabmax.kool.math.* import de.fabmax.kool.modules.ksl.KslBlinnPhongShader import de.fabmax.kool.modules.ui2.* import de.fabmax.kool.scene.Scene import de.fabmax.kool.scene.colorMesh import de.fabmax.kool.scene.defaultCamTransform import de.fabmax.kool.scene.group import de.fabmax.kool.toString import de.fabmax.kool.util.Color import de.fabmax.kool.util.Gizmo import de.fabmax.kool.util.InputStack import de.fabmax.kool.util.MdColor class GizmoTest : DemoScene("Gizmo Test") { private val gizmo1 = Gizmo() private val gizmo2 = Gizmo() private val transform1 = TransformProps(gizmo1) private val transform2 = TransformProps(gizmo2) override fun Scene.setupMainScene(ctx: KoolContext) { gizmo1.gizmoListener = object : Gizmo.GizmoListener { override fun onDragAxis(axis: Vec3f, distance: Float, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.translate(axis.x * distance, axis.y * distance, axis.z * distance) } override fun onDragPlane(planeNormal: Vec3f, dragPosition: Vec3f, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.translate(dragPosition) } override fun onDragRotate(rotationAxis: Vec3f, angle: Float, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.rotate(angle, rotationAxis) } } +group { onUpdate += { gizmo1.getGizmoTransform(this) } +colorMesh { generate { cube { centered() } } shader = KslBlinnPhongShader { color { vertexColor() } } } } // gizmo must be added after scene objects for correct depth / alpha behavior +gizmo1 gizmo2.setFixedScale(1f) gizmo2.axisHandleX.set(4f, 0f, 0f) gizmo2.setGizmoTransform(Mat4d().translate(0.0, 0.0, 3.0)) gizmo2.properties = Gizmo.GizmoProperties( axisColorX = Color.WHITE, axisColorNegX = Color.WHITE, axisHandleColorX = MdColor.AMBER, axisHandleColorNegX = MdColor.AMBER, isOnlyShowAxisTowardsCam = false, rotationHandleRadius = 0.75f, hasAxisY = false, hasAxisNegY = false, hasRotationX = false, hasRotationY = true, hasRotationZ = false, hasPlaneXY = false, hasPlaneXZ = true, hasPlaneYZ = false ) +gizmo2 var axX = 1f var axNegX = -1f gizmo2.gizmoListener = object : Gizmo.GizmoListener { override fun onDragStart(ctx: KoolContext) { axX = gizmo2.axisHandleX.x axNegX = gizmo2.axisHandleNegX.x } override fun onDragAxis(axis: Vec3f, distance: Float, targetTransform: Mat4d, ctx: KoolContext) { if (axis.z != 0f || ctx.inputMgr.isAltDown) { targetTransform.translate(axis.x * distance, axis.y * distance, axis.z * distance) } else if (axis.x > 0f) { gizmo2.axisHandleX.x = max(0.1f, axX + distance) } else { gizmo2.axisHandleNegX.x = min(-0.1f, axNegX - distance) } gizmo2.updateMesh() } override fun onDragPlane(planeNormal: Vec3f, dragPosition: Vec3f, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.translate(dragPosition) } override fun onDragRotate(rotationAxis: Vec3f, angle: Float, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.rotate(angle, rotationAxis) } } InputStack.defaultInputHandler.pointerListeners += gizmo1 InputStack.defaultInputHandler.pointerListeners += gizmo2 // add cam transform after gizmo, so that gizmo can consume drag events before cam transform defaultCamTransform() onUpdate += { transform1.update() transform2.update() } onDispose += { InputStack.defaultInputHandler.pointerListeners -= gizmo1 InputStack.defaultInputHandler.pointerListeners -= gizmo2 } camera.setClipRange(0.2f, 500f) } override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface { Text("Gizmo 1") { sectionTitleStyle() } MenuRow { val isDynScale1 = weakRememberState(gizmo1.isDynamicScale()).onChange { if (it) gizmo1.setDynamicScale() else gizmo1.setFixedScale() } LabeledSwitch("Dynamic scale", isDynScale1) } translation(transform1) rotation(transform1) Text("Gizmo 2") { sectionTitleStyle() } MenuRow { val isDynScale2 = weakRememberState(gizmo2.isDynamicScale()).onChange { if (it) gizmo2.setDynamicScale() else gizmo2.setFixedScale() } LabeledSwitch("Dynamic scale", isDynScale2) } translation(transform2) rotation(transform2) } private fun UiScope.translation(props: TransformProps) = MenuRow { Column(sizes.largeGap * 4f) { Text("Location") { modifier.margin(vertical = sizes.smallGap * 0.75f) } } Column(Grow.Std) { Row(Grow.Std) { Text("x:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.tx, 3) } Row(Grow.Std) { Text("y:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.ty, 3) } Row(Grow.Std) { Text("z:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.tz, 3) } } } private fun UiScope.rotation(props: TransformProps) = MenuRow { Column(sizes.largeGap * 4f) { Text("Rotation") { modifier.margin(vertical = sizes.smallGap * 0.75f) } } Column(Grow.Std) { Row(Grow.Std) { Text("x:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.rx, 1) } Row(Grow.Std) { Text("y:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.ry, 1) } Row(Grow.Std) { Text("z:") { modifier.alignY(AlignmentY.Center) } TransformTextField(props.rz, 1) } } } private fun UiScope.TransformTextField(state: MutableStateValue<Float>, precision: Int) = TextField { val text = weakRememberState(state.value.toString(precision)) if (!isFocused.value) { text.set(state.use().toString(precision)) } modifier .text(text.use()) .padding(vertical = sizes.smallGap * 0.75f) .margin(start = sizes.gap) .width(Grow.Std) .textAlignX(AlignmentX.End) .onEnterPressed { text.set(state.use().toString(precision)) } .onChange { txt -> text.set(txt) txt.toFloatOrNull()?.let { state.set(it) } } } class TransformProps(val gizmo: Gizmo) { private var isUpdateFromGizmo = false val tx = mutableStateOf(0f).onChange { updateTranslation(x = it) } val ty = mutableStateOf(0f).onChange { updateTranslation(y = it) } val tz = mutableStateOf(0f).onChange { updateTranslation(z = it) } val rx = mutableStateOf(0f).onChange { updateRotation(x = it) } val ry = mutableStateOf(0f).onChange { updateRotation(y = it) } val rz = mutableStateOf(0f).onChange { updateRotation(z = it) } private val tmpMat4 = Mat4d() private val tmpMat3 = Mat3f() private val tmpVec = MutableVec3f() fun update() { gizmo.getGizmoTransform(tmpMat4) isUpdateFromGizmo = true tmpMat4.transform(tmpVec.set(Vec3f.ZERO)) tx.set(tmpVec.x) ty.set(tmpVec.y) tz.set(tmpVec.z) tmpMat4.getRotation(tmpMat3).getEulerAngles(tmpVec) rx.set(tmpVec.x) ry.set(tmpVec.y) rz.set(tmpVec.z) isUpdateFromGizmo = false } private fun updateTranslation(x: Float = tx.value, y: Float = ty.value, z: Float = tz.value) { if (isUpdateFromGizmo) { return } gizmo.setTranslation(tmpVec.set(x, y, z)) } private fun updateRotation(x: Float = rx.value, y: Float = ry.value, z: Float = rz.value) { if (isUpdateFromGizmo) { return } gizmo.setEulerAngles(tmpVec.set(x, y, z)) } } }
apache-2.0
4d2a0722b5dbc053d68768f2211c4cbb
34.329502
121
0.561714
4.21968
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/ProjectUpdateViewHolder.kt
1
2140
package com.kickstarter.ui.viewholders import com.kickstarter.R import com.kickstarter.databinding.ActivityProjectUpdateViewBinding import com.kickstarter.libs.utils.DateTimeUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.Activity import com.squareup.picasso.Picasso import org.joda.time.DateTime class ProjectUpdateViewHolder( private val binding: ActivityProjectUpdateViewBinding, private val delegate: Delegate? ) : ActivityListViewHolder(binding.root) { private val ksString = requireNotNull(environment().ksString()) interface Delegate { fun projectUpdateProjectClicked(viewHolder: ProjectUpdateViewHolder?, activity: Activity?) fun projectUpdateClicked(viewHolder: ProjectUpdateViewHolder?, activity: Activity?) } override fun onBind() { val context = context() val project = activity().project() val user = activity().user() val photo = project?.photo() val update = activity().update() if (project != null && user != null && photo != null && update != null) { val publishedAt = ObjectUtils.coalesce(update.publishedAt(), DateTime()) binding.projectName.text = project.name() Picasso.get() .load(photo.little()) .into(binding.projectPhoto) binding.timestamp.text = DateTimeUtils.relative(context, ksString, publishedAt) binding.updateBody.text = update.truncatedBody() binding.updateSequence.text = ksString.format( context.getString(R.string.activity_project_update_update_count), "update_count", update.sequence().toString() ) binding.updateTitle.text = update.title() binding.projectInfo.setOnClickListener { this.projectOnClick() } binding.updateInfo.setOnClickListener { this.updateOnClick() } } } private fun projectOnClick() { delegate?.projectUpdateProjectClicked(this, activity()) } private fun updateOnClick() { delegate?.projectUpdateClicked(this, activity()) } }
apache-2.0
acf54086d0c5c0e1846e7c397581b02b
37.909091
98
0.678505
4.953704
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/ShaderGraph.kt
1
3437
package de.fabmax.kool.pipeline.shadermodel import de.fabmax.kool.math.Vec4f import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.DescriptorSetLayout import de.fabmax.kool.pipeline.PushConstantRange import de.fabmax.kool.pipeline.ShaderStage class ShaderInterfaceIoVar(val location: Int, val variable: ModelVar, val isFlat: Boolean, val locationInc: Int = 1) open class ShaderGraph(val model: ShaderModel, val stage: ShaderStage) { val descriptorSet = DescriptorSetLayout.Builder() val pushConstants = PushConstantRange.Builder() val inputs = mutableListOf<ShaderInterfaceIoVar>() private val mutOutputs = mutableListOf<ShaderInterfaceIoVar>() val outputs: List<ShaderInterfaceIoVar> get() = mutOutputs protected val mutNodes = mutableListOf<ShaderNode>() val nodes: List<ShaderNode> get() = mutNodes var nextNodeId = 1 internal set inline fun <reified T: ShaderNode> findNode(name: String): T? { return nodes.find { it.name == name && it is T } as T? } fun findNodeByName(name: String): ShaderNode? { return nodes.find { it.name == name} } fun addStageOutput(output: ModelVar, isFlat: Boolean, locationInc: Int = 1): ShaderInterfaceIoVar { val location = mutOutputs.sumOf { it.locationInc } val ifVar = ShaderInterfaceIoVar(location, output, isFlat, locationInc) mutOutputs += ifVar return ifVar } fun addNode(node: ShaderNode) { if (node.graph !== this) { throw IllegalStateException("Node can only be added to it's parent graph") } mutNodes.add(node) } open fun clear() { descriptorSet.clear() pushConstants.clear() inputs.clear() mutOutputs.clear() } open fun setup() { nodes.forEach { it.setup(this) } } open fun generateCode(generator: CodeGenerator) { sortNodesByDependencies() nodes.forEach { it.generateCode(generator) } } private fun sortNodesByDependencies() { val sortedNodes = linkedSetOf<ShaderNode>() while (nodes.isNotEmpty()) { val ndIt = mutNodes.iterator() var anyAdded = false for (nd in ndIt) { if (sortedNodes.containsAll(nd.dependencies)) { sortedNodes.add(nd) ndIt.remove() anyAdded = true } } if (!anyAdded) { println("${model.modelName} - Remaining nodes:") nodes.forEach { println(it.name) it.dependencies.forEach { dep -> val state = if (sortedNodes.contains(dep)) "[ok]" else "[missing]" println(" -> ${dep.name} $state") } } throw IllegalStateException("Unable to resolve shader graph (circular or missing dependency?)") } } mutNodes.addAll(sortedNodes) } } class VertexShaderGraph(model: ShaderModel) : ShaderGraph(model, ShaderStage.VERTEX_SHADER) { val requiredVertexAttributes = mutableSetOf<Attribute>() val requiredInstanceAttributes = mutableSetOf<Attribute>() var positionOutput = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO), null) } class FragmentShaderGraph(model: ShaderModel) : ShaderGraph(model, ShaderStage.FRAGMENT_SHADER)
apache-2.0
ebd3c3a9881dd9ddc369c715ba0a63f1
34.081633
116
0.627873
4.552318
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/tooManyOutputValues.kt
4
507
// WITH_RUNTIME // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int // PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo // PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo // PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo // SIBLING: fun foo(a: Int): Int { var b: Int = 1 var c: Int = 1 var d: Int = 1 var e: Int = 1 <selection>b += a c -= a d += c e -= d println(b) println(c)</selection> return b + c + d + e }
apache-2.0
226f4edaa47d137a4b8c06303f5091d7
21.086957
65
0.597633
3.12963
false
false
false
false
JetBrains/xodus
environment/src/main/kotlin/jetbrains/exodus/env/CopyEnvironment.kt
1
5939
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.env import jetbrains.exodus.ArrayByteIterable import jetbrains.exodus.runtime.OOMGuard import mu.KLogger import java.io.File import java.util.* import kotlin.math.min fun Environment.copyTo(there: File, forcePrefixing: Boolean, logger: KLogger? = null, progress: ((Any?) -> Unit)? = null) { if (there.list().run { this != null && isNotEmpty() }) { progress?.invoke("Target environment path is expected to be an empty directory: $there") return } val maxMemory = Runtime.getRuntime().maxMemory() val guard = OOMGuard(if (maxMemory == Long.MAX_VALUE) 20_000_000 else min(maxMemory / 50L, 1000_000_000).toInt()) Environments.newInstance(there, environmentConfig).use { newEnv -> progress?.invoke("Copying environment to " + newEnv.location) val names = computeInReadonlyTransaction { txn -> getAllStoreNames(txn) } val storesCount = names.size progress?.invoke("Stores found: $storesCount") names.forEachIndexed { i, name -> val started = Date() print(copyStoreMessage(started, name, i + 1, storesCount, 0L)) var storeSize = 0L var storeIsBroken: Throwable? = null try { newEnv.executeInExclusiveTransaction { targetTxn -> try { executeInReadonlyTransaction { sourceTxn -> val sourceStore = openStore(name, StoreConfig.USE_EXISTING, sourceTxn) val targetConfig = sourceStore.config.let { sourceConfig -> if (forcePrefixing) StoreConfig.getStoreConfig(sourceConfig.duplicates, true) else sourceConfig } val targetStore = newEnv.openStore(name, targetConfig, targetTxn) storeSize = sourceStore.count(sourceTxn) sourceStore.openCursor(sourceTxn).forEachIndexed { targetStore.putRight(targetTxn, ArrayByteIterable(key), ArrayByteIterable(value)) if ((it + 1) % 100_000 == 0 || guard.isItCloseToOOM()) { targetTxn.flush() guard.reset() print(copyStoreMessage(started, name, i + 1, storesCount, (it.toLong() * 100L / storeSize))) } } } } catch (t: Throwable) { targetTxn.flush() throw t } } } catch (t: Throwable) { logger?.warn(t) { "Failed to completely copy $name, proceeding in reverse order..." } if (t is VirtualMachineError) { throw t } storeIsBroken = t } if (storeIsBroken != null) { try { newEnv.executeInExclusiveTransaction { targetTxn -> try { executeInReadonlyTransaction { sourceTxn -> val sourceStore = openStore(name, StoreConfig.USE_EXISTING, sourceTxn) val targetConfig = sourceStore.config.let { sourceConfig -> if (forcePrefixing) StoreConfig.getStoreConfig(sourceConfig.duplicates, true) else sourceConfig } val targetStore = newEnv.openStore(name, targetConfig, targetTxn) storeSize = sourceStore.count(sourceTxn) sourceStore.openCursor(sourceTxn).forEachReversed { targetStore.put(targetTxn, ArrayByteIterable(key), ArrayByteIterable(value)) if (guard.isItCloseToOOM()) { targetTxn.flush() guard.reset() } } } } catch (t: Throwable) { targetTxn.flush() throw t } } } catch (t: Throwable) { logger?.error(t) { "Failed to completely copy $name" } if (t is VirtualMachineError) { throw t } } println() logger?.error("Failed to completely copy store $name", storeIsBroken) } val actualSize = newEnv.computeInReadonlyTransaction { txn -> if (newEnv.storeExists(name, txn)) { newEnv.openStore(name, StoreConfig.USE_EXISTING, txn).count(txn) } else 0L } progress?.invoke("\r$started Copying store $name (${i + 1} of $storesCount): saved store size = $storeSize, actual number of pairs = $actualSize") } } } private fun copyStoreMessage(started: Date, name: String, n: Int, totalCount: Int, percent: Long) = "\r$started Copying store $name ($n of $totalCount): $percent%"
apache-2.0
a5e267a52f5dba21bea82053ce03b2ed
48.5
163
0.521468
5.115418
false
true
false
false
jwren/intellij-community
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt
1
9197
// 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.test import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiFile import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.assertEqualsToFile import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import java.io.File object DirectiveBasedActionUtils { const val DISABLE_ERRORS_DIRECTIVE = "// DISABLE-ERRORS" const val DISABLE_WARNINGS_DIRECTIVE = "// DISABLE-WARNINGS" const val ENABLE_WARNINGS_DIRECTIVE = "// ENABLE-WARNINGS" const val ACTION_DIRECTIVE = "// ACTION:" fun checkForUnexpectedErrors(file: KtFile, diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics }) { if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_ERRORS_DIRECTIVE).isNotEmpty()) { return } checkForUnexpected(file, diagnosticsProvider, "// ERROR:", "errors", Severity.ERROR) } fun checkForUnexpectedWarnings( file: KtFile, disabledByDefault: Boolean = true, directiveName: String = Severity.WARNING.name, diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics } ) { if (disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, ENABLE_WARNINGS_DIRECTIVE).isEmpty() || !disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_WARNINGS_DIRECTIVE).isNotEmpty() ) { return } checkForUnexpected(file, diagnosticsProvider, "// $directiveName:", "warnings", Severity.WARNING) } private fun checkForUnexpected( file: KtFile, diagnosticsProvider: (KtFile) -> Diagnostics, directive: String, name: String, severity: Severity, ) { val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive) .sorted() .map { "$directive $it" } val diagnostics = diagnosticsProvider(file) val actual = diagnostics .filter { it.severity == severity } .map { "$directive ${DefaultErrorMessages.render(it).replace("\n", "<br>")}" } .sorted() if (actual.isEmpty() && expected.isEmpty()) return UsefulTestCase.assertOrderedEquals( "All actual $name should be mentioned in test data with '$directive' directive. " + "But no unnecessary $name should be me mentioned, file:\n${file.text}", actual, expected, ) } fun inspectionChecks(name: String, file: PsiFile) { val inspectionNames = InTextDirectivesUtils.findLinesWithPrefixesRemoved( /* fileText = */ file.text, /* ...prefixes = */ "// INSPECTION-CLASS:", ).ifEmpty { return } val inspectionManager = InspectionManager.getInstance(file.project) val inspections = inspectionNames.map { Class.forName(it).getDeclaredConstructor().newInstance() as AbstractKotlinInspection } val problems = mutableListOf<ProblemDescriptor>() ProgressManager.getInstance().executeProcessUnderProgress( /* process = */ { for (inspection in inspections) { problems += inspection.processFile( file, inspectionManager ) } }, /* progress = */ DaemonProgressIndicator(), ) val directive = "// INSPECTION:" val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive) .sorted() .map { "$directive $it" } val actual = problems // lineNumber is 0-based .map { "$directive [${it.highlightType.name}:${it.lineNumber + 1}] $it" } .sorted() if (actual.isEmpty() && expected.isEmpty()) return KotlinLightCodeInsightFixtureTestCaseBase.assertOrderedEquals( "All actual $name should be mentioned in test data with '$directive' directive. " + "But no unnecessary $name should be me mentioned, file:\n${file.text}", actual, expected, ) } fun checkAvailableActionsAreExpected(file: File, availableActions: Collection<IntentionAction>) { val fileText = file.readText() checkAvailableActionsAreExpected( fileText, availableActions, ) { expectedActionsDirectives, actualActionsDirectives -> if (expectedActionsDirectives != actualActionsDirectives) { assertEqualsToFile( description = "Some unexpected actions available at current position. Use '$ACTION_DIRECTIVE' directive", expected = file, actual = fileText.let { text -> val lines = text.split('\n') val firstActionIndex = lines.indexOfFirst { it.startsWith(ACTION_DIRECTIVE) }.takeIf { it != -1 } val textWithoutActions = lines.filterNot { it.startsWith(ACTION_DIRECTIVE) } textWithoutActions.subList(0, firstActionIndex ?: 1) .plus(actualActionsDirectives) .plus(textWithoutActions.drop(firstActionIndex ?: 1)) .joinToString("\n") } ) } } } fun checkAvailableActionsAreExpected(file: PsiFile, availableActions: Collection<IntentionAction>) { checkAvailableActionsAreExpected( file.text, availableActions, ) { expectedDirectives, actualActionsDirectives -> UsefulTestCase.assertOrderedEquals( "Some unexpected actions available at current position. Use '$ACTION_DIRECTIVE' directive\n", actualActionsDirectives, expectedDirectives ) } } private fun checkAvailableActionsAreExpected( fileText: String, availableActions: Collection<IntentionAction>, assertion: (expectedDirectives: List<String>, actualActionsDirectives: List<String>) -> Unit, ) { val expectedActions = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, ACTION_DIRECTIVE).sorted() UsefulTestCase.assertEmpty( "Irrelevant actions should not be specified in $ACTION_DIRECTIVE directive for they are not checked anyway", expectedActions.filter(::isIrrelevantAction), ) if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// IGNORE_IRRELEVANT_ACTIONS").isNotEmpty()) { return } val actualActions = availableActions.map { it.text }.sorted() val actualActionsDirectives = filterOutIrrelevantActions(actualActions).map { "$ACTION_DIRECTIVE $it" } val expectedActionsDirectives = expectedActions.map { "$ACTION_DIRECTIVE $it" } assertion(expectedActionsDirectives, actualActionsDirectives) } //TODO: hack, implemented because irrelevant actions behave in different ways on build server and locally // this behaviour should be investigated and hack can be removed private fun filterOutIrrelevantActions(actions: Collection<String>): Collection<String> { return actions.filter { !isIrrelevantAction(it) } } private fun isIrrelevantAction(action: String) = action.isEmpty() || IRRELEVANT_ACTION_PREFIXES.any { action.startsWith(it) } private val IRRELEVANT_ACTION_PREFIXES = listOf( "Disable ", "Edit intention settings", "Edit inspection profile setting", "Inject language or reference", "Suppress '", "Run inspection on", "Inspection '", "Suppress for ", "Suppress all ", "Edit cleanup profile settings", "Fix all '", "Cleanup code", "Go to ", "Show local variable type hints", "Show function return type hints", "Show property type hints", "Show parameter type hints", "Show argument name hints", "Show hints for suspending calls", "Add 'JUnit", "Add 'testng", CodeInsightBundle.message("assign.intention.shortcut"), CodeInsightBundle.message("edit.intention.shortcut"), CodeInsightBundle.message("remove.intention.shortcut"), ) }
apache-2.0
5a27fe12ad9bdd1b7492c0ac73939df3
42.178404
136
0.64869
5.419564
false
true
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/GitHubPowTest.kt
1
2209
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.jsontestsuite import org.ethereum.jsontestsuite.suite.EthashTestSuite import org.ethereum.jsontestsuite.suite.JSONReader import org.junit.Assert.assertArrayEquals import org.junit.Test import org.slf4j.LoggerFactory import java.io.IOException /** * @author Mikhail Kalinin * * * @since 03.09.2015 */ class GitHubPowTest { private val shacommit = "92bb72cccf4b5a2d29d74248fdddfe8b43baddda" @Test @Throws(IOException::class) fun runEthashTest() { val json = JSONReader.loadJSONFromCommit("PoWTests/ethash_tests.json", shacommit) val testSuite = EthashTestSuite(json) for (testCase in testSuite.testCases) { logger.info("Running {}\n", testCase.name) val header = testCase.blockHeader assertArrayEquals(testCase.resultBytes, header.calcPowValue()) } } companion object { private val logger = LoggerFactory.getLogger("TCK-Test") } }
mit
3a579067bd2d7ddd40dc03dd4864e119
31.970149
89
0.7311
4.090741
false
true
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/OpenInRightSplitAction.kt
3
3596
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.psi.PsiFile import javax.swing.JComponent class OpenInRightSplitAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val project = getEventProject(e) ?: return val file = getVirtualFile(e) ?: return val element = e.getData(CommonDataKeys.PSI_ELEMENT) as? Navigatable val editorWindow = openInRightSplit(project, file, element) if (element == null && editorWindow != null) { val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return if (files.size > 1) { files.forEach { if (file == it) return@forEach val fileEditorManager = FileEditorManagerEx.getInstanceEx(project) fileEditorManager.openFileWithProviders(it, true, editorWindow) } } } } override fun update(e: AnActionEvent) { val project = getEventProject(e) val editor = e.getData(CommonDataKeys.EDITOR) val fileEditor = e.getData(PlatformCoreDataKeys.FILE_EDITOR) val place = e.place if (project == null || fileEditor != null || editor != null || place == ActionPlaces.EDITOR_TAB_POPUP || place == ActionPlaces.EDITOR_POPUP) { e.presentation.isEnabledAndVisible = false return } val contextFile = getVirtualFile(e) e.presentation.isEnabledAndVisible = contextFile != null && !contextFile.isDirectory } companion object { private fun getVirtualFile(e: AnActionEvent): VirtualFile? = e.getData(CommonDataKeys.VIRTUAL_FILE) @JvmOverloads fun openInRightSplit(project: Project, file: VirtualFile, element: Navigatable? = null, requestFocus: Boolean = true): EditorWindow? { val fileEditorManager = FileEditorManagerEx.getInstanceEx(project) val splitters = fileEditorManager.splitters if (!fileEditorManager.canOpenFile(file)) { element?.navigate(requestFocus) return null } val editorWindow = splitters.openInRightSplit(file, requestFocus) if (editorWindow == null) { element?.navigate(requestFocus) return null } if (element != null && element !is PsiFile) { ApplicationManager.getApplication().invokeLater({ element.navigate(requestFocus) }, project.disposed) } return editorWindow } fun overrideDoubleClickWithOneClick(component: JComponent) { val action = ActionManager.getInstance().getAction(IdeActions.ACTION_OPEN_IN_RIGHT_SPLIT) ?: return val set = action.shortcutSet for (shortcut in set.shortcuts) { if (shortcut is MouseShortcut) { //convert double click -> one click if (shortcut.clickCount == 2) { val customSet = CustomShortcutSet(MouseShortcut(shortcut.button, shortcut.modifiers, 1)) object: AnAction(null as String?) { override fun actionPerformed(e: AnActionEvent) { action.actionPerformed(e) } }.registerCustomShortcutSet(customSet, component) } } } } } }
apache-2.0
6d78758271b9d2c4fac1b58dcf14ed51
34.97
138
0.690489
4.75033
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/ui/ViewBindingHelper.kt
1
2662
package info.dvkr.screenstream.ui import android.os.Handler import android.os.Looper import androidx.activity.ComponentActivity import androidx.annotation.MainThread import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.viewbinding.ViewBinding import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty abstract class ViewBindingProperty<in R, T : ViewBinding>( private val viewBinder: (R) -> T ) : ReadOnlyProperty<R, T> { internal var viewBinding: T? = null private val lifecycleObserver = ClearOnDestroyLifecycleObserver() protected abstract fun getLifecycleOwner(thisRef: R): LifecycleOwner @MainThread override fun getValue(thisRef: R, property: KProperty<*>): T { viewBinding?.let { return it } getLifecycleOwner(thisRef).lifecycle.addObserver(lifecycleObserver) return viewBinder(thisRef).also { viewBinding = it } } private inner class ClearOnDestroyLifecycleObserver : DefaultLifecycleObserver { @MainThread override fun onDestroy(owner: LifecycleOwner) { owner.lifecycle.removeObserver(this) Handler(Looper.getMainLooper()).post { viewBinding = null } } } } internal class ActivityViewBindingProperty<A : ComponentActivity, T : ViewBinding>( viewBinder: (A) -> T ) : ViewBindingProperty<A, T>(viewBinder) { override fun getLifecycleOwner(thisRef: A) = thisRef } @PublishedApi internal class FragmentViewBindingProperty<F : Fragment, T : ViewBinding>( viewBinder: (F) -> T ) : ViewBindingProperty<F, T>(viewBinder) { override fun getLifecycleOwner(thisRef: F) = thisRef.viewLifecycleOwner } @PublishedApi internal class DialogFragmentViewBindingProperty<F : DialogFragment, T : ViewBinding>( viewBinder: (F) -> T ) : ViewBindingProperty<F, T>(viewBinder) { override fun getLifecycleOwner(thisRef: F): LifecycleOwner { return if (thisRef.showsDialog) thisRef else thisRef.viewLifecycleOwner } } @Suppress("unused") fun <A : ComponentActivity, T : ViewBinding> A.viewBinding(viewBinder: (A) -> T): ViewBindingProperty<A, T> { return ActivityViewBindingProperty(viewBinder) } @Suppress("unused") fun <F : Fragment, T : ViewBinding> F.viewBinding(viewBinder: (F) -> T): ViewBindingProperty<F, T> { return FragmentViewBindingProperty(viewBinder) } @Suppress("unused") fun <F : DialogFragment, T : ViewBinding> F.dialogViewBinding(viewBinder: (F) -> T): ViewBindingProperty<F, T> { return DialogFragmentViewBindingProperty(viewBinder) }
mit
e12886fe734ead6d46d67bdaeae7347e
32.708861
112
0.746807
4.47395
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/mapper/impl/CheatMapperImpl.kt
1
1225
package com.github.vhromada.catalog.web.mapper.impl import com.github.vhromada.catalog.web.connector.entity.ChangeCheatRequest import com.github.vhromada.catalog.web.connector.entity.Cheat import com.github.vhromada.catalog.web.fo.CheatFO import com.github.vhromada.catalog.web.mapper.CheatDataMapper import com.github.vhromada.catalog.web.mapper.CheatMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for cheats. * * @author Vladimir Hromada */ @Component("cheatMapper") class CheatMapperImpl( /** * Mapper for cheat's data */ private val mapper: CheatDataMapper ) : CheatMapper { override fun map(source: Cheat): CheatFO { return CheatFO( uuid = source.uuid, gameSetting = source.gameSetting, cheatSetting = source.cheatSetting, data = mapper.mapList(source = source.data) ) } override fun mapRequest(source: CheatFO): ChangeCheatRequest { return ChangeCheatRequest( gameSetting = source.gameSetting, cheatSetting = source.cheatSetting, data = mapper.mapRequests(source = source.data!!.filterNotNull()) ) } }
mit
898defb19f36ba1f1170946bb3b4e07d
29.625
77
0.697959
4.209622
false
false
false
false
androidx/androidx
wear/watchface/watchface-client/src/androidTest/java/androidx/wear/watchface/client/test/TestWatchFaceServices.kt
3
27501
/* * 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.wear.watchface.client.test import android.app.PendingIntent import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.Canvas import android.graphics.Rect import android.graphics.RectF import android.view.SurfaceHolder import androidx.wear.watchface.BoundingArc import androidx.wear.watchface.CanvasComplication import androidx.wear.watchface.CanvasType import androidx.wear.watchface.ComplicationSlot import androidx.wear.watchface.ComplicationSlotsManager import androidx.wear.watchface.RenderParameters import androidx.wear.watchface.Renderer import androidx.wear.watchface.WatchFace import androidx.wear.watchface.WatchFaceService import androidx.wear.watchface.WatchFaceType import androidx.wear.watchface.WatchState import androidx.wear.watchface.complications.ComplicationSlotBounds import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy import androidx.wear.watchface.complications.SystemDataSources import androidx.wear.watchface.complications.data.ComplicationData import androidx.wear.watchface.complications.data.ComplicationExperimental import androidx.wear.watchface.complications.data.ComplicationText import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.NoDataComplicationData import androidx.wear.watchface.complications.data.PlainComplicationText import androidx.wear.watchface.complications.data.ShortTextComplicationData import androidx.wear.watchface.samples.ExampleCanvasAnalogWatchFaceService import androidx.wear.watchface.samples.ExampleCanvasAnalogWatchFaceService.Companion.COMPLICATIONS_STYLE_SETTING import androidx.wear.watchface.samples.ExampleCanvasAnalogWatchFaceService.Companion.LEFT_COMPLICATION import androidx.wear.watchface.samples.ExampleCanvasAnalogWatchFaceService.Companion.NO_COMPLICATIONS import androidx.wear.watchface.samples.ExampleOpenGLBackgroundInitWatchFaceService import androidx.wear.watchface.samples.R import androidx.wear.watchface.style.CurrentUserStyleRepository import androidx.wear.watchface.style.UserStyleSchema import androidx.wear.watchface.style.UserStyleSetting import androidx.wear.watchface.style.WatchFaceLayer import java.time.ZoneId import java.time.ZonedDateTime import java.util.concurrent.CountDownLatch import kotlinx.coroutines.CompletableDeferred internal class TestLifeCycleWatchFaceService : WatchFaceService() { companion object { val lifeCycleEvents = ArrayList<String>() } override fun onCreate() { super.onCreate() lifeCycleEvents.add("WatchFaceService.onCreate") } override fun onDestroy() { super.onDestroy() lifeCycleEvents.add("WatchFaceService.onDestroy") } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.GlesRenderer( surfaceHolder, currentUserStyleRepository, watchState, 16 ) { init { lifeCycleEvents.add("Renderer.constructed") } override fun onDestroy() { super.onDestroy() lifeCycleEvents.add("Renderer.onDestroy") } override fun render(zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer(zonedDateTime: ZonedDateTime) {} } ) } internal class TestExampleCanvasAnalogWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder ) : ExampleCanvasAnalogWatchFaceService() { internal lateinit var watchFace: WatchFace init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { watchFace = super.createWatchFace( surfaceHolder, watchState, complicationSlotsManager, currentUserStyleRepository ) return watchFace } companion object { var systemTimeMillis = 1000000000L } override fun getSystemTimeProvider() = object : SystemTimeProvider { override fun getSystemTimeMillis() = systemTimeMillis override fun getSystemTimeZoneId() = ZoneId.of("UTC") } } internal class TestExampleOpenGLBackgroundInitWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder ) : ExampleOpenGLBackgroundInitWatchFaceService() { internal lateinit var watchFace: WatchFace init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { watchFace = super.createWatchFace( surfaceHolder, watchState, complicationSlotsManager, currentUserStyleRepository ) return watchFace } } internal open class TestCrashingWatchFaceService : WatchFaceService() { companion object { const val COMPLICATION_ID = 123 } override fun createComplicationSlotsManager( currentUserStyleRepository: CurrentUserStyleRepository ): ComplicationSlotsManager { return ComplicationSlotsManager( listOf( ComplicationSlot.createRoundRectComplicationSlotBuilder( COMPLICATION_ID, { _, _ -> throw Exception("Deliberately crashing") }, listOf(ComplicationType.LONG_TEXT), DefaultComplicationDataSourcePolicy( SystemDataSources.DATA_SOURCE_SUNRISE_SUNSET, ComplicationType.LONG_TEXT ), ComplicationSlotBounds(RectF(0.1f, 0.1f, 0.4f, 0.4f)) ).build() ), currentUserStyleRepository ) } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { throw Exception("Deliberately crashing") } } internal class TestWatchfaceOverlayStyleWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder, private var watchFaceOverlayStyle: WatchFace.OverlayStyle ) : WatchFaceService() { init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) { // Actually rendering something isn't required. } override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { // Actually rendering something isn't required. } } ).setOverlayStyle(watchFaceOverlayStyle) } internal class TestAsyncCanvasRenderInitWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder, private var initCompletableDeferred: CompletableDeferred<Unit> ) : WatchFaceService() { init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override suspend fun init() { initCompletableDeferred.await() } override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) { // Actually rendering something isn't required. } override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { TODO("Not yet implemented") } } ) override fun getSystemTimeProvider() = object : SystemTimeProvider { override fun getSystemTimeMillis() = 123456789L override fun getSystemTimeZoneId() = ZoneId.of("UTC") } } internal class TestAsyncGlesRenderInitWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder, private var onUiThreadGlSurfaceCreatedCompletableDeferred: CompletableDeferred<Unit>, private var onBackgroundThreadGlContextCreatedCompletableDeferred: CompletableDeferred<Unit> ) : WatchFaceService() { internal lateinit var watchFace: WatchFace init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.GlesRenderer( surfaceHolder, currentUserStyleRepository, watchState, 16 ) { override suspend fun onUiThreadGlSurfaceCreated(width: Int, height: Int) { onUiThreadGlSurfaceCreatedCompletableDeferred.await() } override suspend fun onBackgroundThreadGlContextCreated() { onBackgroundThreadGlContextCreatedCompletableDeferred.await() } override fun render(zonedDateTime: ZonedDateTime) { // GLES rendering is complicated and not strictly necessary for our test. } override fun renderHighlightLayer(zonedDateTime: ZonedDateTime) { TODO("Not yet implemented") } } ) } internal class TestComplicationProviderDefaultsWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder ) : WatchFaceService() { init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override fun createComplicationSlotsManager( currentUserStyleRepository: CurrentUserStyleRepository ): ComplicationSlotsManager { return ComplicationSlotsManager( listOf( ComplicationSlot.createRoundRectComplicationSlotBuilder( 123, { _, _ -> object : CanvasComplication { override fun render( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters, slotId: Int ) { } override fun drawHighlight( canvas: Canvas, bounds: Rect, boundsType: Int, zonedDateTime: ZonedDateTime, color: Int ) { } override fun getData() = NoDataComplicationData() override fun loadData( complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean ) { } } }, listOf( ComplicationType.PHOTO_IMAGE, ComplicationType.LONG_TEXT, ComplicationType.SHORT_TEXT ), DefaultComplicationDataSourcePolicy( ComponentName("com.package1", "com.app1"), ComplicationType.PHOTO_IMAGE, ComponentName("com.package2", "com.app2"), ComplicationType.LONG_TEXT, SystemDataSources.DATA_SOURCE_STEP_COUNT, ComplicationType.SHORT_TEXT ), ComplicationSlotBounds( RectF(0.1f, 0.2f, 0.3f, 0.4f) ) ) .build() ), currentUserStyleRepository ) } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { } } ) } internal class TestEdgeComplicationWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder ) : WatchFaceService() { init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride @OptIn(ComplicationExperimental::class) override fun createComplicationSlotsManager( currentUserStyleRepository: CurrentUserStyleRepository ): ComplicationSlotsManager { return ComplicationSlotsManager( listOf( ComplicationSlot.createEdgeComplicationSlotBuilder( 123, { _, _ -> object : CanvasComplication { override fun render( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters, slotId: Int ) { } override fun drawHighlight( canvas: Canvas, bounds: Rect, boundsType: Int, zonedDateTime: ZonedDateTime, color: Int ) { } override fun getData() = NoDataComplicationData() override fun loadData( complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean ) { } } }, listOf( ComplicationType.PHOTO_IMAGE, ComplicationType.LONG_TEXT, ComplicationType.SHORT_TEXT ), DefaultComplicationDataSourcePolicy( ComponentName("com.package1", "com.app1"), ComplicationType.PHOTO_IMAGE, ComponentName("com.package2", "com.app2"), ComplicationType.LONG_TEXT, SystemDataSources.DATA_SOURCE_STEP_COUNT, ComplicationType.SHORT_TEXT ), ComplicationSlotBounds( RectF(0f, 0f, 1f, 1f) ), BoundingArc(45f, 90f, 0.1f) ) .build() ), currentUserStyleRepository ) } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.DIGITAL, @Suppress("deprecation") object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { } } ) } internal class TestWatchFaceServiceWithPreviewImageUpdateRequest( testContext: Context, private var surfaceHolderOverride: SurfaceHolder, ) : WatchFaceService() { val rendererInitializedLatch = CountDownLatch(1) init { attachBaseContext(testContext) } override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride @Suppress("deprecation") private lateinit var renderer: Renderer.CanvasRenderer fun triggerPreviewImageUpdateRequest() { renderer.sendPreviewImageNeedsUpdateRequest() } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { @Suppress("deprecation") renderer = object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override suspend fun init() { rendererInitializedLatch.countDown() } override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { } } return WatchFace(WatchFaceType.DIGITAL, renderer) } } internal class TestComplicationStyleUpdateWatchFaceService( testContext: Context, private var surfaceHolderOverride: SurfaceHolder ) : WatchFaceService() { init { attachBaseContext(testContext) } @Suppress("deprecation") private val complicationsStyleSetting = UserStyleSetting.ComplicationSlotsUserStyleSetting( UserStyleSetting.Id(COMPLICATIONS_STYLE_SETTING), resources, R.string.watchface_complications_setting, R.string.watchface_complications_setting_description, icon = null, complicationConfig = listOf( UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotsOption( UserStyleSetting.Option.Id(NO_COMPLICATIONS), resources, R.string.watchface_complications_setting_none, null, listOf( UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotOverlay( 123, enabled = false ) ) ), UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotsOption( UserStyleSetting.Option.Id(LEFT_COMPLICATION), resources, R.string.watchface_complications_setting_left, null, listOf( UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotOverlay( 123, enabled = true, nameResourceId = R.string.left_complication_screen_name, screenReaderNameResourceId = R.string.left_complication_screen_reader_name ) ) ) ), listOf(WatchFaceLayer.COMPLICATIONS) ) override fun createUserStyleSchema(): UserStyleSchema = UserStyleSchema(listOf(complicationsStyleSetting)) override fun getWallpaperSurfaceHolderOverride() = surfaceHolderOverride override fun createComplicationSlotsManager( currentUserStyleRepository: CurrentUserStyleRepository ): ComplicationSlotsManager { return ComplicationSlotsManager( listOf( ComplicationSlot.createRoundRectComplicationSlotBuilder( 123, { _, _ -> object : CanvasComplication { override fun render( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters, slotId: Int ) { } override fun drawHighlight( canvas: Canvas, bounds: Rect, boundsType: Int, zonedDateTime: ZonedDateTime, color: Int ) { } override fun getData() = NoDataComplicationData() override fun loadData( complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean ) { } } }, listOf( ComplicationType.PHOTO_IMAGE, ComplicationType.LONG_TEXT, ComplicationType.SHORT_TEXT ), DefaultComplicationDataSourcePolicy( ComponentName("com.package1", "com.app1"), ComplicationType.PHOTO_IMAGE, ComponentName("com.package2", "com.app2"), ComplicationType.LONG_TEXT, SystemDataSources.DATA_SOURCE_STEP_COUNT, ComplicationType.SHORT_TEXT ), ComplicationSlotBounds( RectF(0.1f, 0.2f, 0.3f, 0.4f) ) ).build() ), currentUserStyleRepository ) } override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ) = WatchFace( WatchFaceType.ANALOG, @Suppress("deprecation") object : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, 16 ) { override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) {} override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { } } ) } internal object TestServicesHelpers { fun createTestComplications(context: Context) = mapOf( ExampleCanvasAnalogWatchFaceService.EXAMPLE_CANVAS_WATCHFACE_LEFT_COMPLICATION_ID to ShortTextComplicationData.Builder( PlainComplicationText.Builder("ID").build(), ComplicationText.EMPTY ).setTitle(PlainComplicationText.Builder("Left").build()) .setTapAction( PendingIntent.getActivity(context, 0, Intent("left"), PendingIntent.FLAG_IMMUTABLE ) ) .build(), ExampleCanvasAnalogWatchFaceService.EXAMPLE_CANVAS_WATCHFACE_RIGHT_COMPLICATION_ID to ShortTextComplicationData.Builder( PlainComplicationText.Builder("ID").build(), ComplicationText.EMPTY ).setTitle(PlainComplicationText.Builder("Right").build()) .setTapAction( PendingIntent.getActivity(context, 0, Intent("right"), PendingIntent.FLAG_IMMUTABLE ) ) .build() ) inline fun <reified T>componentOf(): ComponentName { return ComponentName( T::class.java.`package`?.name!!, T::class.java.name ) } }
apache-2.0
2c208688c3f9f305db0e0fc9cf6b607a
34.808594
112
0.588124
6.513738
false
false
false
false
kotlinx/kotlinx.html
src/commonMain/kotlin/util.kt
1
325
package kotlinx.html fun HEAD.styleLink(url: String): Unit = link { rel = LinkRel.stylesheet type = LinkType.textCss href = url } val Tag.br: Unit get() { val tag = BR(emptyMap(), consumer) consumer.onTagStart(tag) consumer.onTagEnd(tag) } expect fun currentTimeMillis(): Long
apache-2.0
3269534c4b2d14fa47ea4e4b80763438
18.117647
46
0.633846
3.611111
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/findDecompiledDeclaration.kt
4
4910
// 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.decompiler.navigation import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtDecompiledFile import org.jetbrains.kotlin.analysis.decompiler.psi.text.ByDescriptorIndexer import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.BinaryModuleInfo import org.jetbrains.kotlin.idea.caches.project.binariesScope import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.error.ErrorUtils fun findDecompiledDeclaration( project: Project, referencedDescriptor: DeclarationDescriptor, // TODO: should not require explicitly specified scope to search for builtIns, use SourceElement to provide such information builtInsSearchScope: GlobalSearchScope? ): KtDeclaration? { if (ErrorUtils.isError(referencedDescriptor)) return null if (isLocal(referencedDescriptor)) return null if (referencedDescriptor is PackageFragmentDescriptor || referencedDescriptor is PackageViewDescriptor) return null val binaryInfo = referencedDescriptor.module.getCapability(ModuleInfo.Capability) as? BinaryModuleInfo binaryInfo?.binariesScope?.let { return findInScope(referencedDescriptor, it) } if (KotlinBuiltIns.isBuiltIn(referencedDescriptor)) { // builtin module does not contain information about it's origin return builtInsSearchScope?.let { findInScope(referencedDescriptor, it) } // fallback on searching everywhere since builtIns are accessible from any context ?: findInScope(referencedDescriptor, GlobalSearchScope.allScope(project)) ?: findInScope(referencedDescriptor, GlobalSearchScope.everythingScope(project)) } return null } private fun findInScope(referencedDescriptor: DeclarationDescriptor, scope: GlobalSearchScope): KtDeclaration? { val project = scope.project ?: return null val decompiledFiles = findCandidateDeclarationsInIndex( referencedDescriptor, KotlinSourceFilterScope.libraryClasses(scope, project), project ).mapNotNullTo(LinkedHashSet()) { it?.containingFile as? KtDecompiledFile } return decompiledFiles.asSequence().mapNotNull { file -> ByDescriptorIndexer.getDeclarationForDescriptor(referencedDescriptor, file) }.firstOrNull() } private fun isLocal(descriptor: DeclarationDescriptor): Boolean = if (descriptor is ParameterDescriptor) { isLocal(descriptor.containingDeclaration) } else { DescriptorUtils.isLocal(descriptor) } private fun findCandidateDeclarationsInIndex( referencedDescriptor: DeclarationDescriptor, scope: GlobalSearchScope, project: Project ): Collection<KtDeclaration?> { val containingClass = DescriptorUtils.getParentOfType(referencedDescriptor, ClassDescriptor::class.java, false) if (containingClass != null) { return KotlinFullClassNameIndex.get(containingClass.fqNameSafe.asString(), project, scope) } val topLevelDeclaration = DescriptorUtils.getParentOfType(referencedDescriptor, PropertyDescriptor::class.java, false) as DeclarationDescriptor? ?: DescriptorUtils.getParentOfType(referencedDescriptor, TypeAliasConstructorDescriptor::class.java, false)?.typeAliasDescriptor ?: DescriptorUtils.getParentOfType(referencedDescriptor, FunctionDescriptor::class.java, false) ?: DescriptorUtils.getParentOfType(referencedDescriptor, TypeAliasDescriptor::class.java, false) ?: return emptyList() // filter out synthetic descriptors if (!DescriptorUtils.isTopLevelDeclaration(topLevelDeclaration)) return emptyList() val fqName = topLevelDeclaration.fqNameSafe.asString() return when (topLevelDeclaration) { is FunctionDescriptor -> KotlinTopLevelFunctionFqnNameIndex.get(fqName, project, scope) is PropertyDescriptor -> KotlinTopLevelPropertyFqnNameIndex.get(fqName, project, scope) is TypeAliasDescriptor -> KotlinTopLevelTypeAliasFqNameIndex.get(fqName, project, scope) else -> error("Referenced non local declaration that is not inside top level function, property, class or typealias:\n $referencedDescriptor") } }
apache-2.0
7f774eca2a51cc9441c7fdc4b71c9d56
49.102041
158
0.790428
5.371991
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/util/valueContainerIterators.kt
4
2825
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.test.util import com.intellij.debugger.ui.impl.watch.NodeDescriptorProvider import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl import com.intellij.xdebugger.XDebuggerTestUtil import com.intellij.xdebugger.XTestValueNode import com.intellij.xdebugger.frame.XStackFrame import com.intellij.xdebugger.frame.XValue import com.intellij.xdebugger.frame.XValueContainer import com.intellij.xdebugger.frame.XValuePlace import org.jetbrains.org.objectweb.asm.Type import java.util.* abstract class ValueContainerIterator(container: XValueContainer) : Iterator<XValueContainer> { private companion object { private val OPAQUE_TYPE_DESCRIPTORS = listOf(String::class.java).map { Type.getType(it).descriptor } } protected val queue = LinkedList<XValueContainer>(collectChildren(container)) override fun hasNext() = queue.isNotEmpty() protected fun collectChildren(container: XValueContainer): List<XValue> { if (container.childrenCanBeCollected()) { return XDebuggerTestUtil.collectChildren(container) } return emptyList() } private fun XValueContainer.childrenCanBeCollected() = when (this) { is XStackFrame -> true is XValue -> mightHaveChildren() is NodeDescriptorProvider -> descriptor.isExpandable else -> false } private fun XValue.mightHaveChildren(): Boolean { val node = XTestValueNode() computePresentation(node, XValuePlace.TREE) node.waitFor(XDebuggerTestUtil.TIMEOUT_MS.toLong()) val descriptor = if (this is NodeDescriptorProvider) descriptor else null return node.myHasChildren && (descriptor == null || descriptor.isExpandable) && !(descriptor is ValueDescriptorImpl && isOpaqueValue(descriptor)) } private fun isOpaqueValue(descriptor: ValueDescriptorImpl): Boolean { val type = descriptor.type ?: return false return type.signature() in OPAQUE_TYPE_DESCRIPTORS } } class ValueContainerIteratorImpl(container: XValueContainer) : ValueContainerIterator(container) { override fun next(): XValueContainer = queue.pop() } class RecursiveValueContainerIterator(container: XValueContainer) : ValueContainerIterator(container) { override fun next(): XValueContainer { val nextContainer = queue.pop() queue.addAll(collectChildren(nextContainer)) return nextContainer } } operator fun XValueContainer.iterator() = ValueContainerIteratorImpl(this) fun XValueContainer.recursiveIterator() = RecursiveValueContainerIterator(this)
apache-2.0
88a50708877fb464351e55a68f2edd61
39.942029
158
0.736637
4.812606
false
true
false
false
GunoH/intellij-community
plugins/full-line/python/src/org/jetbrains/completion/full/line/python/formatters/ImportFormatter.kt
2
1952
package org.jetbrains.completion.full.line.python.formatters import com.intellij.extapi.psi.StubBasedPsiElementBase import com.intellij.psi.PsiElement import com.jetbrains.python.PyElementTypes import com.jetbrains.python.psi.PyFromImportStatement import com.jetbrains.python.psi.PyImportElement import com.jetbrains.python.psi.PyImportStatementBase import com.jetbrains.python.psi.stubs.PyFromImportStatementStub import org.jetbrains.completion.full.line.language.ElementFormatter class ImportFormatter : ElementFormatter { override fun condition(element: PsiElement): Boolean = element is PyImportStatementBase override fun filter(element: PsiElement): Boolean? = element is PyImportStatementBase override fun format(element: PsiElement): String { element as PyImportStatementBase val from = presentableFrom(element) var imports = element.importElements.map { presentableImport(it) }.ifEmpty { listOf("") }.joinToString(", ") if (isStar(element)) { imports = "*" } return when { from == null -> "import $imports" !element.text.contains("import") -> "from $from" else -> "from $from import $imports" }.trimEnd() } private fun isStar(element: PyImportStatementBase): Boolean { return (element as StubBasedPsiElementBase<PyFromImportStatementStub>).getStubOrPsiChild(PyElementTypes.STAR_IMPORT_ELEMENT) != null } private fun presentableImport(element: PyImportElement): String { val asPart = if (element.asName == null) { "" } else { " as " + element.asName } return (element.importedQName?.toString() ?: "") + asPart } private fun presentableFrom(element: PyImportStatementBase): String? { return if (element is PyFromImportStatement) { ".".repeat(element.relativeLevel) + if (element.importSource == null) { "" } else { element.importSource!!.text } } else { null } } }
apache-2.0
c5afc2eec444a0ce4b450a7542e2f7ac
30.483871
136
0.713115
4.32816
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirSameAsFileClassifierNameCompletionContributor.kt
4
1700
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.contributors import com.intellij.codeInsight.lookup.LookupElementBuilder import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirClassifierNamePositionContext import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.renderer.render internal class FirSameAsFileClassifierNameCompletionContributor( basicContext: FirBasicCompletionContext, priority: Int ) : FirCompletionContributorBase<FirClassifierNamePositionContext>(basicContext, priority) { override fun KtAnalysisSession.complete(positionContext: FirClassifierNamePositionContext) { if (positionContext.classLikeDeclaration is KtClassOrObject) { completeTopLevelClassName(positionContext.classLikeDeclaration) } } private fun completeTopLevelClassName(classOrObject: KtClassOrObject) { if (!classOrObject.isTopLevel()) return val name = originalKtFile.virtualFile.nameWithoutExtension if (!isValidUpperCapitalizedClassName(name)) return if (originalKtFile.declarations.any { it is KtClassOrObject && it.name == name }) return sink.addElement(LookupElementBuilder.create(name)) } private fun isValidUpperCapitalizedClassName(name: String) = Name.isValidIdentifier(name) && Name.identifier(name).render() == name && name[0].isUpperCase() }
apache-2.0
bb934382094ccee8cb91fe4b3da727fd
49
158
0.791765
4.97076
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddJvmNameAnnotationFix.kt
3
3746
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.psi.* class AddJvmNameAnnotationFix(element: KtElement, private val jvmName: String) : KotlinQuickFixAction<KtElement>(element) { override fun getText(): String = if (element is KtAnnotationEntry) { KotlinBundle.message("fix.change.jvm.name") } else { KotlinBundle.message("fix.add.annotation.text.self", JvmFileClassUtil.JVM_NAME.shortName()) } override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return when (element) { is KtAnnotationEntry -> { val argList = element.valueArgumentList val newArgList = KtPsiFactory(element).createCallArguments("(\"$jvmName\")") if (argList != null) { argList.replace(newArgList) } else { element.addAfter(newArgList, element.lastChild) } } is KtFunction -> element.addAnnotation(JvmFileClassUtil.JVM_NAME, annotationInnerText = "\"$jvmName\"") } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement as? KtNamedFunction ?: return null val functionName = function.name ?: return null val containingDeclaration = function.parent ?: return null val nameValidator = Fe10KotlinNewDeclarationNameValidator( containingDeclaration, function, KotlinNameSuggestionProvider.ValidatorTarget.FUNCTION ) val receiverTypeElements = function.receiverTypeReference?.typeElements()?.joinToString("") { it.text } ?: "" val jvmName = Fe10KotlinNameSuggester.suggestNameByName(functionName + receiverTypeElements, nameValidator) return AddJvmNameAnnotationFix(function.findAnnotation(JvmFileClassUtil.JVM_NAME) ?: function, jvmName) } private fun KtTypeReference.typeElements(): List<KtTypeElement> { val typeElements = mutableListOf<KtTypeElement>() fun collect(typeReference: KtTypeReference?) { val typeElement = typeReference?.typeElement ?: return val typeArguments = typeElement.typeArgumentsAsTypes if (typeArguments.isEmpty()) { typeElements.add(typeElement) } else { typeArguments.forEach { collect(it) } } } typeElement?.typeArgumentsAsTypes?.forEach { collect(it) } return typeElements } } }
apache-2.0
d74754a56f98fb4602a6ffd0f561721a
48.289474
158
0.685531
5.452693
false
false
false
false
LateNightProductions/CardKeeper
app/src/main/java/com/awscherb/cardkeeper/ui/create/CodeTypesAdapter.kt
1
1389
package com.awscherb.cardkeeper.ui.create import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.awscherb.cardkeeper.R class CodeTypesAdapter( private val context: Context, private val onClick: (CreateType) -> Unit ) : RecyclerView.Adapter<CodeTypesViewHolder>() { override fun getItemCount() = TYPES.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CodeTypesViewHolder = CodeTypesViewHolder( LayoutInflater.from(context).inflate(R.layout.adapter_code_type, parent, false) ) override fun onBindViewHolder(holder: CodeTypesViewHolder, position: Int) { holder.apply { codeName.text = TYPES[position].title itemView.setOnClickListener { onClick(TYPES[position]) } } } companion object { private val TYPES = arrayOf<CreateType>( CreateType.Aztec, CreateType.Code128, CreateType.DataMatrix, CreateType.PDF417, CreateType.QRCode ) } } class CodeTypesViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val codeName: TextView = itemView.findViewById(R.id.adapter_code_type_name) }
apache-2.0
ba7c80bd389c6304c7e66fc7bc20aa5f
29.888889
92
0.685385
4.539216
false
false
false
false
jwren/intellij-community
platform/util/xmlDom/src/com/intellij/util/xml/dom/xmlDom.kt
1
6330
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("XmlDomReader") package com.intellij.util.xml.dom import com.fasterxml.aalto.WFCException import com.fasterxml.aalto.impl.ErrorConsts import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import org.codehaus.stax2.XMLStreamReader2 import org.jetbrains.annotations.ApiStatus import java.io.InputStream import java.io.Reader import java.util.* import javax.xml.stream.XMLStreamConstants import javax.xml.stream.XMLStreamException private class XmlElementBuilder(@JvmField var name: String, @JvmField var attributes: Map<String, String>) { @JvmField var content: String? = null @JvmField val children: ArrayList<XmlElement> = ArrayList() } interface XmlInterner { fun name(value: String): String /** * [name] is interned. */ fun value(name: String, value: String): String } object NoOpXmlInterner : XmlInterner { override fun name(value: String) = value override fun value(name: String, value: String) = value } @ApiStatus.Experimental fun readXmlAsModel(inputReader: Reader): XmlElement { return readAndClose(createXmlStreamReader(inputReader)) } @ApiStatus.Experimental fun readXmlAsModel(inputStream: InputStream): XmlElement { return readAndClose(createXmlStreamReader(inputStream)) } @ApiStatus.Experimental fun readXmlAsModel(inputData: ByteArray): XmlElement { return readAndClose(createXmlStreamReader(inputData)) } private fun readAndClose(reader: XMLStreamReader2): XmlElement { try { val rootName = if (nextTag(reader) == XMLStreamConstants.START_ELEMENT) reader.localName else null return readXmlAsModel(reader, rootName, NoOpXmlInterner) } finally { reader.closeCompletely() } } @ApiStatus.Internal fun readXmlAsModel(reader: XMLStreamReader2, rootName: String?, interner: XmlInterner): XmlElement { val fragment = XmlElementBuilder(name = if (rootName == null) "" else interner.name(rootName), attributes = readAttributes(reader = reader, interner = interner)) var current = fragment val stack = ArrayDeque<XmlElementBuilder>() val elementPool = ArrayDeque<XmlElementBuilder>() var depth = 1 while (reader.hasNext()) { when (reader.next()) { XMLStreamConstants.START_ELEMENT -> { val name = interner.name(reader.localName) val attributes = readAttributes(reader, interner = interner) if (reader.isEmptyElement) { current.children.add(XmlElement(name = name, attributes = attributes, children = Collections.emptyList(), content = null)) reader.skipElement() continue } var child = elementPool.pollLast() if (child == null) { child = XmlElementBuilder(name = name, attributes = attributes) } else { child.name = name child.attributes = attributes } stack.addLast(current) current = child depth++ } XMLStreamConstants.END_ELEMENT -> { val children: List<XmlElement> if (current.children.isEmpty()) { children = Collections.emptyList() } else { @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") children = Arrays.asList(*current.children.toArray(arrayOfNulls<XmlElement>(current.children.size))) current.children.clear() } val result = XmlElement(name = current.name, attributes = current.attributes, children = children, content = current.content) current.content = null elementPool.addLast(current) depth-- if (depth == 0) { return result } current = stack.removeLast() current.children.add(result) } XMLStreamConstants.CDATA -> { if (current.content == null) { current.content = interner.value(current.name, reader.text) } else { current.content += reader.text } } XMLStreamConstants.CHARACTERS -> { if (!reader.isWhiteSpace) { if (current.content == null) { current.content = reader.text } else { current.content += reader.text } } } XMLStreamConstants.SPACE, XMLStreamConstants.ENTITY_REFERENCE, XMLStreamConstants.COMMENT, XMLStreamConstants.PROCESSING_INSTRUCTION -> { } else -> throw XMLStreamException("Unexpected XMLStream event ${reader.eventType}", reader.location) } } throw XMLStreamException("Unexpected end of input: ${reader.eventType}", reader.location) } private fun readAttributes(reader: XMLStreamReader2, interner: XmlInterner): Map<String, String> { return when (val attributeCount = reader.attributeCount) { 0 -> Collections.emptyMap() 1 -> { val name = interner.name(reader.getAttributeLocalName(0)) Collections.singletonMap(name, interner.value(name, reader.getAttributeValue(0))) } else -> { // Map.of cannot be used here - in core-impl only Java 8 is allowed @Suppress("SSBasedInspection") val result = Object2ObjectOpenHashMap<String, String>(attributeCount) var i = 0 while (i < attributeCount) { val name = interner.name(reader.getAttributeLocalName(i)) result[name] = interner.value(name, reader.getAttributeValue(i)) i++ } result } } } private fun nextTag(reader: XMLStreamReader2): Int { while (true) { val next = reader.next() when (next) { XMLStreamConstants.SPACE, XMLStreamConstants.COMMENT, XMLStreamConstants.PROCESSING_INSTRUCTION, XMLStreamConstants.DTD -> continue XMLStreamConstants.CDATA, XMLStreamConstants.CHARACTERS -> { if (reader.isWhiteSpace) { continue } throw WFCException("Received non-all-whitespace CHARACTERS or CDATA event in nextTag().", reader.location) } XMLStreamConstants.START_ELEMENT, XMLStreamConstants.END_ELEMENT -> return next } throw WFCException("Received event " + ErrorConsts.tokenTypeDesc(next) + ", instead of START_ELEMENT or END_ELEMENT.", reader.location) } }
apache-2.0
f59d2cff983149acb2af5ed3495a04b2
33.595628
163
0.666509
4.457746
false
false
false
false
jwren/intellij-community
spellchecker/src/com/intellij/spellchecker/grazie/GrazieSpellCheckerEngine.kt
2
3636
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.spellchecker.grazie import ai.grazie.spell.GrazieSpeller import ai.grazie.spell.GrazieSplittingSpeller import ai.grazie.spell.language.English import ai.grazie.spell.utils.DictionaryResources import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.spellchecker.dictionary.Dictionary import com.intellij.spellchecker.dictionary.EditableDictionary import com.intellij.spellchecker.dictionary.Loader import com.intellij.spellchecker.engine.SpellCheckerEngine import com.intellij.spellchecker.engine.Transformation import com.intellij.spellchecker.grazie.async.GrazieAsyncSpeller import com.intellij.spellchecker.grazie.async.WordListLoader import com.intellij.spellchecker.grazie.dictionary.ExtendedWordListWithFrequency import com.intellij.spellchecker.grazie.dictionary.WordListAdapter import com.intellij.util.containers.SLRUCache import org.apache.lucene.analysis.hunspell.TimeoutPolicy internal class GrazieSpellCheckerEngine(project: Project) : SpellCheckerEngine { override fun getTransformation(): Transformation = Transformation() private val loader = WordListLoader(project) private val adapter = WordListAdapter() private val mySpeller: GrazieAsyncSpeller = GrazieAsyncSpeller(project) { GrazieSplittingSpeller( GrazieSpeller( GrazieSpeller.UserConfig( GrazieSpeller.UserConfig.Dictionary( dictionary = ExtendedWordListWithFrequency( DictionaryResources.getHunspellDict("/dictionary/en", TimeoutPolicy.NO_TIMEOUT) { ProgressManager.checkCanceled() }, adapter), isAlien = { word -> English.isAlien(word) && adapter.isAlien(word) } ) ) ), GrazieSplittingSpeller.UserConfig() ) } private data class SuggestionsRequest(val word: String, val maxSuggestions: Int) private val suggestionsCache = SLRUCache.create<SuggestionsRequest, List<String>>(1024, 1024) { request -> mySpeller.suggest(request.word, request.maxSuggestions).take(request.maxSuggestions) } override fun isDictionaryLoad(name: String) = adapter.containsSource(name) override fun loadDictionary(loader: Loader) { this.loader.loadWordList(loader) { name, list -> adapter.addList(name, list) } } override fun addDictionary(dictionary: Dictionary) { adapter.addDictionary(dictionary) } override fun addModifiableDictionary(dictionary: EditableDictionary) { addDictionary(dictionary) } override fun isCorrect(word: String): Boolean { if (mySpeller.isAlien(word)) return true return mySpeller.isMisspelled(word, false).not() } override fun getSuggestions(word: String, maxSuggestions: Int, maxMetrics: Int): List<String> { if (mySpeller.isCreated) { return synchronized(mySpeller) { suggestionsCache.get(SuggestionsRequest(word, maxSuggestions)) } } return emptyList() } override fun reset() { adapter.reset() } override fun removeDictionary(name: String) { adapter.removeSource(name) } override fun getVariants(prefix: String): List<String> = emptyList() override fun removeDictionariesRecursively(directory: String) { val toRemove: List<String> = adapter.names.filter { name: String -> FileUtil.isAncestor(directory, name, false) && isDictionaryLoad(name) } for (name in toRemove) { adapter.removeSource(name) } } }
apache-2.0
07d58a2348555a67769fb32abf30a169
34.647059
140
0.757701
4.354491
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/fromJavaToKotlin/delegateStaticToStaticMethod.kt
48
683
fun a() { JavaClass.field val d = JavaClass() JavaClass.field d.let { JavaClass.field } d.also { JavaClass.field } with(d) { JavaClass.field } with(d) out@{ with(4) { JavaClass.field } } } fun a2() { val d: JavaClass? = null d?.field d?.let { JavaClass.field } d?.also { JavaClass.field } with(d) { JavaClass.field } with(d) out@{ with(4) { JavaClass.field } } } fun JavaClass.b(): Int? = JavaClass.field fun JavaClass.c(): Int = JavaClass.field fun d(d: JavaClass) = JavaClass.field
apache-2.0
6305e321d092e7576e2167b55e67b9ab
12.392157
41
0.47877
3.632979
false
false
false
false
smmribeiro/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalTabCloseListener.kt
9
2332
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal import com.intellij.execution.TerminateRemoteProcessDialog import com.intellij.execution.process.NopProcessHandler import com.intellij.execution.ui.BaseContentCloseListener import com.intellij.execution.ui.RunContentManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.ui.content.Content class TerminalTabCloseListener(val content: Content, val project: Project, parentDisposable: Disposable) : BaseContentCloseListener(content, project, parentDisposable) { override fun disposeContent(content: Content) { } override fun closeQuery(content: Content, projectClosing: Boolean): Boolean { if (projectClosing) { return true } if (content.getUserData(SILENT) == true) { return true } val widget = TerminalView.getWidgetByContent(content) if (widget == null || !widget.isSessionRunning) { return true } val connector = ShellTerminalWidget.getProcessTtyConnector(widget.ttyConnector) try { if (connector != null && !TerminalUtil.hasRunningCommands(connector)) { return true } } catch (e: Exception) { LOG.error(e) } val proxy = NopProcessHandler().apply { startNotify() } // don't show 'disconnect' button proxy.putUserData(RunContentManagerImpl.ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY, true) val result = TerminateRemoteProcessDialog.show(project, "Terminal ${content.displayName}", proxy) return result != null } override fun canClose(project: Project): Boolean { return project === this.project && closeQuery(this.content, true) } companion object { fun executeContentOperationSilently(content: Content, runnable: () -> Unit) { content.putUserData(SILENT, true) try { runnable() } finally { content.putUserData(SILENT, null) } } } } private val SILENT = Key.create<Boolean>("Silent content operation") private val LOG = logger<TerminalTabCloseListener>()
apache-2.0
b7c8668be872b70d140a7fb2058e337a
34.876923
140
0.710978
4.441905
false
false
false
false
simonnorberg/dmach
app/src/main/java/net/simno/dmach/machine/ChaosPad.kt
1
6051
package net.simno.dmach.machine import androidx.compose.foundation.background import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.forEachGesture import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.changedToDown import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChanged import androidx.compose.ui.layout.layout import net.simno.dmach.core.DarkLargeText import net.simno.dmach.core.DrawableCircle import net.simno.dmach.core.draw import net.simno.dmach.data.Position import net.simno.dmach.theme.AppTheme @Composable fun ChaosPad( settingId: Int, position: Position?, horizontalText: String, verticalText: String, modifier: Modifier = Modifier, onPosition: (Position) -> Unit ) { Box( modifier = modifier .fillMaxSize() .background( color = MaterialTheme.colorScheme.secondary, shape = MaterialTheme.shapes.small ) ) { DarkLargeText( text = verticalText.uppercase(), modifier = Modifier .layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.height, placeable.width) { placeable.place( x = -(placeable.width / 2 - placeable.height / 2), y = -(placeable.height / 2 - placeable.width / 2) ) } } .rotate(-90f) .align(Alignment.CenterStart) ) DarkLargeText( text = horizontalText.uppercase(), modifier = Modifier .align(Alignment.BottomCenter) .padding(bottom = AppTheme.dimens.PaddingSmall) ) Circle( settingId = settingId, position = position, onPosition = onPosition ) } } @Composable private fun Circle( settingId: Int, position: Position?, onPosition: (Position) -> Unit, modifier: Modifier = Modifier ) { val color = MaterialTheme.colorScheme.surface val circleRadius = AppTheme.dimens.CircleRadius val marginSmall = AppTheme.dimens.PaddingSmall var circle by remember { mutableStateOf<DrawableCircle?>(null) } Box( modifier = modifier .fillMaxSize() .pointerInput(settingId) { val strokeWidth = marginSmall.toPx() val radius = circleRadius.toPx() val stroke = Stroke(width = strokeWidth) val minX = strokeWidth / 2f + radius val minY = strokeWidth / 2f + radius val maxX = size.width - minX val maxY = size.height - minY fun notifyPosition(x: Float, y: Float) { // Convert pixels to a position value [0.0-1.0] val posX = ((x - minX) / (maxX - minX)).coerceIn(0f, 1f) val posY = 1 - ((y - minY) / (maxY - minY)).coerceIn(0f, 1f) onPosition(Position(posX, posY)) } fun getDrawableCircle(x: Float, y: Float): DrawableCircle { val newX = x .coerceAtLeast(minX) .coerceAtMost(maxX) val newY = y .coerceAtLeast(minY) .coerceAtMost(maxY) return DrawableCircle( color = color, radius = radius, style = stroke, center = Offset(newX, newY), alpha = 0.94f ) } fun onPointerDownOrMove(pointer: PointerInputChange) { circle = getDrawableCircle(pointer.position.x, pointer.position.y) notifyPosition(pointer.position.x, pointer.position.y) } if (position != null) { // Convert position value [0.0-1.0] to pixels. val newX = position.x * (maxX - minX) + minX val newY = (1 - position.y) * (maxY - minY) + minY circle = getDrawableCircle(newX, newY) } forEachGesture { awaitPointerEventScope { val firstPointer = awaitFirstDown() if (firstPointer.changedToDown()) { firstPointer.consume() } onPointerDownOrMove(firstPointer) do { val event = awaitPointerEvent() event.changes.forEach { pointer -> if (pointer.positionChanged()) { pointer.consume() } onPointerDownOrMove(pointer) } } while (event.changes.any { it.pressed }) } } } .drawBehind { circle?.let(::draw) } ) }
gpl-3.0
2ed6848c34e12befc4096aab953d1d75
36.583851
86
0.544373
5.207401
false
false
false
false
sksamuel/ktest
kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/longs/LongMatchers.kt
1
1641
package io.kotest.matchers.longs import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot fun lt(x: Long) = beLessThan(x) fun beLessThan(x: Long) = object : Matcher<Long> { override fun test(value: Long) = MatcherResult(value < x, "$value should be < $x", "$value should not be < $x") } fun lte(x: Long) = beLessThanOrEqualTo(x) fun beLessThanOrEqualTo(x: Long) = object : Matcher<Long> { override fun test(value: Long) = MatcherResult(value <= x, "$value should be <= $x", "$value should not be <= $x") } fun gt(x: Long) = beGreaterThan(x) fun beGreaterThan(x: Long) = object : Matcher<Long> { override fun test(value: Long) = MatcherResult(value > x, "$value should be > $x", "$value should not be > $x") } fun gte(x: Long) = beGreaterThanOrEqualTo(x) fun beGreaterThanOrEqualTo(x: Long) = object : Matcher<Long> { override fun test(value: Long) = MatcherResult(value >= x, "$value should be >= $x", "$value should not be >= $x") } infix fun Long.shouldBeInRange(range: LongRange) = this should beInRange(range) infix fun Long.shouldNotBeInRange(range: LongRange) = this shouldNot beInRange(range) fun beInRange(range: LongRange) = object : Matcher<Long> { override fun test(value: Long): MatcherResult = MatcherResult( value in range, "$value should be in range $range", "$value should not be in range $range" ) } fun exactly(x: Long) = object : Matcher<Long> { override fun test(value: Long) = MatcherResult( value == x, "$value should be equal to $x", "$value should not be equal to $x" ) }
mit
ae0c80351065411946b77ad307af5c40
35.466667
116
0.691651
3.484076
false
true
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/ui/activity/BaseActivity.kt
1
16801
package com.dreampany.framework.ui.activity import android.os.Bundle import android.os.Parcelable import android.view.MenuItem import android.view.View import android.view.Window import android.view.WindowManager import androidx.annotation.ColorRes import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.Toolbar import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.codemybrainsout.ratingdialog.RatingDialog import com.dreampany.framework.R import com.dreampany.framework.app.BaseApp import com.dreampany.framework.data.model.Color import com.dreampany.framework.data.model.Task import com.dreampany.framework.misc.AppExecutors import com.dreampany.framework.misc.Constants import com.dreampany.framework.ui.callback.UiCallback import com.dreampany.framework.ui.fragment.BaseFragment import com.dreampany.framework.util.* import com.karumi.dexter.Dexter import com.karumi.dexter.MultiplePermissionsReport import com.karumi.dexter.PermissionToken import com.karumi.dexter.listener.DexterError import com.karumi.dexter.listener.PermissionRequest import com.karumi.dexter.listener.PermissionRequestErrorListener import com.karumi.dexter.listener.multi.MultiplePermissionsListener import com.tapadoo.alerter.Alerter import dagger.Lazy import dagger.android.support.DaggerAppCompatActivity import timber.log.Timber import javax.inject.Inject import kotlin.reflect.KClass /** * Created by Hawladar Roman on 5/22/2018. * BJIT Group * [email protected] */ @Suppress("UNCHECKED_CAST") abstract class BaseActivity : DaggerAppCompatActivity(), View.OnClickListener, UiCallback<BaseActivity, BaseFragment, Task<*>, ViewModelProvider.Factory, ViewModel>, MultiplePermissionsListener, PermissionRequestErrorListener { @Inject protected lateinit var ex: AppExecutors protected lateinit var binding: ViewDataBinding protected var toolbar: Toolbar? = null protected var task: Task<*>? = null protected var childTask: Task<*>? = null protected var currentFragment: BaseFragment? = null protected var color: Color? = null protected var fireOnStartUi: Boolean = true private var ratingDialog: RatingDialog? = null //private var progress: ProgressDialog? = null private var doubleBackToExitPressedOnce: Boolean = false open fun getLayoutId(): Int { return 0 } open fun getToolbarId(): Int { return R.id.toolbar } open fun isFullScreen(): Boolean { return false } open fun isHomeUp(): Boolean { return true } open fun isScreenOn(): Boolean { return false } open fun hasRemoteUi(): Boolean { return false } open fun hasColor(): Boolean { return getApp().hasColor() } open fun applyColor(): Boolean { return getApp().applyColor() } open fun hasTheme(): Boolean { return getApp().hasTheme() } open fun getAppTheme(): Int { return R.style.AppTheme } open fun hasBackPressed(): Boolean { return false } open fun hasDoubleBackPressed(): Boolean { return false } open fun hasRatePermitted(): Boolean { return false; } open fun getScreen(): String { return javaClass.simpleName } protected abstract fun onStartUi(state: Bundle?) protected abstract fun onStopUi() override fun onCreate(savedInstanceState: Bundle?) { if (AndroidUtil.hasLollipop()) { requestWindowFeature(Window.FEATURE_CONTENT_TRANSITIONS) } if (hasTheme()) { //Aesthetic.attach(this) } super.onCreate(savedInstanceState) if (isScreenOn()) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } val app = getApp() if (hasColor()) { color = app.getColor() } AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) val layoutId = getLayoutId() if (layoutId != 0) { initLayout(layoutId) initToolbar() if (hasTheme()) { initTheme() } } if (fireOnStartUi) { onStartUi(savedInstanceState) getApp().throwAnalytics(Constants.Event.ACTIVITY, getScreen()) } if (app.hasRate() && hasRatePermitted()) { startRate() } var root = isTaskRoot Timber.v("%s RootTask %s", getScreen(), root) } override fun onResume() { super.onResume() if (hasTheme()) { //Aesthetic.resume(this) } } override fun onPause() { if (hasTheme()) { //Aesthetic.pause(this) } super.onPause() } override fun onDestroy() { val app = getApp(); if (app.hasRate()) { stopRate() } hideAlert() //hideProgress() onStopUi() super.onDestroy() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onBackPressed() return true } } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (hasBackPressed()) { return } val fragment = currentFragment if (fragment != null && fragment.hasBackPressed()) { return } /* val manager = supportFragmentManager; if (manager.getBackStackEntryCount() > 0) { manager.popBackStack(); }*/ if (hasDoubleBackPressed()) { if (doubleBackToExitPressedOnce) { //super.onBackPressed() finish() Animato.animateSlideRight(this) return; } doubleBackToExitPressedOnce = true NotifyUtil.shortToast(this, R.string.back_pressed) ex.postToUi(Runnable{ doubleBackToExitPressedOnce = false }, 2000) } else { finish() Animato.animateSlideRight(this) } } override fun onClick(view: View) { } override fun getUiActivity(): BaseActivity { return this } override fun getUiFragment(): BaseFragment? { return currentFragment } override fun set(t: Task<*>) { childTask = t } override fun get(): ViewModelProvider.Factory { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getX(): ViewModel { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun execute(t: Task<*>) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onPermissionsChecked(report: MultiplePermissionsReport) { } override fun onPermissionRationaleShouldBeShown( permissions: List<PermissionRequest>, token: PermissionToken ) { } override fun onError(error: DexterError) { } fun getToolbarRef(): Toolbar? { return toolbar } fun isAlive(): Boolean { return AndroidUtil.isAlive(this) } fun getApp(): BaseApp { return application as BaseApp } open fun getUiColor(): Color? { return color } private fun initLayout(layoutId: Int) { if (isFullScreen()) { requestWindowFeature(Window.FEATURE_NO_TITLE) //BarUtil.hide(this) } else { //BarUtil.show(this) } binding = DataBindingUtil.setContentView(this, layoutId) } private fun initToolbar() { toolbar = findViewById<Toolbar>(getToolbarId()) if (toolbar != null) { if (isFullScreen()) { if (toolbar!!.isShown) { toolbar!!.visibility = View.GONE } } else { if (!toolbar!!.isShown) { toolbar!!.visibility = View.VISIBLE } setSupportActionBar(toolbar) if (isHomeUp()) { val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setHomeButtonEnabled(true) } } } } } private fun initTheme() { /* if (Aesthetic.isFirstTime || true) { Aesthetic.config { isDark(true) colorPrimaryRes(R.color.colorPrimary) colorPrimaryDarkRes(R.color.colorPrimaryDark) colorAccentRes(R.color.colorAccent) colorWindowBackgroundRes(R.color.grey_300) textColorPrimaryRes(R.color.white) textColorSecondary(R.color.material_grey700) textColorPrimaryInverseRes(R.color.black) textColorSecondaryInverseRes(R.color.grey_300) //toolbarIconColorRes(R.color.white) //colorStatusBarAuto() //colorNavigationBarAuto() colorNavigationBarRes(R.color.material_grey300) //bottomNavigationBackgroundMode(BottomNavBgMode.BLACK_WHITE_AUTO) //lightStatusBarMode(AutoSwitchMode.AUTO) //lightNavigationBarMode(AutoSwitchMode.AUTO) //tabLayoutBackgroundMode(ColorMode.PRIMARY) tabLayoutIndicatorMode(ColorMode.ACCENT) //navigationViewMode(NavigationViewMode.SELECTED_ACCENT) bottomNavigationBackgroundMode(BottomNavBgMode.PRIMARY) bottomNavigationIconTextMode(BottomNavIconTextMode.BLACK_WHITE_AUTO) swipeRefreshLayoutColorsRes( R.color.material_green700, R.color.material_red700, R.color.material_yellow700 ) } }*/ } protected fun <T : Task<*>> getCurrentTask(freshTask: Boolean): T? { if (task == null || freshTask) { task = getIntentValue<T>(Constants.Task.TASK) } return task as T? } protected fun <T> getIntentValue(key: String): T? { val bundle = getBundle() return getIntentValue<T>(key, bundle) } protected fun <T> getIntentValue(key: String, bundle: Bundle?): T? { var t: T? = null if (bundle != null) { t = bundle.getParcelable<Parcelable>(key) as T? } if (bundle != null && t == null) { t = bundle.getSerializable(key) as T? } return t } protected fun getBundle(): Bundle? { return intent.extras } override fun setTitle(titleId: Int) { if (titleId <= 0) { return } setSubtitle(TextUtil.getString(this, titleId)) } fun setSubtitle(subtitleId: Int) { if (subtitleId <= 0) { return } setSubtitle(TextUtil.getString(this, subtitleId)) } fun setTitle(title: String?) { val actionBar = supportActionBar if (actionBar != null) { actionBar.title = title } } fun setSubtitle(subtitle: String?) { val actionBar = supportActionBar if (actionBar != null) { actionBar.subtitle = subtitle } } fun <T : Any> openActivity(target: KClass<T>, finish: Boolean) { openActivity(target.java, finish) } fun openActivity(target: Class<*>, finish: Boolean) { AndroidUtil.openActivity(this, target, finish) } fun openActivity(target: Class<*>, requestCode: Int) { AndroidUtil.openActivity(this, target, requestCode) } fun openActivity(target: Class<*>, task: Task<*>) { AndroidUtil.openActivity(this, target, task) } fun openActivity(target: Class<*>, task: Task<*>, finish: Boolean) { AndroidUtil.openActivity(this, target, task, finish) } protected fun <T : BaseFragment> commitFragment( clazz: Class<T>, fragmentProvider: Lazy<T>, parentId: Int ): T? { /* val manager = getSupportFragmentManager() val transaction = manager?.beginTransaction(); val current = manager?.primaryNavigationFragment if (current != null) { transaction?.detach(current); } var fragment: T? = FragmentUtil.getFragmentByTag(this, clazz.simpleName) if (fragment == null) { Timber.v("New Fragment Created %s", clazz) fragment = fragmentProvider.get() transaction?.add(parentId, fragment, clazz.simpleName) } else { transaction?.attach(fragment) } this.currentFragment = fragment transaction?.setPrimaryNavigationFragment(fragment) transaction?.setReorderingAllowed(true) transaction?.commitNowAllowingStateLoss() return currentFragment as T*/ var fragment: T? = FragmentUtil.getFragmentByTag(this, clazz.simpleName) if (fragment == null) { //Timber.v("New Fragment Created %s", clazz) fragment = fragmentProvider.get() } val currentFragment = FragmentUtil.commitFragment<T>(ex, this, fragment, parentId) this.currentFragment = currentFragment return currentFragment } protected fun <T : BaseFragment> commitFragment( clazz: Class<T>, fragmentProvider: Lazy<T>, parentId: Int, task: Task<*> ): T? { var fragment: T? = FragmentUtil.getFragmentByTag(this, clazz.simpleName) if (fragment == null) { fragment = fragmentProvider.get() val bundle = Bundle() bundle.putParcelable(Constants.Task.TASK, task) fragment!!.arguments = bundle } else { fragment.arguments!!.putParcelable(Constants.Task.TASK, task) } val currentFragment = FragmentUtil.commitFragment(ex, this, fragment, parentId) this.currentFragment = currentFragment return currentFragment } fun checkPermissions(vararg permissions: String, listener: MultiplePermissionsListener) { if (!isAlive()) { return } Dexter.withActivity(this) .withPermissions(*permissions) .withListener(listener) .check() } fun showInfo(info: String) { if (!isAlive()) { return } NotifyUtil.showInfo(this, info) } fun showError(error: String) { if (!isAlive()) { return } NotifyUtil.showInfo(this, error) } fun showAlert(title: String, text: String, @ColorRes backgroundColor: Int, timeout: Long) { showAlert(title, text, backgroundColor, timeout, null) } fun showAlert( title: String, text: String, @ColorRes backgroundColor: Int, timeout: Long, listener: View.OnClickListener? ) { hideAlert() val alerter = Alerter.create(this) .setTitle(title) .setText(text) .setBackgroundColorRes(backgroundColor) .setIcon(R.drawable.alerter_ic_face) .setDuration(timeout) .enableSwipeToDismiss(); if (listener != null) { alerter.setOnClickListener(listener) } alerter.show() } fun hideAlert() { if (Alerter.isShowing) { Alerter.hide() } } /* fun showProgress(message: String) { if (progress == null) { progress = ProgressDialog(this) progress?.setCancelable(true) } if (progress?.isShowing()!!) { return } progress?.let { it.setMessage(message + "...") it.show() } } fun hideProgress() { progress?.let { if (it.isShowing) { it.dismiss() } } }*/ private fun startRate() { if (ratingDialog == null || !ratingDialog!!.isShowing) { ratingDialog = RatingDialog.Builder(this) .threshold(3f) .session(7) .onRatingBarFormSumbit({ }).build() ratingDialog?.show() } } private fun stopRate() { ratingDialog?.let { if (it.isShowing) { it.dismiss() } } } }
apache-2.0
a04641b3b968fd5493a6ee701d864210
27.770548
107
0.590798
4.812661
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/pom/DependencyVersions.kt
1
3077
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.core.pom /** * Map that provides extra configuration for versions of dependencies generated by Jetifier. */ data class DependencyVersions(private val currentSet: Map<String, String>) { companion object { val EMPTY = DependencyVersions(emptyMap()) const val DATA_BINDING_VAR_NAME = "newDataBindingVersion" private const val DEFAULT_DEPENDENCY_SET = "latestReleased" fun parseFromVersionSetTypeId( versionsMap: DependencyVersionsMap, versionSetType: String? ): DependencyVersions { val name = versionSetType ?: DEFAULT_DEPENDENCY_SET if (versionsMap.data.isEmpty()) { return DependencyVersions(emptyMap()) } val map = versionsMap.data[name] if (map == null) { throw IllegalArgumentException("The given versions map is invalid as it does not " + "contain version set called '$name' or maybe you passed incorrect version " + "set identifier?") } return DependencyVersions(map) } } /** * Puts the given version into the map to be referred to using the given variable name. * * Ignored if null is given. * * @param newVersion New version to be put into the map * @param forVariable Then name of the variable to be used to refer to the version */ fun replaceVersionIfAny(forVariable: String, newVersion: String?): DependencyVersions { newVersion ?: return this val temp = currentSet.toMutableMap() temp[forVariable] = newVersion return DependencyVersions(temp) } /** Takes a version from a configuration file and rewrites any variables related to the map. */ fun applyOnVersionRef(version: String): String { if (version.matches(Regex("^\\{[a-zA-Z0-9]+\\}$"))) { val variableName = version.removePrefix("{").removeSuffix("}") return currentSet[variableName] ?: throw IllegalArgumentException( "The version variable '$variableName' was not found") } return version } fun applyOnConfigPomDep(dep: PomDependency): PomDependency { return PomDependency( groupId = dep.groupId, artifactId = dep.artifactId, version = applyOnVersionRef(dep.version!!)) } }
apache-2.0
96c27a73ef4522dc3e684d5a29161718
34.37931
100
0.645759
4.830455
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/util/QuranPartialPageChecker.kt
2
3520
package com.quran.labs.androidquran.util import android.graphics.BitmapFactory import timber.log.Timber import java.io.File import javax.inject.Inject class QuranPartialPageChecker @Inject constructor() { /** * Checks all the pages to find partially downloaded images. */ fun checkPages(directory: String, numberOfPages: Int, width: String): List<Int> { // past versions of the partial page checker didn't run the checker // whenever any .vX file exists. this was noted as a "works sometimes" // solution because not all zip files contain .vX files (ex naskh and // warsh). removed this now because it is actually invalid for madani // in some cases as well due to the fact that someone could have manually // downloaded images, have broken images, and then get a patch zip which // contains the .vX file. try { // check the partial images for the width return checkPartialImages(directory, width, numberOfPages) } catch (throwable: Throwable) { Timber.e(throwable, "Error while checking partial pages: $width") } return emptyList() } /** * Check for partial images and return them. * This opens every downloaded image and looks at the last set of pixels. * If the last few rows are blank, the image is assumed to be partial and * the image is returned. */ private fun checkPartialImages(directoryName: String, width: String, numberOfPages: Int): List<Int> { val result = mutableListOf<Int>() // scale images down to 1/16th of size val options = BitmapFactory.Options() .apply { inSampleSize = 16 } val directory = File(directoryName) // optimization to avoid re-generating the pixel array every time var pixelArray: IntArray? = null // skip pages 1 and 2 since they're "special" (not full pages) for (page in 3..numberOfPages) { val filename = QuranFileUtils.getPageFileName(page) if (File(directory, filename).exists()) { val bitmap = BitmapFactory.decodeFile( directoryName + File.separator + filename, options ) // this is an optimization to avoid allocating 8 * width of memory // for everything. val rowsToCheck = // madani, 9 for 1920, 7 for 1280, 5 for 1260 and 1024, and // less for smaller images. // for naskh, 1 for everything // for qaloon, 2 for largest size, 1 for smallest // for warsh, 2 for everything when (width) { "_1024", "_1260" -> 5 "_1280" -> 7 "_1920" -> 9 else -> 4 } val bitmapWidth = bitmap.width // these should all be the same size, so we can just allocate once val pixels = if (pixelArray?.size == (bitmapWidth * rowsToCheck)) { pixelArray } else { pixelArray = IntArray(bitmapWidth * rowsToCheck) pixelArray } // get the set of pixels bitmap.getPixels( pixels, 0, bitmapWidth, 0, bitmap.height - rowsToCheck, bitmapWidth, rowsToCheck ) // see if there's any non-0 pixel val foundPixel = pixels.any { it != 0 } // if all are non-zero, assume the image is partially blank if (!foundPixel) { result.add(page) } } } return result } }
gpl-3.0
188d7e91f29bb1f0408e4f4b02917a6f
32.52381
83
0.605398
4.530245
false
false
false
false
siosio/nablarch-helper
src/main/java/siosio/repository/extension/domElement.kt
1
788
import com.intellij.psi.* import com.intellij.util.xml.* import siosio.repository.xml.* fun DomElement.inHandlerQueue(): Boolean { val list = getParentOfType(ListObject::class.java, true) val property = getParentOfType(Property::class.java, true) return list?.let { it.isHandlerQueue() || property?.isHandlerQueue() ?: false } ?: false } fun Property.isHandlerQueue(): Boolean { val element = DomUtil.getValueElement(this.name) if (element == null) { return false } else { return element.text == "\"handlerQueue\"" } } fun ListObject.isHandlerQueue(): Boolean { return this.name.value == "handlerQueue" } fun Property.parameterList(): Array<PsiParameter> { return name.value?.parameterList?.parameters ?: emptyArray() }
apache-2.0
301e01ae10807924c9b3153cae0b49b4
27.142857
66
0.68401
3.959799
false
false
false
false
AndroidDeveloperLB/AutoFitTextView
AutoFitTextViewLibrary/src/com/lb/auto_fit_textview/AutoResizeTextView.kt
1
9172
package com.lb.auto_fit_textview import android.annotation.TargetApi import android.content.Context import android.content.res.Resources import android.graphics.RectF import android.graphics.Typeface import android.os.Build import android.text.Layout.Alignment import android.text.StaticLayout import android.text.TextPaint import android.util.AttributeSet import android.util.TypedValue import androidx.appcompat.widget.AppCompatTextView /** * a textView that is able to self-adjust its font size depending on the min and max size of the font, and its own size.<br></br> * code is heavily based on this StackOverflow thread: * http://stackoverflow.com/questions/16017165/auto-fit-textview-for-android/21851239#21851239 <br></br> * It should work fine with most Android versions, but might have some issues on Android 3.1 - 4.04, as setTextSize will only work for the first time. <br></br> * More info here: https://code.google.com/p/android/issues/detail?id=22493 and here in case you wish to fix it: http://stackoverflow.com/a/21851239/878126 */ class AutoResizeTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = android.R.attr.textViewStyle) : AppCompatTextView(context, attrs, defStyle) { private val availableSpaceRect = RectF() private val sizeTester: SizeTester private var maxTextSize: Float = 0.toFloat() private var spacingMult = 1.0f private var spacingAdd = 0.0f private var minTextSize: Float = 0.toFloat() private var widthLimit: Int = 0 private var maxLines: Int = 0 private var initialized = false private var textPaint: TextPaint? = null private interface SizeTester { /** * @param suggestedSize Size of text to be tested * @param availableSpace available space in which text must fit * @return an integer < 0 if after applying `suggestedSize` to * text, it takes less space than `availableSpace`, > 0 * otherwise */ fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int } init { // using the minimal recommended font size minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, resources.displayMetrics) maxTextSize = textSize textPaint = TextPaint(paint) if (maxLines == 0) // no value was assigned during construction maxLines = NO_LINE_LIMIT // prepare size tester: sizeTester = object : SizeTester { internal val textRect = RectF() @TargetApi(Build.VERSION_CODES.JELLY_BEAN) override fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int { textPaint!!.textSize = suggestedSize.toFloat() val transformationMethod = transformationMethod val text: String if (transformationMethod != null) text = transformationMethod.getTransformation(getText(), this@AutoResizeTextView).toString() else text = getText().toString() val singleLine = maxLines == 1 if (singleLine) { textRect.bottom = textPaint!!.fontSpacing textRect.right = textPaint!!.measureText(text) } else { val layout: StaticLayout = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { StaticLayout.Builder.obtain(text, 0, text.length, textPaint!!, widthLimit).setLineSpacing(spacingAdd, spacingMult).setAlignment(Alignment.ALIGN_NORMAL).setIncludePad(true).build() } else StaticLayout(text, textPaint, widthLimit, Alignment.ALIGN_NORMAL, spacingMult, spacingAdd, true) // return early if we have more lines if (maxLines != NO_LINE_LIMIT && layout.lineCount > maxLines) return 1 textRect.bottom = layout.height.toFloat() var maxWidth = -1 val lineCount = layout.lineCount for (i in 0 until lineCount) { val end = layout.getLineEnd(i) if (i < lineCount - 1 && end > 0 && !isValidWordWrap(text[end - 1])) return 1 if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i)) maxWidth = layout.getLineRight(i).toInt() - layout.getLineLeft(i).toInt() } //for (int i = 0; i < layout.getLineCount(); i++) // if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i)) // maxWidth = (int) layout.getLineRight(i) - (int) layout.getLineLeft(i); textRect.right = maxWidth.toFloat() } textRect.offsetTo(0f, 0f) return if (availableSpace.contains(textRect)) -1 else 1 // else, too big } } initialized = true } fun isValidWordWrap(c: Char): Boolean { return c == ' ' || c == '-' } override fun setAllCaps(allCaps: Boolean) { super.setAllCaps(allCaps) adjustTextSize() } override fun setTypeface(tf: Typeface?) { super.setTypeface(tf) adjustTextSize() } override fun setTextSize(size: Float) { maxTextSize = size adjustTextSize() } override fun setMaxLines(maxLines: Int) { super.setMaxLines(maxLines) this.maxLines = maxLines adjustTextSize() } override fun getMaxLines(): Int { return maxLines } override fun setSingleLine() { super.setSingleLine() maxLines = 1 adjustTextSize() } override fun setSingleLine(singleLine: Boolean) { super.setSingleLine(singleLine) if (singleLine) maxLines = 1 else maxLines = NO_LINE_LIMIT adjustTextSize() } override fun setLines(lines: Int) { super.setLines(lines) maxLines = lines adjustTextSize() } override fun setTextSize(unit: Int, size: Float) { val c = context val r: Resources r = if (c == null) Resources.getSystem() else c.resources maxTextSize = TypedValue.applyDimension(unit, size, r.displayMetrics) adjustTextSize() } override fun setLineSpacing(add: Float, mult: Float) { super.setLineSpacing(add, mult) spacingMult = mult spacingAdd = add } /** * Set the lower text size limit and invalidate the view * * @param minTextSize */ fun setMinTextSize(minTextSize: Float) { this.minTextSize = minTextSize adjustTextSize() } private fun adjustTextSize() { // This is a workaround for truncated text issue on ListView, as shown here: https://github.com/AndroidDeveloperLB/AutoFitTextView/pull/14 // TODO think of a nicer, elegant solution. // post(new Runnable() // { // @Override // public void run() // { if (!initialized) return val startSize = minTextSize.toInt() val heightLimit = measuredHeight - compoundPaddingBottom - compoundPaddingTop widthLimit = measuredWidth - compoundPaddingLeft - compoundPaddingRight if (widthLimit <= 0) return textPaint = TextPaint(paint) availableSpaceRect.right = widthLimit.toFloat() availableSpaceRect.bottom = heightLimit.toFloat() superSetTextSize(startSize) // } // }); } private fun superSetTextSize(startSize: Int) { val textSize = binarySearch(startSize, maxTextSize.toInt(), sizeTester, availableSpaceRect) super.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat()) } private fun binarySearch(start: Int, end: Int, sizeTester: SizeTester, availableSpace: RectF): Int { var lastBest = start var lo = start var hi = end - 1 var mid: Int while (lo <= hi) { mid = (lo + hi).ushr(1) val midValCmp = sizeTester.onTestSize(mid, availableSpace) if (midValCmp < 0) { lastBest = lo lo = mid + 1 } else if (midValCmp > 0) { hi = mid - 1 lastBest = hi } else return mid } // make sure to return last best // this is what should always be returned return lastBest } override fun onTextChanged(text: CharSequence, start: Int, before: Int, after: Int) { super.onTextChanged(text, start, before, after) adjustTextSize() } override fun onSizeChanged(width: Int, height: Int, oldwidth: Int, oldheight: Int) { super.onSizeChanged(width, height, oldwidth, oldheight) if (width != oldwidth || height != oldheight) adjustTextSize() } companion object { private val NO_LINE_LIMIT = -1 } }
apache-2.0
e04be7f7071222e09d5ce1ce3bf9af32
36.900826
203
0.600087
4.66531
false
true
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/module/common/fragment/MusicListFragment.kt
1
9688
/* * Copyright (C) 2017 YangBin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package tech.summerly.quiet.module.common.fragment import android.annotation.SuppressLint import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.util.DiffUtil import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.PopupMenu import kotlinx.android.synthetic.main.common_fragment_music_list.view.* import kotlinx.android.synthetic.main.common_item_playlist_music.view.* import kotlinx.android.synthetic.main.content_item_music.view.* import kotlinx.android.synthetic.main.header_music_list.view.* import me.drakeet.multitype.MultiTypeAdapter import org.jetbrains.anko.toast import tech.summerly.quiet.R import tech.summerly.quiet.extensions.PopupMenuHelper import tech.summerly.quiet.extensions.color import tech.summerly.quiet.extensions.lib.KItemViewBinder import tech.summerly.quiet.extensions.multiTypeAdapter import tech.summerly.quiet.extensions.string import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.module.common.bus.RxBus import tech.summerly.quiet.module.common.bus.event.MusicPlayerEvent import tech.summerly.quiet.module.common.player.MusicPlayerWrapper import tech.summerly.quiet.ui.activity.netease.MvPlayerActivity /** * author : yangbin10 * date : 2017/11/15 */ class MusicListFragment : Fragment() { private val items = ArrayList<Any>() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.common_fragment_music_list, container, false) rootView.listMusic.adapter = MultiTypeAdapter(items).also { it.register(Music::class.java, CommonMusicItemViewBinder(this::playMusic)) it.register(Header::class.java, HeaderViewBinder({ @Suppress("UNCHECKED_CAST") //该类型强制转换是安全的 val musicList: ArrayList<Music> = items.filter { it is Music } as ArrayList<Music> if (musicList.isNotEmpty()) { RxBus.publish(MusicPlayerEvent.PlayEvent(musicList[0], musicList, true)) } }, { val popupMenu = PopupMenu(context, it) popupMenu.inflate(R.menu.popup_menu_music_list_header) popupMenu.setOnMenuItemClickListener { when (it.itemId) { R.id.menu_music_header_multi_select -> { //TODO } } true } popupMenu.show() })) } return rootView } private fun playMusic(music: Music) { @Suppress("UNCHECKED_CAST") val musicList = items.filter { it is Music } as List<Music> RxBus.publish(MusicPlayerEvent.PlayEvent(music, musicList, replace = true)) } /** * 设置要显示的音乐列表 */ fun setMusicList(musics: List<Music>) { val newItems: ArrayList<Any> = ArrayList(musics) newItems.add(0, Header(musics.size)) val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { if (oldItemPosition == 0 && newItemPosition == 0) { return true } return items[oldItemPosition] == newItems[newItemPosition] } override fun getOldListSize(): Int = items.size override fun getNewListSize(): Int = newItems.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = items[oldItemPosition] == newItems[newItemPosition] }, true) items.clear() items.addAll(newItems) view?.listMusic?.multiTypeAdapter?.let { diffResult.dispatchUpdatesTo(it) } } private class Header(val count: Int) /** * 音乐列表头部视图,提供的下列按钮功能 * 播放全部音乐 * 对音乐列表进行一些其他的操作 */ private class HeaderViewBinder( private val onHeaderClick: () -> Unit, private val onHeaderMoreActionClick: (view: View) -> Unit) : KItemViewBinder<Header>() { override fun onBindViewHolder(holder: KViewHolder, item: Header) { holder.itemView.headerContainer.setOnClickListener { onHeaderClick() } holder.itemView.headerMore.setOnClickListener(onHeaderMoreActionClick) holder.itemView.headerText.text = string(R.string.action_music_list_header_play_all, item.count) } override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder { val header = inflater.inflate(R.layout.header_music_list, parent, false) return KViewHolder(header) } } open class CommonMusicItemViewBinder(private val onItemClick: (item: Music) -> Unit) : KItemViewBinder<Music>() { private val currentPlaying: Music? get() = MusicPlayerWrapper.currentPlaying() override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder { val root = inflater.inflate(R.layout.common_item_playlist_music, parent, false) return MusicItemViewHolder(root) } override fun onBindViewHolder(holder: KItemViewBinder.KViewHolder, item: Music) { holder as MusicItemViewHolder holder.bindData(item) //(由于header的存在,所以此position就是音乐真实的序号) holder.setNo(holder.adapterPosition) holder.setIsPlaying(false) } inner class MusicItemViewHolder(private val view: View) : KItemViewBinder.KViewHolder(view) { fun setIsPlaying(isPlaying: Boolean): Unit = with(view) { if (isPlaying) { textNo.visibility = View.GONE imagePlayingIndicator.visibility = View.VISIBLE } else { textNo.visibility = View.VISIBLE imagePlayingIndicator.visibility = View.GONE } } @SuppressLint("SetTextI18n") fun bindData(music: Music): Unit = with(view) { val canPlay = music.url != null itemMusic.setOnClickListener { if (canPlay) { onItemClick(music) } else { it.context.toast(string(R.string.toast_error_can_not_fetch_music_url)) } } if (!canPlay) { itemMusicTitle.setTextColor(color(R.color.textDisable)) itemMusicArtist.setTextColor(color(R.color.textDisable)) } else { itemMusicTitle.setTextColor(color(R.color.textPrimary)) itemMusicArtist.setTextColor(color(R.color.textSecondary)) } itemMusicTitle.text = music.title itemMusicArtist.text = music.artistAlbum() //如果存在MV ID,那么表示其有MV itemMusicVideoIndicator.visibility = if (music.mvId > 0) View.VISIBLE else View.GONE itemMusicVideoIndicator.setOnClickListener { MvPlayerActivity.start(it.context, music.mvId, music.type) } actionMore.setOnClickListener { showMusicMoreAction(it, music) } //set bitrate when { music.bitrate in 224000..320000 -> { itemMusicQualityIndicator.visibility = View.VISIBLE itemMusicQualityIndicator.text = "HQ" } music.bitrate > 320000 -> { itemMusicQualityIndicator.visibility = View.VISIBLE itemMusicQualityIndicator.text = "SQ" } else -> itemMusicQualityIndicator.visibility = View.GONE } //为了防止view的复用导致标题和歌手长度显示不正确,所以需要重新测量 itemMusicTitle 和 itemMusicArtist 的宽度 itemMusicTitle.requestLayout() itemMusicArtist.requestLayout() } //设置序号 fun setNo(position: Int) { view.textNo.text = position.toString() } private fun showMusicMoreAction(anchor: View, music: Music) { val popupMenu = PopupMenuHelper(anchor.context) .getMusicPopupMenu(target = anchor, music = music) popupMenu.show() } } } }
gpl-2.0
627cb9a6cad73dd61f3e04548b76870c
39.527897
116
0.615653
4.721
false
false
false
false
coil-kt/coil
coil-compose-base/src/androidTest/java/coil/compose/utils/ImageMockWebServer.kt
1
2206
package coil.compose.utils import androidx.annotation.RawRes import androidx.test.platform.app.InstrumentationRegistry import coil.compose.base.test.R import java.util.concurrent.TimeUnit import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import okio.Buffer /** * A [MockWebServer] which returns a valid image responses at various paths, and a 404 * for anything else. * * @param responseDelayMillis Allows the setting of a response delay to simulate 'real-world' * network conditions. Defaults to 0ms. */ fun ImageMockWebServer(responseDelayMillis: Long = 0): MockWebServer { val dispatcher = object : Dispatcher() { override fun dispatch(request: RecordedRequest) = when (request.path) { "/image" -> { rawResourceAsResponse( id = R.drawable.sample, mimeType = "image/jpeg", ).setHeadersDelay(responseDelayMillis, TimeUnit.MILLISECONDS) } "/blue" -> { rawResourceAsResponse( id = R.drawable.blue_rectangle, mimeType = "image/png", ).setHeadersDelay(responseDelayMillis, TimeUnit.MILLISECONDS) } "/red" -> { rawResourceAsResponse( id = R.drawable.red_rectangle, mimeType = "image/png", ).setHeadersDelay(responseDelayMillis, TimeUnit.MILLISECONDS) } else -> { MockResponse() .setHeadersDelay(responseDelayMillis, TimeUnit.MILLISECONDS) .setResponseCode(404) } } } val server = MockWebServer() server.dispatcher = dispatcher return server } private fun rawResourceAsResponse( @RawRes id: Int, mimeType: String ): MockResponse { val resources = InstrumentationRegistry.getInstrumentation().targetContext.resources return MockResponse() .addHeader("Content-Type", mimeType) .setBody(Buffer().apply { readFrom(resources.openRawResource(id)) }) }
apache-2.0
fdb125ed1721b517f50edd510249303e
35.163934
93
0.635539
5.03653
false
false
false
false
Burning-Man-Earth/iBurn-Android
iBurn/src/main/java/com/gaiagps/iburn/database/Event.kt
1
3556
package com.gaiagps.iburn.database //import com.gaiagps.iburn.database.Event.Companion.ColCampPlayaId //import com.gaiagps.iburn.database.Event.Companion.ColStartTime //import com.gaiagps.iburn.database.Event.Companion.ColStartTimePretty //import com.gaiagps.iburn.database.Event.Companion.ColType //import com.gaiagps.iburn.database.Event.Companion.TableName //import com.gaiagps.iburn.database.PlayaItem.Companion.ColName /** * Created by dbro on 6/6/17. */ //@Entity(tableName = TableName) //class Event( // id: Int = 0, // name: String, // description: String, // url: String, // contact: String, // playaAddress: String, // playaId: String, // location: Location, // isFavorite: Boolean, // // @ColumnInfo(name = ColType) val type: String, // @ColumnInfo(name = ColAllDay) val allDay: Boolean, // @ColumnInfo(name = ColCheckLocation) val checkLocation: Boolean, // @ColumnInfo(name = ColCampPlayaId) val campPlayaId: Int, // @ColumnInfo(name = ColStartTime) val startTime: Date, // @ColumnInfo(name = ColStartTimePretty) val startTimePretty: String, // @ColumnInfo(name = ColEndTime) val endTime: Date, // @ColumnInfo(name = ColEndTimePretty) val endTimePretty: String) // // : PlayaItem(id, name, description, url, contact, playaAddress, playaId, location, isFavorite) { // // companion object { // const val TableName = "events" // // const val ColType = "type" // const val ColAllDay = "all_day" // const val ColCheckLocation = "check_location" // const val ColCampPlayaId = "camp_playa_id" // const val ColStartTime = "start_time" // const val ColStartTimePretty = "start_time_pretty" // const val ColEndTime = "end_time" // const val ColEndTimePretty = "end_time_pretty" // } //} //@Dao //interface EventDao { // // TODO : 'p0' is used vs 'name' b/c Kotlin isn't preserving function parameter names properly // // https://youtrack.jetbrains.com/issue/KT-17959 // // @Query("SELECT * FROM $TableName") // fun getAll(): Flowable<List<Event>> // // @Query("SELECT * FROM $TableName") // fun getFavorites(): Flowable<List<Event>> // // @Query("SELECT * FROM $TableName WHERE $ColCampPlayaId = :p0 ORDER BY $ColStartTime") // fun findByCampPlayaId(campPlayaId: Int): Flowable<List<Event>> // // @Query("SELECT * FROM $TableName WHERE $ColStartTimePretty LIKE :p0 ORDER BY $ColStartTime") // fun findByDay(day: String): Flowable<List<Event>> // // @Query("SELECT * FROM $TableName WHERE ( start_time_pretty LIKE :day% AND $ColType IN (:types) ) ORDER BY $ColStartTime") // fun findByDayAndType(day: String, types: List<String>): Flowable<List<Event>> // // @Query("SELECT * FROM $TableName WHERE $ColName LIKE :p0 GROUP BY $ColName") // GROUP_BY name eliminates duplicate entries for separate occurrences // fun findByName(name: String): Flowable<List<Event>> // // @Insert // fun insert(vararg event: Event) // // @Update // fun update(vararg events: Event) // // @Delete // fun delete(event: Event) //} // //class Converters { // @TypeConverter // fun fromTimestamp(value: Long?): Date? { // return if (value == null) null else Date(value) // } // // @TypeConverter // fun dateToTimestamp(date: Date?): Long? { // return date?.time // } //}
mpl-2.0
188dca36968de779f0613de5c80b4de1
36.840426
153
0.630202
3.577465
false
false
false
false
nfrankel/kaadin
kaadin-core/src/test/kotlin/ch/frankel/kaadin/datainput/InlineDateFieldTest.kt
1
2419
/* * Copyright 2016 Nicolas Fränkel * * 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 ch.frankel.kaadin.datainput import ch.frankel.kaadin.* import com.vaadin.data.util.* import com.vaadin.ui.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import java.util.* class InlineDateFieldTest { @Test fun `inline date field should be added to layout`() { val layout = horizontalLayout { inlineDateField() } assertThat(layout.componentCount).isEqualTo(1) val component = layout.getComponent(0) assertThat(component).isNotNull.isInstanceOf(InlineDateField::class.java) } @Test(dependsOnMethods = ["inline date field should be added to layout"]) fun `inline date field value can be initialized`() { val date = Date() val layout = horizontalLayout { inlineDateField(value = date) } val component = layout.getComponent(0) as InlineDateField assertThat(component.value).isEqualTo(date) } @Test(dependsOnMethods = ["inline date field should be added to layout"]) fun `inline date field value can be initialized via property`() { val date = Date() val property = ObjectProperty(date) val layout = horizontalLayout { inlineDateField(dataSource = property) } val component = layout.getComponent(0) as InlineDateField assertThat(component.value).isEqualTo(date) } @Test(dependsOnMethods = ["inline date field should be added to layout"]) fun `inline date field should be configurable`() { val date = Date() val layout = horizontalLayout { inlineDateField { value = date } } val component = layout.getComponent(0) as InlineDateField assertThat(component.value).isEqualTo(date) } }
apache-2.0
2299130468cb71579d90ebcbc92bd02f
34.057971
81
0.674938
4.579545
false
true
false
false
nguyenhoanglam/ImagePicker
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/helper/ImageHelper.kt
1
2546
/* * Copyright (C) 2021 Image Picker * Author: Nguyen Hoang Lam <[email protected]> */ package com.nguyenhoanglam.imagepicker.helper import android.net.Uri import android.provider.MediaStore import com.nguyenhoanglam.imagepicker.model.Folder import com.nguyenhoanglam.imagepicker.model.Image object ImageHelper { fun singleListFromImage(image: Image): ArrayList<Image> { val images = arrayListOf<Image>() images.add(image) return images } fun folderListFromImages(images: List<Image>): List<Folder> { val folderMap: MutableMap<Long, Folder> = LinkedHashMap() for (image in images) { val bucketId = image.bucketId val bucketName = image.bucketName var folder = folderMap[bucketId] if (folder == null) { folder = Folder(bucketId, bucketName) folderMap[bucketId] = folder } folder.images.add(image) } return ArrayList(folderMap.values) } fun filterImages(images: ArrayList<Image>, bucketId: Long?): ArrayList<Image> { if (bucketId == null || bucketId == 0L) return images val filteredImages = arrayListOf<Image>() for (image in images) { if (image.bucketId == bucketId) { filteredImages.add(image) } } return filteredImages } fun findImageIndex(image: Image, images: ArrayList<Image>): Int { for (i in images.indices) { if (images[i].uri == image.uri) { return i } } return -1 } fun findImageIndexes(subImages: ArrayList<Image>, images: ArrayList<Image>): ArrayList<Int> { val indexes = arrayListOf<Int>() for (image in subImages) { for (i in images.indices) { if (images[i].uri == image.uri) { indexes.add(i) break } } } return indexes } fun isGifFormat(image: Image): Boolean { val fileName = image.name; val extension = if (fileName.contains(".")) { fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length) } else "" return extension.equals("gif", ignoreCase = true) } fun getImageCollectionUri(): Uri { return if (DeviceHelper.isMinSdk29) MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) else MediaStore.Images.Media.EXTERNAL_CONTENT_URI } }
apache-2.0
12db297fc4ee8ec7632a0b474679f796
29.321429
117
0.588767
4.389655
false
false
false
false
spaceisstrange/ToListen
ToListen/app/src/main/java/io/spaceisstrange/tolisten/data/database/Database.kt
1
6053
/* * Made with <3 by Fran González (@spaceisstrange) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.spaceisstrange.tolisten.data.database import io.realm.Realm import io.realm.RealmResults import io.spaceisstrange.tolisten.data.model.Album import io.spaceisstrange.tolisten.data.model.Artist import io.spaceisstrange.tolisten.data.model.Song /** * Represents the operations that can be performed in the database */ class Database { companion object { /** * Returns whether an artist with the given ID exists */ fun artistExists(id: String): Boolean { val realm = Realm.getDefaultInstance() val results = realm.where(Artist::class.java) .equalTo("id", id) .findAll() return !results.isEmpty() } /** * Returns the specified artist with that name (if it exists) from the database */ fun findArtistByName(name: String): RealmResults<Artist> { val realm = Realm.getDefaultInstance() val artists = realm.where(Artist::class.java) .equalTo("name", name) .findAll() return artists } /** * Returns all artists stored in the database */ fun getArtists(): RealmResults<Artist> { val realm = Realm.getDefaultInstance() val artists = realm.where(Artist::class.java).findAllSorted("name") return artists } /** * Adds an artist to the database */ fun addArtist(artist: Artist) { val realm = Realm.getDefaultInstance() realm.executeTransaction { realm.copyToRealmOrUpdate(artist) } } /** * Removes an artist from the database */ fun removeArtist(artist: Artist) { val realm = Realm.getDefaultInstance() val result = realm.where(Artist::class.java).equalTo("id", artist.id).findAll() realm.executeTransaction { result.deleteFirstFromRealm() } } /** * Returns whether an album with the given ID exists */ fun albumExists(id: String): Boolean { val realm = Realm.getDefaultInstance() val results = realm.where(Album::class.java) .equalTo("id", id) .findAll() return !results.isEmpty() } /** * Returns the album with that name (if it exists) from the database */ fun findAlbumByName(name: String): RealmResults<Album> { val realm = Realm.getDefaultInstance() val albums = realm.where(Album::class.java) .equalTo("name", name) .findAll() return albums } /** * Returns all albums stored in the database */ fun getAlbums(): RealmResults<Album> { val realm = Realm.getDefaultInstance() val albums = realm.where(Album::class.java).findAllSorted("name") return albums } /** * Adds an album to the database */ fun addAlbum(album: Album) { val realm = Realm.getDefaultInstance() realm.executeTransaction { realm.copyToRealmOrUpdate(album) } } /** * Removes an album from the database */ fun removeAlbum(album: Album) { val realm = Realm.getDefaultInstance() val result = realm.where(Album::class.java).equalTo("id", album.id).findAll() realm.executeTransaction { result.deleteFirstFromRealm() } } /** * Returns whether a song with the given ID exists */ fun songExists(id: String): Boolean { val realm = Realm.getDefaultInstance() val results = realm.where(Song::class.java) .equalTo("id", id) .findAll() return !results.isEmpty() } /** * Returns all songs stored in the database */ fun getSongs(): RealmResults<Song> { val realm = Realm.getDefaultInstance() val songs = realm.where(Song::class.java).findAllSorted("name") return songs } /** * Adds a song to the database */ fun addSong(song: Song) { val realm = Realm.getDefaultInstance() realm.executeTransaction { realm.copyToRealmOrUpdate(song) } } /** * Removes a song from the database */ fun removeSong(song: Song) { val realm = Realm.getDefaultInstance() val result = realm.where(Song::class.java).equalTo("id", song.id).findAll() realm.executeTransaction { result.deleteFirstFromRealm() } } /** * Wipes the database completely. Probably just for testing purposes */ fun nuke() { val realm = Realm.getDefaultInstance() realm.executeTransaction { realm.deleteAll() } } } }
gpl-3.0
67c212146d326a49322260aebdc3e614
28.965347
91
0.554197
5.00579
false
false
false
false
RyanAndroidTaylor/Rapido
rapidosqlite/src/main/java/com/izeni/rapidosqlite/query/Join.kt
1
318
package com.izeni.rapidosqlite.query /** * Created by ner on 2/16/17. */ abstract class Join { protected val stringBuilder = StringBuilder() protected val leftJoin = " LEFT JOIN " protected val on = " ON " protected val space = " " protected val period = "." protected val equals = " = " }
mit
5f070f54d07da61011262dc57987a17a
20.266667
49
0.638365
4.025316
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/transport/ice/IceTransport.kt
1
21940
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.transport.ice import com.google.common.net.InetAddresses import org.ice4j.Transport import org.ice4j.TransportAddress import org.ice4j.ice.Agent import org.ice4j.ice.CandidateType import org.ice4j.ice.HostCandidate import org.ice4j.ice.IceMediaStream import org.ice4j.ice.IceProcessingState import org.ice4j.ice.LocalCandidate import org.ice4j.ice.RemoteCandidate import org.ice4j.ice.harvest.MappingCandidateHarvesters import org.ice4j.socket.SocketClosedException import org.jitsi.utils.OrderedJsonObject import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.createChildLogger import org.jitsi.videobridge.ice.Harvesters import org.jitsi.videobridge.ice.IceConfig import org.jitsi.videobridge.ice.TransportUtils import org.jitsi.videobridge.metrics.VideobridgeMetricsContainer import org.jitsi.xmpp.extensions.jingle.CandidatePacketExtension import org.jitsi.xmpp.extensions.jingle.IceCandidatePacketExtension import org.jitsi.xmpp.extensions.jingle.IceRtcpmuxPacketExtension import org.jitsi.xmpp.extensions.jingle.IceUdpTransportPacketExtension import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import java.io.IOException import java.net.DatagramPacket import java.net.Inet6Address import java.time.Clock import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.LongAdder class IceTransport @JvmOverloads constructor( id: String, /** * Whether the ICE agent created by this transport should be the * 'controlling' role. */ controlling: Boolean, /** * Whether the ICE agent created by this transport should use * unique local ports, rather than the configured port. */ useUniquePort: Boolean, parentLogger: Logger, private val clock: Clock = Clock.systemUTC() ) { private val logger = createChildLogger(parentLogger) /** * The handler which will be invoked when data is received. The handler * does *not* own the buffer passed to it, so a copy must be made if it wants * to use the data after the handler call finishes. This field should be * set by some other entity which wishes to handle the incoming data * received over the ICE connection. * NOTE: we don't create a packet in [IceTransport] because * RTP packets want space before and after and [IceTransport] * has no notion of what kind of data is contained within the buffer. */ @JvmField var incomingDataHandler: IncomingDataHandler? = null /** * The handler which will be invoked when events fired by [IceTransport] * occur. This field should be set by another entity who wishes to handle * the events. Handlers will only be notified of events which occur * *after* the handler has been set. */ @JvmField var eventHandler: EventHandler? = null /** * Whether or not this [IceTransport] has connected. */ private val iceConnected = AtomicBoolean(false) /** * Whether or not this [IceTransport] has failed to connect. */ private val iceFailed = AtomicBoolean(false) fun hasFailed(): Boolean = iceFailed.get() fun isConnected(): Boolean = iceConnected.get() /** * Whether or not this transport is 'running'. If it is not * running, no more data will be read from the socket or sent out. */ private val running = AtomicBoolean(true) private val iceStateChangeListener = PropertyChangeListener { ev -> iceStateChanged(ev) } private val iceStreamPairChangedListener = PropertyChangeListener { ev -> iceStreamPairChanged(ev) } private val iceAgent = Agent(IceConfig.config.ufragPrefix, logger).apply { if (useUniquePort) { setUseDynamicPorts(true) } else { appendHarvesters(this) } isControlling = controlling performConsentFreshness = true nominationStrategy = IceConfig.config.nominationStrategy addStateChangeListener(iceStateChangeListener) }.also { logger.addContext("local_ufrag", it.localUfrag) } // TODO: Do we still need the id here now that we have logContext? private val iceStream = iceAgent.createMediaStream("stream-$id").apply { addPairChangeListener(iceStreamPairChangedListener) } private val iceComponent = iceAgent.createComponent( iceStream, IceConfig.config.keepAliveStrategy, IceConfig.config.useComponentSocket ) private val packetStats = PacketStats() val icePassword: String get() = iceAgent.localPassword /** * Tell this [IceTransport] to start ICE connectivity establishment. */ fun startConnectivityEstablishment(transportPacketExtension: IceUdpTransportPacketExtension) { if (!running.get()) { logger.warn("Not starting connectivity establishment, transport is not running") return } if (iceAgent.state.isEstablished) { logger.cdebug { "Connection already established" } return } logger.cdebug { "Starting ICE connectivity establishment" } // Set the remote ufrag/password iceStream.remoteUfrag = transportPacketExtension.ufrag iceStream.remotePassword = transportPacketExtension.password // If ICE is running already, we try to update the checklists with the // candidates. Note that this is a best effort. val iceAgentStateIsRunning = IceProcessingState.RUNNING == iceAgent.state val remoteCandidates = transportPacketExtension.getChildExtensionsOfType(CandidatePacketExtension::class.java) if (iceAgentStateIsRunning && remoteCandidates.isEmpty()) { logger.cdebug { "Ignoring transport extensions with no candidates, " + "the Agent is already running." } return } val remoteCandidateCount = addRemoteCandidates(remoteCandidates, iceAgentStateIsRunning) if (iceAgentStateIsRunning) { when (remoteCandidateCount) { 0 -> { // XXX Effectively, the check above but realizing that all // candidates were ignored: // iceAgentStateIsRunning && candidates.isEmpty(). } else -> iceComponent.updateRemoteCandidates() } } else if (remoteCandidateCount != 0) { // Once again, because the ICE Agent does not support adding // candidates after the connectivity establishment has been started // and because multiple transport-info JingleIQs may be used to send // the whole set of transport candidates from the remote peer to the // local peer, do not really start the connectivity establishment // until we have at least one remote candidate per ICE Component. if (iceComponent.remoteCandidateCount > 0) { logger.info("Starting the agent with remote candidates.") iceAgent.startConnectivityEstablishment() } } else if (iceStream.remoteUfragAndPasswordKnown()) { // We don't have any remote candidates, but we already know the // remote ufrag and password, so we can start ICE. logger.info("Starting the Agent without remote candidates.") iceAgent.startConnectivityEstablishment() } else { logger.cdebug { "Not starting ICE, no ufrag and pwd yet. ${transportPacketExtension.toXML()}" } } } fun startReadingData() { logger.cdebug { "Starting to read incoming data" } val socket = iceComponent.socket val receiveBuf = ByteArray(1500) val packet = DatagramPacket(receiveBuf, 0, receiveBuf.size) var receivedTime: Instant while (running.get()) { try { socket.receive(packet) receivedTime = clock.instant() } catch (e: SocketClosedException) { logger.info("Socket closed, stopping reader") break } catch (e: IOException) { logger.warn("Stopping reader", e) break } packetStats.numPacketsReceived.increment() incomingDataHandler?.dataReceived(receiveBuf, packet.offset, packet.length, receivedTime) ?: run { logger.cdebug { "Data handler is null, dropping data" } packetStats.numIncomingPacketsDroppedNoHandler.increment() } } logger.info("No longer running, stopped reading packets") } /** * Send data out via this transport */ fun send(data: ByteArray, off: Int, length: Int) { if (running.get()) { try { iceComponent.socket.send(DatagramPacket(data, off, length)) packetStats.numPacketsSent.increment() } catch (e: IOException) { logger.error("Error sending packet", e) throw RuntimeException() } } else { packetStats.numOutgoingPacketsDroppedStopped.increment() } } fun stop() { if (running.compareAndSet(true, false)) { logger.info("Stopping") iceAgent.removeStateChangeListener(iceStateChangeListener) iceStream.removePairStateChangeListener(iceStreamPairChangedListener) iceAgent.free() } } fun getDebugState(): OrderedJsonObject = OrderedJsonObject().apply { put("useComponentSocket", IceConfig.config.useComponentSocket) put("keepAliveStrategy", IceConfig.config.keepAliveStrategy.toString()) put("nominationStrategy", IceConfig.config.nominationStrategy.toString()) put("advertisePrivateCandidates", IceConfig.config.advertisePrivateCandidates) put("closed", !running.get()) put("iceConnected", iceConnected.get()) put("iceFailed", iceFailed.get()) putAll(packetStats.toJson()) } fun describe(pe: IceUdpTransportPacketExtension) { if (!running.get()) { logger.warn("Not describing, transport is not running") } with(pe) { password = iceAgent.localPassword ufrag = iceAgent.localUfrag iceComponent.localCandidates?.forEach { cand -> cand.toCandidatePacketExtension()?.let { pe.addChildExtension(it) } } addChildExtension(IceRtcpmuxPacketExtension()) } } /** * @return the number of network reachable remote candidates contained in * the given list of candidates. */ private fun addRemoteCandidates( remoteCandidates: List<CandidatePacketExtension>, iceAgentIsRunning: Boolean ): Int { var remoteCandidateCount = 0 // Sort the remote candidates (host < reflexive < relayed) in order to // create first the host, then the reflexive, the relayed candidates and // thus be able to set the relative-candidate matching the // rel-addr/rel-port attribute. remoteCandidates.sorted().forEach { candidate -> // Is the remote candidate from the current generation of the // iceAgent? if (candidate.generation != iceAgent.generation) { return@forEach } if (candidate.ipNeedsResolution() && !IceConfig.config.resolveRemoteCandidates) { logger.cdebug { "Ignoring remote candidate with non-literal address: ${candidate.ip}" } return@forEach } val component = iceStream.getComponent(candidate.component) val remoteCandidate = RemoteCandidate( TransportAddress(candidate.ip, candidate.port, Transport.parse(candidate.protocol)), component, CandidateType.parse(candidate.type.toString()), candidate.foundation, candidate.priority.toLong(), null ) // XXX IceTransport harvests host candidates only and the // ICE Components utilize the UDP protocol/transport only at the // time of this writing. The ice4j library will, of course, check // the theoretical reachability between the local and the remote // candidates. However, we would like (1) to not mess with a // possibly running iceAgent and (2) to return a consistent return // value. if (!TransportUtils.canReach(component, remoteCandidate)) { return@forEach } if (iceAgentIsRunning) { component.addUpdateRemoteCandidates(remoteCandidate) } else { component.addRemoteCandidate(remoteCandidate) } remoteCandidateCount++ } return remoteCandidateCount } private fun iceStateChanged(ev: PropertyChangeEvent) { val oldState = ev.oldValue as IceProcessingState val newState = ev.newValue as IceProcessingState val transition = IceProcessingStateTransition(oldState, newState) logger.info("ICE state changed old=$oldState new=$newState") when { transition.completed() -> { if (iceConnected.compareAndSet(false, true)) { eventHandler?.connected() if (iceComponent.selectedPair.remoteCandidate.transport.isTcpType()) { iceSucceededTcp.inc() } if (iceComponent.selectedPair.remoteCandidate.type == CandidateType.RELAYED_CANDIDATE || iceComponent.selectedPair.localCandidate.type == CandidateType.RELAYED_CANDIDATE ) { iceSucceededRelayed.inc() } iceSucceeded.inc() } } transition.failed() -> { if (iceFailed.compareAndSet(false, true)) { eventHandler?.failed() Companion.iceFailed.inc() } } } } /** Update IceStatistics once an initial round-trip-time measurement is available. */ fun updateStatsOnInitialRtt(rttMs: Double) { val selectedPair = iceComponent.selectedPair val localCandidate = selectedPair?.localCandidate ?: return val harvesterName = if (localCandidate is HostCandidate) { "host" } else { MappingCandidateHarvesters.findHarvesterForAddress(localCandidate.transportAddress)?.name ?: "other" } IceStatistics.stats.add(harvesterName, rttMs) } private fun iceStreamPairChanged(ev: PropertyChangeEvent) { if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED == ev.propertyName) { /* TODO: Currently ice4j only triggers this event for the selected * pair, but should we double-check the pair anyway? */ val time = Instant.ofEpochMilli(ev.newValue as Long) eventHandler?.consentUpdated(time) } } companion object { fun appendHarvesters(iceAgent: Agent) { Harvesters.initializeStaticConfiguration() Harvesters.tcpHarvester?.let { iceAgent.addCandidateHarvester(it) } Harvesters.singlePortHarvesters?.forEach(iceAgent::addCandidateHarvester) } /** * The total number of times an ICE Agent failed to establish * connectivity. */ val iceFailed = VideobridgeMetricsContainer.instance.registerCounter( "ice_failed", "Number of times an ICE Agent failed to establish connectivity." ) /** * The total number of times an ICE Agent succeeded. */ val iceSucceeded = VideobridgeMetricsContainer.instance.registerCounter( "ice_succeeded", "Number of times an ICE Agent succeeded." ) /** * The total number of times an ICE Agent succeeded and the selected * candidate was a TCP candidate. */ val iceSucceededTcp = VideobridgeMetricsContainer.instance.registerCounter( "ice_succeeded_tcp", "Number of times an ICE Agent succeeded and the selected candidate was a TCP candidate." ) /** * The total number of times an ICE Agent succeeded and the selected * candidate pair included a relayed candidate. */ val iceSucceededRelayed = VideobridgeMetricsContainer.instance.registerCounter( "ice_succeeded_relayed", "Number of times an ICE Agent succeeded and the selected pair included a relayed candidate." ) } private class PacketStats { val numPacketsReceived = LongAdder() val numIncomingPacketsDroppedNoHandler = LongAdder() val numPacketsSent = LongAdder() val numOutgoingPacketsDroppedStopped = LongAdder() fun toJson(): OrderedJsonObject = OrderedJsonObject().apply { put("num_packets_received", numPacketsReceived.sum()) put("num_incoming_packets_dropped_no_handler", numIncomingPacketsDroppedNoHandler.sum()) put("num_packets_sent", numPacketsSent.sum()) put("num_outgoing_packets_dropped_stopped", numOutgoingPacketsDroppedStopped.sum()) } } interface IncomingDataHandler { /** * Notify the handler that data was received (contained * within [data] at [offset] with [length]) at [receivedTime] */ fun dataReceived(data: ByteArray, offset: Int, length: Int, receivedTime: Instant) } interface EventHandler { /** * Notify the event handler that ICE connected successfully */ fun connected() /** * Notify the event handler that ICE failed to connect */ fun failed() /** * Notify the event handler that ICE consent was updated */ fun consentUpdated(time: Instant) } } /** * Models a transition from one ICE state to another and provides convenience * functions to test the transition. */ private data class IceProcessingStateTransition( val oldState: IceProcessingState, val newState: IceProcessingState ) { // We should be using newState.isEstablished() here, but we see // transitions from RUNNING to TERMINATED, which can happen if the Agent is // free prior to being started, so we handle that case separately below. fun completed(): Boolean = newState == IceProcessingState.COMPLETED fun failed(): Boolean { return newState == IceProcessingState.FAILED || (oldState == IceProcessingState.RUNNING && newState == IceProcessingState.TERMINATED) } } private fun IceMediaStream.remoteUfragAndPasswordKnown(): Boolean = remoteUfrag != null && remotePassword != null private fun CandidatePacketExtension.ipNeedsResolution(): Boolean = !InetAddresses.isInetAddress(ip) private fun TransportAddress.isPrivateAddress(): Boolean = address.isSiteLocalAddress || /* 0xfc00::/7 */ ((address is Inet6Address) && ((addressBytes[0].toInt() and 0xfe) == 0xfc)) private fun Transport.isTcpType(): Boolean = this == Transport.TCP || this == Transport.SSLTCP private fun generateCandidateId(candidate: LocalCandidate): String = buildString { append(java.lang.Long.toHexString(hashCode().toLong())) append(java.lang.Long.toHexString(candidate.parentComponent.parentStream.parentAgent.hashCode().toLong())) append(java.lang.Long.toHexString(candidate.parentComponent.parentStream.parentAgent.generation.toLong())) append(java.lang.Long.toHexString(candidate.hashCode().toLong())) } private fun LocalCandidate.toCandidatePacketExtension(): CandidatePacketExtension? { if (!IceConfig.config.advertisePrivateCandidates && transportAddress.isPrivateAddress()) { return null } val cpe = IceCandidatePacketExtension() cpe.component = parentComponent.componentID cpe.foundation = foundation cpe.generation = parentComponent.parentStream.parentAgent.generation cpe.id = generateCandidateId(this) cpe.network = 0 cpe.setPriority(priority) // Advertise 'tcp' candidates for which SSL is enabled as 'ssltcp' // (although internally their transport protocol remains "tcp") cpe.protocol = if (transport == Transport.TCP && isSSL) { Transport.SSLTCP.toString() } else { transport.toString() } if (transport.isTcpType()) { cpe.tcpType = tcpType.toString() } cpe.type = org.jitsi.xmpp.extensions.jingle.CandidateType.valueOf(type.toString()) cpe.ip = transportAddress.hostAddress cpe.port = transportAddress.port relatedAddress?.let { if (!IceConfig.config.advertisePrivateCandidates && it.isPrivateAddress()) { cpe.relAddr = "0.0.0.0" cpe.relPort = 9 } else { cpe.relAddr = it.hostAddress cpe.relPort = it.port } } return cpe }
apache-2.0
a9b95b9547ceec5d6c510c32255f4f46
39.036496
118
0.652552
4.804029
false
false
false
false
Livin21/KotlinSolitaire
src/TableauPile.kt
1
1088
/** * Created by livin on 29/5/17. */ class TableauPile(var cards: MutableList<Card> = mutableListOf()) { init { if (cards.size > 0) cards.last().faceUp = true } fun addCards(newCards: MutableList<Card>): Boolean { if (cards.size > 0) { if (newCards.first().value == cards.last().value - 1 && suitCheck(newCards.first(), cards.last())) { cards.addAll(newCards) return true } } else if (newCards.first().value == 12) { cards.addAll(newCards) return true } return false } fun removeCards(tappedIndex: Int) { for (i in tappedIndex..cards.lastIndex) { cards.removeAt(tappedIndex) } if (cards.size > 0) { cards.last().faceUp = true } } private fun suitCheck(c1: Card, c2: Card): Boolean { return (redSuits.contains(c1.suit) && blackSuits.contains(c2.suit)) || (blackSuits.contains(c1.suit) && redSuits.contains(c2.suit)) } }
mit
fbb03f506de222c819fcc7bc0891aad1
28.432432
78
0.525735
3.751724
false
false
false
false
springboot-angular2-tutorial/boot-app
src/main/kotlin/com/myapp/auth/StatelessAuthenticationFilter.kt
1
1408
package com.myapp.auth import io.jsonwebtoken.JwtException import org.springframework.security.core.AuthenticationException import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Component import org.springframework.web.filter.GenericFilterBean import javax.servlet.FilterChain import javax.servlet.ServletRequest import javax.servlet.ServletResponse import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @Component class StatelessAuthenticationFilter( private val tokenAuthenticationService: TokenAuthenticationService ) : GenericFilterBean() { override fun doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) { try { val authentication = tokenAuthenticationService.authentication(req as HttpServletRequest) SecurityContextHolder.getContext().authentication = authentication chain.doFilter(req, res) SecurityContextHolder.getContext().authentication = null } catch (e: AuthenticationException) { SecurityContextHolder.clearContext() (res as HttpServletResponse).status = HttpServletResponse.SC_UNAUTHORIZED } catch (e: JwtException) { SecurityContextHolder.clearContext() (res as HttpServletResponse).status = HttpServletResponse.SC_UNAUTHORIZED } } }
mit
63d49981fb8680c69590c32a3f2ac9bd
40.411765
101
0.769176
5.457364
false
false
false
false
Shynixn/PetBlocks
petblocks-sponge-plugin/src/test/java/integrationtest/PersistenceSQLiteIT.kt
1
22032
@file:Suppress("UNCHECKED_CAST") package integrationtest import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.business.enumeration.ParticleType import com.github.shynixn.petblocks.api.business.enumeration.Permission import com.github.shynixn.petblocks.api.business.enumeration.Version import com.github.shynixn.petblocks.api.business.proxy.PluginProxy import com.github.shynixn.petblocks.api.business.service.* import com.github.shynixn.petblocks.api.persistence.context.SqlDbContext import com.github.shynixn.petblocks.api.persistence.entity.* import com.github.shynixn.petblocks.core.logic.business.service.* import com.github.shynixn.petblocks.core.logic.persistence.context.SqlDbContextImpl import com.github.shynixn.petblocks.core.logic.persistence.entity.AIMovementEntity import com.github.shynixn.petblocks.core.logic.persistence.repository.PetMetaSqlRepository import com.github.shynixn.petblocks.sponge.logic.business.service.ConfigurationServiceImpl import com.github.shynixn.petblocks.sponge.logic.business.service.EntityServiceImpl import com.github.shynixn.petblocks.sponge.logic.business.service.ItemTypeServiceImpl import com.github.shynixn.petblocks.sponge.logic.business.service.YamlServiceImpl import helper.MockedLoggingService import org.apache.commons.io.FileUtils import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito import org.spongepowered.api.asset.Asset import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.plugin.PluginContainer import java.io.File import java.nio.file.Paths import java.util.* import java.util.logging.Logger /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class PersistenceSQLiteIT { /** * Given * initial empty database and production configuration in config.yml * When * getAll is called the database should still be empty and when getOrCreateFromPlayerUUID with a new uuid is called * Then * the default pet with the default production configuration from the config.yml should be generated. */ @Test fun getOrCreateFromPlayerUUID_ProductionConfiguration_ShouldGenerateCorrectPet() { // Arrange val classUnderTest = createWithDependencies() val uuid = UUID.fromString("c7d21810-d2a0-407d-a389-14efd3eb79d2") val player = Mockito.mock(Player::class.java) Mockito.`when`(player.uniqueId).thenReturn(uuid) // Act val initialSize = classUnderTest.getAll().get().size val actual = classUnderTest.getPetMetaFromPlayer(player) // Assert Assertions.assertEquals(0, initialSize) Assertions.assertEquals(1, actual.id) Assertions.assertEquals(false, actual.enabled) Assertions.assertEquals("Kenny's Pet", actual.displayName) Assertions.assertEquals(true, actual.soundEnabled) Assertions.assertEquals(true, actual.particleEnabled) Assertions.assertEquals(1, actual.skin.id) Assertions.assertEquals("GRASS", actual.skin.typeName) Assertions.assertEquals(0, actual.skin.dataValue) Assertions.assertEquals("", actual.skin.nbtTag) Assertions.assertEquals("", actual.skin.owner) Assertions.assertEquals(1, actual.playerMeta.id) Assertions.assertEquals("Kenny", actual.playerMeta.name) Assertions.assertEquals(9, actual.aiGoals.size) Assertions.assertEquals("hopping", (actual.aiGoals[0] as AIMovementEntity).type) Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).climbingHeight) Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSpeed) Assertions.assertEquals(-1.0, (actual.aiGoals[0] as AIMovementEntity).movementYOffSet) Assertions.assertEquals("CHICKEN_WALK", (actual.aiGoals[0] as AIMovementEntity).movementSound.name) Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSound.volume) Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSound.pitch) Assertions.assertEquals(ParticleType.NONE.name, (actual.aiGoals[0] as AIMovementEntity).movementParticle.typeName) Assertions.assertEquals(1, (actual.aiGoals[0] as AIMovementEntity).movementParticle.amount) Assertions.assertEquals("follow-owner", (actual.aiGoals[1] as AIFollowOwner).type) Assertions.assertEquals(3.0, (actual.aiGoals[1] as AIFollowOwner).distanceToOwner) Assertions.assertEquals(50.0, (actual.aiGoals[1] as AIFollowOwner).maxRange) Assertions.assertEquals(1.5, (actual.aiGoals[1] as AIFollowOwner).speed) Assertions.assertEquals("float-in-water", (actual.aiGoals[2] as AIFloatInWater).type) Assertions.assertEquals("feeding", (actual.aiGoals[3] as AIFeeding).type) Assertions.assertEquals("391", (actual.aiGoals[3] as AIFeeding).typeName) Assertions.assertEquals(ParticleType.HEART.name, (actual.aiGoals[3] as AIFeeding).clickParticle.typeName) Assertions.assertEquals("EAT", (actual.aiGoals[3] as AIFeeding).clickSound.name) Assertions.assertEquals("ambient-sound", (actual.aiGoals[5] as AIAmbientSound).type) Assertions.assertEquals("CHICKEN_IDLE", (actual.aiGoals[5] as AIAmbientSound).sound.name) } /** * Given * initial empty database and production configuration in config.yml * When * getAll is called the database should still be empty and when getOrCreateFromPlayerUUID is called * Then * the default pet with the default production configuration should be correctly editable and storeAble again. */ @Test fun getOrCreateFromPlayerUUID_ProductionConfiguration_ShouldAllowChangingPet() { // Arrange val classUnderTest = createWithDependencies() val uuid = UUID.fromString("c7d21810-d2a0-407d-a389-14efd3eb79d2") val player = Mockito.mock(Player::class.java) Mockito.`when`(player.uniqueId).thenReturn(uuid) // Act val initialSize = classUnderTest.getAll().get().size val petMeta = classUnderTest.getPetMetaFromPlayer(player) petMeta.enabled = true petMeta.displayName = "This is a very long displayname in order to check if column size is dynamic" petMeta.soundEnabled = false petMeta.particleEnabled = false petMeta.skin.typeName = "DIRT" petMeta.skin.dataValue = 2 petMeta.skin.nbtTag = "{Unbreakable:1}" petMeta.skin.owner = "Pikachu" petMeta.playerMeta.name = "Superman" (petMeta.aiGoals[0] as AIHopping).climbingHeight = 23.5 (petMeta.aiGoals[0] as AIHopping).movementSpeed = 105.3 (petMeta.aiGoals[0] as AIHopping).movementYOffSet = 93.4 (petMeta.aiGoals[0] as AIHopping).movementParticle.offSetY = 471.2 (petMeta.aiGoals[0] as AIHopping).movementSound.pitch = 44.2 (petMeta.aiGoals[1] as AIFollowOwner).maxRange = 100.2 (petMeta.aiGoals[1] as AIFollowOwner).distanceToOwner = 14.45 (petMeta.aiGoals[1] as AIFollowOwner).speed = 42.2 (petMeta.aiGoals[2] as AIFloatInWater).userId = "43" (petMeta.aiGoals[3] as AIFeeding).clickParticle.offSetZ = 25.4 (petMeta.aiGoals[3] as AIFeeding).clickSound.name = "COOKIE_SOUND" (petMeta.aiGoals[3] as AIFeeding).dataValue = 4 (petMeta.aiGoals[3] as AIFeeding).typeName = "POWER_BANK" (petMeta.aiGoals[5] as AIAmbientSound).sound.volume = 41.55 classUnderTest.save(petMeta).get() val actual = classUnderTest.getPetMetaFromPlayer(player) // Assert Assertions.assertEquals(0, initialSize) Assertions.assertEquals(1, actual.id) Assertions.assertEquals(true, actual.enabled) Assertions.assertEquals("This is a very long displayname in order to check if column size is dynamic", actual.displayName) Assertions.assertEquals(false, actual.soundEnabled) Assertions.assertEquals(false, actual.particleEnabled) Assertions.assertEquals(1, actual.skin.id) Assertions.assertEquals("DIRT", actual.skin.typeName) Assertions.assertEquals(2, actual.skin.dataValue) Assertions.assertEquals("{Unbreakable:1}", actual.skin.nbtTag) Assertions.assertEquals("Pikachu", actual.skin.owner) Assertions.assertEquals(1, actual.playerMeta.id) Assertions.assertEquals("Superman", actual.playerMeta.name) Assertions.assertEquals("hopping", (actual.aiGoals[0] as AIMovementEntity).type) Assertions.assertEquals(23.5, (actual.aiGoals[0] as AIMovementEntity).climbingHeight) Assertions.assertEquals(105.3, (actual.aiGoals[0] as AIMovementEntity).movementSpeed) Assertions.assertEquals(93.4, (actual.aiGoals[0] as AIMovementEntity).movementYOffSet) Assertions.assertEquals(44.2, (actual.aiGoals[0] as AIMovementEntity).movementSound.pitch) Assertions.assertEquals(471.2, (actual.aiGoals[0] as AIMovementEntity).movementParticle.offSetY) Assertions.assertEquals("follow-owner", (actual.aiGoals[1] as AIFollowOwner).type) Assertions.assertEquals(14.45, (actual.aiGoals[1] as AIFollowOwner).distanceToOwner) Assertions.assertEquals(100.2, (actual.aiGoals[1] as AIFollowOwner).maxRange) Assertions.assertEquals(42.2, (actual.aiGoals[1] as AIFollowOwner).speed) Assertions.assertEquals("43", (actual.aiGoals[2] as AIFloatInWater).userId!!) Assertions.assertEquals("feeding", (actual.aiGoals[3] as AIFeeding).type) Assertions.assertEquals("POWER_BANK", (actual.aiGoals[3] as AIFeeding).typeName) Assertions.assertEquals(4, (actual.aiGoals[3] as AIFeeding).dataValue) Assertions.assertEquals("COOKIE_SOUND", (actual.aiGoals[3] as AIFeeding).clickSound.name) Assertions.assertEquals(25.4, (actual.aiGoals[3] as AIFeeding).clickParticle.offSetZ) Assertions.assertEquals("ambient-sound", (actual.aiGoals[5] as AIAmbientSound).type) Assertions.assertEquals(41.55, (actual.aiGoals[5] as AIAmbientSound).sound.volume) } companion object { private var dbContext: SqlDbContext? = null fun createWithDependencies(): PersistencePetMetaService { if (dbContext != null) { dbContext!!.close() } val folder = File("integrationtest-sqlite") if (folder.exists()) { FileUtils.deleteDirectory(folder) } val sqliteFile = File("../petblocks-core/src/main/resources/assets/petblocks/PetBlocks.db") if (sqliteFile.exists()) { sqliteFile.delete() } val plugin = Mockito.mock(PluginContainer::class.java) Mockito.`when`(plugin.getAsset(Mockito.anyString())).then { p -> val path = p.getArgument<String>(0) val url = File("../petblocks-core/src/main/resources/$path").toURI() val asset = Mockito.mock(Asset::class.java) Mockito.`when`(asset.url).thenReturn(url.toURL()) Optional.of(asset) } val configurationService = ConfigurationServiceImpl( Paths.get("../petblocks-core/src/main/resources/assets/petblocks") , LoggingUtilServiceImpl(Logger.getAnonymousLogger()), plugin ) val aiService = AIServiceImpl( LoggingUtilServiceImpl(Logger.getAnonymousLogger()), MockedProxyService(), YamlServiceImpl(), configurationService ) val localizationService = LocalizationServiceImpl(configurationService, LoggingUtilServiceImpl(Logger.getAnonymousLogger())) localizationService.reload() val guiItemLoadService = GUIItemLoadServiceImpl( configurationService, ItemTypeServiceImpl(), aiService, localizationService ) val method = PetBlocksApi::class.java.getDeclaredMethod("initializePetBlocks", PluginProxy::class.java) method.isAccessible = true method.invoke(PetBlocksApi, MockedPluginProxy()) EntityServiceImpl( MockedProxyService(), Mockito.mock(PetService::class.java), YamlSerializationServiceImpl(), Version.VERSION_1_12_R1, aiService, LoggingUtilServiceImpl(Logger.getAnonymousLogger()), ItemTypeServiceImpl() ) dbContext = SqlDbContextImpl(configurationService, LoggingUtilServiceImpl(Logger.getAnonymousLogger())) val sqlite = PetMetaSqlRepository(dbContext!!, aiService, guiItemLoadService, configurationService) return PersistencePetMetaServiceImpl( MockedProxyService(), sqlite, MockedConcurrencyService(), MockedEventService(), aiService, MockedLoggingService() ) } } class MockedPluginProxy : PluginProxy { /** * Gets the installed version of the plugin. */ override val version: String get() = "" /** * Gets the server version this plugin is currently running on. */ override fun getServerVersion(): Version { return Version.VERSION_UNKNOWN } /** * Gets a business logic from the PetBlocks plugin. * All types in the service package can be accessed. * Throws a [IllegalArgumentException] if the service could not be found. * @param S the type of service class. */ override fun <S> resolve(service: Any): S { throw IllegalArgumentException() } /** * Creates a new entity from the given [entity]. * Throws a [IllegalArgumentException] if the entity could not be found. * @param E the type of entity class. */ override fun <E> create(entity: Any): E { throw IllegalArgumentException() } } class MockedProxyService : ProxyService { /** * Applies the given [potionEffect] to the given [player]. */ override fun <P> applyPotionEffect(player: P, potionEffect: PotionEffect) { } /** * Gets a list of points between 2 locations. */ override fun <L> getPointsBetweenLocations(location1: L, location2: L, amount: Int): List<L> { throw IllegalArgumentException() } /** * Drops the given item at the given position. */ override fun <L, I> dropInventoryItem(location: L, item: I) { throw IllegalArgumentException() } /** * Gets the inventory item at the given index. */ override fun <I, IT> getInventoryItem(inventory: I, index: Int): IT? { throw IllegalArgumentException() } /** * Gets if the given player has got the given permission. */ override fun <P> hasPermission(player: P, permission: String): Boolean { throw IllegalArgumentException() } /** * Closes the inventory of the given player. */ override fun <P> closeInventory(player: P) { throw IllegalArgumentException() } /** * Gets if the given inventory belongs to a player. Returns null if not. */ override fun <P, I> getPlayerFromInventory(inventory: I): P? { throw IllegalArgumentException() } /** * Gets the lower inventory of an inventory. */ override fun <I> getLowerInventory(inventory: I): I { throw IllegalArgumentException() } /** * Clears the given inventory. */ override fun <I> clearInventory(inventory: I) { throw IllegalArgumentException() } /** * Opens a new inventory for the given player. */ override fun <P, I> openInventory(player: P, title: String, size: Int): I { throw IllegalArgumentException() } /** * Updates the inventory. */ override fun <I, IT> setInventoryItem(inventory: I, index: Int, item: IT) { throw IllegalArgumentException() } /** * Updates the given player inventory. */ override fun <P> updateInventory(player: P) { throw IllegalArgumentException() } /** * Gets if the given instance can be converted to a player. */ override fun <P> isPlayer(instance: P): Boolean { return true } /** * Gets the name of a player. */ override fun <P> getPlayerName(player: P): String { return "Kenny" } /** * Gets the player from the given UUID. */ override fun <P> getPlayerFromUUID(uuid: String): P { throw IllegalArgumentException() } /** * Gets the entity id. */ override fun <E> getEntityId(entity: E): Int { throw IllegalArgumentException() } /** * Gets the location of the player. */ override fun <L, P> getPlayerLocation(player: P): L { throw IllegalArgumentException() } /** * Converts the given [location] to a [Position]. */ override fun <L> toPosition(location: L): Position { throw IllegalArgumentException() } /** * Converts the given [position] to a Location.. */ override fun <L> toLocation(position: Position): L { throw IllegalArgumentException() } /** * Gets the looking direction of the player. */ override fun <P> getDirectionVector(player: P): Position { throw IllegalArgumentException() } /** * Gets the item in the player hand. */ override fun <P, I> getPlayerItemInHand(player: P, offhand: Boolean): I? { throw IllegalArgumentException() } /** * Sets the item in the player hand. */ override fun <P, I> setPlayerItemInHand(player: P, itemStack: I, offhand: Boolean) { throw IllegalArgumentException() } /** * Gets if the given player has got the given permission. */ override fun <P> hasPermission(player: P, permission: Permission): Boolean { throw IllegalArgumentException() } /** * Gets the player uuid. */ override fun <P> getPlayerUUID(player: P): String { return (player as Player).uniqueId.toString() } /** * Sends a message to the [sender]. */ override fun <S> sendMessage(sender: S, message: String) { throw IllegalArgumentException() } /** * Executes a server command. */ override fun executeServerCommand(message: String) { throw IllegalArgumentException() } /** * Executes a player command. */ override fun <P> executePlayerCommand(player: P, message: String) { throw IllegalArgumentException() } /** * Gets if the player is currently online. */ override fun <P> isPlayerOnline(player: P): Boolean { TODO("Not yet implemented") } /** * Gets if the player with the given uuid is currently online. */ override fun isPlayerUUIDOnline(uuid: String): Boolean { TODO("Not yet implemented") } } class MockedConcurrencyService : ConcurrencyService { /** * Runs the given [function] synchronised with the given [delayTicks] and [repeatingTicks]. */ override fun runTaskSync(delayTicks: Long, repeatingTicks: Long, function: () -> Unit) { function.invoke() } /** * Runs the given [function] asynchronous with the given [delayTicks] and [repeatingTicks]. */ override fun runTaskAsync(delayTicks: Long, repeatingTicks: Long, function: () -> Unit) { function.invoke() } } class MockedEventService : EventService { /** * Calls a framework event and returns if it was cancelled. */ override fun callEvent(event: Any): Boolean { return false } } }
apache-2.0
d1a18fec533a92be658e3e0154f2555e
38.483871
130
0.643382
4.626627
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/paypal/PaypalAuthInterceptor.kt
1
1704
package com.baulsupp.okurl.services.paypal import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.queryMapValue import com.baulsupp.okurl.secrets.Secrets import okhttp3.OkHttpClient import okhttp3.Response /** * https://developer.paypal.com/docs/authentication */ open class PaypalAuthInterceptor : Oauth2AuthInterceptor() { override val serviceDefinition: Oauth2ServiceDefinition get() = Oauth2ServiceDefinition( host(), "Paypal API", shortName(), "https://developer.paypal.com/docs/api/", "https://developer.paypal.com/developer/applications/" ) open fun shortName() = "paypal" override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials = ValidatedCredentials( client.queryMapValue<String>( "https://api.paypal.com/v1/oauth2/token/userinfo?schema=openid", TokenValue(credentials), "name" ) ) override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { val clientId = Secrets.prompt("Paypal Client Id", "paypal.clientId", "", false) val clientSecret = Secrets.prompt("Paypal Client Secret", "paypal.clientSecret", "", true) return PaypalAuthFlow.login(client, host(), clientId, clientSecret) } open fun host() = "api.paypal.com" }
apache-2.0
adf101c5b6e3cca21c5129e8a232c8bd
32.411765
94
0.752934
4.403101
false
false
false
false
mrebollob/LoteriadeNavidad
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/settings/manageticket/ui/ManageTicketsScreen.kt
1
7083
package com.mrebollob.loteria.android.presentation.settings.manageticket.ui import android.content.res.Configuration import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Divider import androidx.compose.material.ScaffoldState import androidx.compose.material.SnackbarResult import androidx.compose.material.Surface import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.mrebollob.loteria.android.R import com.mrebollob.loteria.android.presentation.home.ui.HomeEmptyView import com.mrebollob.loteria.android.presentation.platform.extension.supportWideScreen import com.mrebollob.loteria.android.presentation.platform.ui.components.LotterySnackbarHost import com.mrebollob.loteria.android.presentation.platform.ui.layout.BaseScaffold import com.mrebollob.loteria.android.presentation.platform.ui.layout.LoadingContent import com.mrebollob.loteria.android.presentation.platform.ui.theme.Grey2 import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme import com.mrebollob.loteria.android.presentation.settings.manageticket.ManageTicketsUiState import com.mrebollob.loteria.android.presentation.settings.manageticket.ManageTicketsViewModel import com.mrebollob.loteria.domain.entity.Ticket @Composable fun ManageTicketsScreen( manageTicketsViewModel: ManageTicketsViewModel, onCreateTicketClick: (() -> Unit), navController: NavController ) { val uiState by manageTicketsViewModel.uiState.collectAsState() ManageTicketsScreen( uiState = uiState, onDeleteTicketClick = { manageTicketsViewModel.onDeleteTicketClick(it) }, onBackClick = { navController.popBackStack() }, onRefreshData = { manageTicketsViewModel.refreshData() }, onCreateTicketClick = onCreateTicketClick, onErrorDismiss = { manageTicketsViewModel.errorShown(it) }, ) } @Composable fun ManageTicketsScreen( modifier: Modifier = Modifier, scaffoldState: ScaffoldState = rememberScaffoldState(), uiState: ManageTicketsUiState, onDeleteTicketClick: ((Ticket) -> Unit), onBackClick: (() -> Unit), onRefreshData: () -> Unit, onCreateTicketClick: (() -> Unit), onErrorDismiss: (Long) -> Unit, ) { Surface( modifier = Modifier.supportWideScreen(), ) { BaseScaffold( modifier = modifier, scaffoldState = scaffoldState, snackbarHost = { LotterySnackbarHost(hostState = it) }, toolbarText = stringResource(id = R.string.manage_tickets_screen_title), onBackClick = onBackClick, content = { LoadingContent( empty = uiState.tickets.isEmpty(), emptyContent = { HomeEmptyView( modifier = Modifier .padding(16.dp) .fillMaxSize(), onCreateTicketClick = onCreateTicketClick ) }, loading = uiState.isLoading, onRefresh = onRefreshData, content = { LazyColumn( modifier = Modifier .fillMaxSize() .padding(4.dp) ) { item { Divider(color = Grey2) } uiState.tickets.forEach { ticket -> item { ManageTicketItemView( modifier = Modifier.padding( start = 24.dp, end = 24.dp ), title = ticket.name, subTitle = stringResource( id = R.string.lottery_ticket_number_format, ticket.number ) + " - " + stringResource( id = R.string.lottery_stats_money_format, ticket.bet ), onClick = { onDeleteTicketClick(ticket) } ) Divider(color = Grey2) } } item { Spacer(modifier = Modifier.height(24.dp)) } } } ) } ) if (uiState.errorMessages.isNotEmpty()) { val errorMessage = remember(uiState) { uiState.errorMessages[0] } val errorMessageText: String = stringResource(errorMessage.messageId) val retryMessageText = stringResource(id = R.string.retry) val onRefreshDataState by rememberUpdatedState(onRefreshData) val onErrorDismissState by rememberUpdatedState(onErrorDismiss) LaunchedEffect(errorMessageText, retryMessageText, scaffoldState) { val snackbarResult = scaffoldState.snackbarHostState.showSnackbar( message = errorMessageText, actionLabel = retryMessageText ) if (snackbarResult == SnackbarResult.ActionPerformed) { onRefreshDataState() } onErrorDismissState(errorMessage.id) } } } } @Preview("Manage tickets screen") @Preview("Manage tickets screen (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun PreviewManageTicketsScreen() { val uiState = ManageTicketsUiState( tickets = emptyList(), isLoading = false, errorMessages = emptyList(), ) LotteryTheme { ManageTicketsScreen( uiState = uiState, onDeleteTicketClick = {}, onBackClick = {}, onRefreshData = {}, onCreateTicketClick = {}, onErrorDismiss = {}, ) } }
apache-2.0
3d4daeebae4b0372b5c61541f120d7a3
39.942197
94
0.576309
5.767915
false
false
false
false
Kotlin/dokka
plugins/javadoc/src/test/kotlin/org/jetbrains/dokka/javadoc/search/JavadocIndexSearchTest.kt
1
2604
package org.jetbrains.dokka.javadoc.search import org.jetbrains.dokka.javadoc.AbstractJavadocTemplateMapTest import org.junit.jupiter.api.Test import utils.TestOutputWriterPlugin import org.junit.jupiter.api.Assertions.* internal class JavadocIndexSearchTest : AbstractJavadocTemplateMapTest() { @Test fun `javadoc index search tag`(){ val writerPlugin = TestOutputWriterPlugin() dualTestTemplateMapInline( java = """ /src/ClassA.java package package0; /** * Documentation for ClassA * Defines the implementation of the system Java compiler and its command line equivalent, {@index javac}, as well as javah. */ public class ClassA { } """, pluginsOverride = listOf(writerPlugin) ) { val contents = writerPlugin.writer.contents val expectedSearchTagJson = """var tagSearchIndex = [{"p":"package0","c":"ClassA","l":"javac","url":"package0/ClassA.html#javac"}]""" assertEquals(expectedSearchTagJson, contents["tag-search-index.js"]) } } @Test fun `javadoc type with member search`(){ val writerPlugin = TestOutputWriterPlugin() dualTestTemplateMapInline( java = """ /src/ClassA.java package package0; public class ClassA { public String propertyOfClassA = "Sample"; public void sampleFunction(){ } } """, pluginsOverride = listOf(writerPlugin) ) { val contents = writerPlugin.writer.contents val expectedPackageJson = """var packageSearchIndex = [{"l":"package0","url":"package0/package-summary.html"}, {"l":"All packages","url":"index.html"}]""" val expectedClassesJson = """var typeSearchIndex = [{"p":"package0","l":"ClassA","url":"package0/ClassA.html"}, {"l":"All classes","url":"allclasses.html"}]""" val expectedMembersJson = """var memberSearchIndex = [{"p":"package0","c":"ClassA","l":"sampleFunction()","url":"package0/ClassA.html#sampleFunction()"}, {"p":"package0","c":"ClassA","l":"propertyOfClassA","url":"package0/ClassA.html#propertyOfClassA"}]""" assertEquals(expectedPackageJson, contents["package-search-index.js"]) assertEquals(expectedClassesJson, contents["type-search-index.js"]) assertEquals(expectedMembersJson, contents["member-search-index.js"]) } } }
apache-2.0
8c5eb1b10c1cb1d6b94f301a52747150
43.152542
268
0.600998
4.822222
false
true
false
false
y2k/RssReader
app/src/main/kotlin/y2k/rssreader/components/RssComponent.kt
1
1415
package y2k.rssreader.components import android.content.Context import android.text.Html import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ListView import android.widget.TextView import y2k.rssreader.Provider.getRssItems import y2k.rssreader.toLiveCycleObservable /** * Created by y2k on 17/08/16. */ @Suppress("DEPRECATION") class RssComponent(context: Context, attrs: AttributeSet?) : ListView(context, attrs) { init { getRssItems() .toLiveCycleObservable(context) .subscribe { items -> adapter = object : BaseAdapter() { override fun getView(index: Int, view: View?, p2: ViewGroup?): View { val v = view ?: View.inflate(context, android.R.layout.simple_list_item_2, null) val s = items[index] (v.findViewById(android.R.id.text1) as TextView).text = s.title (v.findViewById(android.R.id.text2) as TextView).text = Html.fromHtml(s.description) return v } override fun getItemId(index: Int): Long = index.toLong() override fun getCount(): Int = items.size override fun getItem(index: Int): Any = TODO() } } } }
mit
2ddbee48a46f361b914d0adf2a9090a9
34.4
108
0.601413
4.380805
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/facebook/FbItem.kt
1
4027
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.facebook import androidx.annotation.StringRes import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import com.mikepenz.iconics.typeface.library.materialdesigniconic.MaterialDesignIconic import com.pitchedapps.frost.R import com.pitchedapps.frost.fragments.BaseFragment import com.pitchedapps.frost.fragments.WebFragment import com.pitchedapps.frost.utils.EnumBundle import com.pitchedapps.frost.utils.EnumBundleCompanion import com.pitchedapps.frost.utils.EnumCompanion enum class FbItem( @StringRes val titleId: Int, val icon: IIcon, relativeUrl: String, val fragmentCreator: () -> BaseFragment = ::WebFragment, prefix: String = FB_URL_BASE ) : EnumBundle<FbItem> { ACTIVITY_LOG(R.string.activity_log, GoogleMaterial.Icon.gmd_list, "me/allactivity"), BIRTHDAYS(R.string.birthdays, GoogleMaterial.Icon.gmd_cake, "events/birthdays"), CHAT(R.string.chat, GoogleMaterial.Icon.gmd_chat, "buddylist"), EVENTS(R.string.events, GoogleMaterial.Icon.gmd_event_note, "events/upcoming"), FEED(R.string.feed, CommunityMaterial.Icon3.cmd_newspaper, ""), FEED_MOST_RECENT(R.string.most_recent, GoogleMaterial.Icon.gmd_history, "home.php?sk=h_chr"), FEED_TOP_STORIES(R.string.top_stories, GoogleMaterial.Icon.gmd_star, "home.php?sk=h_nor"), FRIENDS(R.string.friends, GoogleMaterial.Icon.gmd_person_add, "friends/center/requests"), GROUPS(R.string.groups, GoogleMaterial.Icon.gmd_group, "groups"), MARKETPLACE(R.string.marketplace, GoogleMaterial.Icon.gmd_store, "marketplace"), MENU(R.string.menu, GoogleMaterial.Icon.gmd_menu, "bookmarks"), MESSAGES(R.string.messages, MaterialDesignIconic.Icon.gmi_comments, "messages"), MESSENGER( R.string.messenger, CommunityMaterial.Icon2.cmd_facebook_messenger, "", prefix = HTTPS_MESSENGER_COM ), NOTES(R.string.notes, CommunityMaterial.Icon3.cmd_note, "notes"), NOTIFICATIONS(R.string.notifications, MaterialDesignIconic.Icon.gmi_globe, "notifications"), ON_THIS_DAY(R.string.on_this_day, GoogleMaterial.Icon.gmd_today, "onthisday"), PAGES(R.string.pages, GoogleMaterial.Icon.gmd_flag, "pages"), PHOTOS(R.string.photos, GoogleMaterial.Icon.gmd_photo, "me/photos"), PROFILE(R.string.profile, CommunityMaterial.Icon.cmd_account, "me"), SAVED(R.string.saved, GoogleMaterial.Icon.gmd_bookmark, "saved"), /** Note that this url only works if a query (?q=) is provided */ _SEARCH(R.string.kau_search, GoogleMaterial.Icon.gmd_search, "search/top"), /** Non mbasic search cannot be parsed. */ _SEARCH_PARSE( R.string.kau_search, GoogleMaterial.Icon.gmd_search, "search/top", prefix = FB_URL_MBASIC_BASE ), SETTINGS(R.string.settings, GoogleMaterial.Icon.gmd_settings, "settings"), ; val url = "$prefix$relativeUrl" val isFeed: Boolean get() = when (this) { FEED, FEED_MOST_RECENT, FEED_TOP_STORIES -> true else -> false } override val bundleContract: EnumBundleCompanion<FbItem> get() = Companion companion object : EnumCompanion<FbItem>("frost_arg_fb_item", values()) } fun defaultTabs(): List<FbItem> = listOf(FbItem.FEED, FbItem.MESSAGES, FbItem.NOTIFICATIONS, FbItem.MENU)
gpl-3.0
044a5971d0622fbbbf2a1443ea1c6af1
41.389474
95
0.748448
3.650952
false
false
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/PinTab.kt
1
3448
package com.simplemobiletools.commons.views import android.content.Context import android.graphics.PorterDuff import android.util.AttributeSet import android.widget.RelativeLayout import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.baseConfig import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.commons.extensions.updateTextColors import com.simplemobiletools.commons.helpers.PROTECTION_PIN import com.simplemobiletools.commons.interfaces.HashListener import com.simplemobiletools.commons.interfaces.SecurityTab import kotlinx.android.synthetic.main.tab_pin.view.* import java.math.BigInteger import java.security.MessageDigest import java.util.* class PinTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab { private var hash = "" private var requiredHash = "" private var pin = "" lateinit var hashListener: HashListener override fun onFinishInflate() { super.onFinishInflate() context.updateTextColors(pin_lock_holder) pin_0.setOnClickListener { addNumber("0") } pin_1.setOnClickListener { addNumber("1") } pin_2.setOnClickListener { addNumber("2") } pin_3.setOnClickListener { addNumber("3") } pin_4.setOnClickListener { addNumber("4") } pin_5.setOnClickListener { addNumber("5") } pin_6.setOnClickListener { addNumber("6") } pin_7.setOnClickListener { addNumber("7") } pin_8.setOnClickListener { addNumber("8") } pin_9.setOnClickListener { addNumber("9") } pin_c.setOnClickListener { clear() } pin_ok.setOnClickListener { confirmPIN() } pin_ok.setColorFilter(context.baseConfig.textColor, PorterDuff.Mode.SRC_IN) } override fun initTab(requiredHash: String, listener: HashListener) { this.requiredHash = requiredHash hash = requiredHash hashListener = listener } private fun addNumber(number: String) { if (pin.length < 10) { pin += number updatePinCode() } } private fun clear() { if (pin.isNotEmpty()) { pin = pin.substring(0, pin.length - 1) updatePinCode() } } private fun confirmPIN() { val newHash = getHashedPin() if (pin.isEmpty()) { context.toast(R.string.please_enter_pin) } else if (hash.isEmpty()) { hash = newHash resetPin() pin_lock_title.setText(R.string.repeat_pin) } else if (hash == newHash) { hashListener.receivedHash(hash, PROTECTION_PIN) } else { resetPin() context.toast(R.string.wrong_pin) if (requiredHash.isEmpty()) { hash = "" pin_lock_title.setText(R.string.enter_pin) } } } private fun resetPin() { pin = "" pin_lock_current_pin.text = "" } private fun updatePinCode() { pin_lock_current_pin.text = "*".repeat(pin.length) } private fun getHashedPin(): String { val messageDigest = MessageDigest.getInstance("SHA-1") messageDigest.update(pin.toByteArray(charset("UTF-8"))) val digest = messageDigest.digest() val bigInteger = BigInteger(1, digest) return String.format(Locale.getDefault(), "%0${digest.size * 2}x", bigInteger).toLowerCase() } }
apache-2.0
b397da19b6c59e43d2316f715bada638
33.48
100
0.646172
4.288557
false
false
false
false
swishy/Mitsumame
services/src/main/kotlin/com/st8vrt/mitsumame/mitsumame.kt
1
2960
package com.st8vrt.mitsumame import com.st8vrt.mitsumame.authentication.MitsumameAuthentication import com.st8vrt.mitsumame.configuration.mitsumameConfiguration import com.st8vrt.mitsumame.library.utilities.RootDocument import com.st8vrt.mitsumame.storage.interfaces.DeviceStorageProvider import com.st8vrt.mitsumame.storage.interfaces.SessionStorageProvider import com.st8vrt.mitsumame.storage.interfaces.UserStorageProvider import com.st8vrt.mitsumame.storage.providers.InMemoryStorageProvider import com.st8vrt.mitsumame.storage.types.User import com.st8vrt.mitsumame.webservices.core.onetimeLoginTokenHandler import com.st8vrt.mitsumame.webservices.core.rootDocumentHandler import com.st8vrt.mitsumame.webservices.core.sessionCreationHandler import com.st8vrt.mitsumame.webservices.core.sessionSetupHandler import org.slf4j.LoggerFactory import org.wasabi.app.AppServer import org.wasabi.interceptors.useAuthentication import uy.kohesive.injekt.InjektMain import uy.kohesive.injekt.api.InjektRegistrar import uy.kohesive.injekt.api.addSingleton import java.net.URI /** * Created by swishy on 10/1/13. */ val rootDocument = RootDocument() public class Startup { public fun addRootDocumentEntries() { rootDocument.addRootDocumentUri("TestEndpointUri", URI("http://localhost/testendpoint")) } } public class Test { var something = "TestValue" var somethingElse = "AnotherValue" } public open class MitsumameServer() : AppServer() { companion object : InjektMain() { override fun InjektRegistrar.registerInjectables() { addSingleton<SessionStorageProvider>(InMemoryStorageProvider()) addSingleton<DeviceStorageProvider>(InMemoryStorageProvider()) addSingleton<UserStorageProvider>(InMemoryStorageProvider()) } } private var log = LoggerFactory.getLogger(MitsumameServer::class.java); init { // Generate Mitsumame RootDocument var startup = Startup() startup.addRootDocumentEntries() // TODO remove initial setup crud implemented during development for testing var user = User("admin", "password") mitsumameConfiguration.userStorageProvider.storeUser(user) log!!.info("Admin Created: ${user}") // TODO investigate websockets for login negotiation // this.channel("/session", core.sessionChannelHandler) this.post("/session", sessionCreationHandler) this.get("/session/:id", sessionSetupHandler) // Assign Core Routes this.get("/mitsumame", rootDocumentHandler) this.post("/onetimetoken", onetimeLoginTokenHandler) this.get("/testendpoint", { var testObject = com.st8vrt.mitsumame.Test() log!!.info("Test Object Created: ${testObject}") response.send(testObject) }) // Setup Mitsumame Authentication and Crypto this.useAuthentication(MitsumameAuthentication()) } }
apache-2.0
c27cffc43964e9df8481b107fa522269
33.823529
96
0.745608
4.240688
false
true
false
false
pacien/tincapp
app/src/main/java/org/pacien/tincapp/activities/start/NetworkListFragment.kt
1
3158
/* * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon * Copyright (C) 2017-2020 Pacien TRAN-GIRARD * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.pacien.tincapp.activities.start import androidx.lifecycle.Observer import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.TextView import kotlinx.android.synthetic.main.start_network_list.* import org.pacien.tincapp.R import org.pacien.tincapp.activities.BaseFragment import org.pacien.tincapp.context.AppPaths import org.pacien.tincapp.extensions.hideBottomSeparator import org.pacien.tincapp.extensions.setElements /** * @author pacien */ class NetworkListFragment : BaseFragment() { private val networkListViewModel by lazy { NetworkListViewModel() } private val networkListAdapter by lazy { ArrayAdapter<String>(requireContext(), R.layout.start_network_list_item) } var connectToNetworkAction = { _: String -> Unit } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) networkListViewModel.networkList.observe(this, Observer { updateNetworkList(it.orEmpty()) }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.start_network_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val listHeaderView = layoutInflater.inflate(R.layout.start_network_list_header, start_network_list, false) start_network_list.addHeaderView(listHeaderView, null, false) start_network_list.hideBottomSeparator() start_network_list.emptyView = start_network_list_placeholder start_network_list.onItemClickListener = AdapterView.OnItemClickListener(this::onItemClick) start_network_list.adapter = networkListAdapter } @Suppress("UNUSED_PARAMETER") private fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) = when (view) { is TextView -> connectToNetworkAction(view.text.toString()) else -> Unit } private fun updateNetworkList(networks: List<String>) { networkListAdapter.setElements(networks) if (networks.isEmpty()) updatePlaceholder() } private fun updatePlaceholder() { start_network_list_placeholder.post { start_network_list_placeholder_text?.text = getString(R.string.start_network_list_empty_none_found) } } }
gpl-3.0
9b04a8c40fba7514e6cbddf230fa23c3
39.487179
117
0.768208
4.250336
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/test/kotlin/glimpse/models/MeshSpec.kt
1
7053
package glimpse.models import glimpse.Point import glimpse.TextureCoordinates import glimpse.Vector import glimpse.buffers.toList import glimpse.test.GlimpseSpec class MeshSpec : GlimpseSpec() { companion object { val positions = listOf( Point(1f, 2f, 3f), Point(4f, 5f, 6f), Point(7f, 8f, 9f), Point(11f, 12f, 13f), Point(14f, 15f, 16f), Point(17f, 18f, 19f), Point(21f, 22f, 23f), Point(24f, 25f, 26f), Point(27f, 28f, 29f)) val textureCoordinates = listOf( TextureCoordinates(1f, 2f), TextureCoordinates(3f, 4f), TextureCoordinates(5f, 6f), TextureCoordinates(11f, 12f), TextureCoordinates(13f, 14f), TextureCoordinates(15f, 16f), TextureCoordinates(21f, 22f), TextureCoordinates(23f, 24f), TextureCoordinates(25f, 26f)) val normals = listOf( Vector(1f, 2f, 3f), Vector(4f, 5f, 6f), Vector(7f, 8f, 9f), Vector(11f, 12f, 13f), Vector(14f, 15f, 16f), Vector(17f, 18f, 19f), Vector(21f, 22f, 23f), Vector(24f, 25f, 26f), Vector(27f, 28f, 29f)) } init { "Initializing a mesh with a list of positions of a wrong size" should { "cause an exception" { shouldThrow<IllegalArgumentException> { val positions = listOf(Point(1f, 2f, 3f), Point(4f, 5f, 6f)) val textureCoordinates = listOf(TextureCoordinates(1f, 2f), TextureCoordinates(3f, 4f)) val normals = listOf(Vector(1f, 2f, 3f), Vector(4f, 5f, 6f)) Mesh(positions, textureCoordinates, normals) } } } "Initializing a mesh with a list of texture coordinates of a wrong size" should { "cause an exception" { shouldThrow<IllegalArgumentException> { val textureCoordinates = listOf(TextureCoordinates(1f, 2f), TextureCoordinates(3f, 4f), TextureCoordinates(5f, 6f)) Mesh(positions, textureCoordinates, normals) } } } "Initializing a mesh with a list of normals of a wrong size" should { "cause an exception" { shouldThrow<IllegalArgumentException> { val normals = listOf(Vector(1f, 2f, 3f), Vector(4f, 5f, 6f), Vector(7f, 8f, 9f)) Mesh(positions, textureCoordinates, normals) } } } "Vertices of a mesh" should { "should have a correct size" { Mesh(positions, textureCoordinates, normals).vertices should haveSize(9) } "should have a correct values" { Mesh(positions, textureCoordinates, normals).vertices shouldBe listOf( Vertex(Point(1f, 2f, 3f), TextureCoordinates(1f, 2f), Vector(1f, 2f, 3f)), Vertex(Point(4f, 5f, 6f), TextureCoordinates(3f, 4f), Vector(4f, 5f, 6f)), Vertex(Point(7f, 8f, 9f), TextureCoordinates(5f, 6f), Vector(7f, 8f, 9f)), Vertex(Point(11f, 12f, 13f), TextureCoordinates(11f, 12f), Vector(11f, 12f, 13f)), Vertex(Point(14f, 15f, 16f), TextureCoordinates(13f, 14f), Vector(14f, 15f, 16f)), Vertex(Point(17f, 18f, 19f), TextureCoordinates(15f, 16f), Vector(17f, 18f, 19f)), Vertex(Point(21f, 22f, 23f), TextureCoordinates(21f, 22f), Vector(21f, 22f, 23f)), Vertex(Point(24f, 25f, 26f), TextureCoordinates(23f, 24f), Vector(24f, 25f, 26f)), Vertex(Point(27f, 28f, 29f), TextureCoordinates(25f, 26f), Vector(27f, 28f, 29f))) } } "Faces of a mesh" should { "should have a correct size" { Mesh(positions, textureCoordinates, normals).faces should haveSize(3) } "should have a correct values" { Mesh(positions, textureCoordinates, normals).faces shouldBe listOf( Face( Vertex(Point(1f, 2f, 3f), TextureCoordinates(1f, 2f), Vector(1f, 2f, 3f)), Vertex(Point(4f, 5f, 6f), TextureCoordinates(3f, 4f), Vector(4f, 5f, 6f)), Vertex(Point(7f, 8f, 9f), TextureCoordinates(5f, 6f), Vector(7f, 8f, 9f))), Face( Vertex(Point(11f, 12f, 13f), TextureCoordinates(11f, 12f), Vector(11f, 12f, 13f)), Vertex(Point(14f, 15f, 16f), TextureCoordinates(13f, 14f), Vector(14f, 15f, 16f)), Vertex(Point(17f, 18f, 19f), TextureCoordinates(15f, 16f), Vector(17f, 18f, 19f))), Face( Vertex(Point(21f, 22f, 23f), TextureCoordinates(21f, 22f), Vector(21f, 22f, 23f)), Vertex(Point(24f, 25f, 26f), TextureCoordinates(23f, 24f), Vector(24f, 25f, 26f)), Vertex(Point(27f, 28f, 29f), TextureCoordinates(25f, 26f), Vector(27f, 28f, 29f)))) } } "Positions buffer" should { "be a direct buffer" { Mesh(positions, textureCoordinates, normals).positionsBuffer.isDirect shouldBe true } "have correct size" { Mesh(positions, textureCoordinates, normals).positionsBuffer.capacity() shouldBe 27 } "contain correct values" { Mesh(positions, textureCoordinates, normals).positionsBuffer.toList() shouldBe listOf( 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 11f, 12f, 13f, 14f, 15f, 16f, 17f, 18f, 19f, 21f, 22f, 23f, 24f, 25f, 26f, 27f, 28f, 29f) } } "Augmented positions buffer" should { "be a direct buffer" { Mesh(positions, textureCoordinates, normals).augmentedPositionsBuffer.isDirect shouldBe true } "have correct size" { Mesh(positions, textureCoordinates, normals).augmentedPositionsBuffer.capacity() shouldBe 36 } "contain correct values" { Mesh(positions, textureCoordinates, normals).augmentedPositionsBuffer.toList() shouldBe listOf( 1f, 2f, 3f, 1f, 4f, 5f, 6f, 1f, 7f, 8f, 9f, 1f, 11f, 12f, 13f, 1f, 14f, 15f, 16f, 1f, 17f, 18f, 19f, 1f, 21f, 22f, 23f, 1f, 24f, 25f, 26f, 1f, 27f, 28f, 29f, 1f) } } "Texture coordinates buffer" should { "be a direct buffer" { Mesh(positions, textureCoordinates, normals).textureCoordinatesBuffer.isDirect shouldBe true } "have correct size" { Mesh(positions, textureCoordinates, normals).textureCoordinatesBuffer.capacity() shouldBe 18 } "contain correct values" { Mesh(positions, textureCoordinates, normals).textureCoordinatesBuffer.toList() shouldBe listOf( 1f, 2f, 3f, 4f, 5f, 6f, 11f, 12f, 13f, 14f, 15f, 16f, 21f, 22f, 23f, 24f, 25f, 26f) } } "Normals buffer" should { "be a direct buffer" { Mesh(positions, textureCoordinates, normals).normalsBuffer.isDirect shouldBe true } "have correct size" { Mesh(positions, textureCoordinates, normals).normalsBuffer.capacity() shouldBe 27 } "contain correct values" { Mesh(positions, textureCoordinates, normals).normalsBuffer.toList() shouldBe listOf( 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 11f, 12f, 13f, 14f, 15f, 16f, 17f, 18f, 19f, 21f, 22f, 23f, 24f, 25f, 26f, 27f, 28f, 29f) } } "Augmented normals buffer" should { "be a direct buffer" { Mesh(positions, textureCoordinates, normals).augmentedNormalsBuffer.isDirect shouldBe true } "have correct size" { Mesh(positions, textureCoordinates, normals).augmentedNormalsBuffer.capacity() shouldBe 36 } "contain correct values" { Mesh(positions, textureCoordinates, normals).augmentedNormalsBuffer.toList() shouldBe listOf( 1f, 2f, 3f, 1f, 4f, 5f, 6f, 1f, 7f, 8f, 9f, 1f, 11f, 12f, 13f, 1f, 14f, 15f, 16f, 1f, 17f, 18f, 19f, 1f, 21f, 22f, 23f, 1f, 24f, 25f, 26f, 1f, 27f, 28f, 29f, 1f) } } } }
apache-2.0
db8deab3b76f284b8ea2b1e5a0aa4da0
40.005814
120
0.670778
2.870574
false
false
false
false
kwiecienm/scraps
src/main/kotlin/com/marekkwiecien/scraps/App.kt
1
3866
package com.marekkwiecien.scraps import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import freemarker.cache.ClassTemplateLoader import io.ktor.application.Application import io.ktor.application.call import io.ktor.application.install import io.ktor.auth.* import io.ktor.content.resources import io.ktor.content.static import io.ktor.features.CallLogging import io.ktor.features.Compression import io.ktor.features.ContentNegotiation import io.ktor.features.DefaultHeaders import io.ktor.freemarker.FreeMarker import io.ktor.freemarker.respondTemplate import io.ktor.jackson.jackson import io.ktor.request.receive import io.ktor.response.respond import io.ktor.routing.* val service = ScrapsService() fun Application.main() { install(DefaultHeaders) install(Compression) install(CallLogging) install(ContentNegotiation) { jackson { configure(SerializationFeature.INDENT_OUTPUT, true) registerModule(JavaTimeModule()) } } install(FreeMarker) { templateLoader = ClassTemplateLoader(Application::class.java.classLoader, "templates") } install(Authentication) { basic { realm = "ktor" validate { credentials -> if (credentials.password == "test1234") { UserIdPrincipal(credentials.name) } else { null } } } } routing { get("/context") { call.respond(service.findAllContexts()) call.authentication.principal } post("/context") { val context = call.receive<Context>() if (context.id == 0L) { val newContext = service.createNewContext(context.name) call.respond(newContext) } else { val updatedContext = service.saveContext(context) call.respond(updatedContext) } } put("/context") { val context = call.receive<Context>() if (context.id == 0L) { val newContext = service.createNewContext(context.name) call.respond(newContext) } else { val updatedContext = service.saveContext(context) call.respond(updatedContext) } } delete("/context/{contextId}") { val contextId = call.parameters["contextId"]!!.toLong() val context = service.findContext(contextId) service.deleteContext(context!!) call.respond(service.findAllContexts()) } get("/context/{contextId}/scrap") { call.respond(service.findScrapsForContext(call.parameters["contextId"]!!.toLong())) } post("/context/{contextId}/scrap") { val scrap = call.receive<Scrap>() val updatedScrap = service.saveScrap(scrap) call.respond(updatedScrap) } put("/context/{contextId}/scrap") { val scrap = call.receive<Scrap>() val updatedScrap = service.saveScrap(scrap) call.respond(updatedScrap) } delete("/context/{contextId}/scrap/{scrapId}") { val scrapId = call.parameters["scrapId"]!!.toLong() val scrap = service.findScrap(scrapId) service.deleteScrap(scrap!!) call.respond(service.findScrapsForContext(call.parameters["contextId"]!!.toLong())) } authenticate { get("/") { val ctx = Context(1L, "test") call.respondTemplate("index.ftl", mapOf("context" to ctx), "e") } } static("static") { resources("css") resources("js") resources("img") } } }
apache-2.0
5f566df9dff7929db9a14fa5c388c21a
33.526786
95
0.592861
4.613365
false
false
false
false
gmillz/SlimFileManager
manager/src/main/java/com/slim/slimfilemanager/utils/ArchiveUtils.kt
1
11600
package com.slim.slimfilemanager.utils import android.content.Context import com.slim.slimfilemanager.utils.file.BaseFile import org.apache.commons.compress.archivers.ArchiveException import org.apache.commons.compress.archivers.ArchiveOutputStream import org.apache.commons.compress.archivers.ArchiveStreamFactory import org.apache.commons.compress.archivers.tar.TarArchiveEntry import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream import org.apache.commons.compress.utils.IOUtils import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.ArrayList import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream object ArchiveUtils { private val BUFFER = 4096 fun extractZipFiles(zipFile: String, location: String): String? { var location = location val data = ByteArray(BUFFER) val zipstream: ZipInputStream if (!location.endsWith(File.separator)) { location += File.separator } location += FileUtil.removeExtension(File(zipFile).name) + File.separator if (!File(location).mkdirs()) return null try { zipstream = ZipInputStream(FileInputStream(zipFile)) var entry: ZipEntry = zipstream.nextEntry while (entry != null) { var buildDir = location val dirs = entry.name.split("/".toRegex()).dropLastWhile({ it.isEmpty() }) .toTypedArray() if (dirs.size > 0) { for (i in 0 until dirs.size - 1) { buildDir += dirs[i] + "/" if (!File(buildDir).mkdirs()) return null } } var read: Int = zipstream.read(data, 0, BUFFER) val out = FileOutputStream( location + entry.name) while (read != -1) { out.write(data, 0, read) read = zipstream.read(data, 0, BUFFER) } zipstream.closeEntry() out.close() entry = zipstream.nextEntry } } catch (e: IOException) { e.printStackTrace() } return location } fun createZipFile(zip: String, files: ArrayList<BaseFile>): String { var zip = zip if (!zip.startsWith(File.separator)) { zip = BackgroundUtils.ARCHIVE_LOCATION + File.separator + zip } if (!zip.endsWith("zip")) { zip += ".zip" } val outFile = File(zip) try { val dest = FileOutputStream(outFile) val out = ZipOutputStream(BufferedOutputStream( dest)) for (bf in files) { bf.getFile { file -> try { if (file.isDirectory) { zipFolder(out, file, file.parent.length) } else { zipFile(out, file) } } catch (e: IOException) { e.printStackTrace() } } } out.close() } catch (e: Exception) { e.printStackTrace() } return BackgroundUtils.ARCHIVE_LOCATION } @Throws(IOException::class) private fun zipFolder(out: ZipOutputStream, folder: File, basePathLength: Int) { val fileList = folder.listFiles() for (file in fileList) { if (file.isDirectory) { zipFolder(out, file, basePathLength) } else { val origin: BufferedInputStream val data = ByteArray(BUFFER) val unmodifiedFilePath = file.path val relativePath = unmodifiedFilePath .substring(basePathLength) val fi = FileInputStream(unmodifiedFilePath) origin = BufferedInputStream(fi, BUFFER) val entry = ZipEntry(relativePath) out.putNextEntry(entry) var count: Int = origin.read(data, 0, BUFFER) while (count != -1) { out.write(data, 0, count) count = origin.read(data, 0, BUFFER) } origin.close() } } } @Throws(IOException::class) private fun zipFile(out: ZipOutputStream, file: File) { val origin: BufferedInputStream val data = ByteArray(BUFFER) val str = file.path val fi = FileInputStream(str) origin = BufferedInputStream(fi, BUFFER) val entry = ZipEntry(str.substring(str.lastIndexOf("/") + 1)) out.putNextEntry(entry) var count: Int = origin.read(data, 0, BUFFER) while (count != -1) { out.write(data, 0, count) count = origin.read(data, 0, BUFFER) } origin.close() } fun unTar(context: Context, input: String, output: String): String? { var output = output var inputFile = File(input) var deleteAfter = false if (FileUtil.getExtension(inputFile.name) == "gz") { inputFile = File(unGzip(input, BackgroundUtils.EXTRACTED_LOCATION)) deleteAfter = true } if (!output.endsWith(File.separator)) { output += File.separator } output += FileUtil.removeExtension(inputFile.name) var outputDir = File(output) if (outputDir.exists()) { for (i in 1 until Integer.MAX_VALUE) { val test = File(outputDir.toString() + "-" + i) if (test.exists()) continue outputDir = test break } } if (!outputDir.mkdirs()) return null try { val `is` = FileInputStream(inputFile) val tis = ArchiveStreamFactory().createArchiveInputStream("tar", `is`) as TarArchiveInputStream var entry: TarArchiveEntry = tis.nextTarEntry while (entry != null) { val outputFile = File(outputDir, entry.name) if (entry.isDirectory) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw IllegalStateException( String.format("Couldn't create directory %s.", outputFile.absolutePath)) } } } else { val out = FileOutputStream(outputFile) IOUtils.copy(tis, out) out.close() } entry = tis.nextEntry as TarArchiveEntry } tis.close() `is`.close() } catch (e: IOException) { e.printStackTrace() } catch (e: ArchiveException) { e.printStackTrace() } if (deleteAfter) FileUtil.deleteFile(context, input) return outputDir.absolutePath } fun createTar(tar: String, files: ArrayList<BaseFile>): String { var tar = tar if (!tar.startsWith(File.separator)) { tar = BackgroundUtils.ARCHIVE_LOCATION + File.separator + tar } var tarFile = File(tar) if (FileUtil.getExtension(tarFile.name) != "tar") { tar += ".tar" tarFile = File(tar) } try { val os = FileOutputStream(tarFile) val aos = ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.TAR, os) for (bf in files) { bf.getFile { file -> try { addFilesToCompression(aos, file, ".") } catch (e: IOException) { e.printStackTrace() } } } aos.finish() } catch (e: IOException) { e.printStackTrace() } catch (e: ArchiveException) { e.printStackTrace() } return BackgroundUtils.ARCHIVE_LOCATION } fun createTarGZ(tarFile: String, files: ArrayList<BaseFile>): String { var tarFile = tarFile if (!tarFile.startsWith(File.separator)) { tarFile = BackgroundUtils.ARCHIVE_LOCATION + File.separator + tarFile } if (!tarFile.endsWith("tar.gz")) { tarFile += ".tar.gz" } val outFile = File(tarFile) try { val fos = FileOutputStream(outFile) val taos = TarArchiveOutputStream( GZIPOutputStream(BufferedOutputStream(fos))) taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR) taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU) for (bf in files) { bf.getFile { file -> try { addFilesToCompression(taos, file, ".") } catch (e: IOException) { e.printStackTrace() } } } taos.close() } catch (e: IOException) { e.printStackTrace() } return BackgroundUtils.ARCHIVE_LOCATION } //add entries to archive file... @Throws(IOException::class) private fun addFilesToCompression( taos: ArchiveOutputStream, file: File, dir: String) { taos.putArchiveEntry(TarArchiveEntry(file, dir + "/" + file.name)) if (file.isFile) { // Add the file to the archive val bis = BufferedInputStream(FileInputStream(file)) IOUtils.copy(bis, taos) taos.closeArchiveEntry() bis.close() } else if (file.isDirectory) { // close the archive entry taos.closeArchiveEntry() // go through all the files in the directory and using recursion, add them to the archive for (childFile in file.listFiles()) { addFilesToCompression(taos, childFile, file.name) } } } fun unGzip(input: String, output: String): String { val inputFile = File(input) var outputFile = File(output) outputFile = File(outputFile, FileUtil.removeExtension(input)) if (outputFile.exists()) { val ext = FileUtil.getExtension(outputFile.name) val file = FileUtil.removeExtension(outputFile.absolutePath) for (i in 1 until Integer.MAX_VALUE) { val test = File("$file-$i.$ext") if (test.exists()) continue outputFile = test break } } try { val `in` = GZIPInputStream(FileInputStream(inputFile)) val out = FileOutputStream(outputFile) IOUtils.copy(`in`, out) `in`.close() out.close() } catch (e: IOException) { e.printStackTrace() } return outputFile.absolutePath } }
gpl-3.0
bf4c2ff26fd46ba3ee31129c397d28a0
31.676056
101
0.529828
5.004314
false
false
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/bit/EmvBit.kt
1
981
package io.github.binaryfoo.bit /** * EMV specs seem to follow the convention: bytes are numbered left to right, bits are numbered byte right to left, * both start at 1. */ data class EmvBit(val byteNumber: Int, val bitNumber: Int, val set: Boolean) : Comparable<EmvBit> { val value: String get() = if (set) "1" else "0" override fun toString(): String = toString(true) fun toString(includeComma: Boolean, includeValue: Boolean = true): String { val separator = if (includeComma) "," else "" if (includeValue) { return "Byte $byteNumber$separator Bit $bitNumber = $value" } return "Byte $byteNumber$separator Bit $bitNumber" } override fun compareTo(other: EmvBit): Int { val byteOrder = byteNumber.compareTo(other.byteNumber) if (byteOrder != 0) { return byteOrder } val bitOrder = other.bitNumber.compareTo(bitNumber) if (bitOrder != 0) { return bitOrder } return set.compareTo(other.set) } }
mit
3bf9e972e782a53870e58e1eb08e5578
28.727273
115
0.672783
3.68797
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/encryptedlogging/SecretStreamKey.kt
2
1489
package org.wordpress.android.fluxc.model.encryptedlogging import com.goterl.lazysodium.interfaces.Box import com.goterl.lazysodium.interfaces.SecretStream import com.goterl.lazysodium.utils.Key /** * A class representing an unencrypted Secret Stream Key. * * It can be encrypted to provide an EncryptedSecretStreamKey, which is used to secure * an Encrypted Log file. * * @see EncryptedSecretStreamKey */ class SecretStreamKey(val bytes: ByteArray) { companion object { /** * Generate a new (and securely random) secret stream key */ fun generate(): SecretStreamKey { return SecretStreamKey(EncryptionUtils.sodium.cryptoSecretStreamKeygen().asBytes) } } init { require(bytes.size == SecretStream.KEYBYTES) { "A Secret Stream Key must be exactly ${SecretStream.KEYBYTES} bytes" } } val size: Long = bytes.size.toLong() fun encrypt(publicKey: Key): EncryptedSecretStreamKey { val sodium = EncryptionUtils.sodium require(Box.Checker.checkPublicKey(publicKey.asBytes.size)) { "The public key must be the right length" } val encryptedBytes = ByteArray(EncryptedSecretStreamKey.size) // Stores the encrypted bytes check(sodium.cryptoBoxSeal(encryptedBytes, bytes, size, publicKey.asBytes)) { "Encrypting the message key must not fail" } return EncryptedSecretStreamKey(encryptedBytes) } }
gpl-2.0
ce1a8f7cf380f28332ff1420d1b672af
30.680851
99
0.687038
4.353801
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/effect/potion/PotionEffect.kt
1
2899
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("FunctionName", "NOTHING_TO_INLINE") package org.lanternpowered.api.effect.potion import org.lanternpowered.api.registry.builderOf import java.util.function.Supplier typealias PotionEffect = org.spongepowered.api.effect.potion.PotionEffect typealias PotionEffectBuilder = org.spongepowered.api.effect.potion.PotionEffect.Builder typealias PotionEffectType = org.spongepowered.api.effect.potion.PotionEffectType typealias PotionEffectTypes = org.spongepowered.api.effect.potion.PotionEffectTypes fun potionEffectOf( type: PotionEffectType, amplifier: Int, duration: Int, ambient: Boolean = false, showParticles: Boolean = true, showIcon: Boolean = true ): PotionEffect = PotionEffect.builder().potionType(type).amplifier(amplifier).duration(duration) .ambient(ambient).showParticles(showParticles).showIcon(showIcon).build() fun potionEffectOf( type: Supplier<out PotionEffectType>, amplifier: Int, duration: Int, ambient: Boolean = false, showParticles: Boolean = true, showIcon: Boolean = true ): PotionEffect = PotionEffect.builder().potionType(type).amplifier(amplifier).duration(duration) .ambient(ambient).showParticles(showParticles).showIcon(showIcon).build() fun Collection<PotionEffect>.mergeWith(that: Collection<PotionEffect>): MutableList<PotionEffect> { val effectsByType = mutableMapOf<PotionEffectType, PotionEffect>() for (effect in this) { effectsByType[effect.type] = effect } val result = mutableListOf<PotionEffect>() for (effect in that) { val other = effectsByType.remove(effect.type) if (other != null) { result.add(effect.mergeWith(other)) } else { result.add(effect) } } result.addAll(effectsByType.values) return result } /** * Merges this [PotionEffect] with the other one. * * @param that The potion effect to merge with * @return The merged potion effect */ fun PotionEffect.mergeWith(that: PotionEffect): PotionEffect { val builder = builderOf<PotionEffectBuilder>().from(this) if (that.amplifier > amplifier) { builder.amplifier(that.amplifier).duration(that.duration) } else if (that.amplifier == amplifier && duration < that.duration) { builder.duration(that.duration) } else if (!that.isAmbient && isAmbient) { builder.ambient(that.isAmbient) } builder.showParticles(that.showsParticles()) builder.showIcon(that.showsIcon()) return builder.build() }
mit
f3a432faf4a572dca904fdefd99ab54e
35.696203
99
0.708865
4.183261
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/data/structure/entity/EntityData.kt
1
1376
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.api.data.structure.entity import org.lanternpowered.api.data.persistence.DataView import org.lanternpowered.api.data.persistence.dataQueryOf import org.lanternpowered.api.entity.Entity import org.lanternpowered.api.entity.EntityType import org.spongepowered.api.data.persistence.DataContainer import org.spongepowered.api.data.persistence.DataSerializable import org.spongepowered.math.vector.Vector3d /** * Represents the data of an [Entity]. */ data class EntityData( val type: EntityType<*>, val position: Vector3d, val data: DataView ) : DataSerializable { override fun getContentVersion(): Int = 1 override fun toContainer(): DataContainer = DataContainer.createNew() .set(Queries.Type, this.type.key.formatted) .set(Queries.Position, this.position.toArray()) .set(Queries.Data, this.data) object Queries { val Type = dataQueryOf("Type") val Position = dataQueryOf("Position") val Data = dataQueryOf("Data") } }
mit
74e8917e65ff2775d51066c06cbcd0c4
31
73
0.715116
4.071006
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/cause/entity/damage/Damage.kt
1
1156
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("NOTHING_TO_INLINE") package org.lanternpowered.api.cause.entity.damage typealias DamageFunction = org.spongepowered.api.event.cause.entity.damage.DamageFunction typealias DamageModifier = org.spongepowered.api.event.cause.entity.damage.DamageModifier typealias DamageModifierType = org.spongepowered.api.event.cause.entity.damage.DamageModifierType typealias DamageModifierTypes = org.spongepowered.api.event.cause.entity.damage.DamageModifierTypes typealias DamageType = org.spongepowered.api.event.cause.entity.damage.DamageType /** * Constructs a new [DamageFunction]. * * @param modifier The damage modifier * @param fn The function * @return The damage function */ inline fun damageFunctionOf(modifier: DamageModifier, noinline fn: (Double) -> Double): DamageFunction = DamageFunction.of(modifier, fn)
mit
a26089d00ac8e8eeb11fc0193014a4a3
40.285714
136
0.782872
3.931973
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/encoding/Decoding.kt
1
25602
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.encoding import kotlinx.serialization.* import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.modules.* /** * Decoder is a core deserialization primitive that encapsulates the knowledge of the underlying * format and an underlying storage, exposing only structural methods to the deserializer, making it completely * format-agnostic. Deserialization process takes a decoder and asks him for a sequence of primitive elements, * defined by a deserializer serial form, while decoder knows how to retrieve these primitive elements from an actual format * representations. * * Decoder provides high-level API that operates with basic primitive types, collections * and nested structures. Internally, the decoder represents input storage, and operates with its state * and lower level format-specific details. * * To be more specific, serialization asks a decoder for a sequence of "give me an int, give me * a double, give me a list of strings and give me another object that is a nested int", while decoding * transforms this sequence into a format-specific commands such as "parse the part of the string until the next quotation mark * as an int to retrieve an int, parse everything within the next curly braces to retrieve elements of a nested object etc." * * The symmetric interface for the serialization process is [Encoder]. * * ### Deserialization. Primitives * * If a class is represented as a single [primitive][PrimitiveKind] value in its serialized form, * then one of the `decode*` methods (e.g. [decodeInt]) can be used directly. * * ### Deserialization. Structured types * * If a class is represented as a structure or has multiple values in its serialized form, * `decode*` methods are not that helpful, because format may not require a strict order of data * (e.g. JSON or XML), do not allow working with collection types or establish structure boundaries. * All these capabilities are delegated to the [CompositeDecoder] interface with a more specific API surface. * To denote a structure start, [beginStructure] should be used. * ``` * // Denote the structure start, * val composite = decoder.beginStructure(descriptor) * // Decode all elements within the structure using 'composite' * ... * // Denote the structure end * composite.endStructure(descriptor) * ``` * * E.g. if the decoder belongs to JSON format, then [beginStructure] will parse an opening bracket * (`{` or `[`, depending on the descriptor kind), returning the [CompositeDecoder] that is aware of colon separator, * that should be read after each key-value pair, whilst [CompositeDecoder.endStructure] will parse a closing bracket. * * ### Exception guarantees. * For the regular exceptions, such as invalid input, missing control symbols or attributes and unknown symbols, * [SerializationException] can be thrown by any decoder methods. It is recommended to declare a format-specific * subclass of [SerializationException] and throw it. * * ### Format encapsulation * * For example, for the following deserializer: * ``` * class StringHolder(val stringValue: String) * * object StringPairDeserializer : DeserializationStrategy<StringHolder> { * override val descriptor = ... * * override fun deserializer(decoder: Decoder): StringHolder { * // Denotes start of the structure, StringHolder is not a "plain" data type * val composite = decoder.beginStructure(descriptor) * if (composite.decodeElementIndex(descriptor) != 0) * throw MissingFieldException("Field 'stringValue' is missing") * // Decode the nested string value * val value = composite.decodeStringElement(descriptor, index = 0) * // Denotes end of the structure * composite.endStructure(descriptor) * } * } * ``` * * ### Exception safety * * In general, catching [SerializationException] from any of `decode*` methods is not allowed and produces unspecified behaviour. * After thrown exception, current decoder is left in an arbitrary state, no longer suitable for further decoding. * * This deserializer does not know anything about the underlying data and will work with any properly-implemented decoder. * JSON, for example, parses an opening bracket `{` during the `beginStructure` call, checks that the next key * after this bracket is `stringValue` (using the descriptor), returns the value after the colon as string value * and parses closing bracket `}` during the `endStructure`. * XML would do roughly the same, but with different separators and parsing structures, while ProtoBuf * machinery could be completely different. * In any case, all these parsing details are encapsulated by a decoder. * * ### Decoder implementation * * While being strictly typed, an underlying format can transform actual types in the way it wants. * For example, a format can support only string types and encode/decode all primitives in a string form: * ``` * StringFormatDecoder : Decoder { * * ... * override fun decodeDouble(): Double = decodeString().toDouble() * override fun decodeInt(): Int = decodeString().toInt() * ... * } * ``` * * ### Not stable for inheritance * * `Decoder` interface is not stable for inheritance in 3rd-party libraries, as new methods * might be added to this interface or contracts of the existing methods can be changed. */ public interface Decoder { /** * Context of the current serialization process, including contextual and polymorphic serialization and, * potentially, a format-specific configuration. */ public val serializersModule: SerializersModule /** * Returns `true` if the current value in decoder is not null, false otherwise. * This method is usually used to decode potentially nullable data: * ``` * // Could be String? deserialize() method * public fun deserialize(decoder: Decoder): String? { * if (decoder.decodeNotNullMark()) { * return decoder.decodeString() * } else { * return decoder.decodeNull() * } * } * ``` */ @ExperimentalSerializationApi public fun decodeNotNullMark(): Boolean /** * Decodes the `null` value and returns it. * * It is expected that `decodeNotNullMark` was called * prior to `decodeNull` invocation and the case when it returned `true` was handled. */ @ExperimentalSerializationApi public fun decodeNull(): Nothing? /** * Decodes a boolean value. * Corresponding kind is [PrimitiveKind.BOOLEAN]. */ public fun decodeBoolean(): Boolean /** * Decodes a single byte value. * Corresponding kind is [PrimitiveKind.BYTE]. */ public fun decodeByte(): Byte /** * Decodes a 16-bit short value. * Corresponding kind is [PrimitiveKind.SHORT]. */ public fun decodeShort(): Short /** * Decodes a 16-bit unicode character value. * Corresponding kind is [PrimitiveKind.CHAR]. */ public fun decodeChar(): Char /** * Decodes a 32-bit integer value. * Corresponding kind is [PrimitiveKind.INT]. */ public fun decodeInt(): Int /** * Decodes a 64-bit integer value. * Corresponding kind is [PrimitiveKind.LONG]. */ public fun decodeLong(): Long /** * Decodes a 32-bit IEEE 754 floating point value. * Corresponding kind is [PrimitiveKind.FLOAT]. */ public fun decodeFloat(): Float /** * Decodes a 64-bit IEEE 754 floating point value. * Corresponding kind is [PrimitiveKind.DOUBLE]. */ public fun decodeDouble(): Double /** * Decodes a string value. * Corresponding kind is [PrimitiveKind.STRING]. */ public fun decodeString(): String /** * Decodes a enum value and returns its index in [enumDescriptor] elements collection. * Corresponding kind is [SerialKind.ENUM]. * * E.g. for the enum `enum class Letters { A, B, C, D }` and * underlying input "C", [decodeEnum] method should return `2` as a result. * * This method does not imply any restrictions on the input format, * the format is free to store the enum by its name, index, ordinal or any other enum representation. */ public fun decodeEnum(enumDescriptor: SerialDescriptor): Int /** * Returns [Decoder] for decoding an underlying type of a value class in an inline manner. * [descriptor] describes a target value class. * * Namely, for the `@Serializable @JvmInline value class MyInt(val my: Int)`, the following sequence is used: * ``` * thisDecoder.decodeInline(MyInt.serializer().descriptor).decodeInt() * ``` * * Current decoder may return any other instance of [Decoder] class, depending on the provided [descriptor]. * For example, when this function is called on `Json` decoder with * `UInt.serializer().descriptor`, the returned decoder is able to decode unsigned integers. * * Note that this function returns [Decoder] instead of the [CompositeDecoder] * because value classes always have the single property. * * Calling [Decoder.beginStructure] on returned instance leads to an unspecified behavior and, in general, is prohibited. */ public fun decodeInline(descriptor: SerialDescriptor): Decoder /** * Decodes the beginning of the nested structure in a serialized form * and returns [CompositeDecoder] responsible for decoding this very structure. * * Typically, classes, collections and maps are represented as a nested structure in a serialized form. * E.g. the following JSON * ``` * { * "a": 2, * "b": { "nested": "c" } * "c": [1, 2, 3], * "d": null * } * ``` * has three nested structures: the very beginning of the data, "b" value and "c" value. */ public fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder /** * Decodes the value of type [T] by delegating the decoding process to the given [deserializer]. * For example, `decodeInt` call us equivalent to delegating integer decoding to [Int.serializer][Int.Companion.serializer]: * `decodeSerializableValue(IntSerializer)` */ public fun <T : Any?> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T = deserializer.deserialize(this) /** * Decodes the nullable value of type [T] by delegating the decoding process to the given [deserializer]. */ @ExperimentalSerializationApi public fun <T : Any> decodeNullableSerializableValue(deserializer: DeserializationStrategy<T?>): T? { val isNullabilitySupported = deserializer.descriptor.isNullable return if (isNullabilitySupported || decodeNotNullMark()) decodeSerializableValue(deserializer) else decodeNull() } } /** * [CompositeDecoder] is a part of decoding process that is bound to a particular structured part of * the serialized form, described by the serial descriptor passed to [Decoder.beginStructure]. * * Typically, for unordered data, [CompositeDecoder] is used by a serializer withing a [decodeElementIndex]-based * loop that decodes all the required data one-by-one in any order and then terminates by calling [endStructure]. * Please refer to [decodeElementIndex] for example of such loop. * * All `decode*` methods have `index` and `serialDescriptor` parameters with a strict semantics and constraints: * * `descriptor` argument is always the same as one used in [Decoder.beginStructure]. * * `index` of the element being decoded. For [sequential][decodeSequentially] decoding, it is always a monotonic * sequence from `0` to `descriptor.elementsCount` and for indexing-loop it is always an index that [decodeElementIndex] * has returned from the last call. * * The symmetric interface for the serialization process is [CompositeEncoder]. * * ### Not stable for inheritance * * `CompositeDecoder` interface is not stable for inheritance in 3rd party libraries, as new methods * might be added to this interface or contracts of the existing methods can be changed. */ public interface CompositeDecoder { /** * Results of [decodeElementIndex] used for decoding control flow. */ public companion object { /** * Value returned by [decodeElementIndex] when the underlying input has no more data in the current structure. * When this value is returned, no methods of the decoder should be called but [endStructure]. */ public const val DECODE_DONE: Int = -1 /** * Value returned by [decodeElementIndex] when the format encountered an unknown element * (expected neither by the structure of serial descriptor, nor by the format itself). */ public const val UNKNOWN_NAME: Int = -3 } /** * Context of the current decoding process, including contextual and polymorphic serialization and, * potentially, a format-specific configuration. */ public val serializersModule: SerializersModule /** * Denotes the end of the structure associated with current decoder. * For example, composite decoder of JSON format will expect (and parse) * a closing bracket in the underlying input. */ public fun endStructure(descriptor: SerialDescriptor) /** * Checks whether the current decoder supports strictly ordered decoding of the data * without calling to [decodeElementIndex]. * If the method returns `true`, the caller might skip [decodeElementIndex] calls * and start invoking `decode*Element` directly, incrementing the index of the element one by one. * This method can be called by serializers (either generated or user-defined) as a performance optimization, * but there is no guarantee that the method will be ever called. Practically, it means that implementations * that may benefit from sequential decoding should also support a regular [decodeElementIndex]-based decoding as well. * * Example of usage: * ``` * class MyPair(i: Int, d: Double) * * object MyPairSerializer : KSerializer<MyPair> { * // ... other methods omitted * * fun deserialize(decoder: Decoder): MyPair { * val composite = decoder.beginStructure(descriptor) * if (composite.decodeSequentially()) { * val i = composite.decodeIntElement(descriptor, index = 0) // Mind the sequential indexing * val d = composite.decodeIntElement(descriptor, index = 1) * composite.endStructure(descriptor) * return MyPair(i, d) * } else { * // Fallback to `decodeElementIndex` loop, refer to its documentation for details * } * } * } * ``` * This example is a rough equivalent of what serialization plugin generates for serializable pair class. * * Sequential decoding is a performance optimization for formats with strictly ordered schema, * usually binary ones. Regular formats such as JSON or ProtoBuf cannot use this optimization, * because e.g. in the latter example, the same data can be represented both as * `{"i": 1, "d": 1.0}`"` and `{"d": 1.0, "i": 1}` (thus, unordered). */ @ExperimentalSerializationApi public fun decodeSequentially(): Boolean = false /** * Decodes the index of the next element to be decoded. * Index represents a position of the current element in the serial descriptor element that can be found * with [SerialDescriptor.getElementIndex]. * * If this method returns non-negative index, the caller should call one of the `decode*Element` methods * with a resulting index. * Apart from positive values, this method can return [DECODE_DONE] to indicate that no more elements * are left or [UNKNOWN_NAME] to indicate that symbol with an unknown name was encountered. * * Example of usage: * ``` * class MyPair(i: Int, d: Double) * * object MyPairSerializer : KSerializer<MyPair> { * // ... other methods omitted * * fun deserialize(decoder: Decoder): MyPair { * val composite = decoder.beginStructure(descriptor) * var i: Int? = null * var d: Double? = null * while (true) { * when (val index = composite.decodeElementIndex(descriptor)) { * 0 -> i = composite.decodeIntElement(descriptor, 0) * 1 -> d = composite.decodeDoubleElement(descriptor, 1) * DECODE_DONE -> break // Input is over * else -> error("Unexpected index: $index) * } * } * composite.endStructure(descriptor) * require(i != null && d != null) * return MyPair(i, d) * } * } * ``` * This example is a rough equivalent of what serialization plugin generates for serializable pair class. * * The need in such a loop comes from unstructured nature of most serialization formats. * For example, JSON for the following input `{"d": 2.0, "i": 1}`, will first read `d` key with index `1` * and only after `i` with the index `0`. * * A potential implementation of this method for JSON format can be the following: * ``` * fun decodeElementIndex(descriptor: SerialDescriptor): Int { * // Ignore arrays * val nextKey: String? = myStringJsonParser.nextKey() * if (nextKey == null) return DECODE_DONE * return descriptor.getElementIndex(nextKey) // getElementIndex can return UNKNOWN_NAME * } * ``` * * If [decodeSequentially] returns `true`, the caller might skip calling this method. */ public fun decodeElementIndex(descriptor: SerialDescriptor): Int /** * Method to decode collection size that may be called before the collection decoding. * Collection type includes [Collection], [Map] and [Array] (including primitive arrays). * Method can return `-1` if the size is not known in advance, though for [sequential decoding][decodeSequentially] * knowing precise size is a mandatory requirement. */ public fun decodeCollectionSize(descriptor: SerialDescriptor): Int = -1 /** * Decodes a boolean value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.BOOLEAN] kind. */ public fun decodeBooleanElement(descriptor: SerialDescriptor, index: Int): Boolean /** * Decodes a single byte value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.BYTE] kind. */ public fun decodeByteElement(descriptor: SerialDescriptor, index: Int): Byte /** * Decodes a 16-bit unicode character value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.CHAR] kind. */ public fun decodeCharElement(descriptor: SerialDescriptor, index: Int): Char /** * Decodes a 16-bit short value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.SHORT] kind. */ public fun decodeShortElement(descriptor: SerialDescriptor, index: Int): Short /** * Decodes a 32-bit integer value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.INT] kind. */ public fun decodeIntElement(descriptor: SerialDescriptor, index: Int): Int /** * Decodes a 64-bit integer value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.LONG] kind. */ public fun decodeLongElement(descriptor: SerialDescriptor, index: Int): Long /** * Decodes a 32-bit IEEE 754 floating point value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.FLOAT] kind. */ public fun decodeFloatElement(descriptor: SerialDescriptor, index: Int): Float /** * Decodes a 64-bit IEEE 754 floating point value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.DOUBLE] kind. */ public fun decodeDoubleElement(descriptor: SerialDescriptor, index: Int): Double /** * Decodes a string value from the underlying input. * The resulting value is associated with the [descriptor] element at the given [index]. * The element at the given index should have [PrimitiveKind.STRING] kind. */ public fun decodeStringElement(descriptor: SerialDescriptor, index: Int): String /** * Returns [Decoder] for decoding an underlying type of a value class in an inline manner. * Serializable value class is described by the [child descriptor][SerialDescriptor.getElementDescriptor] * of given [descriptor] at [index]. * * Namely, for the `@Serializable @JvmInline value class MyInt(val my: Int)`, * and `@Serializable class MyData(val myInt: MyInt)` the following sequence is used: * ``` * thisDecoder.decodeInlineElement(MyData.serializer().descriptor, 0).decodeInt() * ``` * * This method provides an opportunity for the optimization to avoid boxing of a carried value * and its invocation should be equivalent to the following: * ``` * thisDecoder.decodeSerializableElement(MyData.serializer.descriptor, 0, MyInt.serializer()) * ``` * * Current decoder may return any other instance of [Decoder] class, depending on the provided descriptor. * For example, when this function is called on `Json` decoder with descriptor that has * `UInt.serializer().descriptor` at the given [index], the returned decoder is able * to decode unsigned integers. * * Note that this function returns [Decoder] instead of the [CompositeDecoder] * because value classes always have the single property. * Calling [Decoder.beginStructure] on returned instance leads to an unspecified behavior and, in general, is prohibited. * * @see Decoder.decodeInline * @see SerialDescriptor.getElementDescriptor */ public fun decodeInlineElement( descriptor: SerialDescriptor, index: Int ): Decoder /** * Decodes value of the type [T] with the given [deserializer]. * * Implementations of [CompositeDecoder] may use their format-specific deserializers * for particular data types, e.g. handle [ByteArray] specifically if format is binary. * * If value at given [index] was already decoded with previous [decodeSerializableElement] call with the same index, * [previousValue] would contain a previously decoded value. * This parameter can be used to aggregate multiple values of the given property to the only one. * Implementation can safely ignore it and return a new value, effectively using 'the last one wins' strategy, * or apply format-specific aggregating strategies, e.g. appending scattered Protobuf lists to a single one. */ public fun <T : Any?> decodeSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, previousValue: T? = null ): T /** * Decodes nullable value of the type [T] with the given [deserializer]. * * If value at given [index] was already decoded with previous [decodeSerializableElement] call with the same index, * [previousValue] would contain a previously decoded value. * This parameter can be used to aggregate multiple values of the given property to the only one. * Implementation can safely ignore it and return a new value, efficiently using 'the last one wins' strategy, * or apply format-specific aggregating strategies, e.g. appending scattered Protobuf lists to a single one. */ @ExperimentalSerializationApi public fun <T : Any> decodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?>, previousValue: T? = null ): T? } /** * Begins a structure, decodes it using the given [block], ends it and returns decoded element. */ public inline fun <T> Decoder.decodeStructure( descriptor: SerialDescriptor, crossinline block: CompositeDecoder.() -> T ): T { val composite = beginStructure(descriptor) val result = composite.block() composite.endStructure(descriptor) return result }
apache-2.0
3d4874aa7e9a2976223e1dabe12e14d2
43.994728
129
0.688931
4.745505
false
false
false
false
jonninja/node.kt
src/main/kotlin/node/express/middleware/less.kt
1
1867
package node.express.middleware import java.io.File import node.express.Response import node.express.RouteHandler /** * Compiles less files into CSS * @basePath the root path to look for less files relative to the request path */ public fun lessCompiler(basePath: String): RouteHandler.()->Unit { fun normalizePath(path: String): String { var newPath = path if (newPath.startsWith("/")) { newPath = newPath.substring(1) } if (newPath.endsWith("/")) { newPath = newPath.substring(0, newPath.length() - 1) } return newPath } val base = normalizePath(basePath) val cache = hashMapOf<String, File>() return { var path = req.param("*") as String var cssFile: File? = null if (path.endsWith(".less")) { if (!path.startsWith("/")) { path = "/" + path } var srcFile = File(base + path) if (!srcFile.exists()) { res.send(404) } else { cssFile = cache.get(path) if (cssFile != null && cssFile.exists()) { // check to see if the srcFile has been changed, and force recompile if (cssFile.lastModified() < srcFile.lastModified()) { cssFile = null } } if (cssFile == null) { cssFile = File.createTempFile("LessCss", ".css") var lessCompiler = org.lesscss.LessCompiler() lessCompiler.compile(srcFile, cssFile) cache.put(path, cssFile!!) } } } if (cssFile != null) { res.contentType("text/css") res.sendFile(cssFile) } else { next() } } }
mit
f457002e7908615f72e82f519481abe8
29.622951
88
0.499197
4.774936
false
false
false
false