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
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/preferences/PreferencesExtensionFragment.kt
1
5074
package org.videolan.vlc.gui.preferences import android.content.SharedPreferences import android.os.Bundle import android.view.View import androidx.preference.CheckBoxPreference import androidx.preference.Preference import androidx.preference.SwitchPreferenceCompat import androidx.preference.TwoStatePreference import com.google.android.material.appbar.AppBarLayout import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.vlc.R import org.videolan.vlc.extensions.ExtensionListing import org.videolan.vlc.extensions.ExtensionsManager import org.videolan.tools.Settings import org.videolan.tools.putSingle import java.util.* @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class PreferencesExtensionFragment : BasePreferenceFragment() { private var extension: ExtensionListing? = null private var extensionId: Int = 0 private var extensionTitle: String? = null private var extensionKey: String? = null private var extensionPackageName: String? = null private lateinit var settings: SharedPreferences // private var preferenceScreen: PreferenceScreen? = null private var androidAutoAvailable = false private val preferences = ArrayList<Preference>() override fun onCreate(bundle: Bundle?) { var newBundle = bundle super.onCreate(newBundle) settings = Settings.getInstance(requireActivity()) setHasOptionsMenu(true) if (newBundle == null) newBundle = arguments if (newBundle != null) { extensionKey = newBundle.getString("extension_key") extensionPackageName = extensionKey!!.replace(ExtensionsManager.EXTENSION_PREFIX + "_", "") extensionId = ExtensionsManager.getInstance().getExtensionId(extensionPackageName) extension = ExtensionsManager.getInstance().getExtensions(activity!!.application, false)[extensionId] extensionTitle = extension!!.title() setTitle(extensionTitle) androidAutoAvailable = ExtensionsManager.androidAutoInstalled && extension!!.androidAutoEnabled() createCheckboxes() } } override fun onSaveInstanceState(outState: Bundle) { outState.putString("extension_key", extensionKey) super.onSaveInstanceState(outState) } override fun onStart() { super.onStart() ((activity as PreferencesActivity).findViewById<View>(R.id.appbar) as AppBarLayout).setExpanded(true, false) } override fun getXml(): Int { return R.xml.preferences_extension_page } override fun getTitleId(): Int { return 0 } private fun setTitle(title: String?) { val activity = activity as PreferencesActivity? if (activity != null && activity.supportActionBar != null) (getActivity() as PreferencesActivity).supportActionBar!!.title = title } private fun createCheckboxes() { preferenceScreen = this.preferenceScreen //Main switch val switchPreference = SwitchPreferenceCompat(preferenceScreen!!.context) switchPreference.title = preferenceScreen!!.context.getString(R.string.extension_prefs_activation_title).toUpperCase() switchPreference.key = extensionKey switchPreference.isChecked = settings.getBoolean(extensionKey, false) switchPreference.onPreferenceChangeListener = null preferenceScreen!!.addPreference(switchPreference) //Android-auto if (androidAutoAvailable) { val checkbox = CheckBoxPreference(preferenceScreen!!.context) checkbox.setTitle(R.string.android_auto) val key = extensionKey + "_" + ExtensionsManager.ANDROID_AUTO_SUFFIX checkbox.key = key checkbox.isChecked = switchPreference.isChecked && settings.getBoolean(key, false) checkbox.isEnabled = switchPreference.isChecked preferences.add(checkbox) preferenceScreen!!.addPreference(checkbox) } } override fun onPreferenceTreeClick(preference: Preference): Boolean { val key = preference.key if (key == null || !key.startsWith(extensionKey!!)) return false if (key == extensionKey) { val switchPreference = preference as CheckBoxPreference settings.putSingle(key, switchPreference.isChecked) if (switchPreference.isChecked) { for (checkbox in preferences) checkbox.isEnabled = true } else { for (checkbox in preferences) { (checkbox as CheckBoxPreference).isChecked = false settings.putSingle(checkbox.getKey(), false) checkbox.setEnabled(false) } } } else if (key.endsWith("_" + ExtensionsManager.ANDROID_AUTO_SUFFIX)) { settings.putSingle(preference.key, (preference as TwoStatePreference).isChecked) } return super.onPreferenceTreeClick(preference) } }
gpl-2.0
e22bff61a91d88aeb2df3eef461f5c2f
39.277778
126
0.690382
5.509229
false
false
false
false
Light-Team/ModPE-IDE-Source
data/src/test/kotlin/com/brackeys/ui/data/converter/FontConverterTest.kt
1
2332
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.brackeys.ui.data.converter import com.brackeys.ui.data.storage.database.entity.font.FontEntity import com.brackeys.ui.domain.model.fonts.FontModel import org.junit.Assert.assertEquals import org.junit.Test class FontConverterTest { @Test fun `convert FontEntity to FontModel`() { val fontEntity = FontEntity( fontName = "Droid Sans Mono", fontPath = "/storage/emulated/0/font.ttf", supportLigatures = false ) val fontModel = FontModel( fontName = "Droid Sans Mono", fontPath = "/storage/emulated/0/font.ttf", supportLigatures = false, isExternal = true ) val convert = FontConverter.toModel(fontEntity) assertEquals(fontModel.fontName, convert.fontName) assertEquals(fontModel.fontPath, convert.fontPath) assertEquals(fontModel.supportLigatures, convert.supportLigatures) assertEquals(fontModel.isExternal, convert.isExternal) } @Test fun `convert FontModel to FontEntity`() { val fontEntity = FontEntity( fontName = "Droid Sans Mono", fontPath = "/storage/emulated/0/font.ttf", supportLigatures = false ) val fontModel = FontModel( fontName = "Droid Sans Mono", fontPath = "/storage/emulated/0/font.ttf", supportLigatures = false, isExternal = true ) val convert = FontConverter.toEntity(fontModel) assertEquals(fontEntity.fontName, convert.fontName) assertEquals(fontEntity.fontPath, convert.fontPath) assertEquals(fontEntity.supportLigatures, convert.supportLigatures) } }
apache-2.0
9db3bd5f1778fe2f5bc1383a238b0e9d
34.348485
75
0.670669
4.310536
false
true
false
false
nemerosa/ontrack
ontrack-extension-license/src/main/java/net/nemerosa/ontrack/extension/license/message/LicenseMessage.kt
1
2404
package net.nemerosa.ontrack.extension.license.message import net.nemerosa.ontrack.extension.api.GlobalMessageExtension import net.nemerosa.ontrack.extension.license.License import net.nemerosa.ontrack.extension.license.LicenseExtensionFeature import net.nemerosa.ontrack.extension.license.LicenseService import net.nemerosa.ontrack.extension.license.control.LicenseControlService import net.nemerosa.ontrack.extension.license.control.LicenseExpiration import net.nemerosa.ontrack.extension.support.AbstractExtension import net.nemerosa.ontrack.model.message.Message import net.nemerosa.ontrack.model.message.MessageType import org.springframework.stereotype.Component @Component class LicenseMessage( extensionFeature: LicenseExtensionFeature, private val licenseService: LicenseService, private val licenseControlService: LicenseControlService, ) : AbstractExtension(extensionFeature), GlobalMessageExtension { override val globalMessages: List<Message> get() = checkLicense(licenseService.license) internal fun checkLicense(license: License?): List<Message> { val messages = mutableListOf<Message>() if (license != null) { val control = licenseControlService.control(license) if (!control.active) { messages += Message( type = MessageType.ERROR, content = """License "${license.name}" is not active.""" ) } when (control.expiration) { LicenseExpiration.EXPIRED -> messages += Message( type = MessageType.ERROR, content = """License "${license.name}" is expired. It was valid until ${license.validUntil}.""" ) LicenseExpiration.ALMOST -> messages += Message( type = MessageType.WARNING, content = """License "${license.name}" expires at ${license.validUntil}.""" ) else -> {} // Nothing } if (control.projectCountExceeded) { messages += Message( type = MessageType.ERROR, content = """Maximum number of projects (${license.maxProjects}) for license "${license.name}" has been exceeded. No new project can be created.""" ) } } return messages } }
mit
afffeb7496cb2d377027ae7355d70096
43.518519
167
0.646007
5.1258
false
false
false
false
usbpc102/usbBot
src/main/kotlin/usbbot/modules/Moderation/BulkDeleteCommand.kt
1
9709
package usbbot.modules.Moderation import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.channels.Channel import kotlinx.coroutines.experimental.channels.ClosedSendChannelException import kotlinx.coroutines.experimental.channels.consumeEach import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.newSingleThreadContext import org.slf4j.LoggerFactory import sx.blah.discord.handle.obj.IChannel import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.util.MessageHistory import usbbot.commands.DiscordCommands import usbbot.commands.core.Command import usbbot.util.MessageParsing import usbbot.util.commands.AnnotationExtractor import usbbot.util.commands.DiscordCommand import usbbot.util.commands.DiscordSubCommand import util.* import java.time.LocalDateTime import java.time.ZoneId import java.util.concurrent.Future class BulkDeleteCommand : DiscordCommands { private val logger = LoggerFactory.getLogger(BulkDeleteCommand::class.java) override fun getDiscordCommands(): MutableCollection<Command> = AnnotationExtractor.getCommandList(this) private val bulkDeleteCoroutineContext = newSingleThreadContext("Bulk delete") @DiscordCommand("bulkdelete") fun bulkdelete(msg: IMessage, args: Array<String>) : Int { return 0 } @DiscordSubCommand(name = "range", parent = "bulkdelete") fun bulkdeleteRange(msg: IMessage, args: Array<String>) { launch(bulkDeleteCoroutineContext) { if (args.size < 4) { msg.channel.sendError("Invalid Syntax.") return@launch } val first = args[2].toLongOrNull() val second = args[3].toLongOrNull() if (first == null || second == null) { msg.channel.sendError("Please specify two valid message ids!") return@launch } val firstMsg : IMessage? = msg.channel.getMessageByID(first) val secondMsg : IMessage? = msg.channel.getMessageByID(second) if (firstMsg == null || secondMsg == null) { msg.channel.sendError("Both messages need to be in the same channel, and it has to be the channel where you execute this command!") return@launch } val latestMessageId : Long val oldestMessageId : Long if (firstMsg.timestamp.isAfter(secondMsg.timestamp)) { latestMessageId = firstMsg.longID oldestMessageId = secondMsg.longID } else { latestMessageId = secondMsg.longID oldestMessageId = firstMsg.longID } bulkDeleteHelper(msg.channel.sendProcessing("Starting to delete messages..."), msg.channel, latestMessageId) { inputChannel, collectedMessages -> var msgList = mutableListOf<IMessage>() var message = inputChannel.receive() while (message.longID != oldestMessageId) { msgList = msgList.addAndSend(message, collectedMessages) message = inputChannel.receive() } msgList = msgList.addAndSend(message, collectedMessages) //Send the last messages of to be deleted if the last List isn't empty! if (msgList.size > 0) { collectedMessages.send(msgList) } //Close channels! logger.trace("Closing channels...") collectedMessages.close() inputChannel.closeFromWrongSide() } } } @DiscordSubCommand(name = "last", parent = "bulkdelete") fun bulkdeleteLast(msg: IMessage, args: Array<String>) { launch(bulkDeleteCoroutineContext) { if (args.size < 3) { msg.channel.sendError("Invalid Syntax.") return@launch } val number : Int? = args[2].toIntOrNull() if (number == null) { msg.channel.sendError("You need to specify how many messages to delete!") return@launch } bulkDeleteHelper(msg.channel.sendProcessing("Starting to delete messages..."), msg.channel, msg.longID) { inputChannel, collectedMessages -> var deleted = 0 var msgList = mutableListOf<IMessage>() while (deleted < number) { inputChannel.receive().let { //We've got a message that shall be deleted, so increment the deleted counter! deleted++ //Now add that message to the list of messages to delete msgList = msgList.addAndSend(it, collectedMessages) } } //Send the last messages of to be deleted if the last List isn't empty! if (msgList.size > 0) { collectedMessages.send(msgList) } //Close channels! logger.trace("Closing channels...") collectedMessages.close() inputChannel.closeFromWrongSide() } } } @DiscordSubCommand(name = "user", parent = "bulkdelete") fun bulkdeleteUser(msg: IMessage, args: Array<out String>) { launch(bulkDeleteCoroutineContext) { if (args.size < 4) { msg.channel.sendError("Invalid Syntax.") return@launch } val userID = MessageParsing.getUserID(args[2]) val number = args[3].toIntOrNull() if (userID == -1L) { msg.channel.sendError("Specify a valid user!") return@launch } if (number == null) { msg.channel.sendError("No valid message count provided.") return@launch } bulkDeleteHelper(msg.channel.sendProcessing("Starting to delete messages..."), msg.channel, msg.longID) { inputChannel, collectedMessages -> var deleted = 0 var msgList = mutableListOf<IMessage>() while (deleted < number) { inputChannel.receive().let { if (it.author.longID == userID) { //We've got a message that shall be deleted, so increment the deleted counter! deleted++ //Now add that message to the list of messages to delete msgList = msgList.addAndSend(it, collectedMessages) } } } //Send the last messages of to be deleted if the last List isn't empty! if (msgList.size > 0) { collectedMessages.send(msgList) } //Close channels! logger.trace("Closing channels...") collectedMessages.close() inputChannel.closeFromWrongSide() } } } fun bulkDeleteMessageGetter(discordChannel: IChannel, startId: Long, sendChannel: Channel<IMessage>) = launch(bulkDeleteCoroutineContext) { var startId = startId while (!sendChannel.isClosedForSend) { val msgHistory = discordChannel.getMessageHistoryFrom(startId, 100) startId = msgHistory.earliestMessage.longID for (message in msgHistory) { if (message.longID == startId) continue var endCondition = false try { sendChannel.send(message) } catch (ex: ClosedSendChannelException) { logger.debug("Input Channel was closed!") endCondition = true } if (endCondition) break } } } suspend fun <T> Channel<T>.closeFromWrongSide() { this.close() this.consumeEach {} } suspend fun bulkDeleteHelper(progressMsg: Future<IMessage>, channel: IChannel, startId: Long, block: suspend (Channel<IMessage>, Channel<Collection<IMessage>>) -> Unit) { val inputChannel = Channel<IMessage>() val outputChannel = Channel<Collection<IMessage>>() bulkDeleteMessageGetter(channel, startId, inputChannel) launch(bulkDeleteCoroutineContext) { block(inputChannel, outputChannel) } var progressMsg = progressMsg var counter = 0 outputChannel.consumeEach { val msgHistory = MessageHistory(it) //Making sure that I don't try to delete messages older than 2 weeks... because discord and stuff! if (msgHistory.latestMessage.creationDate.atZone(ZoneId.of("UTC")).isAfter(LocalDateTime.now().atZone(ZoneId.of("UTC")).minusWeeks(2))) { counter += msgHistory.bufferedBulkDelete().get()?.size ?: 0 logger.trace("Before sending the message update!") progressMsg = progressMsg.uptadeProcessing("Deleted $counter messages so far...") logger.trace("After sending the message update!") } } logger.trace("Before sending the end update") progressMsg.updateSuccess("Deleted $counter messages!") logger.trace("After sending the end update") } suspend fun MutableList<IMessage>.addAndSend(msg: IMessage, channel: Channel<Collection<IMessage>>) : MutableList<IMessage> { this.add(msg) return if (this.size == 100) { channel.send(this) mutableListOf() } else { this } } }
mit
455c4fe9ab488f07b746a68c987e2b9b
41.587719
174
0.587393
5.142479
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/test/groovy/graphql/MutationSchema.kt
1
2856
package graphql import graphql.schema.newObject import graphql.schema.newSchema import graphql.schema.newSubscriptionObject import graphql.util.failed import graphql.util.succeeded import reactor.core.publisher.ReplayProcessor import java.util.concurrent.CompletableFuture class NumberHolder(var theNumber: Int) class NumberStore(number: Int) { val changeFeed: ReplayProcessor<NumberHolder> = ReplayProcessor.create<NumberHolder>() internal var numberHolder: NumberHolder = NumberHolder(number) fun closeFeed() { changeFeed.onComplete() } fun changeNumber(newNumber: Int): NumberHolder { this.numberHolder.theNumber = newNumber changeFeed.onNext(NumberHolder(newNumber)) return this.numberHolder } fun failToChangeTheNumber(newNumber: Int): NumberHolder { throw RuntimeException("Cannot change the number") } } private val numberHolderType = newObject { name = "NumberHolder" field<Int> { name = "theNumber" //fetcher { succeeded(it.source<NumberHolder>().theNumber) } } } private val numberQueryType = newObject { name = "queryType" field<Any> { name = "numberHolder" type = numberHolderType } } private val numberMutationType = newObject { name = "mutationType" field<Any> { name = "changeTheNumber" type = numberHolderType argument { name = "newNumber" type = GraphQLInt } fetcher = { environment -> val newNumber = environment.argument<Int>("newNumber")!! val root = environment.source<Any>() as NumberStore CompletableFuture.completedFuture<Any>(root.changeNumber(newNumber)) } } field<Any> { name = "failToChangeTheNumber" type = numberHolderType argument { name = "newNumber" type = GraphQLInt } fetcher = { environment -> val newNumber = environment.argument<Int>("newNumber")!! val root = environment.source<NumberStore>() try { succeeded(root.failToChangeTheNumber(newNumber)) } catch (e: Exception) { failed<Any>(e) } } } } private val numberSubscriptionType = newSubscriptionObject { name = "subscriptionType" subscription<NumberHolder> { name = "changeNumberSubscribe" description = "Description of subscription" type = numberHolderType argument { name = "clientId" type = GraphQLInt } publisher { environment -> environment.source<NumberStore>().changeFeed } } } val schema = newSchema { query = numberQueryType mutation = numberMutationType subscription = numberSubscriptionType }
mit
a858833777f2b556c8805e30dae7f922
24.72973
90
0.632003
4.59164
false
false
false
false
ohmae/mmupnp
xml/src/main/java/net/mm2d/xml/node/XmlAttribute.kt
1
883
/* * Copyright (c) 2021 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.xml.node class XmlAttribute( val uri: String, val qName: String, val value: String ) : XmlNode { override var parent: XmlElement? = null val prefix: String val localName: String init { val index = qName.indexOf(":") if (index == -1) { prefix = "" localName = qName } else { prefix = qName.substring(0, index) localName = qName.substring(index + 1, qName.length) } } override fun toXmlString(indent: Boolean, sb: StringBuilder, depth: Int) { sb.append(" ") sb.append(qName) sb.append("=\"") sb.append(escapeXmlString(value, true)) sb.append("\"") } }
mit
c71d17bb36f1ab19ae52301475e854c6
22.648649
78
0.566857
3.941441
false
false
false
false
Orchextra/orchextra-android-sdk
core/src/main/java/com/gigigo/orchextra/core/domain/interactor/ConfirmAction.kt
1
1950
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.domain.interactor import com.gigigo.orchextra.core.domain.datasources.NetworkDataSource import com.gigigo.orchextra.core.domain.exceptions.NetworkException import com.gigigo.orchextra.core.domain.exceptions.OxException import com.gigigo.orchextra.core.domain.executor.PostExecutionThread import com.gigigo.orchextra.core.domain.executor.PostExecutionThreadImp import com.gigigo.orchextra.core.domain.executor.ThreadExecutor import com.gigigo.orchextra.core.domain.executor.ThreadExecutorImp class ConfirmAction(threadExecutor: ThreadExecutor, postExecutionThread: PostExecutionThread, private val networkDataSource: NetworkDataSource) : Interactor<Unit>(threadExecutor, postExecutionThread) { private lateinit var id: String fun get(id: String, onSuccess: (Unit) -> Unit = onSuccessStub, onError: (OxException) -> Unit = onErrorStub) { this.id = id executeInteractor(onSuccess, onError) } override fun run() = try { notifySuccess(networkDataSource.confirmAction(id)) } catch (error: NetworkException) { notifyError(error) } companion object Factory { fun create(networkDataSource: NetworkDataSource): ConfirmAction = ConfirmAction( ThreadExecutorImp, PostExecutionThreadImp, networkDataSource) } }
apache-2.0
ac5fcf6b49225b109ec3834e279971ef
34.472727
93
0.770256
4.452055
false
false
false
false
mix-it/mixit
src/main/kotlin/mixit/web/handler/GlobalHandler.kt
1
4136
package mixit.web.handler import mixit.model.Role import mixit.model.User import mixit.repository.PostRepository import mixit.repository.TalkRepository import mixit.repository.UserRepository import mixit.util.MarkdownConverter import mixit.util.language import org.springframework.stereotype.Component import org.springframework.web.reactive.function.BodyExtractors import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse.ok @Component class GlobalHandler( val userRepository: UserRepository, val postRepository: PostRepository, val talkRepository: TalkRepository, val markdownConverter: MarkdownConverter ) { fun findAboutView(req: ServerRequest) = userRepository .findByRoles(listOf(Role.STAFF, Role.STAFF_IN_PAUSE)) .collectList() .flatMap { users -> val staff = users.filter { it.role == Role.STAFF }.shuffled() val staffInPause = users.filter { it.role == Role.STAFF_IN_PAUSE }.shuffled() ok().render( "about", mapOf( Pair("staff", staff.map { it.toDto(req.language(), markdownConverter) }), Pair("inactiveStaff", staffInPause.map { it.toDto(req.language(), markdownConverter) }), Pair("title", "about.title") ) ) } fun faqView(req: ServerRequest) = ok().render("faq", mapOf(Pair("title", "faq.title"))) fun comeToMixitView(req: ServerRequest) = ok().render("come", mapOf(Pair("title", "come.title"))) fun scheduleView(req: ServerRequest) = ok().render("schedule", mapOf(Pair("title", "schedule.title"))) fun codeConductView(req: ServerRequest) = ok().render("code-of-conduct", mapOf(Pair("title", "code-of-conduct.title"))) fun speakerView(req: ServerRequest) = ok().render("speaker", mapOf(Pair("title", "speaker.title"))) fun accessibilityView(req: ServerRequest) = ok().render("accessibility", mapOf(Pair("title", "accessibility.title"))) fun findFullTextView(req: ServerRequest) = ok().render("search", mapOf(Pair("title", "search.title"))) fun searchFullTextView(req: ServerRequest) = req.body(BodyExtractors.toFormData()).flatMap { val formData = it.toSingleValueMap() if (formData["search"] == null || formData["search"]!!.trim().length < 3) { ok().render( "search", mapOf( Pair("criteria", formData["search"]), Pair("title", "search.title") ) ) } else { val criteria = formData["search"]!!.trim().split(" ") val users = userRepository.findFullText(criteria) .map { user -> user.toDto(req.language(), markdownConverter, criteria) } val articles = postRepository.findFullText(criteria).map { article -> val user = User("MiXiT", "MiXiT", "MiXiT", "MiXiT") article.toDto(user, req.language(), criteria) } val talks = talkRepository.findFullText(criteria) .map { talk -> talk.toDto(req.language(), emptyList(), false, false, criteria) } ok().render( "search", mapOf( Pair("criteria", formData["search"]), Pair("title", "search.title"), Pair("users", users), Pair("hasUsers", users.hasElements()), Pair("countUsers", users.count()), Pair("talks", talks), Pair("hasTalks", talks.hasElements()), Pair("countTalks", talks.count()), Pair("articles", articles), Pair("hasArticles", articles.hasElements()), Pair("countArticles", articles.count()) ) ) } } }
apache-2.0
c9acebcb16b9469e5636a1f79b176e9f
41.204082
108
0.56528
4.743119
false
false
false
false
icapps/niddler-ui
niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/ui/AbstractToolbar.kt
1
1830
package com.icapps.niddler.ui.form.ui import java.awt.Component import java.awt.Dimension import java.awt.Insets import javax.swing.BorderFactory import javax.swing.Icon import javax.swing.JButton import javax.swing.JToolBar /** * @author nicolaverbeeck */ interface AbstractToolbar { val component: Component fun addAction(icon: Icon, tooltip: String, actionListener: (AbstractAction) -> Unit): AbstractAction fun addSeparator() } interface AbstractAction { var isEnabled: Boolean } class SwingToolbar(orientation: Int = JToolBar.HORIZONTAL, border: Boolean = false) : AbstractToolbar { override val component: JToolBar = JToolBar(orientation).apply { isFloatable = false margin = Insets(0, 4, 0, 4) if (border) this.border = BorderFactory.createLoweredBevelBorder() } override fun addAction(icon: Icon, tooltip: String, actionListener: (AbstractAction) -> Unit): AbstractAction { val button = makeAction(tooltip, icon) component.add(button) return ButtonAction(button, actionListener) } override fun addSeparator() { component.addSeparator() } } private class ButtonAction(private val button: JButton, private val actionListener: (AbstractAction) -> Unit) : AbstractAction { init { button.addActionListener { actionListener(this) } } override var isEnabled: Boolean get() = button.isEnabled set(value) { button.isEnabled = value } } fun makeAction(toolTip: String, icon: Icon): JButton { return JButton().apply { this.icon = icon text = "" toolTipText = toolTip maximumSize = Dimension(32, 32) minimumSize = Dimension(32, 32) preferredSize = Dimension(32, 32) } }
apache-2.0
2c867b8eb5c5e5beeb59cd2497d8c229
24.430556
115
0.665027
4.441748
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/adapter/AdapterPopupDish.kt
1
3848
package com.tamsiree.rxdemo.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.tamsiree.rxdemo.R import com.tamsiree.rxdemo.interfaces.ShopCartInterface import com.tamsiree.rxdemo.model.ModelDish import com.tamsiree.rxdemo.model.ModelShopCart import com.tamsiree.rxkit.TLog import java.util.* /** * * @author tamsiree * @date 16-12-23 */ class AdapterPopupDish(private val context: Context, private val mModelShopCart: ModelShopCart) : RecyclerView.Adapter<RecyclerView.ViewHolder?>() { private var itemCount: Int private val mModelDishList: ArrayList<ModelDish> var shopCartInterface: ShopCartInterface? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.right_dish_item1, parent, false) return DishViewHolder(view) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val dishholder = holder as DishViewHolder? val modelDish = getDishByPosition(position) dishholder!!.right_dish_name_tv.text = modelDish.dishName dishholder.right_dish_price_tv.text = modelDish.dishPrice.toString() val num = mModelShopCart.shoppingSingleMap[modelDish]!! dishholder.right_dish_account_tv.text = num.toString() dishholder.right_dish_add_iv.setOnClickListener { view -> if (mModelShopCart.addShoppingSingle(modelDish)) { notifyItemChanged(position) if (shopCartInterface != null) { shopCartInterface!!.add(view, position) } } } dishholder.right_dish_remove_iv.setOnClickListener { view -> if (mModelShopCart.subShoppingSingle(modelDish)) { mModelDishList.clear() mModelDishList.addAll(mModelShopCart.shoppingSingleMap.keys) itemCount = mModelShopCart.dishAccount notifyDataSetChanged() if (shopCartInterface != null) { shopCartInterface!!.remove(view, position) } } } } override fun getItemCount(): Int { return itemCount } fun getDishByPosition(position: Int): ModelDish { return mModelDishList[position] } private inner class DishViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val right_dish_name_tv: TextView val right_dish_price_tv: TextView private val right_dish_layout: LinearLayout val right_dish_remove_iv: ImageView val right_dish_add_iv: ImageView val right_dish_account_tv: TextView init { right_dish_name_tv = itemView.findViewById<View>(R.id.right_dish_name) as TextView right_dish_price_tv = itemView.findViewById<View>(R.id.right_dish_price) as TextView right_dish_layout = itemView.findViewById<View>(R.id.right_dish_item) as LinearLayout right_dish_remove_iv = itemView.findViewById<View>(R.id.right_dish_remove) as ImageView right_dish_add_iv = itemView.findViewById<View>(R.id.right_dish_add) as ImageView right_dish_account_tv = itemView.findViewById<View>(R.id.right_dish_account) as TextView } } companion object { private const val TAG = "PopupDishAdapter" } init { itemCount = mModelShopCart.dishAccount mModelDishList = ArrayList() mModelDishList.addAll(mModelShopCart.shoppingSingleMap.keys) TLog.e(TAG, "PopupDishAdapter: " + itemCount) } }
apache-2.0
a7b043fdc99b1ca44e66d1ed5d69ad8d
39.09375
148
0.682432
3.987565
false
false
false
false
project-chip/connectedhomeip
examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/CHIPToolActivity.kt
1
10740
/* * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.chip.chiptool import android.content.Intent import android.net.Uri import android.nfc.NdefMessage import android.nfc.NfcAdapter import android.os.Bundle import android.util.Base64 import android.util.Log import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.google.chip.chiptool.NetworkCredentialsParcelable import chip.setuppayload.SetupPayload import chip.setuppayload.SetupPayloadParser import chip.setuppayload.SetupPayloadParser.UnrecognizedQrCodeException import com.google.chip.chiptool.attestation.AttestationTestFragment import com.google.chip.chiptool.clusterclient.clusterinteraction.ClusterInteractionFragment import com.google.chip.chiptool.clusterclient.MultiAdminClientFragment import com.google.chip.chiptool.clusterclient.OpCredClientFragment import com.google.chip.chiptool.clusterclient.BasicClientFragment import com.google.chip.chiptool.clusterclient.OnOffClientFragment import com.google.chip.chiptool.clusterclient.SensorClientFragment import com.google.chip.chiptool.clusterclient.WildcardFragment import com.google.chip.chiptool.provisioning.AddressCommissioningFragment import com.google.chip.chiptool.provisioning.DeviceProvisioningFragment import com.google.chip.chiptool.provisioning.EnterNetworkFragment import com.google.chip.chiptool.provisioning.ProvisionNetworkType import com.google.chip.chiptool.setuppayloadscanner.BarcodeFragment import com.google.chip.chiptool.setuppayloadscanner.CHIPDeviceDetailsFragment import com.google.chip.chiptool.setuppayloadscanner.CHIPDeviceInfo import com.google.chip.chiptool.setuppayloadscanner.CHIPLedgerDetailsFragment import org.json.JSONObject class CHIPToolActivity : AppCompatActivity(), BarcodeFragment.Callback, SelectActionFragment.Callback, DeviceProvisioningFragment.Callback, EnterNetworkFragment.Callback, CHIPDeviceDetailsFragment.Callback, CHIPLedgerDetailsFragment.Callback { private var networkType: ProvisionNetworkType? = null private var deviceInfo: CHIPDeviceInfo? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.top_activity) if (savedInstanceState == null) { val fragment = SelectActionFragment.newInstance() supportFragmentManager .beginTransaction() .add(R.id.fragment_container, fragment, fragment.javaClass.simpleName) .commit() } else { networkType = ProvisionNetworkType.fromName(savedInstanceState.getString(ARG_PROVISION_NETWORK_TYPE)) } if (intent?.action == NfcAdapter.ACTION_NDEF_DISCOVERED) onNfcIntent(intent) if (Intent.ACTION_VIEW == intent?.action) { onReturnIntent(intent) } } override fun onSaveInstanceState(outState: Bundle) { outState.putString(ARG_PROVISION_NETWORK_TYPE, networkType?.name) super.onSaveInstanceState(outState) } override fun onCHIPDeviceInfoReceived(deviceInfo: CHIPDeviceInfo) { this.deviceInfo = deviceInfo if (networkType == null) { showFragment(CHIPDeviceDetailsFragment.newInstance(deviceInfo)) } else { if (deviceInfo.ipAddress != null) { showFragment(DeviceProvisioningFragment.newInstance(deviceInfo!!, null)) } else { showFragment(EnterNetworkFragment.newInstance(networkType!!), false) } } } override fun onCommissioningComplete(code: Int) { runOnUiThread { Toast.makeText( this, getString(R.string.commissioning_completed, code), Toast.LENGTH_SHORT).show() } ChipClient.getDeviceController(this).close() showFragment(SelectActionFragment.newInstance(), false) } override fun handleScanQrCodeClicked() { showFragment(BarcodeFragment.newInstance()) } override fun onProvisionWiFiCredentialsClicked() { networkType = ProvisionNetworkType.WIFI showFragment(BarcodeFragment.newInstance(), false) } override fun onProvisionThreadCredentialsClicked() { networkType = ProvisionNetworkType.THREAD showFragment(BarcodeFragment.newInstance(), false) } override fun onShowDeviceAddressInput() { showFragment(AddressCommissioningFragment.newInstance(), false) } override fun onNetworkCredentialsEntered(networkCredentials: NetworkCredentialsParcelable) { showFragment(DeviceProvisioningFragment.newInstance(deviceInfo!!, networkCredentials)) } override fun handleClusterInteractionClicked() { showFragment(ClusterInteractionFragment.newInstance()) } override fun handleWildcardClicked() { showFragment(WildcardFragment.newInstance()) } override fun handleOnOffClicked() { showFragment(OnOffClientFragment.newInstance()) } override fun handleSensorClicked() { showFragment(SensorClientFragment.newInstance()) } override fun handleMultiAdminClicked() { showFragment(MultiAdminClientFragment.newInstance()) } override fun handleOpCredClicked() { showFragment(OpCredClientFragment.newInstance()) } override fun handleBasicClicked() { showFragment(BasicClientFragment.newInstance()) } override fun handleAttestationTestClicked() { showFragment(AttestationTestFragment.newInstance()) } override fun handleReadFromLedgerClicked(deviceInfo: CHIPDeviceInfo) { showFragment(CHIPLedgerDetailsFragment.newInstance(deviceInfo)) } override fun handleCustomFlowRedirectClicked(redirectUrl: String) { val redirectIntent = Intent(Intent.ACTION_VIEW, Uri.parse(redirectUrl)) startActivity(redirectIntent) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_COMMISSIONING) { // Simply ignore the commissioning result. // TODO: tracking commissioned devices. } } override fun handleCustomFlowClicked() { showFragment(BarcodeFragment.newInstance()) } private fun showFragment(fragment: Fragment, showOnBack: Boolean = true) { val fragmentTransaction = supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, fragment, fragment.javaClass.simpleName) if (showOnBack) { fragmentTransaction.addToBackStack(null) } fragmentTransaction.commit() } private fun onNfcIntent(intent: Intent?) { // Require 1 NDEF message containing 1 NDEF record val messages = intent?.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES) if (messages?.size != 1) return val records = (messages[0] as NdefMessage).records if (records.size != 1) return // Require NDEF URI record starting with "mt:" val uri = records[0].toUri() if (!uri?.scheme.equals("mt", true)) return lateinit var setupPayload: SetupPayload try { setupPayload = SetupPayloadParser().parseQrCode(uri.toString().toUpperCase()) } catch (ex: UnrecognizedQrCodeException) { Log.e(TAG, "Unrecognized QR Code", ex) Toast.makeText(this, "Unrecognized QR Code", Toast.LENGTH_SHORT).show() return } val deviceInfo = CHIPDeviceInfo.fromSetupPayload(setupPayload) val buttons = arrayOf( getString(R.string.nfc_tag_action_show), getString(R.string.nfc_tag_action_wifi), getString(R.string.nfc_tag_action_thread)) AlertDialog.Builder(this) .setTitle(R.string.nfc_tag_action_title) .setItems(buttons) { _, which -> this.networkType = when (which) { 1 -> ProvisionNetworkType.WIFI 2 -> ProvisionNetworkType.THREAD else -> null } onCHIPDeviceInfoReceived(deviceInfo) } .create() .show() } private fun onReturnIntent(intent: Intent) { val appLinkData = intent.data // Require URI schema "mt:" if (!appLinkData?.scheme.equals("mt", true)) { Log.d(TAG, "Unrecognized URI schema : ${appLinkData?.scheme}") return } // Require URI host "modelinfo" if (!appLinkData?.host.equals("modelinfo", true)) { Log.d(TAG, "Unrecognized URI host : ${appLinkData?.host}") return } // parse payload try { val payloadBase64String = appLinkData?.getQueryParameter("payload") if (payloadBase64String.isNullOrEmpty()) { Log.d(TAG, "Unrecognized payload") return } val decodeBytes = Base64.decode(payloadBase64String, Base64.DEFAULT) val payloadString = String(decodeBytes) val payload = JSONObject(payloadString) // parse payload from JSON val setupPayload = SetupPayload() // set defaults setupPayload.discoveryCapabilities = setOf() setupPayload.optionalQRCodeInfo = mapOf() // read from payload setupPayload.version = payload.getInt("version") setupPayload.vendorId = payload.getInt("vendorId") setupPayload.productId = payload.getInt("productId") setupPayload.commissioningFlow = payload.getInt("commissioningFlow") setupPayload.discriminator = payload.getInt("discriminator") setupPayload.setupPinCode = payload.getLong("setupPinCode") val deviceInfo = CHIPDeviceInfo.fromSetupPayload(setupPayload) val buttons = arrayOf( getString(R.string.nfc_tag_action_show) ) AlertDialog.Builder(this) .setTitle(R.string.provision_custom_flow_alert_title) .setItems(buttons) { _, _ -> onCHIPDeviceInfoReceived(deviceInfo) } .create() .show() } catch (ex: UnrecognizedQrCodeException) { Log.e(TAG, "Unrecognized Payload", ex) Toast.makeText(this, "Unrecognized Setup Payload", Toast.LENGTH_SHORT).show() return } } companion object { private const val TAG = "CHIPToolActivity" private const val ADDRESS_COMMISSIONING_FRAGMENT_TAG = "address_commissioning_fragment" private const val ARG_PROVISION_NETWORK_TYPE = "provision_network_type" var REQUEST_CODE_COMMISSIONING = 0xB003 } }
apache-2.0
70994e58c517dffbc7632eb41e110d83
33.095238
97
0.734171
4.484342
false
false
false
false
stripe/stripe-android
link/src/main/java/com/stripe/android/link/ui/LinkButtonView.kt
1
6077
package com.stripe.android.link.ui import android.content.Context import android.util.AttributeSet import androidx.annotation.RestrictTo import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.ContentAlpha import androidx.compose.material.Icon import androidx.compose.material.LocalContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.AbstractComposeView import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.stripe.android.link.LinkPaymentLauncher import com.stripe.android.link.R import com.stripe.android.link.theme.DefaultLinkTheme import com.stripe.android.link.theme.linkColors private val LinkButtonVerticalPadding = 6.dp private val LinkButtonHorizontalPadding = 10.dp private val LinkButtonShape = RoundedCornerShape(22.dp) private val LinkButtonEmailShape = RoundedCornerShape(16.dp) // Button corner radius - padding @Preview @Composable private fun LinkButton() { LinkButton( enabled = true, email = "[email protected]", onClick = {} ) } @Composable private fun LinkButton( linkPaymentLauncher: LinkPaymentLauncher, enabled: Boolean, onClick: (LinkPaymentLauncher.Configuration) -> Unit ) { linkPaymentLauncher.component?.let { component -> val account = component.linkAccountManager.linkAccount.collectAsState() LinkButton( enabled = enabled, email = account.value?.email, onClick = { onClick(component.configuration) } ) } } @Composable private fun LinkButton( enabled: Boolean, email: String?, onClick: () -> Unit ) { CompositionLocalProvider( LocalContentAlpha provides if (enabled) ContentAlpha.high else ContentAlpha.disabled ) { DefaultLinkTheme { Button( onClick = onClick, modifier = Modifier.clip(LinkButtonShape), enabled = enabled, elevation = ButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp, 0.dp), shape = LinkButtonShape, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.primary, disabledBackgroundColor = MaterialTheme.colors.primary ), contentPadding = PaddingValues( start = LinkButtonHorizontalPadding, top = LinkButtonVerticalPadding, end = LinkButtonHorizontalPadding, bottom = LinkButtonVerticalPadding ) ) { Icon( painter = painterResource(R.drawable.ic_link_logo), contentDescription = stringResource(R.string.link), modifier = Modifier .height(22.dp) .padding( horizontal = 5.dp, vertical = 3.dp ), tint = MaterialTheme.linkColors.buttonLabel .copy(alpha = LocalContentAlpha.current) ) email?.let { Spacer(modifier = Modifier.weight(1f)) Box( modifier = Modifier .background( color = Color.Black.copy(alpha = 0.05f), shape = LinkButtonEmailShape ) ) { Text( text = it, modifier = Modifier .padding(6.dp), color = MaterialTheme.linkColors.buttonLabel, fontSize = 14.sp, overflow = TextOverflow.Ellipsis, maxLines = 1 ) } } } } } } /** * Wrapper view around a button for paying with Link, for use in xml layout. * * Set the `onClick` function to launch LinkPaymentLauncher. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class LinkButtonView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : AbstractComposeView(context, attrs, defStyle) { override var shouldCreateCompositionOnAttachedToWindow: Boolean = false private set var linkPaymentLauncher: LinkPaymentLauncher? = null var onClick by mutableStateOf<(LinkPaymentLauncher.Configuration) -> Unit>({}) private var isEnabledState by mutableStateOf(isEnabled) override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) isEnabledState = enabled } @Composable override fun Content() { linkPaymentLauncher?.let { LinkButton( it, isEnabledState, onClick ) } } }
mit
22325857aa9dd37f90b6c3403869778d
34.127168
94
0.624321
5.225279
false
false
false
false
AndroidX/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/OptionalQueryResultAdapter.kt
3
1953
/* * 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 androidx.room.solver.query.result import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.processing.XType import androidx.room.ext.CommonTypeNames import androidx.room.solver.CodeGenScope /** * Wraps a row adapter when there is only 1 item in the result, and the result's outer type is * {@link java.util.Optional}. * * <p>n.b. this will only be useful if the project uses Java 8. */ class OptionalQueryResultAdapter( private val typeArg: XType, private val resultAdapter: SingleItemQueryResultAdapter ) : QueryResultAdapter(resultAdapter.rowAdapters) { override fun convert( outVarName: String, cursorVarName: String, scope: CodeGenScope ) { scope.builder.apply { val valueVarName = scope.getTmpVar("_value") resultAdapter.convert(valueVarName, cursorVarName, scope) addLocalVariable( name = outVarName, typeName = CommonTypeNames.OPTIONAL.parametrizedBy( typeArg.asTypeName() ), assignExpr = XCodeBlock.of( language = language, format = "%T.ofNullable(%L)", CommonTypeNames.OPTIONAL, valueVarName ) ) } } }
apache-2.0
efb110fe3bac30ca53b3005489618b6d
33.875
94
0.656938
4.617021
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/interfaces/permissions/PermissionsResponse.kt
2
541
package abi44_0_0.expo.modules.interfaces.permissions data class PermissionsResponse( val status: PermissionsStatus, val canAskAgain: Boolean = true ) { companion object { const val STATUS_KEY = "status" const val GRANTED_KEY = "granted" const val EXPIRES_KEY = "expires" const val CAN_ASK_AGAIN_KEY = "canAskAgain" const val SCOPE_KEY = "scope" const val PERMISSION_EXPIRES_NEVER = "never" const val SCOPE_IN_USE = "whenInUse" const val SCOPE_ALWAYS = "always" const val SCOPE_NONE = "none" } }
bsd-3-clause
98277d6bdec40932318eef932a67044c
29.055556
53
0.693161
3.680272
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/constants/ConstantsService.kt
2
4289
package abi43_0_0.expo.modules.constants import org.apache.commons.io.IOUtils import com.facebook.device.yearclass.YearClass import abi43_0_0.expo.modules.core.interfaces.InternalModule import abi43_0_0.expo.modules.interfaces.constants.ConstantsInterface import android.os.Build import android.util.Log import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import java.io.FileNotFoundException import java.lang.Exception import java.nio.charset.StandardCharsets import java.util.* private val TAG = ConstantsService::class.java.simpleName private const val CONFIG_FILE_NAME = "app.config" open class ConstantsService(private val context: Context) : InternalModule, ConstantsInterface { var statusBarHeightInternal = context.resources.getIdentifier("status_bar_height", "dimen", "android") .takeIf { it > 0 } ?.let { (context.resources::getDimensionPixelSize)(it) } ?.let { pixels -> convertPixelsToDp(pixels.toFloat(), context) } ?: 0 private val sessionId = UUID.randomUUID().toString() private val exponentInstallationId: ExponentInstallationId = ExponentInstallationId(context) enum class ExecutionEnvironment(val string: String) { BARE("bare"), STANDALONE("standalone"), STORE_CLIENT("storeClient"); } override fun getExportedInterfaces(): List<Class<*>> = listOf(ConstantsInterface::class.java) override fun getConstants(): Map<String, Any?> { val constants = mutableMapOf( "sessionId" to sessionId, "executionEnvironment" to ExecutionEnvironment.BARE.string, "statusBarHeight" to statusBarHeightInternal, "deviceYearClass" to deviceYearClass, "deviceName" to deviceName, "isDevice" to isDevice, "systemFonts" to systemFonts, "systemVersion" to systemVersion, "installationId" to getOrCreateInstallationId(), "manifest" to appConfig, "platform" to mapOf("android" to emptyMap<String, Any>()) ) try { val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) constants["nativeAppVersion"] = pInfo.versionName val versionCode = getLongVersionCode(pInfo).toInt() constants["nativeBuildVersion"] = versionCode.toString() } catch (e: PackageManager.NameNotFoundException) { Log.e(TAG, "Exception: ", e) } return constants } // Just use package name in vanilla React Native apps. override fun getAppScopeKey(): String? = context.packageName override fun getAppOwnership() = "guest" override fun getDeviceName(): String = Build.MODEL override fun getDeviceYearClass() = YearClass.get(context) override fun getIsDevice() = !isRunningOnGenymotion && !isRunningOnStockEmulator override fun getStatusBarHeight() = statusBarHeightInternal override fun getSystemVersion(): String = Build.VERSION.RELEASE open fun getOrCreateInstallationId(): String = exponentInstallationId.getOrCreateUUID() // From https://github.com/dabit3/react-native-fonts override fun getSystemFonts() = listOf( "normal", "notoserif", "sans-serif", "sans-serif-light", "sans-serif-thin", "sans-serif-condensed", "sans-serif-medium", "serif", "Roboto", "monospace" ) private val appConfig: String? get() { try { context.assets.open(CONFIG_FILE_NAME).use { stream -> return IOUtils.toString(stream, StandardCharsets.UTF_8) } } catch (e: FileNotFoundException) { // do nothing, expected in managed apps } catch (e: Exception) { Log.e(TAG, "Error reading embedded app config", e) } return null } companion object { private fun convertPixelsToDp(px: Float, context: Context): Int { val resources = context.resources val metrics = resources.displayMetrics val dp = px / (metrics.densityDpi / 160f) return dp.toInt() } private val isRunningOnGenymotion: Boolean get() = Build.FINGERPRINT.contains("vbox") private val isRunningOnStockEmulator: Boolean get() = Build.FINGERPRINT.contains("generic") private fun getLongVersionCode(info: PackageInfo) = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong() } }
bsd-3-clause
caf824af5eb966c57504d74819b5df1b
31.007463
104
0.711588
4.301906
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/application/showcase/ShowcaseSequence.kt
2
3121
package nl.rsdt.japp.application.showcase import android.app.Activity import com.github.amlcurran.showcaseview.OnShowcaseEventListener import com.github.amlcurran.showcaseview.ShowcaseView import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener import com.github.amlcurran.showcaseview.targets.ViewTarget import nl.rsdt.japp.R import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 4-8-2016 * Description... */ open class ShowcaseSequence<A : Activity> { protected var count = 0 protected var current: ShowcaseView? = null protected var members: ArrayList<ShowcaseSequenceItem>? = ArrayList() protected var activity: A? = null var callback: OnSequenceCompletedCallback<A>? = null fun start() { continueToNext() } protected fun continueToNext() { if (current != null) { /** * Set the EventListener to null, so that it doesn't re-invokes the onShowcaseViewDidHide() method. */ current!!.setOnShowcaseEventListener(null) current!!.hide() current = null } if (members != null) { if (members!!.size > count) { val member = members!![count] val builder = ShowcaseView.Builder(activity!!) current = builder.setTarget(member.target) .setStyle(R.style.ShowCaseTheme) .withMaterialShowcase() .setContentTitle(member.title) .setContentText(member.contentText) .setShowcaseEventListener(member.eventListener) .build() current!!.show() count++ } else { if (callback != null) { callback!!.onSequenceCompleted(this) } onDestroy() } } } fun end() { onDestroy() } private fun onDestroy() { if (current != null) { current!!.setOnShowcaseEventListener(null) current!!.hide() current = null } if (members != null) { members!!.clear() members = null } if (activity != null) { activity = null } if (callback != null) { callback = null } } /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 29-8-2016 * Description... */ abstract inner class ShowcaseSequenceItem { abstract val title: String abstract val contentText: String abstract val target: ViewTarget? open val eventListener: OnShowcaseEventListener get() = object : SimpleShowcaseEventListener() { override fun onShowcaseViewDidHide(showcaseView: ShowcaseView?) { continueToNext() } } } interface OnSequenceCompletedCallback<A : Activity> { fun onSequenceCompleted(sequence: ShowcaseSequence<A>) } }
apache-2.0
ae8eb3109558eec69ba4b30974b6d622
25.226891
111
0.556552
4.977671
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/DataGrid.kt
1
29034
@file:Suppress("UNCHECKED_CAST") package tornadofx import com.sun.javafx.scene.control.behavior.BehaviorBase import com.sun.javafx.scene.control.behavior.CellBehaviorBase import com.sun.javafx.scene.control.skin.CellSkinBase import com.sun.javafx.scene.control.skin.VirtualContainerBase import javafx.beans.InvalidationListener import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.collections.WeakListChangeListener import javafx.css.* import javafx.event.EventTarget import javafx.geometry.Pos import javafx.scene.Node import javafx.scene.control.* import javafx.scene.control.SelectionMode.MULTIPLE import javafx.scene.control.SelectionMode.SINGLE import javafx.scene.input.* import javafx.scene.layout.HBox import javafx.scene.layout.StackPane import java.util.* import kotlin.reflect.KClass fun <T> EventTarget.datagrid( items: List<T>? = null, scope: Scope = DefaultScope, op: DataGrid<T>.() -> Unit = {} ) = DataGrid<T>().attachTo(this, op){ it.scope = scope if (items is ObservableList<T>) it.items = items else if (items is List<T>) it.items.setAll(items) } class DataGridPaginator<T>(private val sourceItems: ObservableList<T>, itemsPerPage: Int = 20): HBox() { val itemsPerPageProperty = SimpleIntegerProperty(itemsPerPage) var itemsPerPage by itemsPerPageProperty val items = FXCollections.observableArrayList<T>() private val listChangeTrigger = SimpleObjectProperty(UUID.randomUUID()) val pageCountProperty = integerBinding(itemsPerPageProperty, sourceItems) { Math.max(1, Math.ceil(sourceItems.size.toDouble() / itemsPerPageProperty.value.toDouble()).toInt()) } val pageCount by pageCountProperty val currentPageProperty = SimpleIntegerProperty(1) var currentPage by currentPageProperty private val listChangeListener = ListChangeListener<T> { listChangeTrigger.value = UUID.randomUUID() setItemsForPage() // Check that the current page is still valid, or regenerate buttons while (currentPage > pageCount) currentPage -= 1 } private val currentFromIndex: Int get() = itemsPerPage * (currentPage - 1) private val currentToIndex: Int get() = Math.min(currentFromIndex + itemsPerPage, sourceItems.size) init { spacing = 5.0 alignment = Pos.CENTER currentPageProperty.onChange { setItemsForPage() } pageCountProperty.onChange { generatePageButtons() } sourceItems.addListener(listChangeListener) generatePageButtons() setItemsForPage() } private fun setItemsForPage() { items.setAll(sourceItems.subList(currentFromIndex, currentToIndex)) } private fun generatePageButtons() { children.clear() togglegroup { // TODO: Support pagination for pages IntRange(1, pageCount).forEach { pageNo -> // TODO: Allow customization of togglebutton graphic/text togglebutton(pageNo.toString()) { whenSelected { currentPage = pageNo } } } } } } @Suppress("unused") class DataGrid<T>(items: ObservableList<T>) : Control() { constructor() : this(FXCollections.observableArrayList()) constructor(items: List<T>) : this(FXCollections.observableArrayList(items)) private val FACTORY = StyleablePropertyFactory<DataGrid<T>>(Control.getClassCssMetaData()) internal var graphicCache = mutableMapOf<T, Node>() val itemsProperty = SimpleListProperty<T>(this, "items", items) var items: ObservableList<T> get() = itemsProperty.get(); set(value) = itemsProperty.set(value) val cellFactoryProperty = SimpleObjectProperty<(DataGrid<T>) -> DataGridCell<T>>(this, "cellFactory") var cellFactory: ((DataGrid<T>) -> DataGridCell<T>)? get() = cellFactoryProperty.get(); set(value) = cellFactoryProperty.set(value) val cellFormatProperty by lazy { SimpleObjectProperty<(DataGridCell<T>.(T) -> Unit)>() } var cellFormat: ((DataGridCell<T>).(T) -> Unit)? get() = cellFormatProperty.get(); set(value) = cellFormatProperty.set(value) fun cellFormat(cellFormat: (DataGridCell<T>).(T) -> Unit) { this.cellFormat = cellFormat } val scopeProperty = SimpleObjectProperty<Scope>() var scope: Scope? by scopeProperty val cellCacheProperty by lazy { SimpleObjectProperty<((T) -> Node)>() } var cellCache: ((T) -> Node)? get() = cellCacheProperty.get(); set(value) = cellCacheProperty.set(value) /** * Assign a Node to the graphic property of this cell. The graphic is cached and will be reused * for whatever cell is currently displaying the current item. Cells will in their life cycle be * used to display serveral different items, but using this function will make sure that there is * never a mismatch between the cached graphic node and the item it was created for. */ fun cellCache(cachedGraphic: (T) -> Node) { this.cellCache = cachedGraphic } val cellFragmentProperty by lazy { SimpleObjectProperty<KClass<DataGridCellFragment<T>>>() } var cellFragment by cellFragmentProperty fun cellFragment(fragment: KClass<DataGridCellFragment<T>>) { properties["tornadofx.cellFragment"] = fragment } inline fun <reified C : DataGridCellFragment<T>> cellFragment() { properties["tornadofx.cellFragment"] = C::class } val cellWidthProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "cellWidth", "-fx-cell-width", { it.cellWidthProperty }, 150.0) as StyleableObjectProperty<Number> var cellWidth: Double get() = cellWidthProperty.value as Double; set(value) { cellWidthProperty.value = value } val maxCellsInRowProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "maxCellsInRow", "-fx-max-cells-in-row", { it.maxCellsInRowProperty }, Int.MAX_VALUE) as StyleableObjectProperty<Number> var maxCellsInRow: Int get() = maxCellsInRowProperty.value.toInt(); set(value) { maxCellsInRowProperty.value = value } val maxRowsProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "maxRows", "-fx-max-rows", { it.maxRowsProperty }, Int.MAX_VALUE) as StyleableObjectProperty<Number> var maxRows: Int get() = maxRowsProperty.value.toInt(); set(value) { maxRowsProperty.value = value } val cellHeightProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "cellHeight", "-fx-cell-height", { it.cellHeightProperty }, 150.0) as StyleableObjectProperty<Number> var cellHeight: Double get() = cellHeightProperty.value as Double; set(value) { cellHeightProperty.value = value } val horizontalCellSpacingProperty: StyleableProperty<Number> = FACTORY.createStyleableNumberProperty(this, "horizontalCellSpacing", "-fx-horizontal-cell-spacing", { it.horizontalCellSpacingProperty }, 8.0) var horizontalCellSpacing: Double get() = horizontalCellSpacingProperty.value as Double; set(value) { horizontalCellSpacingProperty.value = value } val verticalCellSpacingProperty: StyleableProperty<Number> = FACTORY.createStyleableNumberProperty(this, "verticalCellSpacing", "-fx-vertical-cell-spacing", { it.verticalCellSpacingProperty }, 8.0) var verticalCellSpacing: Double get() = verticalCellSpacingProperty.value as Double; set(value) { verticalCellSpacingProperty.value = value } val selectionModel = DataGridSelectionModel(this) val focusModel = DataGridFocusModel(this) var singleSelect: Boolean get() = selectionModel.selectionMode == SINGLE; set(value) { selectionModel.selectionMode = if (value) SINGLE else MULTIPLE } var multiSelect: Boolean get() = selectionModel.selectionMode == MULTIPLE; set(value) { selectionModel.selectionMode = if (value) MULTIPLE else SINGLE } override fun createDefaultSkin() = DataGridSkin(this) override fun getUserAgentStylesheet(): String = DataGrid::class.java.getResource("datagrid.css").toExternalForm() override fun getControlCssMetaData(): MutableList<CssMetaData<out Styleable, *>>? = FACTORY.cssMetaData // Called when the items list changes structurally private val itemsChangeListener = InvalidationListener { selectionModel.clearSelectionAndReapply() (skin as? DataGridSkin<T>)?.handleControlPropertyChanged("ITEMS") } // Called when the items list is swapped for a new private val itemPropertyChangeListener = ChangeListener<ObservableList<T>> { _, oldList, newList -> selectionModel.clearSelectionAndReapply() if (oldList != null) { oldList.removeListener(itemsChangeListener) // Keep cache for elements in present in the new list oldList.filterNot { it in newList }.forEach { graphicCache.remove(it) } } else { graphicCache.clear() } newList.addListener(itemsChangeListener) (skin as? DataGridSkin<T>)?.handleControlPropertyChanged("ITEMS") } val selectedItem: T? get() = this.selectionModel.selectedItem fun onUserSelect(clickCount: Int = 2, action: (T) -> Unit) { val isSelected = { event: InputEvent -> !selectionModel.isEmpty } addEventFilter(MouseEvent.MOUSE_CLICKED) { event -> if (event.clickCount == clickCount && isSelected(event)) action(selectedItem!!) } addEventFilter(KeyEvent.KEY_PRESSED) { event -> if (event.code == KeyCode.ENTER && !event.isMetaDown && isSelected(event)) action(selectedItem!!) } } init { addClass(Stylesheet.datagrid) itemsProperty.addListener(itemPropertyChangeListener) items.addListener(itemsChangeListener) } } open class DataGridCell<T>(val dataGrid: DataGrid<T>) : IndexedCell<T>() { var cache: Node? = null var updating = false private var fresh = true private var cellFragment: DataGridCellFragment<T>? = null init { addClass(Stylesheet.datagridCell) // Update cell content when index changes indexProperty().onChange { if (it == -1) clearCellFragment() if (!updating) doUpdateItem() } } internal fun doUpdateItem() { val totalCount = dataGrid.items.size val item = if (index !in 0 until totalCount) null else dataGrid.items[index] val cacheProvider = dataGrid.cellCache if (item != null) { if (cacheProvider != null) cache = dataGrid.graphicCache.getOrPut(item, { cacheProvider(item) }) updateItem(item, false) } else { cache = null updateItem(null, true) } // Preemptive update of selected state val isActuallySelected = index in dataGrid.selectionModel.selectedIndices if (!isSelected && isActuallySelected) updateSelected(true) else if (isSelected && !isActuallySelected) updateSelected(false) } override fun updateItem(item: T?, empty: Boolean) { super.updateItem(item, empty) if (item == null || empty) { graphic = null text = null clearCellFragment() } else { val formatter = dataGrid.cellFormat if (fresh) { val cellFragmentType = dataGrid.properties["tornadofx.cellFragment"] as KClass<DataGridCellFragment<T>>? cellFragment = if (cellFragmentType != null) find(cellFragmentType, dataGrid.scope ?: DefaultScope) else null fresh = false } cellFragment?.apply { editingProperty.cleanBind(editingProperty()) itemProperty.value = item cellProperty.value = this@DataGridCell graphic = root } if (cache != null) { graphic = StackPane(cache) formatter?.invoke(this, item) } else { if (formatter != null) formatter.invoke(this, item) else if (graphic == null) graphic = StackPane(Label(item.toString())) } } } private fun clearCellFragment() { cellFragment?.apply { cellProperty.value = null itemProperty.value = null editingProperty.unbind() editingProperty.value = false } } override fun createDefaultSkin() = DataGridCellSkin(this) } abstract class DataGridCellFragment<T> : ItemFragment<T>() { val cellProperty: ObjectProperty<DataGridCell<T>?> = SimpleObjectProperty() var cell by cellProperty val editingProperty = SimpleBooleanProperty(false) val editing by editingProperty open fun startEdit() { cell?.startEdit() } open fun commitEdit(newValue: T) { cell?.commitEdit(newValue) } open fun cancelEdit() { cell?.cancelEdit() } open fun onEdit(op: () -> Unit) { editingProperty.onChange { if (it) op() } } } class DataGridCellBehavior<T>(control: DataGridCell<T>) : CellBehaviorBase<DataGridCell<T>>(control, emptyList()) { override fun getFocusModel() = control.dataGrid.focusModel override fun getCellContainer() = control override fun edit(cell: DataGridCell<T>?) { // No editing support for now } override fun getSelectionModel() = control.dataGrid.selectionModel override fun doSelect(x: Double, y: Double, button: MouseButton?, clickCount: Int, shiftDown: Boolean, shortcutDown: Boolean) { // I don't understand what the anchor is for yet, so to keep `focusedIndex = getAnchor(cellContainer, fm.getFocusedIndex())` // from returning something else than the currently focused index, I make sure "isDefaultAnchor" is set to true. // Must understand anchor and revisit this control.properties["isDefaultAnchor"] = true super.doSelect(x, y, button, clickCount, shiftDown, shortcutDown) } } class DataGridCellSkin<T>(control: DataGridCell<T>) : CellSkinBase<DataGridCell<T>, DataGridCellBehavior<T>>(control, DataGridCellBehavior(control)) class DataGridFocusModel<T>(val dataGrid: DataGrid<T>) : FocusModel<T>() { override fun getModelItem(index: Int) = if (index in 0 until itemCount) dataGrid.items[index] else null override fun getItemCount() = dataGrid.items.size } open class DataGridRow<T>(val dataGrid: DataGrid<T>, val dataGridSkin: DataGridSkin<T>) : IndexedCell<T>() { init { addClass(Stylesheet.datagridRow) // Report row as not empty when it's populated indexProperty().addListener(InvalidationListener { updateItem(null, index == -1) }) } override fun createDefaultSkin() = DataGridRowSkin(this) } class DataGridRowSkin<T>(control: DataGridRow<T>) : CellSkinBase<DataGridRow<T>, BehaviorBase<DataGridRow<T>>>(control, BehaviorBase(control, emptyList())) { init { // Remove default label from CellSkinBase children.clear() updateCells() registerChangeListener(skinnable.indexProperty(), "INDEX") registerChangeListener(skinnable.widthProperty(), "WIDTH") registerChangeListener(skinnable.heightProperty(), "HEIGHT") } override fun handleControlPropertyChanged(p: String) { super.handleControlPropertyChanged(p) when (p) { "INDEX" -> updateCells() "WIDTH" -> updateCells() "HEIGHT" -> updateCells() } } /** * This routine is copied from the GridView in ControlsFX. */ private fun updateCells() { val rowIndex = skinnable.index if (rowIndex > -1) { val dataGrid = skinnable.dataGrid val maxCellsInRow = (dataGrid.skin as DataGridSkin<*>).computeMaxCellsInRow() val totalCellsInGrid = dataGrid.items.size val startCellIndex = rowIndex * maxCellsInRow val endCellIndex = startCellIndex + maxCellsInRow - 1 var cacheIndex = 0 var cellIndex = startCellIndex while (cellIndex <= endCellIndex) { if (cellIndex < totalCellsInGrid) { var cell = getCellAtIndex(cacheIndex) if (cell == null) { cell = createCell() children.add(cell) } cell.updating = true cell.updateIndex(-1) cell.updating = false cell.updateIndex(cellIndex) } else { break }// we are going out of bounds -> exist the loop cellIndex++ cacheIndex++ } // In case we are re-using a row that previously had more cells than // this one, we need to remove the extra cells that remain children.remove(cacheIndex, children.size) } } private fun createCell() = skinnable.dataGrid.cellFactory?.invoke(skinnable.dataGrid) ?: DataGridCell<T>(skinnable.dataGrid) @Suppress("UNCHECKED_CAST") fun getCellAtIndex(index: Int): DataGridCell<T>? { if (index < children.size) return children[index] as DataGridCell<T>? return null } override fun computeMaxHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return dataGrid.cellHeight * (dataGrid.skin as DataGridSkin<*>).itemCount } override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return dataGrid.cellHeight + (dataGrid.verticalCellSpacing * 2) } override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return (dataGrid.cellWidth + dataGrid.horizontalCellSpacing * 2) * skinnable.dataGridSkin.computeMaxCellsInRow() } override fun layoutChildren(x: Double, y: Double, w: Double, h: Double) { val dataGrid = skinnable.dataGrid val cellWidth = dataGrid.cellWidth val cellHeight = dataGrid.cellHeight val horizontalCellSpacing = dataGrid.horizontalCellSpacing val verticalCellSpacing = dataGrid.verticalCellSpacing var xPos = 0.0 for (child in children) { child.resizeRelocate(xPos + horizontalCellSpacing, y + verticalCellSpacing, cellWidth, cellHeight) xPos += cellWidth + (horizontalCellSpacing * 2) } } } class DataGridSelectionModel<T>(val dataGrid: DataGrid<T>) : MultipleSelectionModel<T>() { private val selectedIndicies: ObservableList<Int> = FXCollections.observableArrayList() private val selectedItems: ObservableList<T> = FXCollections.observableArrayList() fun getCellAt(index: Int): DataGridCell<T>? { val skin = dataGrid.skin as DataGridSkin<T> val cellsPerRow = skin.computeMaxCellsInRow() val rowIndex = index / cellsPerRow val row = skin.getRow(rowIndex) ?: return null val indexInRow = index - (rowIndex * cellsPerRow) val children = row.childrenUnmodifiable return if (children.size > indexInRow) children[indexInRow] as DataGridCell<T>? else null } init { // Instead of attaching listeners to all cells, distribute selected status directly val selectedIndicesListener = ListChangeListener<Int> { c -> while (c.next()) { if (c.wasAdded()) c.addedSubList.forEach { index -> val cell = getCellAt(index) if (cell != null && !cell.isSelected) { cell.updating = true cell.updateSelected(true) cell.doUpdateItem() cell.updating = false } } if (c.wasRemoved()) c.removed.forEach { index -> val cell = getCellAt(index) if (cell != null && cell.isSelected) { cell.updating = true cell.updateSelected(false) cell.doUpdateItem() cell.updating = false } } } } selectedIndices.addListener(selectedIndicesListener) } override fun selectPrevious() { select(selectedIndex - 1) } override fun selectFirst() { select(0) } override fun selectLast() { select(dataGrid.items.lastIndex) } override fun getSelectedIndices() = selectedIndicies override fun clearAndSelect(index: Int) { selectedIndicies.clear() selectedItems.clear() select(index) } override fun getSelectedItems() = selectedItems override fun selectNext() { select(selectedIndex + 1) } override fun selectAll() { selectedIndicies.clear() selectedItems.clear() dataGrid.items.forEachIndexed { index, item -> selectedIndicies.add(index) selectedItems.add(item) } select(dataGrid.items.lastIndex) } override fun clearSelection(index: Int) { if (index in selectedIndicies) { selectedIndicies.remove(index) selectedItems.remove(dataGrid.items[index]) } if (selectedIndex == index) { selectedIndex = -1 selectedItem = null } } override fun clearSelection() { selectedIndicies.clear() selectedItems.clear() selectedItem = null selectedIndex = -1 } override fun isEmpty() = selectedIndicies.isEmpty() override fun selectIndices(index: Int, vararg indices: Int) { select(index) indices.forEach { select(it) } } override fun isSelected(index: Int) = index in selectedIndicies override fun select(obj: T) { val index = dataGrid.items.indexOf(obj) select(index) } override fun select(index: Int) { if (index !in dataGrid.items.indices) return selectedIndex = index selectedItem = dataGrid.items[index] if (selectionMode == SINGLE) { selectedIndicies.removeAll { it != index } selectedItems.removeAll { it != selectedItem } } if (index !in selectedIndicies) { selectedIndicies.add(index) selectedItems.add(selectedItem) dataGrid.focusModel.focus(index) } } /** * Clear selection and reapply for the items that are still in the list */ fun clearSelectionAndReapply() { val currentItems = selectedItems.toList() val currentIndexes = selectedIndicies.toList() val selectedItemsToIndex = (currentItems zip currentIndexes).toMap() clearSelection() for (item in currentItems) { val index = dataGrid.items.indexOf(item) if (index > -1) { select(index) } else { // If item is gone, select the item at the same index position select(selectedItemsToIndex[item]!!) } } } } @Suppress("UNCHECKED_CAST") class DataGridSkin<T>(control: DataGrid<T>) : VirtualContainerBase<DataGrid<T>, BehaviorBase<DataGrid<T>>, DataGridRow<T>>(control, BehaviorBase(control, emptyList())) { private val gridViewItemsListener = ListChangeListener<T> { updateRowCount() skinnable.requestLayout() } private val weakGridViewItemsListener = WeakListChangeListener(gridViewItemsListener) init { updateItems() flow.id = "virtual-flow" flow.isPannable = false flow.isFocusTraversable = false flow.setCreateCell { createCell() } children.add(flow) updateRowCount() registerChangeListener(control.itemsProperty, "ITEMS") registerChangeListener(control.cellFactoryProperty, "CELL_FACTORY") registerChangeListener(control.parentProperty(), "PARENT") registerChangeListener(control.cellHeightProperty as ObservableValue<Number>, "CELL_HEIGHT") registerChangeListener(control.cellWidthProperty as ObservableValue<Number>, "CELL_WIDTH") registerChangeListener(control.horizontalCellSpacingProperty as ObservableValue<Number>, "HORIZONZAL_CELL_SPACING") registerChangeListener(control.verticalCellSpacingProperty as ObservableValue<Number>, "VERTICAL_CELL_SPACING") registerChangeListener(control.widthProperty(), "WIDTH_PROPERTY") registerChangeListener(control.heightProperty(), "HEIGHT_PROPERTY") focusOnClick() } private fun focusOnClick() { skinnable.addEventFilter(MouseEvent.MOUSE_PRESSED) { if (!skinnable.isFocused && skinnable.isFocusTraversable) skinnable.requestFocus() } } override public fun handleControlPropertyChanged(p: String?) { super.handleControlPropertyChanged(p) when (p) { "ITEMS" -> updateItems() "CELL_FACTORY" -> flow.recreateCells() "CELL_HEIGHT" -> flow.recreateCells() "CELL_WIDTH" -> { updateRowCount() flow.recreateCells() } "HORIZONZAL_CELL_SPACING" -> { updateRowCount() flow.recreateCells() } "VERTICAL_CELL_SPACING" -> flow.recreateCells() "PARENT" -> { if (skinnable.parent != null && skinnable.isVisible) skinnable.requestLayout() } "WIDTH_PROPERTY" -> updateRowCount() "HEIGHT_PROPERTY" -> updateRowCount() } } override fun getItemCount() = Math.ceil(skinnable.items.size.toDouble() / computeMaxCellsInRow()).toInt() /** * Compute the maximum number of cells per row. If the calculated number of cells would result in * more than the configured maxRow rows, the maxRow setting takes presedence and overrides the maxCellsInRow */ fun computeMaxCellsInRow(): Int { val maxCellsInRow = Math.min(Math.max(Math.floor(computeRowWidth() / computeCellWidth()).toInt(), 1), skinnable.maxCellsInRow) val neededRows = Math.ceil(skinnable.items.size.toDouble() / maxCellsInRow) return if (neededRows > skinnable.maxRows) (skinnable.items.size.toDouble() / skinnable.maxRows).toInt() else maxCellsInRow } fun computeRowWidth() = skinnable.width + 14 // Account for scrollbar private fun computeCellWidth() = skinnable.cellWidth + skinnable.horizontalCellSpacing * 2 override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = 500.0 override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = 500.0 override fun updateRowCount() { if (flow == null) return val oldCount = flow.cellCount val newCount = itemCount if (newCount != oldCount) { flow.cellCount = newCount flow.rebuildCells() } else { flow.reconfigureCells() } updateRows(newCount) } override fun createCell() = DataGridRow(skinnable, this) private fun updateItems() { skinnable.items.removeListener(weakGridViewItemsListener) skinnable.items.addListener(weakGridViewItemsListener) updateRowCount() flow.recreateCells() skinnable.requestLayout() } private fun updateRows(rowCount: Int) { for (i in 0..rowCount - 1) getRow(i)?.updateIndex(i) } fun getRow(index: Int) = flow.getVisibleCell(index) override fun layoutChildren(x: Double, y: Double, w: Double, h: Double) { val x1 = skinnable.insets.left val y1 = skinnable.insets.top val w1 = skinnable.width - (skinnable.insets.left + skinnable.insets.right) val h1 = skinnable.height - (skinnable.insets.top + skinnable.insets.bottom) flow.resizeRelocate(x1, y1, w1, h1) } } fun <T> DataGrid<T>.bindSelected(property: Property<T>) { selectionModel.selectedItemProperty().onChange { property.value = it } } fun <T> DataGrid<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty) fun <T> DataGrid<T>.asyncItems(func: () -> Collection<T>) = task { func() } success { items.setAll(it) }
apache-2.0
d9172f4d20b780db899412c7d2edb8ae
37.052425
229
0.652821
4.591082
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/creator/CreatorStep.kt
1
4938
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.creator import com.demonwav.mcdev.creator.buildsystem.BuildSystem import com.demonwav.mcdev.creator.buildsystem.DirectorySet import com.demonwav.mcdev.util.runWriteTask import com.demonwav.mcdev.util.virtualFileOrError import com.intellij.codeInsight.actions.ReformatCodeProcessor import com.intellij.ide.util.EditorHelper import com.intellij.openapi.application.runReadAction import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.util.createSmartPointer import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardOpenOption.CREATE import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING import java.nio.file.StandardOpenOption.WRITE /** * Represents a discrete kind of configuration code for a project. Project creators use these to spread implementation * out between platforms without coupling them, and allow overriding for more complex options for specific build systems * without coupling the build system and the platform. */ interface CreatorStep { fun runStep(indicator: ProgressIndicator) companion object { private val scheduledReformats: MutableList<SmartPsiElementPointer<PsiFile>> = mutableListOf() fun runAllReformats() { runWriteTask { for (scheduledReformat in scheduledReformats) { val file = scheduledReformat.element ?: continue PsiDocumentManager.getInstance(file.project).getDocument(file)?.setReadOnly(false) ReformatCodeProcessor(file, false).run() } } scheduledReformats.clear() } fun writeTextToFile( project: Project, targetDir: Path, fileName: String, text: String ): VirtualFile { if (Files.notExists(targetDir)) { Files.createDirectories(targetDir) } val file = targetDir.resolve(fileName) Files.write(file, text.toByteArray(Charsets.UTF_8), WRITE, CREATE, TRUNCATE_EXISTING) val vFile = file.virtualFileOrError // Reformat the code to match their code style runReadAction { if (project.isDisposed) { return@runReadAction } PsiManager.getInstance(project).findFile(vFile)?.let { scheduledReformats += it.createSmartPointer() } } return vFile } fun writeText(file: Path, text: String, psiManager: PsiManager? = null) { Files.write(file, text.toByteArray(Charsets.UTF_8), CREATE, TRUNCATE_EXISTING, WRITE) psiManager?.findFile(file.virtualFileOrError)?.let { PsiDocumentManager.getInstance(psiManager.project).getDocument(it)?.setReadOnly(false) ReformatCodeProcessor(it, false).run() } } } } class BasicJavaClassStep( private val project: Project, private val buildSystem: BuildSystem, private val className: String, private val classText: String, private val openInEditor: Boolean = true, private val rootProvider: (BuildSystem) -> Path = { it.dirsOrError.sourceDirectory } ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { runWriteTask { indicator.text = "Writing class: $className" val files = className.split(".") val className = files.last() val sourceDir = getMainClassDirectory(rootProvider(buildSystem), files) val classFile = CreatorStep.writeTextToFile(project, sourceDir, "$className.java", classText) if (openInEditor) { // Set the editor focus on the created class PsiManager.getInstance(project).findFile(classFile)?.let { classPsi -> EditorHelper.openInEditor(classPsi) } } } } private fun getMainClassDirectory(dir: Path, files: List<String>): Path { val directories = files.slice(0 until files.lastIndex).toTypedArray() val outputDir = Paths.get(dir.toAbsolutePath().toString(), *directories) Files.createDirectories(outputDir) return outputDir } } class CreateDirectoriesStep(private val buildSystem: BuildSystem, private val directory: Path) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { buildSystem.directories = DirectorySet.create(directory) } }
mit
ee26e36d4794c36133e981af11ccd929
36.409091
120
0.673147
4.987879
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/pub/room/ChatRoomAdapter.kt
1
2596
package me.proxer.app.chat.pub.room import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.widget.AppCompatTextView import androidx.core.view.isGone import androidx.core.view.isVisible import com.gojuno.koptional.rxjava2.filterSome import com.gojuno.koptional.toOptional import com.jakewharton.rxbinding3.view.clicks import com.uber.autodispose.autoDisposable import io.reactivex.subjects.PublishSubject import kotterknife.bindView import me.proxer.app.R import me.proxer.app.base.AutoDisposeViewHolder import me.proxer.app.base.BaseAdapter import me.proxer.app.chat.pub.room.ChatRoomAdapter.ViewHolder import me.proxer.app.util.extension.fastText import me.proxer.app.util.extension.linkClicks import me.proxer.app.util.extension.linkify import me.proxer.app.util.extension.mapAdapterPosition import me.proxer.app.util.extension.toPrefixedUrlOrNull import me.proxer.library.entity.chat.ChatRoom import okhttp3.HttpUrl /** * @author Ruben Gees */ class ChatRoomAdapter : BaseAdapter<ChatRoom, ViewHolder>() { val clickSubject: PublishSubject<ChatRoom> = PublishSubject.create() val linkClickSubject: PublishSubject<HttpUrl> = PublishSubject.create() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_chat_room, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(data[position]) } inner class ViewHolder(view: View) : AutoDisposeViewHolder(view) { internal val container: ViewGroup by bindView(R.id.container) internal val nameView by bindView<TextView>(R.id.name) internal val topic by bindView<AppCompatTextView>(R.id.topic) fun bind(item: ChatRoom) { container.clicks() .mapAdapterPosition({ adapterPosition }) { data[it] } .autoDisposable(this) .subscribe(clickSubject) topic.linkClicks() .map { it.toPrefixedUrlOrNull().toOptional() } .filterSome() .autoDisposable(this) .subscribe(linkClickSubject) nameView.text = item.name if (item.topic.isBlank()) { topic.isGone = true topic.text = item.topic } else { topic.isVisible = true topic.fastText = item.topic.trim().linkify(mentions = false) } } } }
gpl-3.0
f139cdd2b926918780e5e1e2cb277d56
34.561644
110
0.704931
4.437607
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/psi/search/LuaOverridenMethodsSearchExecutor.kt
2
1960
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.psi.search import com.intellij.openapi.progress.ProgressManager import com.intellij.util.Processor import com.intellij.util.QueryExecutor import com.tang.intellij.lua.psi.LuaClassMethod import com.tang.intellij.lua.psi.guessClassType import com.tang.intellij.lua.search.SearchContext import com.tang.intellij.lua.stubs.index.LuaClassMemberIndex import com.tang.intellij.lua.ty.TyClass class LuaOverridenMethodsSearchExecutor : QueryExecutor<LuaClassMethod, LuaOverridenMethodsSearch.SearchParameters> { override fun execute(searchParameters: LuaOverridenMethodsSearch.SearchParameters, processor: Processor<in LuaClassMethod>): Boolean { val method = searchParameters.method val project = method.project val context = SearchContext.get(project) val type = method.guessClassType(context) val methodName = method.name if (type != null && methodName != null) { TyClass.processSuperClass(type, context) { superType-> ProgressManager.checkCanceled() val superTypeName = superType.className val superMethod = LuaClassMemberIndex.findMethod(superTypeName, methodName, context) if (superMethod == null) true else processor.process(superMethod) } } return false } }
apache-2.0
f9b4c735893194abb1845d0baae4cc35
42.577778
138
0.734184
4.454545
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/aliexpress/dto/AliexpressPromoCard.kt
1
2176
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.aliexpress.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseLinkButton import com.vk.sdk.api.photos.dto.PhotosPhoto import kotlin.Int import kotlin.String /** * @param icon - Card icon * @param title - Card title * @param subtitle - Card text * @param cardPosition - Position of card in items set * @param actionButton - Action button url */ data class AliexpressPromoCard( @SerializedName("icon") val icon: PhotosPhoto? = null, @SerializedName("title") val title: String? = null, @SerializedName("subtitle") val subtitle: String? = null, @SerializedName("card_position") val cardPosition: Int? = null, @SerializedName("action_button") val actionButton: BaseLinkButton? = null )
mit
3583588d683d4ea07deafd55825c11bf
39.296296
81
0.690717
4.387097
false
false
false
false
VKCOM/vk-android-sdk
core/src/main/java/com/vk/api/sdk/okhttp/EmojiLoggingPrefixer.kt
1
730
package com.vk.api.sdk.okhttp import java.util.concurrent.atomic.AtomicInteger /** * Create emoji prefix for api logging * Maps into [com.vk.api.sdk.okhttp.LoggingPrefixer] **/ class EmojiLoggingPrefixer : LoggingPrefixer { private val id = AtomicInteger(0) /** * @return emoji in a range from [startEmoji] to [endEmoji] **/ override fun getPrefix(): String { val offset = id.getAndIncrement() % EMOJI_COUNT return String(Character.toChars(START_EMOJI + offset)) } companion object { private const val START_EMOJI: Int = 129292 // 🤌 private const val END_EMOJI: Int = 129535 // 🧿 private const val EMOJI_COUNT = END_EMOJI - START_EMOJI + 1 } }
mit
375ced45177e30f9ae36b5b57c993f62
28
67
0.65884
3.810526
false
false
false
false
teobaranga/T-Tasks
t-tasks/src/main/java/com/teo/ttasks/util/RxUtils.kt
1
3745
package com.teo.ttasks.util import com.teo.ttasks.data.model.Task import com.teo.ttasks.ui.items.TaskItem import io.reactivex.Flowable import io.reactivex.FlowableTransformer import io.reactivex.SingleTransformer import java.util.* import kotlin.collections.ArrayList object RxUtils { /** * 1. Creates [TaskItem]s from [Task]s<br></br> * 2. Groups them by completion status (not completed or no due date first followed by completed ones)<br></br> * 3. Sorts the first group by due date and the second group by completion date */ fun getTaskItems(hideCompleted: Boolean): SingleTransformer<List<Task>, List<TaskItem>> = SingleTransformer { observable -> observable .map { tasks -> val taskItems = ArrayList<TaskItem>() val activeTasks = ArrayList<TaskItem>() val completedTasks = ArrayList<TaskItem>() for (task in tasks) { if (task.completedDate == null) { // Active task activeTasks.add(TaskItem(task, TaskType.ACTIVE)) } else if (!hideCompleted) { // Completed task completedTasks.add(TaskItem(task, TaskType.COMPLETED)) } } // Sort active tasks by due date in descending order activeTasks.sort() taskItems.addAll(activeTasks) if (!hideCompleted) { Collections.sort(completedTasks, TaskItem.completionDateComparator) if (completedTasks.size > 0) { taskItems.addAll(completedTasks) } } return@map taskItems } } fun getTaskItems(sortingMode: SortType): FlowableTransformer<List<Task>, Pair<TaskType, List<Task>>> = FlowableTransformer { observable -> observable .flatMap { tasks -> val activeTasks = ArrayList<Task>(tasks.size) val completedTasks = ArrayList<Task>(tasks.size) for (task in tasks) { if (task.completedDate == null) { // Active task activeTasks.add(task) } else { // Completed task completedTasks.add(task) } } when (sortingMode) { SortType.SORT_DATE -> { // Sort active tasks by due date in ascending order // activeTasks.sort() // Sort completed tasks by completion date in descending order // completedTasks.sortWith(TaskItem.completionDateComparator) } SortType.SORT_ALPHA -> { // activeTasks.sortWith(TaskItem.alphabeticalComparator) // completedTasks.sortWith(TaskItem.alphabeticalComparator) } SortType.SORT_CUSTOM -> { // Do nothing } } return@flatMap Flowable.just( Pair(TaskType.ACTIVE, activeTasks.toList()), Pair(TaskType.COMPLETED, completedTasks.toList()), Pair(TaskType.EOT, emptyList()) ) } } }
apache-2.0
11f3723e92801c13904ce5efb9286234
40.153846
115
0.477704
5.925633
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/account/dto/AccountPushParams.kt
1
3593
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.account.dto import com.google.gson.annotations.SerializedName import kotlin.collections.List /** * @param msg * @param chat * @param like * @param repost * @param comment * @param mention * @param reply * @param newPost * @param wallPost * @param wallPublish * @param friend * @param friendFound * @param friendAccepted * @param groupInvite * @param groupAccepted * @param birthday * @param eventSoon * @param appRequest * @param sdkOpen */ data class AccountPushParams( @SerializedName("msg") val msg: List<AccountPushParamsMode>? = null, @SerializedName("chat") val chat: List<AccountPushParamsMode>? = null, @SerializedName("like") val like: List<AccountPushParamsSettings>? = null, @SerializedName("repost") val repost: List<AccountPushParamsSettings>? = null, @SerializedName("comment") val comment: List<AccountPushParamsSettings>? = null, @SerializedName("mention") val mention: List<AccountPushParamsSettings>? = null, @SerializedName("reply") val reply: List<AccountPushParamsOnoff>? = null, @SerializedName("new_post") val newPost: List<AccountPushParamsOnoff>? = null, @SerializedName("wall_post") val wallPost: List<AccountPushParamsOnoff>? = null, @SerializedName("wall_publish") val wallPublish: List<AccountPushParamsOnoff>? = null, @SerializedName("friend") val friend: List<AccountPushParamsOnoff>? = null, @SerializedName("friend_found") val friendFound: List<AccountPushParamsOnoff>? = null, @SerializedName("friend_accepted") val friendAccepted: List<AccountPushParamsOnoff>? = null, @SerializedName("group_invite") val groupInvite: List<AccountPushParamsOnoff>? = null, @SerializedName("group_accepted") val groupAccepted: List<AccountPushParamsOnoff>? = null, @SerializedName("birthday") val birthday: List<AccountPushParamsOnoff>? = null, @SerializedName("event_soon") val eventSoon: List<AccountPushParamsOnoff>? = null, @SerializedName("app_request") val appRequest: List<AccountPushParamsOnoff>? = null, @SerializedName("sdk_open") val sdkOpen: List<AccountPushParamsOnoff>? = null )
mit
fd04f66d993f57c20092a51a7e42f9fb
37.634409
81
0.698859
4.19743
false
false
false
false
ZieIony/Carbon
component/src/main/java/carbon/component/AvatarTextSubtextDateItem.kt
1
1986
package carbon.component import android.graphics.drawable.Drawable import android.view.ViewGroup import carbon.component.databinding.CarbonRowAvatartextsubtext2dateBinding import carbon.component.databinding.CarbonRowAvatartextsubtextdateBinding import java.io.Serializable interface AvatarTextSubtextDateItem : Serializable { val avatar: Drawable? val text: String? val subtext: String? val date: String? } open class DefaultAvatarTextSubtextDateItem : AvatarTextSubtextDateItem { override var avatar: Drawable? = null override var text: String? = null override var subtext: String? = null override var date: String? = null constructor() constructor(avatar: Drawable, text: String, subtext: String, date: String) { this.avatar = avatar this.text = text this.subtext = subtext this.date = date } } open class AvatarTextSubtextDateRow<Type : AvatarTextSubtextDateItem>(parent: ViewGroup) : LayoutComponent<Type>(parent, R.layout.carbon_row_avatartextsubtextdate) { private val binding = CarbonRowAvatartextsubtextdateBinding.bind(view) override fun bind(data: Type) { binding.carbonAvatar.setImageDrawable(data.avatar) binding.carbonDate.text = data.date ?: "" binding.carbonText.text = data.text ?: "" binding.carbonSubtext.text = data.subtext ?: "" binding.carbonMarker2.text = data.subtext } } open class AvatarTextSubtext2DateRow<Type : AvatarTextSubtextDateItem>(parent: ViewGroup) : LayoutComponent<Type>(parent, R.layout.carbon_row_avatartextsubtext2date) { private val binding = CarbonRowAvatartextsubtext2dateBinding.bind(view) override fun bind(data: Type) { binding.carbonAvatar.setImageDrawable(data.avatar) binding.carbonDate.text = data.date ?: "" binding.carbonText.text = data.text ?: "" binding.carbonSubtext.text = data.subtext ?: "" binding.carbonMarker2.text = data.subtext } }
apache-2.0
23441d0e26108a9df4a7d8cf675904bf
35.777778
167
0.730111
3.863813
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt
3
2194
package info.nightscout.androidaps.plugins.pump.common.bolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.utils.T import org.slf4j.LoggerFactory import java.util.* import kotlin.math.abs object DetailedBolusInfoStorage { private val log = LoggerFactory.getLogger(L.PUMP) val store = ArrayList<DetailedBolusInfo>() @Synchronized fun add(detailedBolusInfo: DetailedBolusInfo) { log.debug("Stored bolus info: $detailedBolusInfo") store.add(detailedBolusInfo) } @Synchronized fun findDetailedBolusInfo(bolusTime: Long, bolus: Double): DetailedBolusInfo? { // Look for info with bolus for (i in store.indices) { val d = store[i] if (L.isEnabled(L.PUMP)) log.debug("Existing bolus info: " + store[i]) if (bolusTime > d.date - T.mins(1).msecs() && bolusTime < d.date + T.mins(1).msecs() && abs(store[i].insulin - bolus) < 0.01) { if (L.isEnabled(L.PUMP)) log.debug("Using & removing bolus info: ${store[i]}") store.removeAt(i) return d } } // If not found use time only for (i in store.indices) { val d = store[i] if (bolusTime > d.date - T.mins(1).msecs() && bolusTime < d.date + T.mins(1).msecs() && bolus <= store[i].insulin + 0.01) { if (L.isEnabled(L.PUMP)) log.debug("Using TIME-ONLY & removing bolus info: ${store[i]}") store.removeAt(i) return d } } // If not found, use last record if amount is the same if (store.size > 0) { val d = store[store.size - 1] if (abs(d.insulin - bolus) < 0.01) { if (L.isEnabled(L.PUMP)) log.debug("Using LAST & removing bolus info: $d") store.removeAt(store.size - 1) return d } } //Not found if (L.isEnabled(L.PUMP)) log.debug("Bolus info not found") return null } }
agpl-3.0
87d713c2c5e35bf55ae359264f3ab583
36.20339
139
0.557885
4.070501
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/utils.kt
1
3137
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.descriptors import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.serialization.deserialization.descriptors.* import org.jetbrains.kotlin.serialization.KonanLinkData import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.types.KotlinType fun ClassDescriptor?.getter2Descriptor(methodName: Name) = this?.let { this.unsubstitutedMemberScope.getContributedDescriptors{true} .firstOrNull { it.name == methodName } ?.let { return@let (it as? PropertyDescriptor)?.getter } } fun ClassDescriptor?.signature2Descriptor(methodName: Name, signature:Array<KotlinType> = emptyArray()) = this?.let { this .unsubstitutedMemberScope .getContributedFunctions(methodName, NoLookupLocation.FROM_BACKEND) .firstOrNull { return@firstOrNull it.valueParameters.size == signature.size && (signature.isEmpty() || it.valueParameters.any { p -> val index = it.valueParameters.indexOf(p) return@any p.type == signature[index] }) } } val DeserializedPropertyDescriptor.backingField: PropertyDescriptor? get() = if (this.proto.getExtension(KonanLinkData.hasBackingField)) this else null fun DeclarationDescriptor.deepPrint() { this.accept(DeepPrintVisitor(PrintVisitor()), 0) } internal val String.synthesizedName get() = Name.identifier(this.synthesizedString) internal val String.synthesizedString get() = "\$$this" internal val DeclarationDescriptor.propertyIfAccessor get() = if (this is PropertyAccessorDescriptor) this.correspondingProperty else this internal val CallableMemberDescriptor.propertyIfAccessor get() = if (this is PropertyAccessorDescriptor) this.correspondingProperty else this internal val FunctionDescriptor.deserializedPropertyIfAccessor: DeserializedCallableMemberDescriptor get() { val member = this.propertyIfAccessor if (member is DeserializedCallableMemberDescriptor) return member else error("Unexpected deserializable callable descriptor") } internal val CallableMemberDescriptor.isDeserializableCallable get () = (this.propertyIfAccessor is DeserializedCallableMemberDescriptor)
apache-2.0
41822aa50fa223a59178dd4f70f9d7ba
35.476744
117
0.715014
4.979365
false
false
false
false
hotmobmobile/hotmob-android-sdk
AndroidStudio/HotmobSDKShowcase/app/src/main/java/com/hotmob/sdk/hotmobsdkshowcase/datacollection/DataCollectionFragment.kt
1
1698
package com.hotmob.sdk.hotmobsdkshowcase.datacollection import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.hotmob.sdk.module.datacollection.HotmobDataCollection import com.hotmob.sdk.hotmobsdkshowcase.databinding.FragmentDataCollectionBinding import com.hotmob.sdk.module.reload.HotmobReloadManager import java.util.HashMap /** * A simple [Fragment] subclass. * */ class DataCollectionFragment : androidx.fragment.app.Fragment() { private var _binding: FragmentDataCollectionBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment _binding = FragmentDataCollectionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.sendEventButton.setOnClickListener { val dataMap = HashMap<String, Any>() dataMap["param1"] = "ABC" dataMap["param2"] = "EFG" dataMap["param3"] = "123" HotmobDataCollection.captureEvent( context!!, "test_user_click", dataMap ) } HotmobReloadManager } override fun onStart() { super.onStart() HotmobDataCollection.captureEvent( context!!, "test_user_action", "enter_page" ) } }
mit
711dca923f7451e869978f6debfd55ca
28.275862
84
0.661366
4.664835
false
false
false
false
android/performance-samples
MacrobenchmarkSample/macrobenchmark/src/main/java/com/example/macrobenchmark/startup/SampleStartupBenchmark.kt
1
1694
/* * 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 com.example.macrobenchmark.startup import androidx.benchmark.macro.StartupTimingMetric import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.example.benchmark.macro.base.util.DEFAULT_ITERATIONS import com.example.benchmark.macro.base.util.TARGET_PACKAGE import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith // [START macrobenchmark_startup] @LargeTest @RunWith(AndroidJUnit4::class) class SampleStartupBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun startup() = benchmarkRule.measureRepeated( packageName = TARGET_PACKAGE, metrics = listOf(StartupTimingMetric()), iterations = DEFAULT_ITERATIONS, setupBlock = { // Press home button before each run to ensure the starting activity isn't visible. pressHome() } ) { // starts default launch activity startActivityAndWait() } } // [END macrobenchmark_startup]
apache-2.0
05b4e5afc82dd9f207684cc17e21d7e0
32.88
95
0.738489
4.422977
false
true
false
false
mtzaperas/burpbuddy
src/main/kotlin/burp/HttpListener.kt
1
1666
package burp import com.github.kittinunf.fuel.Fuel import javax.swing.JTextField import javax.swing.JToggleButton class HttpListener(val requestHooksTextField: JTextField, val responseHooksTextField: JTextField, val requestHooksButton: JToggleButton, val responseHooksButton: JToggleButton, val callbacks: IBurpExtenderCallbacks): IHttpListener { override fun processHttpMessage(toolFlag: Int, messageIsRequest: Boolean, messageInfo: IHttpRequestResponse) { val b2b = BurpToBuddy(callbacks) val httpRequestResponse = messageInfo val reqHookURLs = requestHooksTextField.text.split(",") val resHookURLs = responseHooksTextField.text.split(",") if (!requestHooksButton.isSelected && messageIsRequest && reqHookURLs.size > 0) { val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse) jsonHttpRequestResponse.addProperty("tool", toolFlag) jsonHttpRequestResponse.remove("response") reqHookURLs.forEach{ Fuel.Companion.post(it). body(jsonHttpRequestResponse.toString()).response() } } else if (!responseHooksButton.isSelected && resHookURLs.size > 0) { val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse) jsonHttpRequestResponse.addProperty("tool", toolFlag) jsonHttpRequestResponse.remove("request") resHookURLs.forEach{ Fuel.Companion.post(it). body(jsonHttpRequestResponse.toString()).response() } } } }
mit
6e6d6abdff648a556f04dddcf0169550
44.054054
114
0.683073
5.079268
false
false
false
false
GlenKPeterson/TestUtils
src/main/java/org/organicdesign/testUtils/string/StringDiff.kt
1
2734
package org.organicdesign.testUtils.string object StringDiff { // TODO: Make this work with actual Unicode characters instead of the weird way Strings work today. /** * Takes two strings and returns the different middle section which could be * - Two empty strings (no difference) * - an empty string and a non-empty string (a deletion or addition) * - Two strings (the changed part). * * This works by finding exact matches from the beginning and the end of the string, then returning * everything inbetween. */ @JvmStatic fun differentMiddle( s1: String, s2: String ): DiffResult { var firstDiffIdx = 0 val s1Len = s1.length val s2Len = s2.length while ( (firstDiffIdx < s1Len) && (firstDiffIdx < s2Len) ) { // println("firstDiffIdx: $firstDiffIdx") // If this char is different: if (s1[firstDiffIdx] != s2[firstDiffIdx]) { // println("Different! ${s1[firstDiffIdx]} != ${s2[firstDiffIdx]}") var lastDiffIdxS1 = s1Len - 1 var lastDiffIdxS2 = s2Len - 1 // Find similar part at end of string while ( (lastDiffIdxS1 >= firstDiffIdx) && (lastDiffIdxS2 >= firstDiffIdx) ) { // println("lastDiffIdxS1 = $lastDiffIdxS1 lastDiffIdxS2 = $lastDiffIdxS2") // println("Reverse diff: ${s1[lastDiffIdxS1]} vs. ${s2[lastDiffIdxS2]}") // Found similar part at end of string - return different middle if (s1[lastDiffIdxS1] != s2[lastDiffIdxS2]) { // println("Only middle was different") return DiffResult(s1.substring(firstDiffIdx, lastDiffIdxS1 + 1), s2.substring(firstDiffIdx, lastDiffIdxS2 + 1)) } lastDiffIdxS1 -= 1 lastDiffIdxS2 -= 1 } // Whole end of string was similar // println("Whole end of string was similar") return DiffResult(s1.substring(firstDiffIdx, lastDiffIdxS1 + 1), s2.substring(firstDiffIdx, lastDiffIdxS2 + 1)) } firstDiffIdx += 1 } return if (s1Len == s2Len) { // println("no diff") DiffResult.IDENTICAL } else { // println("returning") return DiffResult(s1.substring(firstDiffIdx), s2.substring(firstDiffIdx)) } } }
apache-2.0
c2c33056ede37ce2e54d9559c9e1f150
37.521127
104
0.51902
4.27856
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquireResponsePacket.kt
1
1904
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * InjectionSnackInquireResponsePacket */ class InjectionSnackInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump init { msgType = 0x87.toByte() aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackInquireResponsePacket init") } override fun handleMessage(data: ByteArray?) { val result = defect(data) if (result != 0) { aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackInquireResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) val result2 = getByteToInt(bufferData) if(!isSuccInquireResponseResult(result2)) { failed = true return } diaconnG8Pump.snackStatus = getByteToInt(bufferData) //주입상태 diaconnG8Pump.snackAmount = getShortToInt(bufferData) / 100.0 // 주입설정량 diaconnG8Pump.snackInjAmount = getShortToInt(bufferData) / 100.0 // 현재주입량 diaconnG8Pump.snackSpeed = getByteToInt(bufferData) //주입속도 aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result2") aapsLogger.debug(LTag.PUMPCOMM, "snackStatus > " + diaconnG8Pump.snackStatus) aapsLogger.debug(LTag.PUMPCOMM, "snackAmount > " + diaconnG8Pump.snackAmount) aapsLogger.debug(LTag.PUMPCOMM, "snackInjAmount > " + diaconnG8Pump.snackInjAmount) aapsLogger.debug(LTag.PUMPCOMM, "snackSpeed > " + diaconnG8Pump.snackSpeed) } override fun getFriendlyName(): String { return "PUMP_INJECTION_SNACK_INQUIRE_RESPONSE" } }
agpl-3.0
d5f935523b145edd356868a8c3331df2
35.647059
102
0.698608
4.141907
false
false
false
false
santoslucas/guarda-filme-android
app/src/main/java/com/guardafilme/ui/searchmovie/SearchMovieAdapter.kt
1
2146
package com.guardafilme.ui.searchmovie import android.content.Context import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.item_movie.view.* import com.guardafilme.R import com.guardafilme.model.Movie import com.guardafilme.ui.UiUtils /** * Created by lucassantos on 11/10/17. */ class SearchMovieAdapter( private val context: Context, private val onMovieSelected: (movie: Movie, watchedDate: Long, rate: Float) -> Unit ): RecyclerView.Adapter<SearchMovieAdapter.SearchMovieViewHolder>() { var movies: List<Movie> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchMovieViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_movie, parent, false) return SearchMovieViewHolder(itemView) } override fun onBindViewHolder(holder: SearchMovieViewHolder, position: Int) { holder.bindItem(movies[position], context, onMovieSelected) } override fun getItemCount(): Int { return movies.size } fun setItems(movieItems: List<Movie>) { movies = movieItems notifyDataSetChanged() } class SearchMovieViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { fun bindItem( movie: Movie, context: Context, onMovieSelected: (movie: Movie, watchedDate: Long, rate: Float) -> Unit ) { itemView.title_text_view.text = movie.title itemView.year_text_view.text = movie.year itemView.setOnClickListener { UiUtils.showDatePickerDialog(context, { watchedDate -> UiUtils.showRateDialog(context, { rate -> Log.d("Teste", "MAOE " + rate.toString()) onMovieSelected(movie, watchedDate, rate) }, { onMovieSelected(movie, watchedDate, 0F) }) }) } } } }
gpl-3.0
02090616c038017f44b71221e8358965
31.044776
102
0.642125
4.556263
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildEntityImpl.kt
3
8446
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildEntityImpl: ChildEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _childData: String? = null override val childData: String get() = _childData!! override val parentEntity: ParentEntity get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildEntityData?): ModifiableWorkspaceEntityBase<ChildEntity>(), ChildEntity.Builder { constructor(): this(ChildEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isChildDataInitialized()) { error("Field ChildEntity#childData should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field ChildEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var childData: String get() = getEntityData().childData set(value) { checkModificationAllowed() getEntityData().childData = value changedProperty.add("childData") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: ParentEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): ChildEntityData = result ?: super.getEntityData() as ChildEntityData override fun getEntityClass(): Class<ChildEntity> = ChildEntity::class.java } } class ChildEntityData : WorkspaceEntityData<ChildEntity>() { lateinit var childData: String fun isChildDataInitialized(): Boolean = ::childData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildEntity> { val modifiable = ChildEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildEntity { val entity = ChildEntityImpl() entity._childData = childData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildEntityData if (this.childData != other.childData) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildEntityData if (this.childData != other.childData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childData.hashCode() return result } }
apache-2.0
48792ade6df3844ffaa7cea56ca122e3
38.84434
181
0.620175
5.985826
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl-tooling-builders/src/main/kotlin/org/gradle/kotlin/dsl/tooling/builders/KotlinBuildScriptTemplateModelBuilder.kt
3
2018
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.tooling.builders import org.gradle.tooling.provider.model.ToolingModelBuilder import org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptTemplateModel import org.gradle.api.Project import org.gradle.api.internal.classpath.ModuleRegistry import org.gradle.internal.classpath.ClassPath import org.gradle.kotlin.dsl.support.serviceOf import java.io.File import java.io.Serializable internal object KotlinBuildScriptTemplateModelBuilder : ToolingModelBuilder { private val gradleModules = listOf("gradle-core", "gradle-tooling-api") override fun canBuild(modelName: String): Boolean = modelName == "org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptTemplateModel" override fun buildAll(modelName: String, project: Project): KotlinBuildScriptTemplateModel = project.serviceOf<ModuleRegistry>().run { StandardKotlinBuildScriptTemplateModel( gradleModules .map { getModule(it) } .flatMap { it.allRequiredModules } .fold(ClassPath.EMPTY) { classPath, module -> classPath + module.classpath } .asFiles ) } } internal data class StandardKotlinBuildScriptTemplateModel( private val classPath: List<File> ) : KotlinBuildScriptTemplateModel, Serializable { override fun getClassPath() = classPath }
apache-2.0
4fbf19805c091176f36a1471240a75db
33.20339
96
0.728444
4.62844
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/ui/TouchImageActivity.kt
1
1122
package org.ligi.passandroid.ui import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.ortiz.touch.TouchImageView import org.koin.android.ext.android.inject import org.ligi.passandroid.model.PassStore class TouchImageActivity : AppCompatActivity() { val passStore: PassStore by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val touchImageView = TouchImageView(this) setContentView(touchImageView) val bitmap = intent.getStringExtra("IMAGE")?.let { image_from_extra -> passStore.currentPass?.getBitmap(passStore, image_from_extra) } if (bitmap == null) { finish() } else { touchImageView.setImageBitmap(bitmap) supportActionBar?.setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } }
gpl-3.0
f3aa9d6686d7b02a50e5a9b4219f2311
26.365854
78
0.667558
4.734177
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/modifier/BorderBuilder.kt
1
1814
package org.hexworks.zircon.api.builder.modifier import org.hexworks.zircon.api.builder.Builder import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.modifier.Border import org.hexworks.zircon.api.modifier.BorderPosition import org.hexworks.zircon.api.modifier.BorderType import kotlin.jvm.JvmStatic /** * Builds [Border]s. * Defaults: * - a simple border * - on all sides (top, right, bottom, left) */ class BorderBuilder private constructor( private var borderType: BorderType = BorderType.SOLID, private var borderColor: TileColor = TileColor.defaultForegroundColor(), private var borderWidth: Int = 2, private var borderPositions: Set<BorderPosition> = BorderPosition.values().toSet() ) : Builder<Border> { fun withBorderType(borderType: BorderType) = also { this.borderType = borderType } fun withBorderColor(borderColor: TileColor) = also { this.borderColor = borderColor } fun withBorderWidth(borderWidth: Int) = also { this.borderWidth = borderWidth } fun withBorderPositions(vararg borderPositions: BorderPosition) = also { withBorderPositions(borderPositions.toSet()) } fun withBorderPositions(borderPositions: Set<BorderPosition>) = also { this.borderPositions = borderPositions } override fun build(): Border = Border( borderType = borderType, borderColor = borderColor, borderWidth = borderWidth, borderPositions = borderPositions ) override fun createCopy() = BorderBuilder( borderType = borderType, borderColor = borderColor, borderPositions = borderPositions, borderWidth = borderWidth ) companion object { @JvmStatic fun newBuilder() = BorderBuilder() } }
apache-2.0
3724fd2772ca82c1e1c71b0ebd92e312
27.793651
86
0.702315
4.512438
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/recycle/IndexedPool.kt
1
5744
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.recycle import com.acornui.collection.* import com.acornui.Disposable /** * A layer between item reuse and an object pool that first seeks an item from the same index. * It is to reduce the amount of changes a pooled item may need to make. * * To use this class, make a series of [obtain] calls to grab recycled elements, then call [flip] to send unused * elements back to the object pool, and make the obtained elements available for the next series. * * A set may look like this: * * ``` * obtain(3) * obtain(4) * obtain(5) * obtain(2) * obtain(1) * flip() // 1 through 5 is available in the next set for fast access. * ``` * * A set pulling in reverse order should look like this: * ``` * obtain(5) * obtain(4) * obtain(3) * obtain(6) * obtain(7) * flip() // 3 through 7 is available in the next set for fast access. * ``` * * Indices may have gaps, but never insertions. That is, for `obtain(index)`, `index` must be either the highest, or the * lowest index obtained in the current set. * * @param pool The indexed cache will call [Pool.obtain] when a new element is needed, and [Pool.free] when an element * is returned. */ open class IndexedPool<E>( /** * @suppress */ internal val pool: Pool<E> ) : AbstractList<E>(), Clearable { /** * Creates an [IndexedPool] with a basic [ObjectPool] implementation. * @param create The factory method for creating new elements. */ constructor(create: () -> E) : this(ObjectPool(create)) /** * The size of this list. This will be updated after a [flip] */ override val size: Int get() = current.size /** * Returns the size of the obtained list. */ val obtainedSize: Int get() = obtained.size override fun get(index: Int): E = current[index] private var current = ArrayList<E>() private var currentIndices = ArrayList<Int>() private var obtained = ArrayList<E>() private var obtainedIndices = ArrayList<Int>() /** * Obtains an element. * This algorithm attempts to obtain an element with the same index that was cached in the last obtain/flip set. */ fun obtain(index: Int): E { if (obtainedIndices.isEmpty()) { val shiftIndex = currentIndices.sortedInsertionIndex(index, matchForwards = false) currentIndices.shiftAll(shiftIndex) current.shiftAll(shiftIndex) } val isForward = if (obtainedIndices.isEmpty()) { if (currentIndices.isEmpty()) true else { val mid = currentIndices.size shr 1 index < currentIndices[mid] } } else index >= obtainedIndices.first() val element: E element = if (current.isEmpty()) { pool.obtain() } else { if (isForward) if (currentIndices.first() == index) { currentIndices.shift() current.shift() } else { currentIndices.pop() current.pop() } else if (currentIndices.last() == index) { currentIndices.pop() current.pop() } else { currentIndices.shift() current.shift() } } if (isForward) { obtained.add(element) obtainedIndices.add(index) } else { obtained.unshift(element) obtainedIndices.unshift(index) } return element } /** * Returns the element obtained via [obtain] in this set for the given index. * @throws IndexOutOfBoundsException If the index is out of range, or the index was not obtained via [obtain]. */ fun getObtainedByIndex(index: Int): E = getByIndex(index, obtained, obtainedIndices) /** * Returns the current element in this set for the given index. * This will only be valid after a [flip]. * @throws IndexOutOfBoundsException If the index is out of range, or the index was not found. */ fun getByIndex(index: Int): E = getByIndex(index, current, currentIndices) private fun getByIndex(index: Int, elements: List<E>, indices: List<Int>): E { if (elements.isEmpty()) throw IndexOutOfBoundsException() val offset = indices.first() return if (indices[index - offset] == index) { elements[index - offset] } else { val i = indices.sortedInsertionIndex(index) if (indices[i] != index) throw IndexOutOfBoundsException("") elements[i] } } /** * Iterates over each unused item still in the cache. */ fun forEachUnused(callback: (index: Int, renderer: E) -> Unit): IndexedPool<E> { if (current.isEmpty()) return this for (i in 0..current.lastIndex) { callback(currentIndices[i], current[i]) } return this } /** * Sets the items returned via [obtain] to be used as the cached items for the next set. */ fun flip() { current.forEach(action = pool::free) val tmp = current val tmpIndices = currentIndices current = obtained currentIndices = obtainedIndices obtained = tmp obtained.clear() obtainedIndices = tmpIndices obtainedIndices.clear() } /** * Clears this list, sending all known elements back to the [pool]. */ override fun clear() { current.freeTo(pool) obtained.freeTo(pool) currentIndices.clear() obtainedIndices.clear() } } /** * Clears the index cache back into the pool, then disposes all elements and clears the pool. */ fun <E : Disposable> IndexedPool<E>.disposeAndClear() { clear() pool.disposeAndClear() }
apache-2.0
04c7adbf284fc99da0f9ae6bd690686b
26.883495
121
0.689415
3.581047
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/wiki/src/test/java/com/github/felipehjcosta/marvelapp/wiki/presentation/HighlightedCharactersViewModelInputOutputTest.kt
1
2233
package com.github.felipehjcosta.marvelapp.wiki.presentation import com.github.felipehjcosta.marvelapp.base.character.data.pojo.Character import com.github.felipehjcosta.marvelapp.wiki.datamodel.HighlightedCharactersDataModel import io.mockk.every import io.mockk.mockk import io.reactivex.Observable import io.reactivex.Observable.just import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.observers.TestObserver import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.junit.Before import org.junit.Test class HighlightedCharactersViewModelInputOutputTest { private val dataModel = mockk<HighlightedCharactersDataModel>() private val viewModel = HighlightedCharactersViewModelInputOutput(dataModel) @Before fun setUp() { RxJavaPlugins.reset() RxJavaPlugins.setInitNewThreadSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.reset() RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() } } @Test fun subscribedToItemsWhenExecuteLoadItemsCommandThenReturnItems() { val characterName = "Wolverine" val character = Character().apply { name = characterName } every { dataModel.getHighlightedCharacters() } returns just(listOf(character)) val itemsObserver = TestObserver.create<List<CharacterItemViewModel>>() viewModel.output.items.subscribe(itemsObserver) val disposable = viewModel.input.loadItemsCommand.execute().subscribe() itemsObserver.assertValue { it[0].name == characterName } disposable.dispose() } @Test fun ensureShowLoadingEmitCorrectValuesWhenExecuteLoadItemsCommandCorrectly() { val characterName = "Wolverine" val character = Character().apply { name = characterName } every { dataModel.getHighlightedCharacters() } returns Observable.just(listOf(character)) val itemsObserver = TestObserver.create<Boolean>() viewModel.output.showLoading.subscribe(itemsObserver) val disposable = viewModel.input.loadItemsCommand.execute().subscribe() itemsObserver.assertValues(true, false) disposable.dispose() } }
mit
a30d49da9b56355a1681f6f49bc001c1
31.852941
97
0.756829
5.052036
false
true
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/input/LongTouch.kt
1
2273
/* * Copyright 2020 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.input import com.acornui.component.WithNode import com.acornui.dom.handle import com.acornui.signal.* import com.acornui.time.schedule import kotlinx.browser.window import org.w3c.dom.TouchEvent import org.w3c.dom.events.MouseEvent import kotlin.time.seconds val longTouchInterval = 0.6.seconds /** * Dispatched when the user has touched down on this element for [longTouchInterval] duration. */ val WithNode.longTouched get() = object : Signal<TouchEvent> { override fun listen(isOnce: Boolean, handler: (TouchEvent) -> Unit): SignalSubscription { val win = window.asWithEventTarget() return buildSubscription(isOnce, handler) { +touchStarted.listen { e -> val timer = schedule(longTouchInterval) { win.contextMenuOpened.listen(EventOptions(isCapture = true, isOnce = true, isPassive = false)) { it.preventDefault() it.handle() } invoke(e) } win.touchEnded.once { timer.dispose() } } } } } /** * Dispatched when the user has moused down on this element for [longTouchInterval] duration. */ val WithNode.longPressed get() = object : Signal<MouseEvent> { override fun listen(isOnce: Boolean, handler: (MouseEvent) -> Unit): SignalSubscription { val win = window.asWithEventTarget() return buildSubscription(isOnce, handler) { +mousePressed.listen { e -> val timer = schedule(longTouchInterval) { win.clicked.listen(EventOptions(isCapture = true, isOnce = true, isPassive = false)) { it.preventDefault() it.handle() } invoke(e) } win.mouseReleased.once { timer.dispose() } } } } }
apache-2.0
deddcc64b5da42415f84a2fa4afdea99
27.772152
102
0.697756
3.642628
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/MenuBarBuilder.kt
1
3091
package org.hexworks.zircon.api.builder.fragment import org.hexworks.cobalt.events.api.CallbackResult import org.hexworks.zircon.api.Beta import org.hexworks.zircon.api.builder.Builder import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.fragment.MenuBar import org.hexworks.zircon.api.fragment.builder.FragmentBuilder import org.hexworks.zircon.api.fragment.menu.DropdownMenu import org.hexworks.zircon.api.fragment.menu.MenuSelection import org.hexworks.zircon.api.resource.TilesetResource import org.hexworks.zircon.api.screen.Screen import org.hexworks.zircon.internal.dsl.ZirconDsl import org.hexworks.zircon.internal.fragment.impl.DefaultMenuBar import kotlin.jvm.JvmStatic @Beta @ZirconDsl class MenuBarBuilder<T : Any> private constructor( var screen: Screen? = null, var menuElements: List<DropdownMenu<T>> = listOf(), var theme: ColorTheme = ColorTheme.unknown(), var tileset: TilesetResource = TilesetResource.unknown(), var position: Position = Position.zero(), var width: Int = -1, var spacing: Int = 1, var onMenuItemSelected: ((menuSelection: MenuSelection<T>) -> CallbackResult)? = null ) : FragmentBuilder<MenuBar<T>, MenuBarBuilder<T>>, Builder<MenuBar<T>> { override fun build(): MenuBar<T> { require(menuElements.isNotEmpty()) { "Cannot build a MenuBar without menu elements" } require(theme.isNotUnknown) { "You must set a theme for a MenuBar" } val minWidth = menuElements.minSize(1).width val finalWidth = if (width > 0) { require(width >= minWidth) { "width ($width) is smaller that the required min width ($minWidth) to fit the menu items." } width } else minWidth return DefaultMenuBar( screen = screen ?: error("Cannot build a MenuBar without a Screen"), position = position, spacing = spacing, theme = theme, tileset = tileset, menuElements = menuElements, width = finalWidth, ).apply { onMenuItemSelected?.let { callback -> this.onMenuItemSelected(callback) } } } override fun createCopy() = MenuBarBuilder( screen = screen, menuElements = menuElements, theme = theme, tileset = tileset, spacing = spacing ) override fun withPosition(position: Position) = also { this.position = position } private fun <T : Any> List<DropdownMenu<T>>.minSize(spacing: Int) = Size.create( width = map { it.width }.fold(0, Int::plus) + (size - 1) * spacing, height = 1 ) companion object { /** * Creates a builder to configure and build a [MenuBar]. * @param T the type of the item(s) that can be selected */ @JvmStatic fun <T : Any> newBuilder(): MenuBarBuilder<T> = MenuBarBuilder() } }
apache-2.0
254cdc917218451403418dcadde6f21a
34.125
106
0.650599
4.341292
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/jetpack/common/CheckboxSpannableLabel.kt
1
1184
package org.wordpress.android.ui.jetpack.common import android.text.Spannable import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan import androidx.annotation.StringRes import org.wordpress.android.R.color import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject class CheckboxSpannableLabel @Inject constructor( private val resourceProvider: ResourceProvider ) { fun buildSpannableLabel( @StringRes labelRes: Int, @StringRes labelHintRes: Int? ): CharSequence? { val labelText = resourceProvider.getString(labelRes) if (labelHintRes == null) { return null } val labelHintText = resourceProvider.getString(labelHintRes) val spannable = SpannableString(labelHintText) spannable.setSpan( ForegroundColorSpan(resourceProvider.getColor(color.neutral)), 0, labelHintText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return SpannableString(SpannableStringBuilder().append(labelText).append(" ").append(spannable)) } }
gpl-2.0
43e625ba8868d23176eb0a7bf64874e6
33.823529
104
0.715372
5.170306
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/deltarnn/DeltaRNNRelevanceHelper.kt
1
9769
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.LayerParameters import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceUtils import com.kotlinnlp.simplednn.core.layers.models.recurrent.GatedRecurrentRelevanceHelper import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which calculates the relevance of the input of a [layer] respect of its output. * * @property layer the [DeltaRNNLayer] in which to calculate the input relevance */ internal class DeltaRNNRelevanceHelper( override val layer: DeltaRNNLayer<DenseNDArray> ) : GatedRecurrentRelevanceHelper(layer) { /** * Propagate the relevance from the output to the gates. * * @param contributions the contributions saved during the last forward */ override fun propagateRelevanceToGates(contributions: LayerParameters) { contributions as DeltaRNNLayerParameters val previousStateExists: Boolean = this.layer.layersWindow.getPrevState() != null val halfOutputRelevance: DenseNDArray = this.layer.outputArray.relevance.div(2.0) val candidateRelevance: DenseNDArray = if (previousStateExists) this.getInputPartition(contributions).div(2.0) else // if there isn't a previous state, all the output relevance is assigned to the candidate // partition (p * c), half to the partition array and half to the candidate array halfOutputRelevance // pRelevance = inputPartition / 2 + recurrentPartition / 2 = outputRelevance / 2 this.layer.partition.assignRelevance(halfOutputRelevance) this.layer.candidate.assignRelevance(candidateRelevance) this.setCandidateRelevancePartitions(previousStateExists = previousStateExists) } /** * @param contributions the contributions saved during the last forward * * @return the relevance of the input respect to the output */ override fun getInputRelevance(contributions: LayerParameters): DenseNDArray { val x = this.layer.inputArray.values val wxContrib: DenseNDArray = (contributions as DeltaRNNLayerParameters).feedforwardUnit.weights.values val relevanceSupport: DeltaRNNRelevanceSupport = this.layer.relevanceSupport val previousStateExists: Boolean = this.layer.layersWindow.getPrevState() != null val bp: DenseNDArray = this.layer.params.recurrentUnit.biases.values val bc: DenseNDArray = this.layer.params.feedforwardUnit.biases.values val beta1: DenseNDArray = this.layer.params.beta1.values val d1Bc: DenseNDArray = if (previousStateExists) bc.div(2.0) else bc // if there is a recurrent contribution bc is divided equally among d1Input and d1Rec, otherwise it is all assigned // to d1Input val pInputRelevance = RelevanceUtils.calculateRelevanceOfArray( x = x, y = this.layer.partition.valuesNotActivated, yRelevance = this.layer.partition.relevance, contributions = wxContrib.copy().partialAssignSum(bp) // w (dot) x + bp ) val d1InputRelevance = RelevanceUtils.calculateRelevanceOfArray( x = x, y = relevanceSupport.d1Input.values, yRelevance = relevanceSupport.d1Input.relevance, contributions = wxContrib.prod(beta1).partialAssignSum(d1Bc) // (w (dot) x) * beta1 + (bc | bc / 2) ) val inputRelevance: DenseNDArray = pInputRelevance.assignSum(d1InputRelevance) if (previousStateExists) { val d2InputRelevance = RelevanceUtils.calculateRelevanceOfArray( x = x, // the product by 'alpha' is not included during the calculation of the relevance // ('alpha' doesn't depend on variables of interest) y = this.layer.wx.values, yRelevance = relevanceSupport.d2.relevance.div(2.0), contributions = wxContrib // w (dot) x ) inputRelevance.assignSum(d2InputRelevance) } return inputRelevance } /** * Calculate the relevance of the output in the previous state respect to the current one and assign it to the output * array of the previous state. * * WARNING: the previous state must exist! * * @param contributions the contributions saved during the last forward */ override fun setRecurrentRelevance(contributions: LayerParameters) { contributions as DeltaRNNLayerParameters val prevStateOutput: AugmentedArray<DenseNDArray> = this.layer.layersWindow.getPrevState()!!.outputArray val yPrev: DenseNDArray = prevStateOutput.values val wyRecContrib: DenseNDArray = contributions.recurrentUnit.weights.values val halfBc: DenseNDArray = this.layer.params.feedforwardUnit.biases.values.div(2.0) val beta2: DenseNDArray = this.layer.params.beta2.values val relevanceSupport: DeltaRNNRelevanceSupport = this.layer.relevanceSupport val d1RecRelevance = RelevanceUtils.calculateRelevanceOfArray( x = yPrev, y = relevanceSupport.d1Rec.values, yRelevance = relevanceSupport.d1Rec.relevance, contributions = wyRecContrib.prod(beta2).partialAssignSum(halfBc) // (wyRec (dot) yPrev) * beta2 + bc / 2 ) val d2RecRelevance = RelevanceUtils.calculateRelevanceOfArray( x = yPrev, // the product by 'alpha' is not included during the calculation of the relevance // ('alpha' doesn't depend on variables of interest) y = this.layer.wyRec.values, yRelevance = relevanceSupport.d2.relevance.div(2.0), contributions = wyRecContrib // wyRec (dot) yPrev ) prevStateOutput.assignRelevance(this.getRecurrentPartition(contributions).div(2.0)) prevStateOutput.relevance.assignSum(d1RecRelevance).assignSum(d2RecRelevance) } /** * Get the partition of relevance in respect of the input. * WARNING: a previous state must exist. * * @param contributions the contributions saved during the last forward * * @return the input relevance partition */ private fun getInputPartition(contributions: DeltaRNNLayerParameters): DenseNDArray { val y: DenseNDArray = this.layer.outputArray.valuesNotActivated val yRec: DenseNDArray = contributions.recurrentUnit.biases.values val yInput: DenseNDArray = y.sub(yRec) return RelevanceUtils.getRelevancePartition1( yRelevance = this.layer.outputArray.relevance, y = y, yContribute1 = yInput, yContribute2 = yRec) } /** * Get the partition of relevance in respect of the previous state. * * @param contributions the contributions saved during the last forward * * @return the recurrent relevance partition */ private fun getRecurrentPartition(contributions: DeltaRNNLayerParameters): DenseNDArray { return RelevanceUtils.getRelevancePartition2( yRelevance = this.layer.outputArray.relevance, y = this.layer.outputArray.valuesNotActivated, yContribute2 = contributions.recurrentUnit.biases.values) } /** * Set the partitions of the relevance of the candidate splitting it respectively among the d1 and d2 arrays. * The d1 array is itself composed by an input partition and a recurrent partition. * If there isn't a previous state all the candidate relevance is assigned to the d1 input partition. */ private fun setCandidateRelevancePartitions(previousStateExists: Boolean) { val cRelevance: DenseNDArray = this.layer.candidate.relevance val relevanceSupport: DeltaRNNRelevanceSupport = this.layer.relevanceSupport if (previousStateExists) { this.splitCandidateRelevancePartitions(cRelevance = cRelevance, relevanceSupport = relevanceSupport) } else { relevanceSupport.d1Input.assignRelevance(cRelevance) } } /** * @param cRelevance the relevance of the candidate array * @param relevanceSupport the relevance support structure used during the last forward * * @return a pair containing the partitions of relevance respectively among the d1 and d2 arrays */ private fun splitCandidateRelevancePartitions(cRelevance: DenseNDArray, relevanceSupport: DeltaRNNRelevanceSupport){ val c: DenseNDArray = this.layer.candidate.valuesNotActivated val d2: DenseNDArray = relevanceSupport.d2.values relevanceSupport.d1Input.assignRelevance( RelevanceUtils.getRelevancePartition1( yRelevance = cRelevance, y = c, yContribute1 = relevanceSupport.d1Input.values, yContribute2 = d2, nPartitions = 3) ) relevanceSupport.d1Rec.assignRelevance( RelevanceUtils.getRelevancePartition1( yRelevance = cRelevance, y = c, yContribute1 = relevanceSupport.d1Rec.values, yContribute2 = d2, nPartitions = 3) ) relevanceSupport.d2.assignRelevance( RelevanceUtils.getRelevancePartition2( yRelevance = cRelevance, y = c, yContribute2 = d2, nPartitions = 3) ) } /** * If n is the number of columns of this [DenseNDArray], [a] / n is added to each column of this. * * @param a the [DenseNDArray] column vector to add to this * * @return this [DenseNDArray] */ private fun DenseNDArray.partialAssignSum(a: DenseNDArray): DenseNDArray { val aPart: DenseNDArray = a.div(this.columns.toDouble()) for (i in 0 until this.rows) { val aPartI: Double = aPart[i] for (j in 0 until this.columns) { this[i, j] += aPartI } } return this } }
mpl-2.0
0ce37bebd777a8e2c4854aaf018e4619
36.573077
119
0.72597
4.380717
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/SelectedSectionManagerTest.kt
1
1942
package org.wordpress.android.ui.stats.refresh.utils import android.content.SharedPreferences import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.MONTHS class SelectedSectionManagerTest : BaseUnitTest() { @Mock lateinit var sharedPreferences: SharedPreferences @Mock lateinit var sharedPreferencesEditor: SharedPreferences.Editor private lateinit var selectedSectionManager: SelectedSectionManager @Before fun setUp() { selectedSectionManager = SelectedSectionManager(sharedPreferences) whenever(sharedPreferences.edit()).thenReturn(sharedPreferencesEditor) } @Test fun `inserts tab selection into shared prefs`() { whenever(sharedPreferencesEditor.putString(any(), any())).thenReturn(sharedPreferencesEditor) var selectedSection: StatsSection? = null selectedSectionManager.liveSelectedSection.observeForever { selectedSection = it } selectedSectionManager.setSelectedSection(MONTHS) val inOrder = inOrder(sharedPreferencesEditor) inOrder.verify(sharedPreferencesEditor).putString(SELECTED_SECTION_KEY, "MONTHS") inOrder.verify(sharedPreferencesEditor).apply() assertThat(selectedSection).isEqualTo(MONTHS) } @Test fun `selects tab selection from shared prefs`() { whenever(sharedPreferences.getString(eq(SELECTED_SECTION_KEY), any())).thenReturn("MONTHS") val selectedSection = selectedSectionManager.getSelectedSection() assertThat(selectedSection).isEqualTo(MONTHS) } }
gpl-2.0
7b908c204fc86b7fac6a7b9c37193eb7
37.84
101
0.776519
4.891688
false
true
false
false
CloudCoders/Katas
src/main/kotlin/bowling/Bowling.kt
1
1966
package bowling private const val SPARE = '/' private const val MISS = '-' private const val STRIKE = 'X' private const val NORMAL_FRAMES: Int = 18 class Bowling { val bowlingRules = listOf<BowlingRule>(LastFrameRule(), NormalRule(), SpareRule(), StrikeRule()) fun score(frames: String): Int { return frames.foldIndexed(0) { idx, score, roll -> score + bowlingRules .filter { !isLastFrame(frames, idx).xor(it is LastFrameRule) } .sumBy { it.scoreRule(frames, idx, roll) } } } } private fun isLastFrame(frames: String, idx: Int) = NORMAL_FRAMES <= frames.substring(0, idx) .sumBy { roll -> if (roll == STRIKE) 2 else 1 } private fun String.next(idx: Int) = if (idx < length - 1) this[idx + 1] else MISS private fun String.previous(idx: Int) = if (idx > 0) this[idx - 1] else MISS private fun score(roll: Char, spareDiff: Int = 0) = when (roll) { in '1'..'9' -> roll.toString().toInt() SPARE -> 10 - spareDiff STRIKE -> 10 else -> 0 } interface BowlingRule { fun scoreRule(frames: String, idx: Int, roll: Char): Int } class NormalRule : BowlingRule { override fun scoreRule(frames: String, idx: Int, roll: Char): Int { return if (roll in '1' .. '9') roll.toString().toInt() else 0 } } class SpareRule() : BowlingRule { override fun scoreRule(frames: String, idx: Int, roll: Char): Int { return if (roll == SPARE) { (10 - score(frames.previous(idx))) + score(frames.next(idx)) } else 0 } } class StrikeRule(): BowlingRule { override fun scoreRule(frames: String, idx: Int, roll: Char): Int { val next = frames.next(idx) return if (roll == STRIKE) { 10 + score(next) + score(frames.next(idx + 1), score(next)) } else 0 } } class LastFrameRule(): BowlingRule { override fun scoreRule(frames: String, idx: Int, roll: Char): Int { return score(frames[idx], score(frames.previous(idx))) } }
apache-2.0
c39b76f5cd683180992d7b11a11cdbff
26.704225
98
0.625636
3.271215
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt
1
2634
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtParenthesizedExpression import org.jetbrains.kotlin.psi.KtPrefixExpression import org.jetbrains.kotlin.psi.prefixExpressionVisitor import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class KotlinDoubleNegationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = prefixExpressionVisitor(fun(expression) { if (expression.operationToken != KtTokens.EXCL || expression.baseExpression?.getType(expression.analyze())?.isBoolean() != true ) { return } var parent = expression.parent while (parent is KtParenthesizedExpression) { parent = parent.parent } if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { holder.registerProblem( expression, KotlinBundle.message("redundant.double.negation"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, DoubleNegationFix() ) } }) private class DoubleNegationFix : LocalQuickFix { override fun getName() = KotlinBundle.message("double.negation.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { applyFix(descriptor.psiElement as? KtPrefixExpression ?: return) } private fun applyFix(expression: KtPrefixExpression) { var parent = expression.parent while (parent is KtParenthesizedExpression) { parent = parent.parent } if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { expression.baseExpression?.let { parent.replaced(it) } } } } }
apache-2.0
69c135fc967cf92f530d78bfeb37072b
43.661017
158
0.683371
5.310484
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/codeInsight/handlers/superDeclarations/KotlinSuperDeclarationsInfoService.kt
1
4134
// 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.fir.codeInsight.handlers.superDeclarations import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.util.EditSourceUtil import com.intellij.openapi.editor.Editor import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.psi.* object KotlinSuperDeclarationsInfoService { fun getForDeclarationAtCaret(file: KtFile, editor: Editor): KotlinSuperDeclarationsInfo? { val element = file.findElementAt(editor.caretModel.offset) ?: return null val declaration = PsiTreeUtil.getParentOfType<KtDeclaration>( element, KtNamedFunction::class.java, KtClass::class.java, KtProperty::class.java, KtObjectDeclaration::class.java ) ?: return null return getForDeclaration(declaration) } fun getForDeclaration(declaration: KtDeclaration): KotlinSuperDeclarationsInfo? { @OptIn(KtAllowAnalysisOnEdt::class) return allowAnalysisOnEdt { analyze(declaration) { val symbol = declaration.getSymbol() // TODO add navigation to expect declarations here createList(symbol) } } } fun navigateToSuperDeclaration(info: KotlinSuperDeclarationsInfo, editor: Editor) { when (info.superDeclarations.size) { 0 -> { } 1 -> { val navigatable = EditSourceUtil.getDescriptor(info.superDeclarations[0]) if (navigatable != null && navigatable.canNavigate()) { navigatable.navigate(true) } } else -> { val popupTitle = getPopupTitle(info.kind) val superDeclarationsArray = PsiUtilCore.toPsiElementArray(info.superDeclarations) val popup = NavigationUtil.getPsiElementPopup(superDeclarationsArray, popupTitle) popup.showInBestPositionFor(editor) } } } @Nls private fun getPopupTitle(declarationKind: KotlinSuperDeclarationsInfo.DeclarationKind): String = when (declarationKind) { KotlinSuperDeclarationsInfo.DeclarationKind.CLASS -> KotlinBundle.message("goto.super.chooser.class.title") KotlinSuperDeclarationsInfo.DeclarationKind.PROPERTY -> KotlinBundle.message("goto.super.chooser.property.title") KotlinSuperDeclarationsInfo.DeclarationKind.FUNCTION -> KotlinBundle.message("goto.super.chooser.function.title") } private fun KtAnalysisSession.createList(symbol: KtSymbol): KotlinSuperDeclarationsInfo? = when (symbol) { is KtCallableSymbol -> KotlinSuperDeclarationsInfo( symbol.getDirectlyOverriddenSymbols().mapNotNull { it.psi }, when (symbol) { is KtPropertySymbol -> KotlinSuperDeclarationsInfo.DeclarationKind.PROPERTY else -> KotlinSuperDeclarationsInfo.DeclarationKind.FUNCTION } ) is KtClassOrObjectSymbol -> KotlinSuperDeclarationsInfo( symbol.superTypes.mapNotNull { (it as? KtNonErrorClassType)?.classSymbol?.psi }, KotlinSuperDeclarationsInfo.DeclarationKind.CLASS, ) else -> null } }
apache-2.0
c2431064679f0346fb0b08a05041a6ca
44.944444
158
0.704886
5.432326
false
false
false
false
Carighan/kotlin-koans
src/i_introduction/_4_Lambdas/n04Lambdas.kt
1
764
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas: return true if the collection contains an even number. You can find the appropriate function to call on 'Collection' by using code completion. Don't use the class 'Iterables'. """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean { val even = { x: Int -> x % 2 == 0} return collection.any(even); }
mit
f3587efb0943c4463c84b7e4f68e6208
26.321429
95
0.615183
3.690821
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/friends/usecase/CreateReactionHistoryItemsUseCase.kt
1
1378
package io.ipoli.android.friends.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.friends.feed.data.Post import io.ipoli.android.friends.persistence.FriendRepository import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository /** * Created by Polina Zhelyazkova <[email protected]> * on 7/20/18. */ class CreateReactionHistoryItemsUseCase( private val playerRepository: PlayerRepository, private val friendsRepository: FriendRepository ) : UseCase<CreateReactionHistoryItemsUseCase.Params, List<CreateReactionHistoryItemsUseCase.ReactionHistoryItem>> { override fun execute(parameters: Params): List<ReactionHistoryItem> { val playerIdToReaction = parameters.reactions.map { it.playerId to it }.toMap() val players = playerRepository.findAll(parameters.reactions.map { it.playerId }) val playerIdToPlayer = players.map { it.id to it }.toMap() return parameters.reactions.sortedByDescending { it.createdAt }.map { ReactionHistoryItem( reaction = playerIdToReaction[it.playerId]!!, player = playerIdToPlayer[it.playerId]!! ) } } data class Params(val reactions: List<Post.Reaction>) data class ReactionHistoryItem( val reaction: Post.Reaction, val player: Player ) }
gpl-3.0
fe1c42a2f6f46e1f4c1384441bf30ed8
36.27027
116
0.727141
4.532895
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/repeatingquest/usecase/SaveQuestsForRepeatingQuestUseCase.kt
1
1769
package io.ipoli.android.repeatingquest.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.quest.Quest import io.ipoli.android.quest.RepeatingQuest import io.ipoli.android.quest.data.persistence.QuestRepository import io.ipoli.android.quest.job.ReminderScheduler import org.threeten.bp.LocalDate /** * Created by Venelin Valkov <[email protected]> * on 02/14/2018. */ class SaveQuestsForRepeatingQuestUseCase( private val questRepository: QuestRepository, private val reminderScheduler: ReminderScheduler ) : UseCase<SaveQuestsForRepeatingQuestUseCase.Params, SaveQuestsForRepeatingQuestUseCase.Result> { override fun execute(parameters: Params): SaveQuestsForRepeatingQuestUseCase.Result { val rq = parameters.repeatingQuest val rqEnd = rq.end if (rqEnd != null && parameters.start.isAfter(rqEnd)) { return Result(listOf(), rq) } val start = if (parameters.start.isBefore(rq.start)) rq.start else parameters.start val (scheduleDates, newRepeatPattern) = rq.repeatPattern.createSchedule( start, rqEnd ) if (scheduleDates.isEmpty()) { return Result(listOf(), rq) } val quests = scheduleDates.map { Quest.createFromRepeatingQuest(repeatingQuest = rq, scheduleDate = it) } questRepository.save(quests) reminderScheduler.schedule() return Result(quests, rq.copy(repeatPattern = newRepeatPattern)) } data class Result(val quests: List<Quest>, val repeatingQuest: RepeatingQuest) /** * @startDate inclusive * @end inclusive */ data class Params( val repeatingQuest: RepeatingQuest, val start: LocalDate ) }
gpl-3.0
526e591cc8d8caf674af4eb9d6a7ebbf
30.607143
99
0.693612
4.571059
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/buffer/ExpandableByteBuffer.kt
1
2805
package com.onyx.buffer import java.nio.Buffer import java.nio.ByteBuffer /** * Created by Tim Osborn on 8/2/16. * * This class is meant to encapsulate the automatic growing and shrinking of a byte expandableByteBuffer. Also it acts as a reference * to a expandableByteBuffer as the underlying ByteBuffer can change. * */ class ExpandableByteBuffer { var buffer: ByteBuffer private var maxBufferSize = 0 private var bufferStartingPosition = 0 /** * Constructor with max size and starting position * @param buffer Buffer to read and write * @param maxBufferSize maximum size to read fro the expandableByteBuffer * @param bufferStartingPosition starting index of the expandableByteBuffer */ constructor(buffer: ByteBuffer, maxBufferSize: Int, bufferStartingPosition: Int) { this.buffer = buffer this.maxBufferSize = maxBufferSize this.bufferStartingPosition = bufferStartingPosition } /** * Default Constructor with expandableByteBuffer. This defaults the max expandableByteBuffer size to the maximum of an integer * and the starting position to 0 * * @param buffer ByteBuffer to initialize with */ constructor(buffer: ByteBuffer) { this.buffer = buffer this.maxBufferSize = Integer.MAX_VALUE this.bufferStartingPosition = 0 } /** * Check to see if the buffer need additional bytes * @param required Number of additional required bytes * @return Whether the buffer already has enough bytes remaining */ fun ensureRequiredSize(required: Int): Boolean = buffer.position() + required < maxBufferSize + bufferStartingPosition /** * Check size and ensure the expandableByteBuffer has enough space to accommodate * * @param needs How many more bytes to allocate if the buffer does not have enough */ fun ensureSize(needs: Int) { if (buffer.limit() < needs + buffer.position() && buffer.capacity() >= needs + buffer.position()) { buffer.limit(buffer.capacity()) } else if (buffer.limit() < needs + buffer.position()) { val tempBuffer = BufferPool.allocate(buffer.limit() + needs + BUFFER_ALLOCATION) buffer.flip() tempBuffer.put(buffer) BufferPool.recycle(buffer) buffer = tempBuffer } } /** * Append a buffer to this expandable buffer * * @since 2.0.0 */ fun put(other: ByteBuffer) { ensureSize(other.limit()) buffer.put(other) } /** * Flip the underlying buffer */ fun flip(): Buffer = buffer.flip() companion object { const val BUFFER_ALLOCATION = BufferPool.MEDIUM_BUFFER_SIZE // Initial Buffer allocation size 6KB } }
agpl-3.0
27b41a693889bb1fcabbabfc4c13478d
31.616279
134
0.664884
4.690635
false
false
false
false
GunoH/intellij-community
plugins/git4idea/tests/git4idea/update/GitSubmoduleTest.kt
9
5025
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.update import com.intellij.dvcs.branch.DvcsSyncSettings import com.intellij.dvcs.repo.Repository import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor.cd import com.intellij.openapi.vcs.Executor.echo import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.update.UpdatedFiles import git4idea.config.UpdateMethod.MERGE import git4idea.config.UpdateMethod.REBASE import git4idea.repo.GitRepository import git4idea.test.* import java.nio.file.Path class GitSubmoduleTest : GitSubmoduleTestBase() { private lateinit var main: GitRepository private lateinit var sub: GitRepository private lateinit var main2: RepositoryAndParent private lateinit var sub2: Path private lateinit var dirtyScopeManager: VcsDirtyScopeManager override fun setUp() { super.setUp() dirtyScopeManager = VcsDirtyScopeManager.getInstance(project) // prepare second clone & parent.git main2 = createPlainRepo("main") val sub3 = createPlainRepo("sub") sub2 = addSubmodule(main2.local, sub3.remote, "sub") // clone into the project cd(testNioRoot) git("clone --recurse-submodules ${main2.remote} maintmp") FileUtil.moveDirWithContent(testNioRoot.resolve("maintmp").toFile(), projectRoot.toNioPath().toFile()) cd(projectRoot) setupDefaultUsername() val subFile = projectNioRoot.resolve("sub") cd(subFile) setupDefaultUsername() refresh() main = registerRepo(project, projectNioRoot) sub = registerRepo(project, subFile) } fun `test submodule in detached HEAD state is updated via 'git submodule update'`() { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") cd(main2.local) val mainHash = addCommit("Advance the submodule") git("push") insertLogMarker("update process") val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), null, false, true).update(MERGE) assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result) assertEquals("Last commit in submodule is incorrect", submoduleHash, sub.last()) assertEquals("Last commit in main repository is incorrect", mainHash, main.last()) assertEquals("Submodule should be in detached HEAD", Repository.State.DETACHED, sub.state) } fun `test submodule in detached HEAD state doesn't fail in case of sync control`() { settings.syncSetting = DvcsSyncSettings.Value.SYNC try { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") cd(main2.local) val mainHash = addCommit("Advance the submodule") git("push") insertLogMarker("update process") val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), null, false, true).update(MERGE) assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result) assertEquals("Last commit in submodule is incorrect", submoduleHash, sub.last()) assertEquals("Last commit in main repository is incorrect", mainHash, main.last()) assertEquals("Submodule should be in detached HEAD", Repository.State.DETACHED, sub.state) } finally { settings.syncSetting = DvcsSyncSettings.Value.NOT_DECIDED } } fun `test submodule on branch is updated as a normal repository`() { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") // prepare commit in first sub clone cd(sub) git("checkout master") echo("b", "content\n") addCommit("msg") insertLogMarker("update process") val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), null, false, true).update(REBASE) assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result) assertEquals("Submodule should be on branch", "master", sub.currentBranchName) assertEquals("Commit from 2nd clone not found in submodule", submoduleHash, sub.git("rev-parse HEAD^")) } // IDEA-234159 fun `test modified submodule is visible in local changes`() { dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() assertNoChanges() cd(sub) echo("a", "content\n") addCommit("in submodule") dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() cd(projectPath) assertChanges { modified("sub") } } private fun insertLogMarker(title: String) { LOG.info("") LOG.info("--------- STARTING ${title.toUpperCase()} -----------") LOG.info("") } }
apache-2.0
742e7d245058c2f388cfa6a1934bcc72
35.158273
145
0.719204
4.506726
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinLambdaMethodFilter.kt
1
4430
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.BreakpointStepMethodFilter import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.psi.util.parentOfType import com.intellij.util.Range import com.sun.jdi.Location import org.jetbrains.kotlin.codegen.coroutines.INVOKE_SUSPEND_METHOD_NAME import org.jetbrains.kotlin.idea.base.psi.isMultiLine import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.isGeneratedIrBackendLambdaMethodName import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.trimIfMangledInBytecode import org.jetbrains.kotlin.idea.debugger.core.isInsideInlineArgument import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer class KotlinLambdaMethodFilter( lambda: KtFunction, private val callingExpressionLines: Range<Int>?, private val lambdaInfo: KotlinLambdaInfo ) : BreakpointStepMethodFilter { private val lambdaPtr = lambda.createSmartPointer() private val firstStatementPosition: SourcePosition? private val lastStatementLine: Int init { val (firstPosition, lastPosition) = findFirstAndLastStatementPositions(lambda) firstStatementPosition = firstPosition lastStatementLine = lastPosition?.line ?: -1 } override fun getBreakpointPosition() = firstStatementPosition override fun getLastStatementLine() = lastStatementLine override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean { val lambda = lambdaPtr.getElementInReadAction() ?: return true if (lambdaInfo.isInline) { return isInsideInlineArgument(lambda, location, process) } val method = location.safeMethod() ?: return true if (method.isBridge) { return false } val methodName = method.name() ?: return false return isTargetLambdaName(methodName) && location.matchesExpression(process, lambda.bodyExpression) } private fun Location.matchesExpression(process: DebugProcessImpl, bodyExpression: KtExpression?): Boolean { val sourcePosition = process.positionManager.getSourcePosition(this) ?: return true val blockAt = runReadAction { sourcePosition.elementAt.parentOfType<KtBlockExpression>(true) } ?: return true return blockAt === bodyExpression } override fun getCallingExpressionLines() = if (lambdaInfo.isInline) Range(0, Int.MAX_VALUE) else callingExpressionLines fun isTargetLambdaName(name: String): Boolean { val actualName = name.trimIfMangledInBytecode(lambdaInfo.isNameMangledInBytecode) if (lambdaInfo.isSuspend) { return actualName == INVOKE_SUSPEND_METHOD_NAME } return actualName == lambdaInfo.methodName || actualName.isGeneratedIrBackendLambdaMethodName() } } fun findFirstAndLastStatementPositions(declaration: KtDeclarationWithBody): Pair<SourcePosition?, SourcePosition?> { val body = declaration.bodyExpression if (body != null && declaration.isMultiLine() && body.children.isNotEmpty()) { var firstStatementPosition: SourcePosition? = null var lastStatementPosition: SourcePosition? = null val statements = (body as? KtBlockExpression)?.statements ?: listOf(body) if (statements.isNotEmpty()) { firstStatementPosition = SourcePosition.createFromElement(statements.first()) if (firstStatementPosition != null) { val lastStatement = statements.last() lastStatementPosition = SourcePosition.createFromOffset( firstStatementPosition.file, lastStatement.textRange.endOffset ) } } return Pair(firstStatementPosition, lastStatementPosition) } val position = SourcePosition.createFromElement(declaration) return Pair(position, position) }
apache-2.0
3144f33a64e34935cc9b1837cdf2b0c6
44.670103
158
0.744244
5.057078
false
false
false
false
jk1/intellij-community
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/print/PrintElementGeneratorImpl.kt
4
12831
/* * Copyright 2000-2014 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.vcs.log.graph.impl.print import com.intellij.openapi.diagnostic.Logger import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.SLRUMap import com.intellij.vcs.log.graph.EdgePrintElement import com.intellij.vcs.log.graph.api.EdgeFilter import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.api.elements.GraphEdge import com.intellij.vcs.log.graph.api.elements.GraphEdgeType import com.intellij.vcs.log.graph.api.elements.GraphElement import com.intellij.vcs.log.graph.api.elements.GraphNode import com.intellij.vcs.log.graph.api.printer.PrintElementGenerator import com.intellij.vcs.log.graph.api.printer.PrintElementManager import com.intellij.vcs.log.graph.impl.print.elements.EdgePrintElementImpl import com.intellij.vcs.log.graph.impl.print.elements.PrintElementWithGraphElement import com.intellij.vcs.log.graph.impl.print.elements.SimplePrintElementImpl import com.intellij.vcs.log.graph.impl.print.elements.TerminalEdgePrintElement import com.intellij.vcs.log.graph.utils.LinearGraphUtils.* import com.intellij.vcs.log.graph.utils.NormalEdge import org.jetbrains.annotations.TestOnly import java.util.* class PrintElementGeneratorImpl @TestOnly constructor(private val linearGraph: LinearGraph, private val printElementManager: PrintElementManager, private val longEdgeSize: Int, private val visiblePartSize: Int, private val edgeWithArrowSize: Int) : PrintElementGenerator { private val cache = SLRUMap<Int, List<GraphElement>>(CACHE_SIZE, CACHE_SIZE * 2) private val edgesInRowGenerator = EdgesInRowGenerator(linearGraph) private val elementComparator: Comparator<GraphElement> get() = printElementManager.graphElementComparator private var recommendedWidth = 0 constructor(graph: LinearGraph, printElementManager: PrintElementManager, showLongEdges: Boolean) : this(graph, printElementManager, if (showLongEdges) VERY_LONG_EDGE_SIZE else LONG_EDGE_SIZE, if (showLongEdges) VERY_LONG_EDGE_PART_SIZE else LONG_EDGE_PART_SIZE, if (showLongEdges) LONG_EDGE_SIZE else Integer.MAX_VALUE) fun getRecommendedWidth(): Int { if (recommendedWidth <= 0) { val n = Math.min(SAMPLE_SIZE, linearGraph.nodesCount()) var sum = 0.0 var sumSquares = 0.0 var edgesCount = 0 val currentNormalEdges = ContainerUtil.newHashSet<NormalEdge>() for (i in 0 until n) { val adjacentEdges = linearGraph.getAdjacentEdges(i, EdgeFilter.ALL) var upArrows = 0 var downArrows = 0 for (e in adjacentEdges) { val normalEdge = asNormalEdge(e) if (normalEdge != null) { if (isEdgeUp(e, i)) { currentNormalEdges.remove(normalEdge) } else { currentNormalEdges.add(normalEdge) } } else { if (e.type == GraphEdgeType.DOTTED_ARROW_UP) { upArrows++ } else { downArrows++ } } } var newEdgesCount = 0 for (e in currentNormalEdges) { if (isEdgeVisibleInRow(e, i)) { newEdgesCount++ } else { val arrow = getArrowType(e, i) if (arrow === EdgePrintElement.Type.DOWN) { downArrows++ } else if (arrow === EdgePrintElement.Type.UP) { upArrows++ } } } /* * 0 <= K < 1; weight is an arithmetic progression, starting at 2 / ( n * (k + 1)) ending at k * 2 / ( n * (k + 1)) * this formula ensures that sum of all weights is 1 */ val width = Math.max(edgesCount + upArrows, newEdgesCount + downArrows) val weight = 2 / (n * (K + 1)) * (1 + (K - 1) * i / (n - 1)) sum += width * weight sumSquares += width.toDouble() * width.toDouble() * weight edgesCount = newEdgesCount } /* weighted variance calculation described here: http://stackoverflow.com/questions/30383270/how-do-i-calculate-the-standard-deviation-between-weighted-measurements s*/ val average = sum val deviation = Math.sqrt(sumSquares - average * average) recommendedWidth = Math.round(average + deviation).toInt() } return recommendedWidth } private fun collectElements(rowIndex: Int, builder: PrintElementBuilder) { val visibleElements = getSortedVisibleElementsInRow(rowIndex) val upPosition = createEndPositionFunction(rowIndex - 1, true) val downPosition = createEndPositionFunction(rowIndex + 1, false) visibleElements.forEachIndexed { position, element -> when (element) { is GraphNode -> { val nodeIndex = element.nodeIndex builder.consumeNode(element, position) linearGraph.getAdjacentEdges(nodeIndex, EdgeFilter.ALL).forEach { edge -> val arrowType = getArrowType(edge, rowIndex) val down = downPosition(edge) val up = upPosition(edge) if (down != null) { builder.consumeDownEdge(edge, position, down, arrowType === EdgePrintElement.Type.DOWN) } if (up != null) { builder.consumeUpEdge(edge, up, position, arrowType === EdgePrintElement.Type.UP) } } } is GraphEdge -> { val arrowType = getArrowType(element, rowIndex) val down = downPosition(element) val up = upPosition(element) if (down != null) { builder.consumeDownEdge(element, position, down, arrowType === EdgePrintElement.Type.DOWN) } else if (arrowType === EdgePrintElement.Type.DOWN) { builder.consumeArrow(element, position, arrowType) } if (up != null) { builder.consumeUpEdge(element, up, position, arrowType === EdgePrintElement.Type.UP) } else if (arrowType === EdgePrintElement.Type.UP) { builder.consumeArrow(element, position, arrowType) } } } } } private fun createEndPositionFunction(visibleRowIndex: Int, up: Boolean): (GraphEdge) -> Int? { if (visibleRowIndex < 0 || visibleRowIndex >= linearGraph.nodesCount()) return { _ -> null } val visibleElementsInNextRow = getSortedVisibleElementsInRow(visibleRowIndex) val toPosition = HashMap<GraphElement, Int>(visibleElementsInNextRow.size) visibleElementsInNextRow.forEachIndexed { position, element -> toPosition[element] = position } return { edge -> toPosition[edge] ?: run { val nodeIndex = if (up) edge.upNodeIndex else edge.downNodeIndex if (nodeIndex != null) toPosition[linearGraph.getGraphNode(nodeIndex)] else null } } } private fun getArrowType(edge: GraphEdge, rowIndex: Int): EdgePrintElement.Type? { val normalEdge = asNormalEdge(edge) if (normalEdge != null) { return getArrowType(normalEdge, rowIndex) } else { // special edges when (edge.type) { GraphEdgeType.DOTTED_ARROW_DOWN, GraphEdgeType.NOT_LOAD_COMMIT -> if (intEqual(edge.upNodeIndex, rowIndex - 1)) { return EdgePrintElement.Type.DOWN } GraphEdgeType.DOTTED_ARROW_UP -> // todo case 0-row arrow if (intEqual(edge.downNodeIndex, rowIndex + 1)) { return EdgePrintElement.Type.UP } else -> LOG.error("Unknown special edge type " + edge.type + " at row " + rowIndex) } } return null } private fun getArrowType(normalEdge: NormalEdge, rowIndex: Int): EdgePrintElement.Type? { val edgeSize = normalEdge.down - normalEdge.up val upOffset = rowIndex - normalEdge.up val downOffset = normalEdge.down - rowIndex if (edgeSize >= longEdgeSize) { if (upOffset == visiblePartSize) { LOG.assertTrue(downOffset != visiblePartSize, "Both up and down arrow at row " + rowIndex) // this can not happen due to how constants are picked out, but just in case return EdgePrintElement.Type.DOWN } if (downOffset == visiblePartSize) return EdgePrintElement.Type.UP } if (edgeSize >= edgeWithArrowSize) { if (upOffset == 1) { LOG.assertTrue(downOffset != 1, "Both up and down arrow at row " + rowIndex) return EdgePrintElement.Type.DOWN } if (downOffset == 1) return EdgePrintElement.Type.UP } return null } private fun isEdgeVisibleInRow(edge: GraphEdge, visibleRowIndex: Int): Boolean { val normalEdge = asNormalEdge(edge) ?: return false // e.d. edge is special. See addSpecialEdges return isEdgeVisibleInRow(normalEdge, visibleRowIndex) } private fun isEdgeVisibleInRow(normalEdge: NormalEdge, visibleRowIndex: Int): Boolean { return normalEdge.down - normalEdge.up < longEdgeSize || getAttachmentDistance(normalEdge, visibleRowIndex) <= visiblePartSize } private fun getSortedVisibleElementsInRow(rowIndex: Int): List<GraphElement> { val graphElements = cache.get(rowIndex) if (graphElements != null) { return graphElements } val result = ArrayList<GraphElement>() result.add(linearGraph.getGraphNode(rowIndex)) edgesInRowGenerator.getEdgesInRow(rowIndex).filterTo(result) { isEdgeVisibleInRow(it, rowIndex) } if (rowIndex > 0) { linearGraph.getAdjacentEdges(rowIndex - 1, EdgeFilter.SPECIAL) .filterTo(result) { isEdgeDown(it, rowIndex - 1) } } if (rowIndex < linearGraph.nodesCount() - 1) { linearGraph.getAdjacentEdges(rowIndex + 1, EdgeFilter.SPECIAL) .filterTo(result) { isEdgeUp(it, rowIndex + 1) } } Collections.sort(result, elementComparator) cache.put(rowIndex, result) return result } override fun getPrintElements(rowIndex: Int): Collection<PrintElementWithGraphElement> { val builder = PrintElementBuilder(rowIndex) collectElements(rowIndex, builder) return builder.build() } private fun getAttachmentDistance(e1: NormalEdge, rowIndex: Int): Int { return Math.min(rowIndex - e1.up, e1.down - rowIndex) } private inner class PrintElementBuilder(private val rowIndex: Int) { private val result = ArrayList<PrintElementWithGraphElement>() private val nodes = ArrayList<PrintElementWithGraphElement>() // nodes at the end, to be drawn over the edges fun consumeNode(node: GraphNode, position: Int) { nodes.add(SimplePrintElementImpl(rowIndex, position, node, printElementManager)) } fun consumeDownEdge(edge: GraphEdge, upPosition: Int, downPosition: Int, hasArrow: Boolean) { result.add(EdgePrintElementImpl(rowIndex, upPosition, downPosition, EdgePrintElement.Type.DOWN, edge, hasArrow, printElementManager)) } fun consumeUpEdge(edge: GraphEdge, upPosition: Int, downPosition: Int, hasArrow: Boolean) { result.add(EdgePrintElementImpl(rowIndex, downPosition, upPosition, EdgePrintElement.Type.UP, edge, hasArrow, printElementManager)) } fun consumeArrow(edge: GraphEdge, position: Int, arrowType: EdgePrintElement.Type) { result.add(TerminalEdgePrintElement(rowIndex, position, arrowType, edge, printElementManager)) } fun build(): Collection<PrintElementWithGraphElement> { result.addAll(nodes) return result } } companion object { private val LOG = Logger.getInstance(PrintElementGeneratorImpl::class.java) private const val VERY_LONG_EDGE_SIZE = 1000 const val LONG_EDGE_SIZE: Int = 30 private const val VERY_LONG_EDGE_PART_SIZE = 250 private const val LONG_EDGE_PART_SIZE = 1 private const val CACHE_SIZE = 100 private const val SAMPLE_SIZE = 20000 private const val K = 0.1 } }
apache-2.0
bf9d15bd35ffa6c44c62998088fa5566
38.601852
144
0.653651
4.201375
false
false
false
false
santaevpavel/ClipboardTranslator
app/src/main/java/ru/santaev/clipboardtranslator/api/ApiService.kt
1
3030
package ru.santaev.clipboardtranslator.api import com.example.santaev.domain.api.IApiService import com.example.santaev.domain.api.LanguagesResponseDto import com.example.santaev.domain.api.TranslateRequestDto import com.example.santaev.domain.api.TranslateResponseDto import com.example.santaev.domain.dto.LanguageDto import io.reactivex.Single import io.reactivex.SingleTransformer import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import ru.santaev.clipboardtranslator.api.YandexApi.Companion.API_KEY import ru.santaev.clipboardtranslator.api.YandexApi.Companion.SERVER_URL import java.io.IOException import java.net.SocketTimeoutException import java.util.* class ApiService : IApiService { private val api: YandexApi init { val okHttpClient = OkHttpClient.Builder().build() val retrofit = Retrofit.Builder() .baseUrl(SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build() api = retrofit.create(YandexApi::class.java) } override fun translate(request: TranslateRequestDto): Single<TranslateResponseDto> { val languagesParam = "${request.originLang.code}-${request.targetLang.code}" return api.translate( request.originText, languagesParam, API_KEY ) .compose(getApiTransformer()) .map { response -> val text = checkNotNull(response.text) TranslateResponseDto(0, request.targetLang, text) } } override fun getLanguages(): Single<LanguagesResponseDto> { return api.getLangs( API_KEY, Locale.getDefault().language ).compose(getApiTransformer()) .map { response -> val directions = checkNotNull(response.directions) val languagesRaw = checkNotNull(response.languages) val languages = languagesRaw.map { LanguageDto(0, it.key, it.value) } LanguagesResponseDto(directions, languages) } } private fun <T> getApiTransformer(): SingleTransformer<T, T> { return SingleTransformer { upstream -> upstream.onErrorResumeNext({ throwable -> if (throwable is SocketTimeoutException) { Single.error<T>(throwApiError("Timeout")) } else if (throwable is IOException) { Single.error<T>(throwApiError("Connection error")) } else { Single.error<T>(throwApiError("Request failed")) } }) } } private fun throwApiError(msg: String): RuntimeException { return RuntimeException(msg) } }
apache-2.0
ba13fb27b42b0dc064dd4af92c9ad567
35.95122
89
0.638614
5.10101
false
false
false
false
g1144146/sds_for_kotlin
src/main/kotlin/sds/classfile/attribute/LineNumberTable.kt
1
638
package sds.classfile.attribute import sds.classfile.ClassfileStream import sds.classfile.constant_pool.Constant class LineNumberTable(data: ClassfileStream, pool: Array<Constant>): Attribute() { val table: Array<Array<Int>> = (0 until data.short()).map { arrayOf(data.short(), -1, data.short()) }.toTypedArray() init { val len = table.size (0 until len).forEach { if(it == len - 1) { table[it][1] = table[it][0] if(len > 1) table[it - 1][1] = table[it][0] } else if(it > 0) { table[it - 1][1] = table[it][0] } } } }
apache-2.0
cb1ddec701fdb84a4b2a78d698f36ccc
32.631579
120
0.547022
3.544444
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/ConfigFragment.kt
1
5197
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.particleswallpaper.userprefs import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.preference.PreferenceGroup import android.view.LayoutInflater import android.view.ViewGroup import androidx.lifecycle.LifecycleObserver import com.doctoror.particleswallpaper.R import com.doctoror.particleswallpaper.framework.app.FragmentHolder import com.doctoror.particleswallpaper.framework.di.get import com.doctoror.particleswallpaper.framework.lifecycle.LifecyclePreferenceFragment import com.doctoror.particleswallpaper.framework.lifecycle.OnActivityResultCallbackHost import com.doctoror.particleswallpaper.framework.lifecycle.OnActivityResultCallbackHostImpl import com.doctoror.particleswallpaper.userprefs.data.DeviceSettings import com.doctoror.particleswallpaper.userprefs.preview.OpenChangeWallpaperIntentProvider import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable @SuppressLint("ValidFragment") // Kotlin constructor with default value generates valid empty java constructor open class ConfigFragment @JvmOverloads constructor( private val ch: OnActivityResultCallbackHostImpl = OnActivityResultCallbackHostImpl() ) : LifecyclePreferenceFragment(), OnActivityResultCallbackHost by ch { private lateinit var intentProvider: OpenChangeWallpaperIntentProvider private var glMonitorDisposable: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intentProvider = get(context = activity) addPreferencesFromResource(R.xml.prefs) hideOpenGlPreferencesIfApplicable() hidePreviewPreferenceIfCannotStartPreview() forEachFragmentHolder(preferenceScreen) { it.fragment = this } forEachLifecycleObserver(preferenceScreen) { lifecycle.addObserver(it) } } private fun hideOpenGlPreferencesIfApplicable() { @Suppress("ConstantConditionIf") val deviceSettings: DeviceSettings = get(context = activity) glMonitorDisposable = deviceSettings .observeOpenglSupported() .observeOn(AndroidSchedulers.mainThread()) .subscribe { if (!it) { val group = findPreference(getString(R.string.pref_key_performance)) if (group is PreferenceGroup) { group.findPreference(getString(R.string.pref_key_engine))?.let { group.removePreference(it) } group.findPreference(getString(R.string.pref_key_multisampling))?.let { group.removePreference(it) } } } } } private fun hidePreviewPreferenceIfCannotStartPreview() { if (intentProvider.provideActionIntent() == null) { val p = findPreference(getString(R.string.pref_key_apply)) if (p != null) { preferenceScreen?.removePreference(p) } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = inflater.inflate(R.layout.fragment_preference, container, false)!! override fun onDestroy() { super.onDestroy() glMonitorDisposable?.dispose() glMonitorDisposable = null forEachFragmentHolder(preferenceScreen) { it.fragment = null } forEachLifecycleObserver(preferenceScreen) { lifecycle.removeObserver(it) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) ch.callbacks.forEach { it.onActivityResult(requestCode, resultCode, data) } } private fun forEachLifecycleObserver(g: PreferenceGroup, c: (LifecycleObserver) -> Unit) { for (i in 0 until g.preferenceCount) { val p = g.getPreference(i) if (p is LifecycleObserver) { c(p) } if (p is PreferenceGroup) { forEachLifecycleObserver(p, c) } } } private fun forEachFragmentHolder(g: PreferenceGroup, c: (FragmentHolder) -> Unit) { for (i in 0 until g.preferenceCount) { val p = g.getPreference(i) if (p is FragmentHolder) { c(p) } if (p is PreferenceGroup) { forEachFragmentHolder(p, c) } } } }
apache-2.0
f4331ead744dedfb50d1bbdca9a43ad5
38.976923
110
0.684048
5.125247
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt
1
5153
package eu.kanade.tachiyomi.ui.library import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.databinding.LibraryCategoryBinding import eu.kanade.tachiyomi.ui.library.setting.DisplayModeSetting import eu.kanade.tachiyomi.widget.RecyclerViewPagerAdapter import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * This adapter stores the categories from the library, used with a ViewPager. * * @constructor creates an instance of the adapter. */ class LibraryAdapter( private val controller: LibraryController, private val preferences: PreferencesHelper = Injekt.get() ) : RecyclerViewPagerAdapter() { /** * The categories to bind in the adapter. */ var categories: List<Category> = emptyList() private set /** * The number of manga in each category. * List order must be the same as [categories] */ private var itemsPerCategory: List<Int> = emptyList() private var boundViews = arrayListOf<View>() private val isPerCategory by lazy { preferences.categorizedDisplaySettings().get() } private var currentDisplayMode = preferences.libraryDisplayMode().get() init { preferences.libraryDisplayMode() .asFlow() .drop(1) .onEach { currentDisplayMode = it } .launchIn(controller.viewScope) } /** * Pair of category and size of category */ fun updateCategories(new: List<Pair<Category, Int>>) { var updated = false val newCategories = new.map { it.first } if (categories != newCategories) { categories = newCategories updated = true } val newItemsPerCategory = new.map { it.second } if (itemsPerCategory !== newItemsPerCategory) { itemsPerCategory = newItemsPerCategory updated = true } if (updated) { notifyDataSetChanged() } } /** * Creates a new view for this adapter. * * @return a new view. */ override fun inflateView(container: ViewGroup, viewType: Int): View { val binding = LibraryCategoryBinding.inflate(LayoutInflater.from(container.context), container, false) val view: LibraryCategoryView = binding.root view.onCreate(controller, binding, viewType) return view } /** * Binds a view with a position. * * @param view the view to bind. * @param position the position in the adapter. */ override fun bindView(view: View, position: Int) { (view as LibraryCategoryView).onBind(categories[position]) boundViews.add(view) } /** * Recycles a view. * * @param view the view to recycle. * @param position the position in the adapter. */ override fun recycleView(view: View, position: Int) { (view as LibraryCategoryView).onRecycle() boundViews.remove(view) } /** * Returns the number of categories. * * @return the number of categories or 0 if the list is null. */ override fun getCount(): Int { return categories.size } /** * Returns the title to display for a category. * * @param position the position of the element. * @return the title to display. */ override fun getPageTitle(position: Int): CharSequence { return if (!preferences.categoryNumberOfItems().get()) { categories[position].name } else { categories[position].let { "${it.name} (${itemsPerCategory[position]})" } } } /** * Returns the position of the view. */ override fun getItemPosition(obj: Any): Int { val view = obj as? LibraryCategoryView ?: return POSITION_NONE val index = categories.indexOfFirst { it.id == view.category.id } return if (index == -1) POSITION_NONE else index } /** * Called when the view of this adapter is being destroyed. */ fun onDestroy() { for (view in boundViews) { if (view is LibraryCategoryView) { view.onDestroy() } } } override fun getViewType(position: Int): Int { val category = categories.getOrNull(position) return if (isPerCategory && category?.id != 0) { if (DisplayModeSetting.fromFlag(category?.displayMode) == DisplayModeSetting.LIST) { LIST_DISPLAY_MODE } else { GRID_DISPLAY_MODE } } else { if (currentDisplayMode == DisplayModeSetting.LIST) { LIST_DISPLAY_MODE } else { GRID_DISPLAY_MODE } } } companion object { const val LIST_DISPLAY_MODE = 1 const val GRID_DISPLAY_MODE = 2 } }
apache-2.0
3d7190230f7821e6fc994b898a115224
28.445714
110
0.619251
4.667572
false
false
false
false
Tickaroo/tikxml
processor/src/main/java/com/tickaroo/tikxml/processor/scanning/DefaultAnnotationDetector.kt
1
21394
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.processor.scanning import com.tickaroo.tikxml.annotation.Attribute import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.ElementNameMatcher import com.tickaroo.tikxml.annotation.GenericAdapter import com.tickaroo.tikxml.annotation.Path import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.TextContent import com.tickaroo.tikxml.annotation.Xml import com.tickaroo.tikxml.processor.ProcessingException import com.tickaroo.tikxml.processor.converter.AttributeConverterChecker import com.tickaroo.tikxml.processor.converter.PropertyElementConverterChecker import com.tickaroo.tikxml.processor.field.AttributeField import com.tickaroo.tikxml.processor.field.ElementField import com.tickaroo.tikxml.processor.field.ListElementField import com.tickaroo.tikxml.processor.field.NamedField import com.tickaroo.tikxml.processor.field.PolymorphicElementField import com.tickaroo.tikxml.processor.field.PolymorphicListElementField import com.tickaroo.tikxml.processor.field.PolymorphicTypeElementNameMatcher import com.tickaroo.tikxml.processor.field.PropertyField import com.tickaroo.tikxml.processor.field.TextContentField import com.tickaroo.tikxml.processor.utils.getSurroundingClassQualifiedName import com.tickaroo.tikxml.processor.utils.hasEmptyParameters import com.tickaroo.tikxml.processor.utils.hasMinimumPackageVisibilityModifiers import com.tickaroo.tikxml.processor.utils.hasSuperClass import com.tickaroo.tikxml.processor.utils.hasTikXmlAnnotation import com.tickaroo.tikxml.processor.utils.isAbstract import com.tickaroo.tikxml.processor.utils.isClass import com.tickaroo.tikxml.processor.utils.isInterface import com.tickaroo.tikxml.processor.utils.isList import com.tickaroo.tikxml.processor.utils.isPrivate import com.tickaroo.tikxml.processor.utils.isProtected import com.tickaroo.tikxml.processor.utils.isPublic import com.tickaroo.tikxml.processor.utils.isSamePackageAs import com.tickaroo.tikxml.processor.utils.isString import java.util.Locale import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.type.DeclaredType import javax.lang.model.type.MirroredTypeException import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.type.WildcardType import javax.lang.model.util.ElementFilter import javax.lang.model.util.Elements import javax.lang.model.util.Types /** * A [AnnotationScanner] that scans the element by checking for TikXml annotations * @author Hannes Dorfmann */ @ExperimentalStdlibApi open class DefaultAnnotationDetector(protected val elementUtils: Elements, protected val typeUtils: Types) : AnnotationDetector { override val genericTypes = mutableMapOf<String, Set<String>?>() protected fun isTextContentAnnotated(element: VariableElement): Boolean { val textContentAnnotated = element.getAnnotation(TextContent::class.java) != null if (textContentAnnotated && element.getAnnotation(Path::class.java) != null) { throw ProcessingException(element, "@${Path::class.simpleName} on @${TextContent::class.simpleName} is not allowed. Use @${PropertyElement::class.simpleName} and @${Path::class.simpleName} instead on field '$element' in class ${element.getSurroundingClassQualifiedName()}") } else { return textContentAnnotated } } override fun addGenericType(key: String, value: String?) { genericTypes[key] = (genericTypes[key]?.toMutableSet() ?: mutableSetOf()).apply { value?.run { add(this) } } } override fun containsGenericType(key: String) = genericTypes.containsKey(key) override fun isXmlTextContent(element: VariableElement): TextContentField? = if (isTextContentAnnotated(element) && isXmlField(element) == null) { if (!element.asType().isString()) { throw ProcessingException(element, "Only type String is supported for @${TextContent::class.simpleName} but field '$element' in class ${element.getSurroundingClassQualifiedName()} is not of type String") } val annotation = element.getAnnotation(TextContent::class.java) TextContentField(element, annotation.writeAsCData) } else null override fun isXmlField(element: VariableElement): NamedField? { var annotationFound = 0 // MAIN ANNOTATIONS val attributeAnnotation = element.getAnnotation(Attribute::class.java) val propertyAnnotation = element.getAnnotation(PropertyElement::class.java) val elementAnnotation = element.getAnnotation(Element::class.java) val textContent = element.getAnnotation(TextContent::class.java) if (attributeAnnotation != null) { annotationFound++; } if (propertyAnnotation != null) { annotationFound++ } if (elementAnnotation != null) { annotationFound++ } if (textContent != null) { annotationFound++ } // No annotations if (annotationFound == 0) { return null } if (annotationFound > 1) { // More than one annotation is not allowed throw ProcessingException(element, "Fields can ONLY be annotated with ONE of the " + "following annotations @${Attribute::class.java.simpleName}, " + "@${PropertyElement::class.java.simpleName}, @${Element::class.java.simpleName} or @${TextContent::class.java.simpleName} " + "and not multiple of them! The field ${element.simpleName} in class " + "${(element.enclosingElement as TypeElement).qualifiedName} is annotated with more than one of these annotations. You must annotate a field with exactly one of these annotations (not multiple)!") } // In the case that only text content annotation has been found if (textContent != null && annotationFound == 1) return null; if (attributeAnnotation != null) { val converterChecker = AttributeConverterChecker() return AttributeField(element, nameFromAnnotationOrField(attributeAnnotation.name, element), converterChecker.getQualifiedConverterName(element, attributeAnnotation)) } if (propertyAnnotation != null) { val converterChecker = PropertyElementConverterChecker() return PropertyField(element, nameFromAnnotationOrField(propertyAnnotation.name, element), propertyAnnotation.writeAsCData, converterChecker.getQualifiedConverterName(element, propertyAnnotation)) } if (elementAnnotation != null) { val nameMatchers = elementAnnotation.typesByElement // Check for primitives if (element.asType().kind != TypeKind.DECLARED) { throw ProcessingException(element, "The type of field '${element.simpleName}' in class ${element.enclosingElement} is not a class nor a interface. Only classes or interfaces can be annotated with @${Element::class.simpleName} annotation. If you try to annotate primitives than @${PropertyElement::class.simpleName}") } val checkTypeElement = fun(typeElement: TypeElement) { if (elementAnnotation.compileTimeChecks) { if (typeElement.isInterface()) { throw ProcessingException(element, "The type of field '${element.simpleName}' in class ${element.getSurroundingClassQualifiedName()} is an interface. Hence polymorphism must be resolved by annotating this interface with @${GenericAdapter::class.simpleName}!") } if (typeElement.isAbstract()) { throw ProcessingException(element, "The type of field '${element.simpleName}' in class ${element.getSurroundingClassQualifiedName()} is an abstract class. Hence polymorphism must be resolved by annotating this abstract class with @${GenericAdapter::class.simpleName}!") } else if (typeElement.isClass()) { checkNameMatchers(nameMatchers, element) } } } if (isList(element)) { val genericListType = getGenericTypeFromList(element) val genericListTypeElement = typeUtils.asElement(genericListType) as TypeElement val genericTypeNames = genericTypes[genericListTypeElement.toString()] if (genericTypeNames == null) { checkTypeElement(genericListTypeElement) val elementName = if (elementAnnotation.name.isEmpty()) { getXmlElementNameOrThrowException(element, genericListTypeElement, elementAnnotation.compileTimeChecks, true) } else { elementAnnotation.name } return ListElementField( element, elementName, genericListType ) } else { checkNameMatchers(nameMatchers, element) return PolymorphicListElementField( element, "placeholderToSubstituteWithPolymorphicListElement", getPolymorphicTypes(element, nameMatchers, genericTypeNames), genericListType ) } } else { val genericTypeNames = genericTypes[element.asType().toString()] val typeElement = (element.asType() as DeclaredType).asElement() as TypeElement return if (genericTypeNames == null) { checkTypeElement(typeElement) val elementName = if (elementAnnotation.name.isEmpty()) { getXmlElementNameOrThrowException(element, typeElement, elementAnnotation.compileTimeChecks, true) } else { elementAnnotation.name } ElementField(element, elementName) } else { checkNameMatchers(nameMatchers, element) PolymorphicElementField(element, "placeholderToSubstituteWithPolymorphicElement", getPolymorphicTypes(element, nameMatchers, genericTypeNames)) } } } throw ProcessingException(element, "Unknown annotation detected! I'm sorry, this should not happen. Please file an issue on github https://github.com/Tickaroo/tikxml/issues ") } /** * Checks whether or not thy element is of type (or subtype) java.util.List */ protected fun isList(element: VariableElement): Boolean = element.isList() val checkNameMatchers = fun(nameMatchers: Array<ElementNameMatcher>, element: VariableElement) { for (matcher in nameMatchers) { try { val typeClass = matcher.type val typeElement = elementUtils.getTypeElement(typeClass.qualifiedName) checkPublicClassWithEmptyConstructorOrAnnotatedConstructor(element, typeElement) checkTargetClassXmlAnnotated(element, typeElement) checkDuplicateNameMatchers(element, nameMatchers, matcher) } catch (mte: MirroredTypeException) { val typeMirror = mte.typeMirror val typeElement = (typeMirror as DeclaredType).asElement() as TypeElement checkPublicClassWithEmptyConstructorOrAnnotatedConstructor(element, typeElement) checkTargetClassXmlAnnotated(element, typeElement) checkDuplicateNameMatchers(element, nameMatchers, matcher) } } } val checkDuplicateNameMatchers = fun(element: VariableElement, nameMatchers: Array<ElementNameMatcher>, matcher: ElementNameMatcher) { val (matcherType, matcherName) = try { Pair(matcher.type, matcher.name) } catch (mte: MirroredTypeException) { Pair(mte.typeMirror, matcher.name.takeIf { it.isNotBlank() } ?: ((mte.typeMirror as DeclaredType).asElement() as TypeElement).getXmlElementName()) } val conflictingNameMatcher = nameMatchers.firstOrNull { nameMatcher -> val (nameMatcherType, nameMatcherName) = try { Pair(nameMatcher.type, matcher.name) } catch (mte: MirroredTypeException) { Pair(mte.typeMirror, nameMatcher.name.takeIf { it.isNotBlank() } ?: ((mte.typeMirror as DeclaredType).asElement() as TypeElement).getXmlElementName()) } nameMatcherName == matcherName && nameMatcherType != matcherType } if (conflictingNameMatcher != null) { val conflictingNameMatcherType = try { conflictingNameMatcher.type } catch (mte: MirroredTypeException) { mte.typeMirror } throw ProcessingException(element, "Conflict: A @${ElementNameMatcher::class.simpleName} with the name \"${matcher.name}\" is already mapped to the type $matcherType to resolve polymorphism. Hence it cannot be mapped to $conflictingNameMatcherType as well.") } } val checkTargetClassXmlAnnotated = fun(element: VariableElement, typeElement: TypeElement) { if (typeElement.getAnnotation(Xml::class.java) == null && (typeUtils.asElement( element.asType()) as TypeElement).hasSuperClass()) { throw ProcessingException(element, "The class ${typeElement.qualifiedName} is not annotated with @${Xml::class.simpleName}, but is used in '$element' in class @${element.getSurroundingClassQualifiedName()} to resolve polymorphism. Please annotate @${element.getSurroundingClassQualifiedName()} with @${Xml::class.simpleName}") } } private fun getPolymorphicTypes( element: VariableElement, matcherAnnotations: Array<ElementNameMatcher>, genericTypes: Set<String>? = null): List<PolymorphicTypeElementNameMatcher> { if (genericTypes == null && matcherAnnotations.isEmpty()) { throw ProcessingException(element, "Neither @${ElementNameMatcher::class.simpleName} nor @${GenericAdapter::class.simpleName} specified to resolve polymorphism!") } val namingMap = hashMapOf<String, PolymorphicTypeElementNameMatcher>() // add generic types first genericTypes?.forEach { qualifiedName -> val simpleName = elementUtils.getTypeElement(qualifiedName).getXmlElementName() namingMap[simpleName] = PolymorphicTypeElementNameMatcher(simpleName, elementUtils.getTypeElement(qualifiedName).asType()) } // maybe override with matcher annotations for (matcher in matcherAnnotations) { try { val typeClass = matcher.type val typeElement = elementUtils.getTypeElement(typeClass.qualifiedName) checkPublicClassWithEmptyConstructorOrAnnotatedConstructor(element, typeElement) checkTargetClassXmlAnnotated(element, typeElement) val xmlElementName = if (matcher.name.isEmpty()) typeElement.getXmlElementName() else matcher.name namingMap.values.firstOrNull { elementNameMatcher -> elementNameMatcher.type == typeElement.asType() } ?.also { elementNameMatcher -> namingMap.remove(elementNameMatcher.xmlElementName) } // delete common generic type if already in list namingMap[xmlElementName] = PolymorphicTypeElementNameMatcher(xmlElementName, typeElement.asType()) } catch (mte: MirroredTypeException) { val typeMirror = mte.typeMirror if (typeMirror.kind != TypeKind.DECLARED) { throw ProcessingException(element, "Only classes can be specified as type in @${ElementNameMatcher::class.simpleName}") } val typeElement = (typeMirror as DeclaredType).asElement() as TypeElement checkPublicClassWithEmptyConstructorOrAnnotatedConstructor(element, typeElement) checkTargetClassXmlAnnotated(element, typeElement) val xmlElementName = if (matcher.name.isEmpty()) typeElement.getXmlElementName() else matcher.name namingMap.values.firstOrNull { elementNameMatcher -> elementNameMatcher.type == typeMirror } ?.also { elementNameMatcher -> namingMap.remove(elementNameMatcher.xmlElementName) } namingMap[xmlElementName] = PolymorphicTypeElementNameMatcher(xmlElementName, typeElement.asType()) } } return namingMap.values.toList() } /** * Checks if a the typeElement is a public class (or default package visibility if in same package as variableElement) */ private fun checkPublicClassWithEmptyConstructorOrAnnotatedConstructor(variableElement: VariableElement, typeElement: TypeElement) { if (!typeElement.isClass()) { throw ProcessingException(variableElement, "@${ElementNameMatcher::class.simpleName} only allows classes. $typeElement is a not a class!") } if (typeElement.isPrivate()) { throw ProcessingException(variableElement, "@${ElementNameMatcher::class.simpleName} does not allow private classes. $typeElement is a private class!") } if (typeElement.isProtected()) { throw ProcessingException(variableElement, "@${ElementNameMatcher::class.simpleName} does not allow protected classes. $typeElement is a protected class!") } val hasSamePackage = typeElement.isSamePackageAs(variableElement.enclosingElement, elementUtils) val classIsPublic = typeElement.isPublic() if (!classIsPublic && !hasSamePackage) { throw ProcessingException(variableElement, "@${ElementNameMatcher::class.simpleName} does not allow package visiblity on classes outside of this package. Make $typeElement is a public class or move this class into the same package") } // Check for subtype val variableType = if (isList(variableElement)) getGenericTypeFromList(variableElement) else variableElement.asType() if (!typeUtils.isAssignable(typeElement.asType(), variableType)) { throw ProcessingException(variableElement, "The type $typeElement must be a sub type of ${variableType}. Otherwise this type cannot be used in @${ElementNameMatcher::class.simpleName} to resolve polymorphism.") } for (constructor in ElementFilter.constructorsIn(typeElement.enclosedElements)) { if (constructor.hasEmptyParameters()) { if (hasSamePackage and constructor.hasMinimumPackageVisibilityModifiers()) { return } if (classIsPublic and constructor.isPublic()) { return } } else if (constructor.parameters.filter { !(it as VariableElement).hasTikXmlAnnotation() }.isEmpty()) { return } } throw ProcessingException(variableElement, "Class $typeElement used in @${ElementNameMatcher:: class.simpleName} must provide an public empty (parameter-less) constructor") } /** * Get the genric type of a List */ protected fun getGenericTypeFromList(listVariableElement: VariableElement): TypeMirror { if (listVariableElement.asType().kind != TypeKind.DECLARED) { throw ProcessingException(listVariableElement, "Element must be of type java.util.List") } val typeMirror = listVariableElement.asType() as DeclaredType return when (typeMirror.typeArguments.size) { 0 -> elementUtils.getTypeElement("java.lang.Object").asType() // Raw types 1 -> if (typeMirror.typeArguments[0].kind == TypeKind.WILDCARD) { val wildCardMirror = typeMirror.typeArguments[0] as WildcardType when { wildCardMirror.extendsBound != null -> wildCardMirror.extendsBound wildCardMirror.superBound != null -> wildCardMirror.superBound else -> elementUtils.getTypeElement("java.lang.Object").asType() } // in case of List<?> } else typeMirror.typeArguments[0] else -> throw ProcessingException(listVariableElement, "Seems that you have annotated a List with more than one generic argument? How is this possible?") } } /** * Get the name of a annotated field from annotation or use the field name if no name set */ private fun nameFromAnnotationOrField(name: String, element: VariableElement) = if (name.isEmpty()) { element.simpleName.toString() } else name /** * Get the xmlElement name which is either @Xml(name = "foo") property or the class name decapitalize (first letter in lower case) */ private fun getXmlElementNameOrThrowException(field: VariableElement, typeElement: TypeElement, compileTimeChecks: Boolean, allowJavaObject: Boolean): String { val xmlAnnotation = typeElement.getAnnotation(Xml::class.java) val genericAdapterAnnotation = typeElement.getAnnotation(GenericAdapter::class.java) val annotationName = if (typeElement.isClass() && !typeElement.isAbstract()) "@${Xml::class.simpleName}" else "@${GenericAdapter::class.simpleName}" val checkAnnotation = (typeElement.isClass() && typeElement.hasSuperClass()) || !allowJavaObject if (xmlAnnotation == null && genericAdapterAnnotation == null && compileTimeChecks && checkAnnotation) { throw ProcessingException(field, "The type ${typeElement.qualifiedName} used for field '$field' in ${field.getSurroundingClassQualifiedName()} can't be used, because it is not annotated with $annotationName. Annotate ${typeElement.qualifiedName} with $annotationName!") } else { return typeElement.getXmlElementName() } } }
apache-2.0
8684fbf205d24dfdd0c331801a1e0bfd
44.232558
299
0.727307
4.993931
false
false
false
false
iSoron/uhabits
uhabits-server/src/main/kotlin/org/isoron/uhabits/sync/app/LinkModule.kt
1
1893
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.sync.app import io.ktor.application.* import io.ktor.http.* import io.ktor.request.* import io.ktor.response.* import io.ktor.routing.* import org.isoron.uhabits.sync.* data class LinkRegisterRequestData( val syncKey: String, ) fun LinkRegisterRequestData.toJson(): String = defaultMapper.writeValueAsString(this) fun Routing.links(app: SyncApplication) { post("/links") { try { val data = call.receive<LinkRegisterRequestData>() val link = app.server.registerLink(data.syncKey) call.respond(HttpStatusCode.OK, link) } catch (e: ServiceUnavailable) { call.respond(HttpStatusCode.ServiceUnavailable) } } get("/links/{id}") { try { val id = call.parameters["id"]!! val link = app.server.getLink(id) call.respond(HttpStatusCode.OK, link) } catch (e: ServiceUnavailable) { call.respond(HttpStatusCode.ServiceUnavailable) } catch (e: KeyNotFoundException) { call.respond(HttpStatusCode.NotFound) } } }
gpl-3.0
08bc060fe5d0ff0ee3bae70a5de02d43
33.4
85
0.682347
4.122004
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
1
32032
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.updateSettings.impl import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.ExternalComponentSource import com.intellij.ide.plugins.* import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.fus.MachineIdManager import com.intellij.notification.* import com.intellij.notification.impl.NotificationsConfigurationImpl import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.* import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.reference.SoftReference import com.intellij.util.Urls import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.jdom.JDOMException import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import javax.swing.JComponent import kotlin.Result import kotlin.concurrent.withLock /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. */ object UpdateChecker { private val LOG = logger<UpdateChecker>() private const val DISABLED_UPDATE = "disabled_update.txt" private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt" private const val PRODUCT_DATA_TTL_MIN = 5L private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled" private const val MACHINE_ID_PARAMETER = "mid" private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL } private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl private val productDataLock = ReentrantLock() private var productDataCache: SoftReference<Result<Product?>>? = null private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap() private val ourShownNotifications = MultiMap<NotificationKind, Notification>() private var machineIdInitialized = false /** * Adding a plugin ID to this collection allows excluding a plugin from a regular update check. * Has no effect on non-bundled plugins. */ val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf() init { UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString()) UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get()) UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ExternalUpdateManager.ACTUAL != null) { val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName UpdateRequestParameters.addParameter("manager", name) } if (ApplicationInfoEx.getInstanceEx().isEAP) { UpdateRequestParameters.addParameter("eap", "") } } @JvmStatic fun getNotificationGroup(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates") @JvmStatic fun getNotificationGroupForPluginUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results") @JvmStatic fun getNotificationGroupForIdeUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE Update Results") /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { return ActionCallback().also { ProcessIOExecutorService.INSTANCE.execute { doUpdateAndShowResult( userInitiated = false, preferDialog = false, showSettingsLink = true, callback = it, ) } } } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action passes customized update settings and forces results presentation in a dialog). */ @JvmStatic @JvmOverloads fun updateAndShowResult( project: Project?, customSettings: UpdateSettings? = null, ) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult( getProject(), customSettings, userInitiated = true, preferDialog = isConditionalModal, showSettingsLink = shouldStartInBackground(), indicator = indicator, ) override fun isConditionalModal(): Boolean = customSettings != null override fun shouldStartInBackground(): Boolean = !isConditionalModal }) } @JvmStatic private fun doUpdateAndShowResult( project: Project? = null, customSettings: UpdateSettings? = null, userInitiated: Boolean, preferDialog: Boolean, showSettingsLink: Boolean, indicator: ProgressIndicator? = null, callback: ActionCallback? = null, ) { if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) { machineIdInitialized = true val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "") if (machineId != null) { UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId) } } val updateSettings = customSettings ?: UpdateSettings.getInstance() val platformUpdates = getPlatformUpdates(updateSettings, indicator) if (platformUpdates is PlatformUpdates.ConnectionError) { if (userInitiated) { showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog) } callback?.setRejected() return } val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates( (platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion, indicator, ) indicator?.text = IdeBundle.message("updates.external.progress") val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator) UpdateSettings.getInstance().saveLastCheckedInfo() if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) { val builder = HtmlBuilder() internalErrors.forEach { (host, ex) -> if (!builder.isEmpty) builder.br() val message = host?.let { IdeBundle.message("updates.plugins.error.message2", it, ex.message) } ?: IdeBundle.message("updates.plugins.error.message1", ex.message) builder.append(message) } externalErrors.forEach { (key, value) -> if (!builder.isEmpty) builder.br() builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message)) } showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog) } ApplicationManager.getApplication().invokeLater { fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) } val enabledPlugins = nonIgnored(pluginUpdates.allEnabled) val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled) val forceDialog = preferDialog || userInitiated && !notificationsEnabled() if (platformUpdates is PlatformUpdates.Loaded) { showResults( project, platformUpdates, updatedPlugins, pluginUpdates.incompatible, showNotification = userInitiated || WelcomeFrame.getInstance() != null, forceDialog, showSettingsLink, ) } else { showResults( project, updatedPlugins, customRepoPlugins, externalUpdates, enabledPlugins.isNotEmpty(), userInitiated, forceDialog, showSettingsLink, ) } callback?.setDone() } } @JvmOverloads @JvmStatic @JvmName("getPlatformUpdates") internal fun getPlatformUpdates( settings: UpdateSettings = UpdateSettings.getInstance(), indicator: ProgressIndicator? = null, ): PlatformUpdates = try { indicator?.text = IdeBundle.message("updates.checking.platform") val productData = loadProductData(indicator) if (productData == null || !settings.isCheckNeeded || ExternalUpdateManager.ACTUAL != null) { PlatformUpdates.Empty } else { UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates() } } catch (e: Exception) { LOG.infoWithDebug(e) when (e) { is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling users else -> PlatformUpdates.ConnectionError(e) } } @JvmStatic @Throws(IOException::class, JDOMException::class) fun loadProductData(indicator: ProgressIndicator?): Product? = productDataLock.withLock { val cached = SoftReference.dereference(productDataCache) if (cached != null) return@withLock cached.getOrThrow() val result = runCatching { var url = Urls.newFromEncoded(updateUrl) if (url.scheme != URLUtil.FILE_PROTOCOL) { url = UpdateRequestParameters.amendUpdateRequest(url) } LOG.debug { "loading ${url}" } HttpRequests.request(url) .connect { JDOMUtil.load(it.getReader(indicator)) } .let { parseUpdateData(it) } ?.also { if (it.disableMachineId) { PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true) UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER) } } } productDataCache = SoftReference(result) AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES) return@withLock result.getOrThrow() } private fun clearProductDataCache() { if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // a longer time means loading now, no much sense in clearing productDataCache = null productDataLock.unlock() } } @ApiStatus.Internal @JvmStatic fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) { if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { ApplicationManager.getApplication().executeOnPooledThread { val updateable = collectUpdateablePlugins() if (updateable.isNotEmpty()) { findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null) } } } } /** * When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version, * otherwise, returns versions compatible with the specified build. */ @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads @JvmStatic fun getInternalPluginUpdates( buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): InternalPluginResults { indicator?.text = IdeBundle.message("updates.checking.plugins") if (System.getProperty("idea.ignore.disabled.plugins") == null) { val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build) if (brokenPlugins.isNotEmpty()) { PluginManagerCore.updateBrokenPlugins(brokenPlugins) } } val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) { return InternalPluginResults(PluginUpdates()) } val toUpdate = HashMap<PluginId, PluginDownloader>() val toUpdateDisabled = HashMap<PluginId, PluginDownloader>() val customRepoPlugins = HashMap<PluginId, PluginNode>() val errors = LinkedHashMap<String?, Exception>() val state = InstalledPluginsState.getInstance() for (host in RepositoryHelper.getPluginHosts()) { try { if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator) } else { RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor -> val id = descriptor.pluginId if (updateable.remove(id) != null) { prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host) } // collect latest plugins from custom repos val storedDescriptor = customRepoPlugins[id] if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) { customRepoPlugins[id] = descriptor } } } } catch (e: Exception) { LOG.info( "failed to load plugins from ${host ?: "default repository"}: ${e.message}", if (LOG.isDebugEnabled) e else null, ) errors[host] = e } } val incompatible = if (buildNumber == null) emptyList() else { // collecting plugins that aren't going to be updated and are incompatible with the new build // (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE) updateable.values.asSequence() .filterNotNull() .filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) } .toSet() } return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors) } private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> { val updateable = HashMap<PluginId, IdeaPluginDescriptor?>() // installed plugins that could be updated (either downloaded or updateable bundled) PluginManagerCore.getPlugins() .filter { !it.isBundled || it.allowBundledUpdate() } .associateByTo(updateable) { it.pluginId } // plugins installed in an instance from which the settings were imported val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { Files.readAllLines(onceInstalled).forEach { line -> val id = PluginId.getId(line.trim { it <= ' ' }) updateable.putIfAbsent(id, null) } } catch (e: IOException) { LOG.error(onceInstalled.toString(), e) } @Suppress("SSBasedInspection") onceInstalled.toFile().deleteOnExit() } // excluding plugins that take care of their own updates if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) { excludedFromUpdateCheckPlugins.forEach { val id = PluginId.getId(it) val plugin = updateable[id] if (plugin != null && plugin.isBundled) { updateable.remove(id) } } } return updateable } @RequiresBackgroundThread @RequiresReadLockAbsence private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber?, state: InstalledPluginsState, indicator: ProgressIndicator?) { val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator) val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet() val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber) updateable.forEach { (id, descriptor) -> val lastUpdate = updates.find { it.pluginId == id.idString } if (lastUpdate != null && (descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor, buildNumber) > 0)) { runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) } .onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it } .onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) } } } (toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) } } private fun prepareDownloader(state: InstalledPluginsState, descriptor: PluginNode, buildNumber: BuildNumber?, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, indicator: ProgressIndicator?, host: String?) { val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber) state.onDescriptorDownload(descriptor) checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator) } @JvmOverloads @JvmStatic fun getExternalPluginUpdates( updateSettings: UpdateSettings, indicator: ProgressIndicator? = null, ): ExternalPluginResults { val result = ArrayList<ExternalUpdate>() val errors = LinkedHashMap<ExternalComponentSource, Exception>() val manager = ExternalComponentManager.getInstance() for (source in ExternalComponentManager.getComponentSources()) { indicator?.checkCanceled() try { val siteResult = source.getAvailableVersions(indicator, updateSettings) .filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) } if (siteResult.isNotEmpty()) { result += ExternalUpdate(source, siteResult) } } catch (e: Exception) { LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null) errors[source] = e } } return ExternalPluginResults(result, errors) } @Throws(IOException::class) @JvmOverloads @JvmStatic fun checkAndPrepareToInstall( originalDownloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ) { val pluginId = originalDownloader.id val pluginVersion = originalDownloader.pluginVersion val installedPlugin = PluginManagerCore.getPlugin(pluginId) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) { val oldDownloader = ourUpdatedPlugins[pluginId] val downloader = if (PluginManagerCore.isDisabled(pluginId)) { originalDownloader } else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { val descriptor = originalDownloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator()) ourUpdatedPlugins[pluginId] = originalDownloader } originalDownloader } else { oldDownloader } val descriptor = downloader.descriptor if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate[pluginId] = downloader } } } private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) { if (preferDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) } } else { getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project) } } @RequiresEdt private fun showResults( project: Project?, updatedPlugins: List<PluginDownloader>, customRepoPlugins: Collection<PluginNode>, externalUpdates: Collection<ExternalUpdate>, pluginsEnabled: Boolean, userInitiated: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (pluginsEnabled) { if (userInitiated) { ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() } } val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins) if (userInitiated) { val updatedPluginNames = updatedPlugins.map { it.pluginName } val (title, message) = when (updatedPluginNames.size) { 1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0]) else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" } } showNotification( project, NotificationKind.PLUGINS, "plugins.update.available", title, message, NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ -> PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null) }, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable), NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) { ignorePlugins(updatedPlugins.map { it.descriptor }) }) } } } if (externalUpdates.isNotEmpty()) { ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (forceDialog) { runnable() } else { val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", ")) showNotification( project, NotificationKind.EXTERNAL, "external.components.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable)) } } } else if (!pluginsEnabled) { if (forceDialog) { NoUpdatesDialog(showSettingsLink).show() } else if (userInitiated) { showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText()) } } } @RequiresEdt private fun showResults( project: Project?, platformUpdates: PlatformUpdates.Loaded, updatedPlugins: List<PluginDownloader>, incompatiblePlugins: Collection<IdeaPluginDescriptor>, showNotification: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (showNotification) { ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() } } val runnable = { UpdateInfoDialog( project, platformUpdates, showSettingsLink, updatedPlugins, incompatiblePlugins, ).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins) if (showNotification) { IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project) val message = IdeBundle.message( "updates.new.build.notification.title", ApplicationNamesInfo.getInstance().fullProductName, platformUpdates.newBuild.version, ) showNotification( project, NotificationKind.PLATFORM, "ide.update.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) { IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project) runnable() }) } } } private fun notificationsEnabled(): Boolean = NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS && NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE private fun showNotification(project: Project?, kind: NotificationKind, displayId: String, @NlsContexts.NotificationTitle title: String, @NlsContexts.NotificationContent message: String, vararg actions: NotificationAction) { val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type) .setDisplayId(displayId) .setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST) notification.whenExpired { ourShownNotifications.remove(kind, notification) } actions.forEach { notification.addAction(it) } notification.notify(project) ourShownNotifications.putValue(kind, notification) } @JvmStatic val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) } @JvmStatic fun saveDisabledToUpdatePlugins() { runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) } .onFailure { LOG.error(it) } } @JvmStatic @JvmName("isIgnored") internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean = descriptor.ignoredKey in ignoredPlugins @JvmStatic @JvmName("ignorePlugins") internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) { ignoredPlugins += descriptors.map { it.ignoredKey } runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) } .onFailure { LOG.error(it) } UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors) } private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) } private val IdeaPluginDescriptor.ignoredKey: String get() = "${pluginId.idString}+${version}" private fun readConfigLines(fileName: String): List<String> { if (!ApplicationManager.getApplication().isUnitTestMode) { runCatching { val file = Path.of(PathManager.getConfigPath(), fileName) if (Files.isRegularFile(file)) { return Files.readAllLines(file) } }.onFailure { LOG.error(it) } } return emptyList() } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) { val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } /** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */ @ApiStatus.Internal fun testPlatformUpdate( project: Project?, updateDataText: String, patchFile: File?, forceUpdate: Boolean, ) { if (!ApplicationManager.getApplication().isInternal) { throw IllegalStateException() } val currentBuild = ApplicationInfo.getInstance().build val productCode = currentBuild.productCode val checkForUpdateResult = if (forceUpdate) { val node = JDOMUtil.load(updateDataText) .getChild("product") ?.getChild("channel") ?: throw IllegalArgumentException("//channel missing") val channel = UpdateChannel(node, productCode) val newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing") val patches = newBuild.patches.firstOrNull() ?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) } PlatformUpdates.Loaded(newBuild, channel, patches) } else { UpdateStrategy( currentBuild, parseUpdateData(updateDataText, productCode), ).checkForUpdates() } val dialog = when (checkForUpdateResult) { is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile) else -> NoUpdatesDialog(true) } dialog.show() } //<editor-fold desc="Deprecated stuff."> @ApiStatus.ScheduledForRemoval @Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()") @Suppress("DEPRECATION", "unused") @JvmField val NOTIFICATIONS = NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID) @get:ApiStatus.ScheduledForRemoval @get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Suppress("unused") @JvmStatic val disabledToUpdatePlugins: Set<String> get() = disabledToUpdate.mapTo(TreeSet()) { it.idString } @ApiStatus.ScheduledForRemoval @Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith("")) @JvmStatic fun getPluginUpdates(): Collection<PluginDownloader>? = getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null } //</editor-fold> }
apache-2.0
ffb77503b426e89f91d4477cf8339134
38.94015
156
0.697271
5.425474
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/implicitCasts/ktij-16665.kt
8
321
object J { private fun byteToInt(b: ByteArray): Int { var i = 0 var result = 0 var shift = 0 while (i < b.size) { val be = b[i] result = result or (be.toInt() and 0xff shl shift) shift += 8 i += 1 } return result } }
apache-2.0
a5b6704e1eab5fdbf5d41e1f87708870
21.928571
62
0.426791
3.914634
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/iam/src/main/kotlin/com/kotlin/iam/DetachRolePolicy.kt
1
1929
// snippet-sourcedescription:[DetachRolePolicy.kt demonstrates how to detach a policy from an AWS Identity and Access Management (IAM) role.] // 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.detach_role_policy.import] import aws.sdk.kotlin.services.iam.IamClient import aws.sdk.kotlin.services.iam.model.DetachRolePolicyRequest import kotlin.system.exitProcess // snippet-end:[iam.kotlin.detach_role_policy.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: <roleName> <policyArn> Where: roleName - A role name that you can obtain from the AWS Management Console. policyArn - A policy ARN that you can obtain from the AWS Management Console. """ if (args.size != 2) { println(usage) exitProcess(0) } val roleName = args[0] val policyArn = args[1] detachPolicy(roleName, policyArn) } // snippet-start:[iam.kotlin.detach_role_policy.main] suspend fun detachPolicy(roleNameVal: String, policyArnVal: String) { val request = DetachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.detachRolePolicy(request) println("Successfully detached policy $policyArnVal from role $roleNameVal") } } // snippet-end:[iam.kotlin.detach_role_policy.main]
apache-2.0
8df2dae421f503c40d40662893d0a218
30.694915
141
0.686366
4.035565
false
false
false
false
nukc/RecyclerAdapter
app/src/main/java/com/github/nukc/recycleradapter/sample/AlphaAndScalePageTransformer.kt
1
737
package com.github.nukc.recycleradapter.sample import android.view.View import androidx.viewpager.widget.ViewPager private const val SCALE_MAX = 0.8f class AlphaAndScalePageTransformer : ViewPager.PageTransformer { override fun transformPage(page: View, position: Float) { val scale = if (position < 0) { (1 - SCALE_MAX) * position + 1 } else { (SCALE_MAX - 1) * position + 1 } if (position < 0) { page.pivotX = page.width.toFloat() page.pivotY = (page.height / 2).toFloat() } else { page.pivotX = 0f page.pivotY = (page.height / 2).toFloat() } page.scaleX = scale page.scaleY = scale } }
apache-2.0
9863959f440e7fd1c21f62d65f1499dd
26.333333
64
0.578019
3.899471
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/model/net/bean/Type.kt
1
785
package xyz.sachil.essence.model.net.bean import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "type_table") data class Type( @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo(name = "category") var category: String = "", @ColumnInfo(name = "type_id") @SerializedName("_id") val typeId: String, @ColumnInfo(name = "cover_image_url") @SerializedName("coverImageUrl") val imageUrl: String, @ColumnInfo(name = "description") @SerializedName("desc") val description: String, @ColumnInfo(name = "title") @SerializedName("title") val title: String, @ColumnInfo(name = "type") @SerializedName("type") val type: String )
apache-2.0
16e0b4c52a9635715d2ad102566c964c
45.176471
96
0.727389
3.886139
false
false
false
false
georocket/georocket
src/main/kotlin/io/georocket/util/StringWindow.kt
1
3597
package io.georocket.util import io.vertx.core.buffer.Buffer import java.nio.CharBuffer import java.lang.StringBuilder import java.lang.IllegalStateException import java.nio.ByteBuffer import java.nio.charset.* /** * A dynamically resizable buffer that acts like a window being moved over * a larger input stream * @author Michel Kraemer */ class StringWindow { companion object { /** * Default size for [.charBuf] */ private const val DEFAULT_CHAR_BUFFER_SIZE = 2048 } /** * Decodes incoming byte buffers into strings */ private val decoder = StandardCharsets.UTF_8.newDecoder() /** * A temporary character buffer used during string decoding */ private var charBuf = CharBuffer.allocate(DEFAULT_CHAR_BUFFER_SIZE) /** * A temporary buffer holding bytes that still need to be decoded */ private var buf = Buffer.buffer() /** * A buffer holding the decoded string */ private val decodedBuf = StringBuilder() /** * The current position in the window (i.e. in the decoded string) */ private var pos: Long = 0 /** * Ensure the character buffer is large enough to hold a given number of * decoded characters * @param length the length of the encoded byte buffer */ private fun ensureCharBuffer(length: Int) { val maxLength = (length.toDouble() * decoder.maxCharsPerByte()).toInt() if (maxLength > charBuf.length) { charBuf = CharBuffer.allocate(maxLength) } } /** * Append data to the window (i.e. make it larger) * @param buf the data to append */ fun append(buf: Buffer) { // append new bytes to buffered bytes or use them directly if (this.buf.length() > 0) { this.buf.appendBuffer(buf) } else { this.buf = buf } // convert Vert.x buffer to ByteBuffer (ugly!) val byteBuf = ByteBuffer.wrap(this.buf.bytes) // prepare temporary CharBuffer ensureCharBuffer(buf.length()) charBuf.position(0) charBuf.limit(charBuf.capacity()) // decode ByteBuffer to temporary CharBuffer val result = decoder.decode(byteBuf, charBuf, false) if (result.isMalformed) { throw IllegalStateException( MalformedInputException(result.length()) ) } if (result.isUnmappable) { throw IllegalStateException( UnmappableCharacterException(result.length()) ) } // reset CharBuffer and remove decoded bytes from byte buffer charBuf.flip() this.buf = this.buf.getBuffer(byteBuf.position(), this.buf.length()) // append to decoded string buffer decodedBuf.append(charBuf) } /** * Return a chunk from the window * @param startCharacter the start position of the chunk (in characters and * not bytes). This value is absolute to the position in the larger input * stream the window is being moved over. * @param endCharacter the end position of the chunk (in characters and not * bytes). This value is absolute to the position in the larger input stream * the window is being moved over. * @return the chunk */ fun getChars(startCharacter: Long, endCharacter: Long): String { return decodedBuf.substring((startCharacter - pos).toInt(), (endCharacter - pos).toInt()) } /** * Remove characters from the beginning of the window (i.e. make it smaller) * @param pos the number of characters to remove (or in other words: the number * of characters to advance the window forward without changing its end) */ fun advanceTo(pos: Long) { decodedBuf.delete(0, (pos - this.pos).toInt()) this.pos = pos } }
apache-2.0
6b3d955de69f3627e3b07820e0753975
27.322835
93
0.682513
4.172854
false
false
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/analytics/FirebaseAnalyticsImpl.kt
3
4794
package com.alexstyl.specialdates.analytics import android.os.Bundle import android.support.annotation.NonNull import android.support.annotation.Size import com.alexstyl.specialdates.TimeOfDay import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.donate.Donation import com.alexstyl.specialdates.events.peopleevents.EventType import com.google.firebase.analytics.FirebaseAnalytics class FirebaseAnalyticsImpl(private val firebase: FirebaseAnalytics) : Analytics { override fun trackThemeSelected(string: String) { firebase.logEvent(Action.SELECT_THEME.name, Bundle().apply { putString("theme name", string) }) } override fun trackScreen(screen: Screen) { val bundle = Bundle() bundle.putString("screen_name", screen.screenName()) firebase.logEvent("screen_view", bundle) } override fun trackAddEventsCancelled() { firebase.logEvent("add_events_cancelled") } override fun trackEventAddedSuccessfully() { firebase.logEvent("add_events_success") } override fun trackContactSelected() { firebase.logEvent("contact_selected") } override fun trackEventDatePicked(eventType: EventType) { val properties = createPropertyFor(eventType) firebase.logEvent("event_date_picked", properties) } override fun trackEventRemoved(eventType: EventType) { val properties = createPropertyFor(eventType) firebase.logEvent("event_removed", properties) } override fun trackImageCaptured() { firebase.logEvent("image_captured") } override fun trackExistingImagePicked() { firebase.logEvent("existing_image_picked") } override fun trackAvatarSelected() { firebase.logEvent("avatar_selected") } override fun trackContactUpdated() { firebase.logEvent("contact_updated") } override fun trackContactCreated() { firebase.logEvent("contact_created") } override fun trackDailyReminderEnabled() { firebase.logEvent("daily_reminder_enabled") } override fun trackDailyReminderDisabled() { firebase.logEvent("daily_reminder_disabled") } override fun trackDailyReminderTimeUpdated(timeOfDay: TimeOfDay) { val properties = createPropertyFor(timeOfDay) firebase.logEvent("daily_reminder_time_updated", properties) } override fun trackWidgetAdded(widget: Widget) { firebase.logEvent("widget_added", widgetNameOf(widget)) } private fun widgetNameOf(widget: Widget): Bundle { return Bundle().apply { putString("widget_name", widget.widgetName) } } override fun trackWidgetRemoved(widget: Widget) { firebase.logEvent("widget_removed", widgetNameOf(widget)) } override fun trackDonationStarted(donation: Donation) { val properties = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, donation.identifier) putString(FirebaseAnalytics.Param.PRICE, donation.amount) } firebase.logEvent("donation_started", properties) } override fun trackAppInviteRequested() { firebase.logEvent("app_invite_requested") } override fun trackDonationRestored() { firebase.logEvent("donation_restored") } override fun trackDonationPlaced(donation: Donation) { val properties = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, donation.identifier) putString(FirebaseAnalytics.Param.PRICE, donation.amount) } firebase.logEvent(FirebaseAnalytics.Event.ECOMMERCE_PURCHASE, properties) } override fun trackFacebookLoggedIn() { firebase.logEvent("facebook_log_in") } override fun trackOnAvatarBounce() { firebase.logEvent("avatar_bounce") } override fun trackFacebookLoggedOut() { firebase.logEvent("facebook_log_out") } override fun trackVisitGithub() { firebase.logEvent("visit_github") } override fun trackContactDetailsViewed(contact: Contact) { firebase.logEvent("view_contact_details") } override fun trackNamedaysScreen() { firebase.logEvent("namedays_screen") } private fun createPropertyFor(eventType: EventType): Bundle { val properties = Bundle() properties.putInt("event_type", eventType.id) return properties } private fun createPropertyFor(timeOfDay: TimeOfDay): Bundle { return Bundle().apply { putString("time", timeOfDay.toString()) } } private fun FirebaseAnalytics.logEvent(@NonNull @Size(min = 1L, max = 40L) eventName: String) { return logEvent(eventName, Bundle.EMPTY) } }
mit
23d21f410ae662503b8dac125bbfc20e
29.150943
99
0.683563
4.7749
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsList.kt
1
5903
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.ide.CopyProvider import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.ide.CopyPasteManager import com.intellij.ui.ListUtil import com.intellij.ui.ScrollingUtil import com.intellij.ui.components.JBList import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.* import icons.GithubIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.GithubSearchedIssue import org.jetbrains.plugins.github.pullrequest.action.GithubPullRequestKeys import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider import org.jetbrains.plugins.github.util.GithubUIUtil import java.awt.Component import java.awt.FlowLayout import java.awt.datatransfer.StringSelection import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* internal class GithubPullRequestsList(private val copyPasteManager: CopyPasteManager, avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory, model: ListModel<GithubSearchedIssue>) : JBList<GithubSearchedIssue>(model), CopyProvider, DataProvider, Disposable { private val avatarIconSize = JBValue.UIInteger("Github.PullRequests.List.Assignee.Avatar.Size", 20) private val avatarIconsProvider = avatarIconsProviderFactory.create(avatarIconSize, this) init { selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION addMouseListener(RightClickSelectionListener()) val renderer = PullRequestsListCellRenderer() cellRenderer = renderer UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer)) ScrollingUtil.installActions(this) } override fun getToolTipText(event: MouseEvent): String? { val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point) if (childComponent !is JComponent) return null return childComponent.toolTipText } override fun performCopy(dataContext: DataContext) { if (selectedIndex < 0) return val selection = model.getElementAt(selectedIndex) copyPasteManager.setContents(StringSelection("#${selection.number} ${selection.title}")) } override fun isCopyEnabled(dataContext: DataContext) = !isSelectionEmpty override fun isCopyVisible(dataContext: DataContext) = false override fun getData(dataId: String): Any? = when { PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this GithubPullRequestKeys.SELECTED_SEARCHED_ISSUE.`is`(dataId) -> selectedValue else -> null } override fun dispose() {} private inner class PullRequestsListCellRenderer : ListCellRenderer<GithubSearchedIssue>, JPanel() { private val stateIcon = JLabel() private val title = JLabel() private val info = JLabel() private val labels = JPanel(FlowLayout(FlowLayout.LEFT, 4, 0)) private val assignees = JPanel().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) } init { border = JBUI.Borders.empty(5, 8) layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fillX()) add(stateIcon, CC() .gapAfter("${JBUI.scale(5)}px")) add(title, CC() .minWidth("0px")) add(labels, CC() .growX() .pushX()) add(assignees, CC() .spanY(2) .wrap()) add(info, CC() .minWidth("0px") .skip(1) .spanX(2)) } override fun getListCellRendererComponent(list: JList<out GithubSearchedIssue>, value: GithubSearchedIssue, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { UIUtil.setBackgroundRecursively(this, GithubUIUtil.List.WithTallRow.background(list, isSelected)) val primaryTextColor = GithubUIUtil.List.WithTallRow.foreground(list, isSelected) val secondaryTextColor = GithubUIUtil.List.WithTallRow.secondaryForeground(list, isSelected) stateIcon.apply { icon = if (value.state == GithubIssueState.open) GithubIcons.PullRequestOpen else GithubIcons.PullRequestClosed } title.apply { text = value.title foreground = primaryTextColor } info.apply { text = "#${value.number} ${value.user.login} on ${DateFormatUtil.formatDate(value.createdAt)}" foreground = secondaryTextColor } labels.apply { removeAll() for (label in value.labels.orEmpty()) add(GithubUIUtil.createIssueLabelLabel(label)) } assignees.apply { removeAll() for (assignee in value.assignees) { if (componentCount != 0) { add(Box.createRigidArea(JBDimension(UIUtil.DEFAULT_HGAP, 0))) } add(JLabel().apply { icon = assignee.let { avatarIconsProvider.getIcon(it) } toolTipText = assignee.login }) } } return this } } private inner class RightClickSelectionListener : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (JBSwingUtilities.isRightMouseButton(e)) { val row = locationToIndex(e.point) if (row != -1) selectionModel.setSelectionInterval(row, row) } } } }
apache-2.0
9fb0930589dc72b712b8845d7b04e79b
36.846154
140
0.688125
4.870462
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/ResponseComparisonDialog.kt
2
2277
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.apache.causeway.client.kroviz.ui.dialog import io.kvision.utils.obj import org.apache.causeway.client.kroviz.core.event.LogEntryComparison import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.core.FormItem import org.apache.causeway.client.kroviz.ui.core.RoDialog import org.apache.causeway.client.kroviz.utils.js.Diff import org.apache.causeway.client.kroviz.utils.js.Diff2Html class ResponseComparisonDialog(obj: LogEntryComparison) : Controller() { init { val html = diff2Html(obj) val fi = FormItem("Diff", ValueType.HTML, html, size = 30) val formItems = mutableListOf<FormItem>() formItems.add(fi) val title = "Diff: " + obj.title dialog = RoDialog( caption = title, items = formItems, controller = this, widthPerc = 80, heightPerc = 70, customButtons = mutableListOf() ) super.open() } private fun diff2Html(obj: LogEntryComparison): String { val oldText: String = obj.expectedResponse!! val newText: String = obj.actualResponse!! val diff = Diff.createTwoFilesPatch("file", "file", oldText, newText); val options = obj { drawFileList = false matching = "lines" outputFormat = "line-by-line" } val html = Diff2Html.html(diff, options) return html } }
apache-2.0
a4940480fcb761a101d42e6240d3b0ee
35.725806
78
0.681159
4.185662
false
false
false
false
google/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerBridge.kt
5
7291
// 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.openapi.externalSystem.service.project import com.intellij.openapi.application.WriteAction import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.module.Module import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ExternalSystemModuleOptionsEntity import com.intellij.workspaceModel.storage.bridgeEntities.getOrCreateExternalSystemModuleOptions class ExternalSystemModulePropertyManagerBridge(private val module: Module) : ExternalSystemModulePropertyManager() { private fun findEntity(): ExternalSystemModuleOptionsEntity? { val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY) val storage = if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).entityStorage.current val moduleEntity = storage.findModuleEntity(module as ModuleBridge) return moduleEntity?.exModuleOptions } @Synchronized private fun editEntity(action: ExternalSystemModuleOptionsEntity.Builder.() -> Unit) { editEntity(getModuleDiff(), action) } @Synchronized private fun editEntity(moduleDiff: MutableEntityStorage?, action: ExternalSystemModuleOptionsEntity.Builder.() -> Unit) { module as ModuleBridge if (moduleDiff != null) { val moduleEntity = (moduleDiff as EntityStorage).findModuleEntity(module) ?: return val options = moduleDiff.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource) moduleDiff.modifyEntity(ExternalSystemModuleOptionsEntity.Builder::class.java, options, action) } else { WriteAction.runAndWait<RuntimeException> { WorkspaceModel.getInstance(module.project).updateProjectModel { builder -> val moduleEntity = builder.findModuleEntity(module) ?: return@updateProjectModel val options = builder.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource) builder.modifyEntity(ExternalSystemModuleOptionsEntity.Builder::class.java, options, action) } } } } @Synchronized private fun updateSource() { updateSource(getModuleDiff()) } @Synchronized private fun updateSource(storageBuilder: MutableEntityStorage?) { module as ModuleBridge val storage = storageBuilder ?: module.entityStorage.current val moduleEntity = storage.findModuleEntity(module) ?: return val externalSystemId = moduleEntity.exModuleOptions?.externalSystem val entitySource = moduleEntity.entitySource if (externalSystemId == null && entitySource is JpsFileEntitySource || externalSystemId != null && (entitySource as? JpsImportedEntitySource)?.externalSystemId == externalSystemId && entitySource.storedExternally == module.project.isExternalStorageEnabled || entitySource !is JpsFileEntitySource && entitySource !is JpsImportedEntitySource) { return } val newSource = if (externalSystemId == null) { (entitySource as JpsImportedEntitySource).internalFile } else { val internalFile = entitySource as? JpsFileEntitySource ?: (entitySource as JpsImportedEntitySource).internalFile JpsImportedEntitySource(internalFile, externalSystemId, module.project.isExternalStorageEnabled) } ModuleManagerBridgeImpl.changeModuleEntitySource(module, storage, newSource, storageBuilder) } override fun getExternalSystemId(): String? = findEntity()?.externalSystem override fun getExternalModuleType(): String? = findEntity()?.externalSystemModuleType override fun getExternalModuleVersion(): String? = findEntity()?.externalSystemModuleVersion override fun getExternalModuleGroup(): String? = findEntity()?.externalSystemModuleGroup override fun getLinkedProjectId(): String? = findEntity()?.linkedProjectId override fun getRootProjectPath(): String? = findEntity()?.rootProjectPath override fun getLinkedProjectPath(): String? = findEntity()?.linkedProjectPath override fun isMavenized(): Boolean = getExternalSystemId() == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID override fun setMavenized(mavenized: Boolean) { setMavenized(mavenized, getModuleDiff()) } fun setMavenized(mavenized: Boolean, storageBuilder: MutableEntityStorage?) { if (mavenized) { unlinkExternalOptions(storageBuilder) } editEntity(storageBuilder) { externalSystem = if (mavenized) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null } updateSource(storageBuilder) } override fun unlinkExternalOptions() { unlinkExternalOptions(getModuleDiff()) } private fun unlinkExternalOptions(storageBuilder: MutableEntityStorage?) { editEntity(storageBuilder) { externalSystem = null externalSystemModuleVersion = null externalSystemModuleGroup = null linkedProjectId = null linkedProjectPath = null rootProjectPath = null } updateSource(storageBuilder) } override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) { editEntity { externalSystem = id.toString() linkedProjectId = moduleData.id linkedProjectPath = moduleData.linkedExternalProjectPath rootProjectPath = projectData?.linkedExternalProjectPath ?: "" externalSystemModuleGroup = moduleData.group externalSystemModuleVersion = moduleData.version } updateSource() } override fun setExternalId(id: ProjectSystemId) { editEntity { externalSystem = id.id } updateSource() } override fun setLinkedProjectPath(path: String?) { editEntity { linkedProjectPath = path } } override fun setRootProjectPath(path: String?) { editEntity { rootProjectPath = path } } override fun setExternalModuleType(type: String?) { editEntity { externalSystemModuleType = type } } override fun swapStore() { } private fun getModuleDiff(): MutableEntityStorage? { val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY) return if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).diff as? MutableEntityStorage } }
apache-2.0
be193a16a5ec33c9c072b00d919176c3
42.664671
140
0.780551
5.894099
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2017/Day15.kt
1
729
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day object Day15 : Day { override fun part1() = solve(40_000_000, Generator(699, 16807), Generator(124, 48271)) override fun part2() = solve(5_000_000, Generator(699, 16807, 4), Generator(124, 48271, 8)) private fun solve(iter: Int, a: Generator, b: Generator) = (1 .. iter).count { a.next().toInt() and 0x0000FFFF == b.next().toInt() and 0x0000FFFF }.toString() class Generator(var current: Long, val factor: Int, val multiples: Int = 1) { fun next(): Long { do { current = current * factor % 2147483647L } while(current % multiples != 0L) return current } } }
mit
771060a1343a9c852a9285287876cf44
35.5
162
0.617284
3.573529
false
false
false
false
StephaneBg/ScoreIt
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/GameViewModel.kt
1
7695
/* * 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.app.ui import androidx.annotation.ColorInt import com.sbgapps.scoreit.app.R import com.sbgapps.scoreit.app.model.BeloteLapRow import com.sbgapps.scoreit.app.model.CoincheLapRow import com.sbgapps.scoreit.app.model.DonationRow import com.sbgapps.scoreit.app.model.Header import com.sbgapps.scoreit.app.model.LapRow import com.sbgapps.scoreit.app.model.TarotLapRow import com.sbgapps.scoreit.app.model.UniversalLapRow import com.sbgapps.scoreit.core.ui.BaseViewModel import com.sbgapps.scoreit.core.utils.string.StringFactory import com.sbgapps.scoreit.core.utils.string.fromResources import com.sbgapps.scoreit.core.utils.string.join import com.sbgapps.scoreit.core.utils.string.toStringFactory import com.sbgapps.scoreit.data.interactor.GameUseCase import com.sbgapps.scoreit.data.model.BeloteGame import com.sbgapps.scoreit.data.model.CoincheGame import com.sbgapps.scoreit.data.model.GameType import com.sbgapps.scoreit.data.model.Player import com.sbgapps.scoreit.data.model.TarotGame import com.sbgapps.scoreit.data.model.TarotLap import com.sbgapps.scoreit.data.model.UniversalGame import com.sbgapps.scoreit.data.repository.BillingRepo import io.uniflow.core.flow.data.UIEvent import io.uniflow.core.flow.data.UIState class GameViewModel( private val useCase: GameUseCase, private val billingRepository: BillingRepo ) : BaseViewModel() { private var displayedLaps = emptyList<LapRow>() private var removedPosition = NO_DELETION fun loadGame(name: String? = null) { action { name?.let { useCase.loadGame(it) } setState { getContent() } } } fun selectGame(gameType: GameType) { action { useCase.setGameType(gameType) setState { getContent() } } } fun setPlayerCount(count: Int) { action { useCase.setPlayerCount(count) setState { getContent() } } } fun resetGame() { action { useCase.reset() setState { getContent() } } } fun createGame(name: String) { action { useCase.createGame(name) setState { getContent() } } } fun addLap() { action { sendEvent(getEditionAction()) } } fun editLap(position: Int) { action { useCase.modifyLap(position) sendEvent(getEditionAction()) } } fun deleteLap(position: Int) { action { if (removedPosition != NO_DELETION) { useCase.deleteLap(removedPosition) setState { getContent() } } val laps = getLaps().toMutableList() laps.removeAt(position) displayedLaps = laps removedPosition = position sendEvent(GameEvent.Deletion(laps)) } } fun confirmDeletion() { action { useCase.deleteLap(removedPosition) removedPosition = NO_DELETION setState { getContent() } } } fun undoDeletion() { action { removedPosition = NO_DELETION setState { getContent() } } } fun canEditPlayer(position: Int): Boolean = useCase.canEditPlayer(position) fun setPlayerName(position: Int, name: String) { action { useCase.editPlayerName(position, name) setState { getContent() } } } fun setPlayerColor(position: Int, @ColorInt color: Int) { action { useCase.editPlayerColor(position, color) setState { getContent() } } } fun onDonationPerformed() { action { setState { getContent() } } } private fun getContent(): Content = Content(getHeader(), getLaps()) fun getPlayerCountOptions(): List<Int> = when (useCase.getGame()) { is UniversalGame -> listOf(2, 3, 4, 5, 6, 7, 8) is TarotGame -> listOf(3, 4, 5) else -> error("Not managed for other games") } fun getEnabledMenuItems(): List<Int> { val items = when (useCase.getGame()) { is UniversalGame -> mutableListOf(R.id.menu_count) is BeloteGame, is CoincheGame -> mutableListOf() is TarotGame -> mutableListOf(R.id.menu_count) } if (useCase.isGameStarted()) { items.add(R.id.menu_chart) items.add(R.id.menu_clear) } if (useCase.getSavedFiles().isNotEmpty()) { items.add(R.id.menu_save) } return items } private fun getHeader(): Header = Header( useCase.getPlayers(true).map { Player(it.name, it.color) }, useCase.getScores(), useCase.getMarkers() ) private fun getLaps(): List<LapRow> { val laps = when (val game = useCase.getGame()) { is UniversalGame -> game.laps.mapIndexed { index, lap -> UniversalLapRow(index, useCase.getResults(lap)) } is TarotGame -> game.laps.mapIndexed { index, lap -> val (displayResults, isWon) = useCase.getDisplayResults(lap) TarotLapRow(index, displayResults, getTarotLapInfo(lap), isWon) } is BeloteGame -> game.laps.mapIndexed { index, lap -> val (displayResults, isWon) = useCase.getDisplayResults(lap) BeloteLapRow(index, displayResults, isWon) } is CoincheGame -> game.laps.mapIndexed { index, lap -> val (displayResults, isWon) = useCase.getDisplayResults(lap) CoincheLapRow(index, displayResults, isWon) } } displayedLaps = laps return if (laps.size > 4) { billingRepository.getDonationSkus()?.let { laps.toMutableList().apply { add(DonationRow(it)) } } ?: laps } else { laps } } private fun getTarotLapInfo(lap: TarotLap): StringFactory { val players = useCase.getPlayers() return when (lap.playerCount) { 3, 4 -> join( " • ", players[lap.taker.index].name.toStringFactory(), fromResources(lap.bid.resId) ) 5 -> join( " • ", (if (lap.taker == lap.partner) players[lap.taker.index].name else "${players[lap.taker.index].name} & ${players[lap.partner.index].name}").toStringFactory(), fromResources(lap.bid.resId) ) else -> error("Can't play Tarot with another player count") } } private fun getEditionAction(): GameEvent.Edition = GameEvent.Edition(useCase.getGame().type) companion object { private const val NO_DELETION = -1 } } data class Content(val header: Header, val results: List<LapRow>) : UIState() sealed class GameEvent : UIEvent() { data class Edition(val gameType: GameType) : GameEvent() data class Deletion(val results: List<LapRow>) : GameEvent() }
apache-2.0
7e67e1aeec394f543d8f3765e000bb32
30.77686
112
0.611704
4.188453
false
false
false
false
JetBrains/intellij-community
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/generation/Utils.kt
1
3082
package org.jetbrains.completion.full.line.local.generation import java.util.* import kotlin.math.exp import kotlin.math.ln import kotlin.math.min internal fun IntArray.toLongArray(): LongArray { return LongArray(size) { this[it].toLong() } } internal fun Array<IntArray>.toLongArray(): LongArray { val arr = LongArray(this.sumOf { it.size }) var off = 0 for (block in this) { for (value in block) arr[off++] = value.toLong() } return arr } internal fun IntArray.sliceArray(indices: IntArray): IntArray { val result = IntArray(indices.size) var targetIndex = 0 for (sourceIndex in indices) { result[targetIndex++] = this[sourceIndex] } return result } internal fun DoubleArray.sliceArray(indices: IntArray): DoubleArray { val result = DoubleArray(indices.size) var targetIndex = 0 for (sourceIndex in indices) { result[targetIndex++] = this[sourceIndex] } return result } internal fun <T> List<T>.slice(indices: IntArray): List<T> { val result = ArrayList<T>(indices.size) for ((targetIndex, sourceIndex) in indices.withIndex()) { result.add(targetIndex, this[sourceIndex]) } return result } internal fun logSoftmax(scores: Array<DoubleArray>): Array<DoubleArray> { val expScores = Array(scores.size) { val curScores = scores[it] DoubleArray(curScores.size) { i -> exp(curScores[i]) } } for (score in expScores) { val scoresSum = score.sum() for (i in score.indices) score[i] = ln(score[i] / scoresSum) } return expScores } //TODO definitely there should be a better algorithm internal fun topk1d(data: DoubleArray, size: Int): IntArray { val pairedData = Array(data.size) { Pair(data[it], it) } Arrays.parallelSort(pairedData) { fst: Pair<Double, Int>, snd: Pair<Double, Int> -> -fst.first.compareTo(snd.first) } return IntArray(size) { pairedData[it].second } } internal fun topk2d(data: Array<DoubleArray>, size: Int, dim: Int = 0): Array<IntArray> { if (data.isEmpty()) { return emptyArray() } when (dim) { 0 -> { val listSize = min(data.size, size) val result = Array(listSize) { IntArray(data[0].size) } for (j in data[0].indices) { val slice = DoubleArray(data.size) { data[it][j] } val topColumn = topk1d(slice, size) for (i in topColumn.indices) result[i][j] = topColumn[i] } return result } 1 -> { return Array(data.size) { topk1d(data[it], size) } } else -> { throw IllegalArgumentException("Index should be 0 or 1") } } } class LapTimer { data class Lap(val name: String, val timeMillis: Long) var startTime: Long = System.currentTimeMillis() var lastLap: Long = startTime val laps: MutableList<Lap> = arrayListOf() private var _endTime: Long? = null val endTime: Long get() = _endTime ?: throw IllegalStateException("Timer hasn't been stopped yet") fun lap(name: String) { val newLap = System.currentTimeMillis() laps.add(Lap(name, newLap - lastLap)) lastLap = newLap } fun end() { _endTime = System.currentTimeMillis() } }
apache-2.0
3a03ee86671068af3683cb576a2ea03f
26.765766
119
0.670344
3.522286
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/controller/CheatController.kt
1
9020
package com.github.vhromada.catalog.web.controller import com.github.vhromada.catalog.web.connector.CheatConnector import com.github.vhromada.catalog.web.connector.GameConnector import com.github.vhromada.catalog.web.fo.CheatDataFO import com.github.vhromada.catalog.web.fo.CheatFO import com.github.vhromada.catalog.web.mapper.CheatMapper import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.validation.Errors import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import javax.servlet.http.HttpServletRequest import javax.validation.Valid /** * A class represents controller for cheats. * * @author Vladimir Hromada */ @Controller("cheatController") @RequestMapping("/games/{gameUuid}/cheats") class CheatController( /** * Connector for cheats */ private val cheatConnector: CheatConnector, /** * Connector for games */ private val gameConnector: GameConnector, /** * Mapper for cheats */ private val mapper: CheatMapper ) { /** * Shows page with cheat. * * @param model model * @param gameUuid game UUID * @return view for page with cheat */ @GetMapping fun showList(model: Model, @PathVariable("gameUuid") gameUuid: String): String { val cheat = cheatConnector.find(game = gameUuid) .throwExceptionIfAny() .get() model.addAttribute("cheat", cheat) model.addAttribute("game", gameUuid) model.addAttribute("title", "Cheats") return "cheat/index" } /** * Shows page for adding cheat. * * @param model model * @param gameUuid game UUID * @return view for page for adding cheat */ @GetMapping("/add") fun showAdd(model: Model, @PathVariable("gameUuid") gameUuid: String): String { gameConnector.get(uuid = gameUuid) val cheat = CheatFO( uuid = null, gameSetting = null, cheatSetting = null, data = null ) return createAddFormView(model = model, cheat = cheat, gameUuid = gameUuid) } /** * Process adding cheat. * * @param model model * @param gameUuid game UUID * @param cheat FO for cheat * @param errors errors * @param request HTTP request * @return view for redirect to page with cheats (no errors) or view for page for adding cheat (errors) * @throws IllegalArgumentException if UUID isn't null */ @PostMapping("/add") fun processAdd(model: Model, @PathVariable("gameUuid") gameUuid: String, @ModelAttribute("cheat") @Valid cheat: CheatFO, errors: Errors, request: HttpServletRequest): String { require(cheat.uuid == null) { "UUID must be null." } if (request.getParameter("create") != null) { if (errors.hasErrors()) { return createAddFormView(model = model, cheat = cheat, gameUuid = gameUuid) } cheatConnector.add(game = gameUuid, request = mapper.mapRequest(source = cheat)) return getCheatsRedirectUrl(gameUuid = gameUuid) } if (request.getParameter("addCheat") != null) { val cheatData = if (cheat.data == null) mutableListOf() else cheat.data!!.toMutableList() cheatData.add(CheatDataFO()) return createAddFormView(model = model, cheat = cheat.copy(data = cheatData), gameUuid = gameUuid) } val index = getRemoveIndex(request = request) if (index != null) { val cheatData = cheat.data!!.toMutableList() cheatData.removeAt(index) return createAddFormView(model = model, cheat = cheat.copy(data = cheatData), gameUuid = gameUuid) } return getCheatsRedirectUrl(gameUuid = gameUuid) } /** * Shows page for editing cheat. * * @param model model * @param gameUuid game UUID * @return view for page for editing cheat */ @GetMapping("/edit") fun showEdit(model: Model, @PathVariable("gameUuid") gameUuid: String): String { val cheat = cheatConnector.find(game = gameUuid) .throwExceptionIfAny() .get() return createEditFormView(model = model, cheat = mapper.map(source = cheat), gameUuid = gameUuid) } /** * Process editing cheat. * * @param model model * @param gameUuid game UUID * @param cheat FO for cheat * @param errors errors * @param request HTTP request * @return view for redirect to page with cheats (no errors) or view for page for editing cheat (errors) * @throws IllegalArgumentException if UUID is null */ @PostMapping("/edit") fun processEdit(model: Model, @PathVariable("gameUuid") gameUuid: String, @ModelAttribute("cheat") @Valid cheat: CheatFO, errors: Errors, request: HttpServletRequest): String { require(cheat.uuid != null) { "UUID mustn't be null." } if (request.getParameter("update") != null) { if (errors.hasErrors()) { return createEditFormView(model = model, cheat = cheat, gameUuid = gameUuid) } cheatConnector.update(game = gameUuid, uuid = cheat.uuid, request = mapper.mapRequest(source = cheat)) return getCheatsRedirectUrl(gameUuid = gameUuid) } if (request.getParameter("addCheat") != null) { val cheatData = cheat.data!!.toMutableList() cheatData.add(CheatDataFO()) return createEditFormView(model = model, cheat = cheat.copy(data = cheatData), gameUuid = gameUuid) } val index = getRemoveIndex(request) if (index != null) { val cheatData = cheat.data!!.toMutableList() cheatData.removeAt(index) return createEditFormView(model = model, cheat = cheat.copy(data = cheatData), gameUuid = gameUuid) } return getCheatsRedirectUrl(gameUuid = gameUuid) } /** * Process removing cheat. * * @param gameUuid game UUID * @return view for redirect to page with cheats */ @GetMapping("/remove") fun processRemove(@PathVariable("gameUuid") gameUuid: String): String { val cheat = cheatConnector.find(game = gameUuid) .throwExceptionIfAny() .get() cheatConnector.remove(game = gameUuid, uuid = cheat.uuid) return "redirect:/games" } /** * Returns page's view with form for adding cheat. * * @param model model * @param cheat FO for cheat * @param gameUuid game UUID * @return page's view with form for adding cheat */ private fun createAddFormView(model: Model, cheat: CheatFO, gameUuid: String): String { return createFormView(model = model, cheat = cheat, gameUuid = gameUuid, title = "Add cheat", action = "add") } /** * Returns page's view with form for editing cheat. * * @param model model * @param cheat FO for cheat * @param gameUuid game UUID * @return page's view with form for editing cheat */ private fun createEditFormView(model: Model, cheat: CheatFO, gameUuid: String): String { return createFormView(model = model, cheat = cheat, gameUuid = gameUuid, title = "Edit cheat", action = "edit") } /** * Returns page's view with form. * * @param model model * @param cheat FO for cheat * @param gameUuid game UUID * @param title page's title * @param action action * @return page's view with form */ private fun createFormView(model: Model, cheat: CheatFO, gameUuid: String, title: String, action: String): String { model.addAttribute("cheat", cheat) model.addAttribute("game", gameUuid) model.addAttribute("title", title) model.addAttribute("action", action) return "cheat/form" } /** * Returns redirect URL to cheats. * * @param gameUuid game UUID * @return redirect URL to cheats */ private fun getCheatsRedirectUrl(gameUuid: String): String { return "redirect:/games/$gameUuid/cheats" } /** * Returns index of removing cheat. * * @param request HTTP request * @return index of removing cheat */ private fun getRemoveIndex(request: HttpServletRequest): Int? { var index: Int? = null val names = request.parameterNames while (names.hasMoreElements() && index == null) { val name = names.nextElement() if (name.startsWith("removeCheat")) { index = (name.substring(11).toInt()) } } return index } }
mit
8c3ae6db7aa8841c00b07e524f9e132b
32.407407
180
0.629047
4.469772
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/profile_certificates/ui/fragment/ProfileCertificatesFragment.kt
1
5456
package org.stepik.android.view.profile_certificates.ui.fragment import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.error_no_connection_with_button_small.* import kotlinx.android.synthetic.main.fragment_profile_certificates.* import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.model.CertificateListItem import org.stepik.android.presentation.profile_certificates.ProfileCertificatesPresenter import org.stepik.android.presentation.profile_certificates.ProfileCertificatesView import org.stepik.android.view.certificate.ui.adapter.delegate.CertificateProfileAdapterDelegate import org.stepik.android.view.certificate.ui.adapter.delegate.CertificatesProfilePlaceholderAdapterDelegate import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import ru.nobird.android.view.base.ui.extension.argument import javax.inject.Inject class ProfileCertificatesFragment : Fragment(R.layout.fragment_profile_certificates), ProfileCertificatesView { companion object { fun newInstance(userId: Long): Fragment = ProfileCertificatesFragment() .apply { this.userId = userId } } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var screenManager: ScreenManager private var userId: Long by argument() private var isCurrentUser: Boolean = false private val certificatesPresenter: ProfileCertificatesPresenter by viewModels { viewModelFactory } private lateinit var viewStateDelegate: ViewStateDelegate<ProfileCertificatesView.State> private lateinit var certificatesAdapter: DefaultDelegateAdapter<CertificateListItem> private var profileId = 0L override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() certificatesAdapter = DefaultDelegateAdapter() certificatesAdapter += CertificatesProfilePlaceholderAdapterDelegate() certificatesAdapter += CertificateProfileAdapterDelegate(::onCertificateClicked) } private fun injectComponent() { App.componentManager() .profileComponent(userId) .inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewStateDelegate = ViewStateDelegate() viewStateDelegate.addState<ProfileCertificatesView.State.Idle>() viewStateDelegate.addState<ProfileCertificatesView.State.SilentLoading>() viewStateDelegate.addState<ProfileCertificatesView.State.Loading>(view, profileCertificatesRecycler) viewStateDelegate.addState<ProfileCertificatesView.State.Error>(view, certificatesLoadingError) viewStateDelegate.addState<ProfileCertificatesView.State.CertificatesCache>(view, profileCertificatesRecycler) viewStateDelegate.addState<ProfileCertificatesView.State.CertificatesRemote>(view, profileCertificatesRecycler) viewStateDelegate.addState<ProfileCertificatesView.State.NoCertificates>() tryAgain.setOnClickListener { setDataToPresenter(forceUpdate = true) } profileCertificatesTitle.setOnClickListener { screenManager.showCertificates(requireContext(), profileId, isCurrentUser) } profileCertificatesRecycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) profileCertificatesRecycler.isNestedScrollingEnabled = false profileCertificatesRecycler.adapter = certificatesAdapter setDataToPresenter() } private fun setDataToPresenter(forceUpdate: Boolean = false) { certificatesPresenter.showCertificatesForUser(forceUpdate) } override fun onStart() { super.onStart() certificatesPresenter.attachView(this) } override fun onStop() { certificatesPresenter.detachView(this) super.onStop() } private fun onCertificateClicked(path: String) { screenManager.showPdfInBrowserByGoogleDocs(requireActivity(), path) } override fun setState(state: ProfileCertificatesView.State) { viewStateDelegate.switchState(state) when (state) { is ProfileCertificatesView.State.Loading -> { certificatesAdapter.items = listOf( CertificateListItem.Placeholder, CertificateListItem.Placeholder, CertificateListItem.Placeholder ) profileId = state.profileData.user.id isCurrentUser = state.profileData.isCurrentUser } is ProfileCertificatesView.State.CertificatesCache -> { certificatesAdapter.items = state.certificates profileId = state.profileData.user.id isCurrentUser = state.profileData.isCurrentUser } is ProfileCertificatesView.State.CertificatesRemote -> { certificatesAdapter.items = state.certificates profileId = state.profileData.user.id isCurrentUser = state.profileData.isCurrentUser } } } }
apache-2.0
84c8ebcadb1f009788b481bc658c0341
41.968504
130
0.741569
5.584442
false
false
false
false
bmunzenb/feed-buddy
src/main/kotlin/com/munzenberger/feed/handler/DownloadEnclosures.kt
1
3770
package com.munzenberger.feed.handler import com.munzenberger.feed.FeedContext import com.munzenberger.feed.Item import com.munzenberger.feed.URLClient import com.munzenberger.feed.config.filteredForPath import com.munzenberger.feed.filename import okio.buffer import okio.sink import okio.source import java.io.File import java.io.IOException import java.io.InputStream import java.net.URL import java.net.URLDecoder import java.text.NumberFormat class DownloadEnclosures : ItemHandler { var targetDirectory: String = "." override fun execute(context: FeedContext, item: Item) { item.enclosures.forEach { enclosure -> print("Resolving enclosure source... ") URLClient.connect(URL(enclosure.url)).run { println(resolvedUrl) contentDisposition?.let { println("Content-Disposition: $it") } val target = targetFileFor(filename) print("Downloading to $target... ") val result = profile { download(inStream, target) } println("${result.first.formatAsSize()} transferred in ${result.second.formatAsTime()}.") item.timestampAsInstant?.let { if (!target.setLastModified(it.toEpochMilli())) { System.err.println("Could not set last modified time on file: $target") } } } } } internal fun targetFileFor(filename: String): File { var path = targetDirectory + File.separator + filename var targetFile = File(path) if (targetFile.exists()) { // insert a timestamp into the filename to make it unique var name = path var extension = "" val i = path.lastIndexOf('.') if (i > 0) { name = path.substring(0, i) extension = path.substring(i) } path = name + "-" + System.currentTimeMillis() + extension targetFile = File(path) if (targetFile.exists()) { throw IOException("Local file already exists: $targetFile") } } return targetFile } } internal val URLClient.Response.filename: String // use the filename from the content disposition header, if present get() = contentDisposition.filename?.filteredForPath() ?: resolvedUrl.filename internal val URL.filename: String get() = this.path.urlDecode().split('/').last() private fun String.urlDecode(encoding: String = "UTF-8"): String { // handles nested URLs return when (val decoded = URLDecoder.decode(this, encoding)) { this -> this else -> decoded.urlDecode(encoding) } } private fun download(inStream: InputStream, target: File): Long { val inputSource = inStream.source().buffer() val outputSink = target.sink().buffer() return inputSource.use { input -> outputSink.use { output -> input.readAll(output) } } } private fun <T> profile(block: () -> T): Pair<T, Long> { val start = System.currentTimeMillis() val v = block.invoke() val time = System.currentTimeMillis() - start return v to time } fun Long.formatAsTime(): String { val seconds = this / 1000 % 60 val minutes = this / 1000 / 60 return when { minutes > 0 -> "$minutes min $seconds sec" seconds > 0 -> "$seconds sec" else -> "$this ms" } } fun Long.formatAsSize(): String { val format = NumberFormat.getInstance().apply { minimumFractionDigits = 1 maximumFractionDigits = 2 } val mbs = this.toDouble() / 1024.0 / 1024.0 return format.format(mbs) + " MB" }
apache-2.0
08607e295d08deccae0a030f3c885504
25.928571
105
0.603448
4.542169
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/index/indexer/HtlTemplateIndexer.kt
1
1465
package com.aemtools.index.indexer import com.aemtools.common.constant.const import com.aemtools.common.util.findChildrenByType import com.aemtools.common.util.getHtmlFile import com.aemtools.index.model.TemplateDefinition import com.aemtools.index.util.extractTemplateDefinition import com.intellij.psi.xml.XmlAttribute import com.intellij.util.indexing.DataIndexer import com.intellij.util.indexing.FileContent /** * @author Dmytro Troynikov */ object HtlTemplateIndexer : DataIndexer<String, TemplateDefinition, FileContent> { override fun map(inputData: FileContent): MutableMap<String, TemplateDefinition> { val content = inputData.contentAsText if (content.contains(const.htl.DATA_SLY_TEMPLATE)) { val file = inputData.psiFile.getHtmlFile() ?: return mutableMapOf() val attributes = file.findChildrenByType(XmlAttribute::class.java) val templates = attributes.filter { it.name.startsWith(const.htl.DATA_SLY_TEMPLATE) } val templateDefinitions: List<TemplateDefinition> = templates.flatMap { with(it.extractTemplateDefinition()) { if (this != null) { listOf(this) } else { listOf() } } } val path = inputData.file.path templateDefinitions.forEach { it.fullName = path } return mutableMapOf(*templateDefinitions.map { "$path.$${it.name}" to it }.toTypedArray()) } return mutableMapOf() } }
gpl-3.0
49e3b9ed6a4e8498142e1f5d11874221
31.555556
91
0.706485
4.373134
false
false
false
false
ursjoss/sipamato
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/config/WicketWebSecurityConfig.kt
1
2299
package ch.difty.scipamato.publ.web.config import ch.difty.scipamato.publ.config.ScipamatoPublicProperties import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.provisioning.InMemoryUserDetailsManager @Configuration open class WicketWebSecurityConfig( private val properties: ScipamatoPublicProperties, ) : WebSecurityConfigurerAdapter() { @Bean(name = ["authenticationManager"]) @Throws(Exception::class) override fun authenticationManagerBean(): AuthenticationManager = super.authenticationManagerBean() @Throws(Exception::class) override fun configure(http: HttpSecurity) { http.csrf().disable() .headers().frameOptions().disable() .and() .authorizeRequests() .requestMatchers(EndpointRequest.to("health", "info")).permitAll() .antMatchers("/actuator/").hasRole(ADMIN_ROLE) .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole(ADMIN_ROLE) .antMatchers("/**").permitAll() .and() .logout().permitAll() } @Bean public override fun userDetailsService(): UserDetailsService = InMemoryUserDetailsManager().apply { createUser(User .withUsername(properties.managementUserName) .password(passwordEncoder().encode(properties.managementUserPassword)) .roles(ADMIN_ROLE) .build()) } companion object { private const val ADMIN_ROLE = "ADMIN" @Bean fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder() } }
gpl-3.0
d95bc34bd45b27e1126cbe60908c1c29
40.8
103
0.735102
5.396714
false
true
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/commit/GitCommitCompletionContributor.kt
4
2918
// 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 git4idea.commit import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationUtil import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.psi.PsiDocumentManager import com.intellij.ui.TextFieldWithAutoCompletionListProvider import git4idea.GitUtil import git4idea.history.GitLogUtil import git4idea.repo.GitRepository class GitCommitCompletionContributor : CompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { val file = parameters.originalFile val project = file.project val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return val commitMessage = document.getUserData(CommitMessage.DATA_KEY) ?: return val completionPrefix = TextFieldWithAutoCompletionListProvider.getCompletionPrefix(parameters) val gitPrefixes = listOf( GitPrefix("fixup!", "fixu"), GitPrefix("squash!", "squ") ) gitPrefixes .filter { prefix -> commitMessage.text.startsWith(prefix.prefixToMatch) } .forEach { prefix -> lastCommitsCompletionWithPrefix(project, result, completionPrefix, prefix.value) } } private fun lastCommitsCompletionWithPrefix(project: Project, result: CompletionResultSet, completionPrefix: String, gitPrefix: String) { if (Registry.`is`("git.commit.completion.fixup.squash")) { val repository = GitUtil.getRepositories(project).singleOrNull() ?: return result.caseInsensitive() .withPrefixMatcher(PlainPrefixMatcher(completionPrefix)) .addAllElements( getLastCommits(repository).reversed().mapIndexed { i, oldCommitMessage -> PrioritizedLookupElement.withPriority(LookupElementBuilder.create("$gitPrefix $oldCommitMessage"), i.toDouble()) } ) result.stopHere() } } private fun getLastCommits(repository: GitRepository, n: Int = 20): List<String> { val future = ApplicationManager.getApplication().executeOnPooledThread<List<String>> { GitLogUtil.collectMetadata(repository.project, repository.root, "-n $n").commits.map { it.subject } } return ApplicationUtil.runWithCheckCanceled(future, ProgressIndicatorProvider.getInstance().progressIndicator) } data class GitPrefix(val value: String, val prefixToMatch: String) }
apache-2.0
bb787b99ed4c897a0459be84784576ee
46.080645
140
0.735093
5.031034
false
false
false
false
allotria/intellij-community
python/src/com/jetbrains/python/sdk/PySdkToInstall.kt
2
13212
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk import com.google.common.hash.HashFunction import com.google.common.hash.Hashing import com.google.common.io.Files import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.icons.AllIcons import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk.* import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.SimpleTextAttributes import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.io.HttpRequests import com.intellij.webcore.packaging.PackageManagementService import com.intellij.webcore.packaging.PackagesNotificationPanel import com.jetbrains.python.PyBundle import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.DownloadResult import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.InstallationResult import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.LookupResult import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkDownload import com.jetbrains.python.sdk.PySdkToInstallCollector.Companion.logSdkInstallation import org.jetbrains.annotations.CalledInAny import java.io.File import java.io.IOException import kotlin.math.absoluteValue private val LOGGER = Logger.getInstance(PySdkToInstall::class.java) @CalledInAny internal fun getSdksToInstall(): List<PySdkToInstall> { return if (SystemInfo.isWindows) listOf(getPy38ToInstallOnWindows(), getPy39ToInstallOnWindows()) else emptyList() } @RequiresEdt fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>): Sdk? { return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks) } else it } } @RequiresEdt fun installSdkIfNeeded(sdk: Sdk?, module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): Sdk? { return sdk.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks, context) } else it } } private fun getPy39ToInstallOnWindows(): PySdkToInstallOnWindows { val version = "3.9" val name = "Python $version" val hashFunction = Hashing.md5() return PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.9.2/python-3.9.2-amd64.exe", 28287512, "efb20aa1b648a2baddd949c142d6eb06", hashFunction, "python-3.9.2-amd64.exe" ) } private fun getPy38ToInstallOnWindows(): PySdkToInstallOnWindows { val version = "3.8" val name = "Python $version" val hashFunction = Hashing.md5() return PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.8.8/python-3.8.8-amd64.exe", 28217976, "77a54a14239b6d7d0dcbe2e3a507d2f0", hashFunction, "python-3.8.8-amd64.exe" ) } internal abstract class PySdkToInstall internal constructor(name: String, version: String) : ProjectJdkImpl(name, PythonSdkType.getInstance(), null, version) { @CalledInAny abstract fun renderInList(renderer: PySdkListCellRenderer) @CalledInAny @NlsContexts.DialogMessage abstract fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String @RequiresEdt abstract fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? } private class PySdkToInstallOnWindows(name: String, private val version: String, private val url: String, private val size: Long, private val hash: String, private val hashFunction: HashFunction, private val targetFileName: String) : PySdkToInstall(name, version) { override fun renderInList(renderer: PySdkListCellRenderer) { renderer.append(name) renderer.append(" $url", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) // NON-NLS renderer.icon = AllIcons.Actions.Download } @NlsContexts.DialogMessage override fun getInstallationWarning(@NlsContexts.Button defaultButtonName: String): String { val fileSize = StringUtil.formatFileSize(size) return HtmlBuilder() .append(PyBundle.message("python.sdk.executable.not.found.header")) .append(tag("ul").children( tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.specify.path", text("...").bold()))), tag("li").children(raw(PyBundle.message("python.sdk.executable.not.found.option.download.and.install", text(defaultButtonName).bold(), fileSize))) )).toString() } override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? { try { val project = module?.project return ProgressManager.getInstance().run( object : Task.WithResult<PyDetectedSdk?, Exception>(project, PyBundle.message("python.sdk.installing", name), true) { override fun compute(indicator: ProgressIndicator): PyDetectedSdk? = install(project, systemWideSdksDetector, indicator) } ) } catch (e: IOException) { handleIOException(e) } catch (e: PyInstallationExecutionException) { handleExecutionException(e) } catch (e: PyInstallationException) { handleInstallationException(e) } return null } private fun install(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>, indicator: ProgressIndicator): PyDetectedSdk? { val targetFile = File(PathManager.getTempPath(), targetFileName) try { indicator.text = PyBundle.message("python.sdk.downloading", targetFileName) if (indicator.isCanceled) { logSdkDownload(project, version, DownloadResult.CANCELLED) return null } downloadInstaller(project, targetFile, indicator) if (indicator.isCanceled) { logSdkDownload(project, version, DownloadResult.CANCELLED) return null } checkInstallerConsistency(project, targetFile) logSdkDownload(project, version, DownloadResult.OK) indicator.text = PyBundle.message("python.sdk.running", targetFileName) indicator.text2 = PyBundle.message("python.sdk.installing.windows.warning") indicator.isIndeterminate = true if (indicator.isCanceled) { logSdkInstallation(project, version, InstallationResult.CANCELLED) return null } runInstaller(project, targetFile, indicator) logSdkInstallation(project, version, InstallationResult.OK) return findInstalledSdk(project, systemWideSdksDetector) } finally { FileUtil.delete(targetFile) } } private fun downloadInstaller(project: Project?, targetFile: File, indicator: ProgressIndicator) { LOGGER.info("Downloading $url to $targetFile") return try { HttpRequests.request(url).saveToFile(targetFile, indicator) } catch (e: IOException) { logSdkDownload(project, version, DownloadResult.EXCEPTION) throw IOException("Failed to download $url to $targetFile.", e) } catch (e: ProcessCanceledException) { logSdkDownload(project, version, DownloadResult.CANCELLED) throw e } } private fun checkInstallerConsistency(project: Project?, installer: File) { LOGGER.debug("Checking installer size") val sizeDiff = installer.length() - size if (sizeDiff != 0L) { logSdkDownload(project, version, DownloadResult.SIZE) throw IOException("Downloaded $installer has incorrect size, difference is ${sizeDiff.absoluteValue} bytes.") } LOGGER.debug("Checking installer checksum") val actualHashCode = Files.asByteSource(installer).hash(hashFunction).toString() if (!actualHashCode.equals(hash, ignoreCase = true)) { logSdkDownload(project, version, DownloadResult.CHECKSUM) throw IOException("Checksums for $installer does not match. Actual value is $actualHashCode, expected $hash.") } } private fun handleIOException(e: IOException) { LOGGER.info(e) e.message?.let { PackagesNotificationPanel.showError( PyBundle.message("python.sdk.failed.to.install.title", name), PackageManagementService.ErrorDescription( it, null, e.cause?.message, PyBundle.message("python.sdk.try.to.install.python.manually") ) ) } } private fun runInstaller(project: Project?, installer: File, indicator: ProgressIndicator) { val commandLine = GeneralCommandLine(installer.absolutePath, "/quiet") LOGGER.info("Running ${commandLine.commandLineString}") val output = runInstaller(project, commandLine, indicator) if (output.isCancelled) logSdkInstallation(project, version, InstallationResult.CANCELLED) if (output.exitCode != 0) logSdkInstallation(project, version, InstallationResult.EXIT_CODE) if (output.isTimeout) logSdkInstallation(project, version, InstallationResult.TIMEOUT) if (output.exitCode != 0 || output.isTimeout) throw PyInstallationException(commandLine, output) } private fun handleInstallationException(e: PyInstallationException) { val processOutput = e.output processOutput.checkSuccess(LOGGER) if (processOutput.isCancelled) { PackagesNotificationPanel.showError( PyBundle.message("python.sdk.installation.has.been.cancelled.title", name), PackageManagementService.ErrorDescription( PyBundle.message("python.sdk.some.installed.python.components.might.get.inconsistent.after.cancellation"), e.commandLine.commandLineString, listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() }, PyBundle.message("python.sdk.consider.installing.python.manually") ) ) } else { PackagesNotificationPanel.showError( PyBundle.message("python.sdk.failed.to.install.title", name), PackageManagementService.ErrorDescription( if (processOutput.isTimeout) PyBundle.message("python.sdk.failed.to.install.timed.out") else PyBundle.message("python.sdk.failed.to.install.exit.code", processOutput.exitCode), e.commandLine.commandLineString, listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() }, PyBundle.message("python.sdk.try.to.install.python.manually") ) ) } } private fun runInstaller(project: Project?, commandLine: GeneralCommandLine, indicator: ProgressIndicator): ProcessOutput { try { return CapturingProcessHandler(commandLine).runProcessWithProgressIndicator(indicator) } catch (e: ExecutionException) { logSdkInstallation(project, version, InstallationResult.EXCEPTION) throw PyInstallationExecutionException(commandLine, e) } } private fun handleExecutionException(e: PyInstallationExecutionException) { LOGGER.info(e) e.cause.message?.let { PackagesNotificationPanel.showError( PyBundle.message("python.sdk.failed.to.install.title", name), PackageManagementService.ErrorDescription( it, e.commandLine.commandLineString, null, PyBundle.message("python.sdk.try.to.install.python.manually") ) ) } } private fun findInstalledSdk(project: Project?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? { LOGGER.debug("Resetting system-wide sdks detectors") resetSystemWideSdksDetectors() return systemWideSdksDetector() .also { sdks -> LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } } } .also { PySdkToInstallCollector.logSdkLookup( project, version, if (it.isEmpty()) LookupResult.NOT_FOUND else LookupResult.FOUND ) } .singleOrNull() } private class PyInstallationException(val commandLine: GeneralCommandLine, val output: ProcessOutput) : Exception() private class PyInstallationExecutionException(val commandLine: GeneralCommandLine, override val cause: ExecutionException) : Exception() }
apache-2.0
ecaab878bdf65b75f7933c1bcb816b60
38.675676
140
0.727293
4.465022
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/ui/ActionKeyPopup.kt
2
3197
// 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 training.ui import com.intellij.execution.target.TargetEnvironmentWizardStepKt import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.impl.ActionShortcutRestrictions import com.intellij.openapi.keymap.impl.ui.KeymapPanel import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.SystemInfo import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.ActionLink import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import training.learn.LearnBundle import training.statistic.StatisticBase import training.util.KeymapUtil import training.util.invokeActionForFocusContext import java.awt.Component import java.awt.Insets import java.awt.Point import javax.swing.JLabel import javax.swing.JPanel internal fun showActionKeyPopup(parent: Component, point: Point, height: Int, actionId: String) { val action = ActionManager.getInstance().getAction(actionId) if (action == null) return lateinit var balloon: Balloon val jPanel = JPanel() jPanel.layout = VerticalLayout(TargetEnvironmentWizardStepKt.VGAP, 250) jPanel.isOpaque = false jPanel.add(JLabel(action.templatePresentation.text)) val shortcuts = KeymapManager.getInstance().activeKeymap.getShortcuts(actionId) for (shortcut in shortcuts) { if (shortcut is KeyboardShortcut) { val keyStrokeText = KeymapUtil.getKeyStrokeText(shortcut.firstKeyStroke) val shortcutLabel = JLabel(if (SystemInfo.isMac) KeymapUtil.decryptMacShortcut(keyStrokeText) else keyStrokeText).also { it.font = it.font.deriveFont((it.font.size - 1).toFloat()) it.foreground = JBUI.CurrentTheme.Tooltip.shortcutForeground() } jPanel.add(shortcutLabel) } } jPanel.add(ActionLink(LearnBundle.message("shortcut.balloon.apply.this.action")) { invokeActionForFocusContext(action) balloon.hide() }) jPanel.add(ActionLink(LearnBundle.message("shortcut.balloon.add.shortcut")) { KeymapPanel.addKeyboardShortcut(actionId, ActionShortcutRestrictions.getInstance().getForActionId(actionId), KeymapManager.getInstance().activeKeymap, parent) balloon.hide() parent.repaint() }) val builder = JBPopupFactory.getInstance() .createBalloonBuilder(jPanel) .setShowCallout(true) .setHideOnKeyOutside(true) .setHideOnClickOutside(true) .setAnimationCycle(0) .setCalloutShift(height/2 + 1) .setCornerToPointerDistance(80) .setBlockClicksThroughBalloon(true) .setBorderColor(JBUI.CurrentTheme.Tooltip.borderColor()) .setFillColor(UIUtil.getToolTipBackground()) .setBorderInsets(Insets(8, 10, 8, 10)) .setShadow(true) balloon = builder.createBalloon() balloon.show(RelativePoint(parent, point), Balloon.Position.below) StatisticBase.logShortcutClicked(actionId) }
apache-2.0
5672e2fdb9d96bb3ae66bfc17e1b6a5c
41.065789
140
0.781045
4.302826
false
false
false
false
ACEMerlin/Reco
reco/src/main/kotlin/com/github/acemerlin/reco/Reco.kt
1
2451
package com.github.acemerlin.reco import kotlinx.coroutines.experimental.* import kotlinx.coroutines.experimental.android.UI import retrofit2.Call import retrofit2.HttpException /** * Created by merlin on 12/15/16. */ fun <T> WithJob.async(job: Job = this.job, start: Boolean = true, block: suspend CoroutineScope.() -> T): Deferred<T> { return kotlinx.coroutines.experimental.async(CommonPool + job, start, block) } fun <T> async(job: Job = Job(), start: Boolean = true, block: suspend CoroutineScope.() -> T): Deferred<T> { return kotlinx.coroutines.experimental.async(CommonPool + job, start, block) } fun WithJob.launch(job: Job = this.job, block: suspend CoroutineScope.() -> Unit): Job = kotlinx.coroutines.experimental.launch(UI + job, true, block) fun launch(job: Job = Job(), block: suspend CoroutineScope.() -> Unit): Job = launch(UI + job, true, block) suspend fun <T> Call<T>.await(handler: (Result.() -> Unit)? = null): T = suspendCancellableCoroutine { cont -> async(cont.context + CommonPool) { try { if (cont.isCancelled) { return@async } launch { val dsl = Result.Empty() if (handler != null) { dsl.handler() } dsl.beforeHelper?.invoke() }.cancel() val ret = execute() if (ret.isSuccessful && ret.body() != null) { launch { val dsl = Result.Succ(ret.body()) if (handler != null) { dsl.handler() } cont.resume(ret.body()) dsl.afterHelper?.invoke() }.cancel() } else { launch { val dsl = Result.Error(HttpException(ret), this@await) if (handler != null) { dsl.handler() } dsl.errorHelper?.invoke(dsl.e, dsl.call) dsl.afterHelper?.invoke() }.cancel() } } catch (e: Throwable) { launch { val dsl = Result.Exception(e) if (handler != null) { dsl.handler() } dsl.exceptionHelper?.invoke(dsl.e) dsl.afterHelper?.invoke() }.cancel() } } }
mit
79df0fe52160a11671a53c06f2c69c6f
34.028571
119
0.501428
4.448276
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/flow/scrabble/FlowPlaysScrabbleOpt.kt
1
5969
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.flow.scrabble import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.flow.Flow import org.openjdk.jmh.annotations.* import java.util.* import java.util.concurrent.* import kotlin.math.* @Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(value = 1) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) open class FlowPlaysScrabbleOpt : ShakespearePlaysScrabble() { @Benchmark public override fun play(): List<Map.Entry<Int, List<String>>> { val histoOfLetters = { word: String -> flow { emit(word.asFlow().fold(HashMap<Int, MutableLong>()) { accumulator, value -> var newValue: MutableLong? = accumulator[value] if (newValue == null) { newValue = MutableLong() accumulator[value] = newValue } newValue.incAndSet() accumulator }) } } val blank = { entry: Map.Entry<Int, MutableLong> -> max(0L, entry.value.get() - scrabbleAvailableLetters[entry.key - 'a'.toInt()]) } val nBlanks = { word: String -> flow { emit(histoOfLetters(word) .flatMapConcatIterable { it.entries } .map({ blank(it) }) .sum() ) } } val checkBlanks = { word: String -> nBlanks(word).map { it <= 2L } } val letterScore = { entry: Map.Entry<Int, MutableLong> -> letterScores[entry.key - 'a'.toInt()] * Integer.min( entry.value.get().toInt(), scrabbleAvailableLetters[entry.key - 'a'.toInt()] ) } val score2 = { word: String -> flow { emit(histoOfLetters(word) .flatMapConcatIterable { it.entries } .map { letterScore(it) } .sum()) } } val first3 = { word: String -> word.asFlow(endIndex = 3) } val last3 = { word: String -> word.asFlow(startIndex = 3) } val toBeMaxed = { word: String -> concat(first3(word), last3(word)) } val bonusForDoubleLetter = { word: String -> flow { emit(toBeMaxed(word) .map { letterScores[it.toInt() - 'a'.toInt()] } .max()) } } val score3 = { word: String -> flow { val sum = score2(word).single() + bonusForDoubleLetter(word).single() emit(sum * 2 + if (word.length == 7) 50 else 0) } } val buildHistoOnScore: (((String) -> Flow<Int>) -> Flow<TreeMap<Int, List<String>>>) = { score -> flow { emit(shakespeareWords.asFlow() .filter({ scrabbleWords.contains(it) && checkBlanks(it).single() }) .fold(TreeMap<Int, List<String>>(Collections.reverseOrder())) { acc, value -> val key = score(value).single() var list = acc[key] as MutableList<String>? if (list == null) { list = ArrayList() acc[key] = list } list.add(value) acc }) } } return runBlocking { buildHistoOnScore(score3) .flatMapConcatIterable { it.entries } .take(3) .toList() } } } public fun String.asFlow() = flow { forEach { emit(it.toInt()) } } public fun String.asFlow(startIndex: Int = 0, endIndex: Int = length) = StringByCharFlow(this, startIndex, endIndex.coerceAtMost(this.length)) public suspend inline fun Flow<Int>.sum(): Int { val collector = object : FlowCollector<Int> { public var sum = 0 override suspend fun emit(value: Int) { sum += value } } collect(collector) return collector.sum } public suspend inline fun Flow<Int>.max(): Int { val collector = object : FlowCollector<Int> { public var max = 0 override suspend fun emit(value: Int) { max = max(max, value) } } collect(collector) return collector.max } @JvmName("longSum") public suspend inline fun Flow<Long>.sum(): Long { val collector = object : FlowCollector<Long> { public var sum = 0L override suspend fun emit(value: Long) { sum += value } } collect(collector) return collector.sum } public class StringByCharFlow(private val source: String, private val startIndex: Int, private val endIndex: Int): Flow<Char> { override suspend fun collect(collector: FlowCollector<Char>) { for (i in startIndex until endIndex) collector.emit(source[i]) } } public fun <T> concat(first: Flow<T>, second: Flow<T>): Flow<T> = flow { first.collect { value -> return@collect emit(value) } second.collect { value -> return@collect emit(value) } } public fun <T, R> Flow<T>.flatMapConcatIterable(transformer: (T) -> Iterable<R>): Flow<R> = flow { collect { value -> transformer(value).forEach { r -> emit(r) } } } public inline fun <T> flow(@BuilderInference crossinline block: suspend FlowCollector<T>.() -> Unit): Flow<T> { return object : Flow<T> { override suspend fun collect(collector: FlowCollector<T>) { collector.block() } } }
apache-2.0
384c1e8ef8f696c5e61a22a9f5511ca7
29.768041
127
0.527894
4.269671
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-app/src/main/kotlin/slatekit/app/AppHelp.kt
1
5979
package slatekit.app import slatekit.common.Types import slatekit.common.args.Args import slatekit.common.args.ArgsSchema import slatekit.utils.writer.ConsoleWriter import slatekit.common.envs.Envs import slatekit.common.info.About import slatekit.common.info.Info import slatekit.common.io.Alias import slatekit.results.* import slatekit.results.builders.Tries /** * Builds the display for help / version / about requests. * ================================================== * ABOUT: * area slatekit * name Slate Kit * desc Slate Kit CLI for creating projects and access to other tools * version 1.0.0 * tags sample, template, app * region NY * contact #slatekit-team | [email protected] * url www.slatekit.life * * __________________________________________________ * OPTIONS: * -env = the environment to run in * ? optional [String] e.g. dev * -region = the region linked to app * ? optional [String] e.g. us * -log.level = the log level for logging * ? optional [String] e.g. info * * __________________________________________________ * USAGE: * - format : java -jar app-name.jar -key=value* * - example : java -jar slatekit.jar -env="dev" -region="us" -log.level="info" * * __________________________________________________ * ENVS: * -loc : dev - Dev environment (local) * -dev : dev - Dev environment (shared) * -qa1 : qat - QA environment (current release) * -pro : pro - LIVE environment * * ================================================== */ class AppHelp(val info: Info, val args: ArgsSchema, val envs: Envs = Envs.defaults()) { private val about = info.about private val writer = ConsoleWriter() companion object { fun process(cls:Class<*>, alias: Alias, rawArgs: List<String>, args: Args, about: About, schema: ArgsSchema?, envs: Envs = Envs.defaults()): Try<Args> { val assist = isAssist(rawArgs) return when (assist) { is Failure -> Success(args) is Success -> { // Delegate help to the AppMeta component for (help | version | about ) val build = AppBuilder.build(cls, args, alias) val appMeta = AppHelp(Info.of(about).copy(build = build), schema ?: AppBuilder.schema(), envs) appMeta.handle(assist) // Prevent futher processing by return failure Tries.errored<Args>(Exception(assist.desc), Codes.ERRORED.copy(assist.status.name, assist.status.code, assist.status.desc)) } } } fun isAssist(rawArgs: List<String>): Outcome<String> = AppUtils.isMetaCommand(rawArgs.toList()) } /** * Checks the command line arguments for help, exit, or invalid arguments based on schema. * * @param rawArgs : the raw command line arguments directly from shell/console. * @param schema : the argument schema that defines what arguments are supported. * @return */ fun handle(check: Outcome<String>) { if (check.success) { when (check.code) { Codes.HELP.code -> help() Codes.ABOUT.code -> about() Codes.VERSION.code -> version() else -> println("Unexpected command: " + check.desc) } } } private fun help() { wrap { title("About") writer.text("area " + about.area) writer.text("name " + about.name) writer.text("desc " + about.desc) writer.text("version " + info.build.version) options() usage() envs() } } private fun about() { wrap { title("About") writer.text("area " + about.area) writer.text("name " + about.name) writer.text("desc " + about.desc) writer.text("tags " + about.tags) writer.text("region " + about.region) writer.text("contact " + about.contact) writer.text("url " + about.url) options() usage() envs() } } private fun usage() { section("Usage") { writer.highlight("format", false) writer.text(" : java -jar app-name.jar -key=value*", true) writer.highlight("example", false) writer.text(" : java -jar ${about.name.toLowerCase().replace(" ", "")}.jar ", false) args.items.forEach { arg -> val example = when (arg.dataType) { Types.JStringClass.simpleName -> "\"${arg.example}\"" else -> arg.example } val display = "-${arg.name}=$example " writer.text(display, false) } println() } } private fun version() { println("version : " + info.build.version) } private fun options() { section("Options") { args.buildHelp() } } private fun envs() { section("Envs") { envs.all.forEach { env -> writer.highlight("${env.name}", false) writer.text(" : ${env.mode.name} - ${env.desc}") } } } private fun wrap(op: () -> Unit) { writer.text(separator("=")) op() println() writer.text(separator("=")) writer.text("") } private fun section(title: String, op: () -> Unit) { println() writer.text(separator("_")) title(title) op() } private fun title(name: String) = writer.title(name.toUpperCase() + ": ") private fun separator(letter: String): String = letter.repeat(50) }
apache-2.0
225f4cf7dad9f081950a847dddd651b1
32.779661
160
0.508446
4.243435
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/definition/DatabaseObjectHolder.kt
1
2037
package com.dbflow5.processor.definition import com.dbflow5.processor.definition.provider.ContentProviderDefinition import com.squareup.javapoet.TypeName /** * Description: Provides overarching holder for [DatabaseDefinition], [TableDefinition], * and more. So we can safely use. */ class DatabaseObjectHolder { var databaseDefinition: DatabaseDefinition? = null set(databaseDefinition) { field = databaseDefinition field?.objectHolder = this } var tableDefinitionMap: MutableMap<TypeName, TableDefinition> = hashMapOf() val tableNameMap: MutableMap<String, TableDefinition> = hashMapOf() val queryModelDefinitionMap: MutableMap<TypeName, QueryModelDefinition> = hashMapOf() var modelViewDefinitionMap: MutableMap<TypeName, ModelViewDefinition> = hashMapOf() val manyToManyDefinitionMap: MutableMap<TypeName, MutableList<ManyToManyDefinition>> = hashMapOf() val providerMap = hashMapOf<TypeName, ContentProviderDefinition>() /** * Retrieve what database class they're trying to reference. */ fun getMissingDBRefs(): List<String> { if (databaseDefinition == null) { val list = mutableListOf<String>() tableDefinitionMap.values.forEach { list += "Database ${it.associationalBehavior.databaseTypeName} not found for Table ${it.associationalBehavior.name}" } queryModelDefinitionMap.values.forEach { list += "Database ${it.associationalBehavior.databaseTypeName} not found for QueryModel ${it.elementName}" } modelViewDefinitionMap.values.forEach { list += "Database ${it.associationalBehavior.databaseTypeName} not found for ModelView ${it.elementName}" } providerMap.values.forEach { list += "Database ${it.databaseTypeName} not found for ContentProvider ${it.elementName}" } return list } else { return listOf() } } }
mit
1e8a727c8054547dbb7d7d8fad2705ed
39.74
132
0.676485
5.105263
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/DFGSerializer.kt
1
44042
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.config.CommonConfigurationKeys import sun.misc.Unsafe internal class ExternalModulesDFG(val allTypes: List<DataFlowIR.Type.Declared>, val publicTypes: Map<Long, DataFlowIR.Type.Public>, val publicFunctions: Map<Long, DataFlowIR.FunctionSymbol.Public>, val functionDFGs: Map<DataFlowIR.FunctionSymbol, DataFlowIR.Function>) private val theUnsafe = Unsafe::class.java.getDeclaredField("theUnsafe").let { it.isAccessible = true it.get(null) as Unsafe } private val byteArrayDataOffset = theUnsafe.arrayBaseOffset(ByteArray::class.java).toLong() private val intArrayDataOffset = theUnsafe.arrayBaseOffset(IntArray::class.java).toLong() private val charArrayDataOffset = theUnsafe.arrayBaseOffset(CharArray::class.java).toLong() private val stringValueOffset = theUnsafe.objectFieldOffset(String::class.java.getDeclaredField("value")) private val VERSION = 1 internal object DFGSerializer { class ArraySlice(var array: ByteArray, var index: Int = 0) { //------------Write------------------------------------------------------------------// fun writeByte(value: Byte) { ensureSize(1) theUnsafe.putByte(array, byteArrayDataOffset + index, value) index++ } fun writeInt(value: Int) { ensureSize(4) theUnsafe.putInt(array, byteArrayDataOffset + index, value) index += 4 } fun writeLong(value: Long) { ensureSize(8) theUnsafe.putLong(array, byteArrayDataOffset + index, value) index += 8 } fun writeBoolean(value: Boolean) { ensureSize(1) theUnsafe.putBoolean(array, byteArrayDataOffset + index, value) index++ } inline fun <T> writeNullable(value: T?, valueWriter: ArraySlice.(T) -> Unit) { writeBoolean(value != null) if (value != null) this.valueWriter(value) } fun writeNullableInt(value: Int?) = writeNullable(value) { this.writeInt(it) } fun writeNullableString(s: String?) = writeNullable(s) { writeString(it) } //------------Read------------------------------------------------------------------// fun readByte(): Byte { checkSize(1) return theUnsafe.getByte(array, byteArrayDataOffset + index).also { index++ } } fun readInt(): Int { checkSize(4) return theUnsafe.getInt(array, byteArrayDataOffset + index).also { index += 4 } } fun readLong(): Long { checkSize(8) return theUnsafe.getLong(array, byteArrayDataOffset + index).also { index += 8 } } fun readBoolean(): Boolean { checkSize(1) return theUnsafe.getBoolean(array, byteArrayDataOffset + index).also { index++ } } inline fun <T> readNullable(valueReader: ArraySlice.() -> T) = if (readBoolean()) this.valueReader() else null fun readNullableInt() = readNullable { this.readInt() } fun readNullableString() = readNullable { readString() } //------------Write arrays------------------------------------------------------------------// fun writeIntArray(source: IntArray) { writeInt(source.size) val dataSize = source.size * 4 ensureSize(dataSize) theUnsafe.copyMemory(source, intArrayDataOffset, array, byteArrayDataOffset + index, dataSize.toLong()) index += dataSize } fun writeString(s: String) { val value = theUnsafe.getObject(s, stringValueOffset) as CharArray writeInt(value.size) val dataSize = value.size * 2 ensureSize(dataSize) theUnsafe.copyMemory(value, charArrayDataOffset, array, byteArrayDataOffset + index, dataSize.toLong()) index += dataSize } inline fun <reified T> writeArray(array: Array<T>, itemWriter: ArraySlice.(T) -> Unit) { writeInt(array.size) array.forEach { this.itemWriter(it) } } //------------Read arrays------------------------------------------------------------------// fun readIntArray(): IntArray { val size = readInt() val result = IntArray(size) val dataSize = size * 4 checkSize(dataSize) theUnsafe.copyMemory(array, byteArrayDataOffset + index, result, intArrayDataOffset, dataSize.toLong()) index += dataSize return result } fun readString(): String { val size = readInt() val data = CharArray(size) val dataSize = size * 2 checkSize(dataSize) theUnsafe.copyMemory(array, byteArrayDataOffset + index, data, charArrayDataOffset, dataSize.toLong()) index += dataSize val str = theUnsafe.allocateInstance(String::class.java) as String theUnsafe.putObject(str, stringValueOffset, data) return str } inline fun <reified T> readArray(itemReader: ArraySlice.() -> T) = Array(readInt()) { this.itemReader() } //------------Resizing------------------------------------------------------------------// fun trim() { if (array.size > index) { val newArray = ByteArray(index) theUnsafe.copyMemory(array, byteArrayDataOffset, newArray, byteArrayDataOffset, index.toLong()) array = newArray } } private fun ensureSize(size: Int) { if (index + size > array.size) { var newSize = array.size while (newSize < index + size) newSize *= 2 val newArray = ByteArray(newSize) theUnsafe.copyMemory(array, byteArrayDataOffset, newArray, byteArrayDataOffset, array.size.toLong()) array = newArray } } private fun checkSize(size: Int) { if (index + size > array.size) error("Unexpected end of data") } } class ExternalType(val hash: Long, val name: String?) { constructor(data: ArraySlice) : this(data.readLong(), data.readNullableString()) fun write(result: ArraySlice) { result.writeLong(hash) result.writeNullableString(name) } } class ItableSlot(val hash: Long, val impl: Int) { constructor(data: ArraySlice) : this(data.readLong(), data.readInt()) fun write(result: ArraySlice) { result.writeLong(hash) result.writeInt(impl) } } class DeclaredType(val isFinal: Boolean, val isAbstract: Boolean, val superTypes: IntArray, val vtable: IntArray, val itable: Array<ItableSlot>) { constructor(data: ArraySlice) : this(data.readBoolean(), data.readBoolean(), data.readIntArray(), data.readIntArray(), data.readArray { ItableSlot(this) }) fun write(result: ArraySlice) { result.writeBoolean(isFinal) result.writeBoolean(isAbstract) result.writeIntArray(superTypes) result.writeIntArray(vtable) result.writeArray(itable) { it.write(this) } } } class PublicType(val hash: Long, val intestines: DeclaredType, val name: String?) { constructor(data: ArraySlice) : this(data.readLong(), DeclaredType(data), data.readNullableString()) fun write(result: ArraySlice) { result.writeLong(hash) intestines.write(result) result.writeNullableString(name) } } class PrivateType(val index: Int, val intestines: DeclaredType, val name: String?) { constructor(data: ArraySlice) : this(data.readInt(), DeclaredType(data), data.readNullableString()) fun write(result: ArraySlice) { result.writeInt(index) intestines.write(result) result.writeNullableString(name) } } class Type(val external: ExternalType?, val public: PublicType?, val private: PrivateType?, val virtual: Boolean) { fun write(result: ArraySlice) { result.writeByte( when { external != null -> 1 public != null -> 2 private != null -> 3 else -> 0 }.toByte() ) external?.write(result) public?.write(result) private?.write(result) } companion object { fun external(hash: Long, name: String?) = Type(ExternalType(hash, name), null, null, false) fun public(hash: Long, intestines: DeclaredType, name: String?) = Type(null, PublicType(hash, intestines, name), null, false) fun private(index: Int, intestines: DeclaredType, name: String?) = Type(null, null, PrivateType(index, intestines, name), false) fun virtual() = Type(null, null, null, true) fun read(data: ArraySlice): Type { val tag = data.readByte().toInt() return when (tag) { 1 -> Type(ExternalType(data), null, null, false) 2 -> Type(null, PublicType(data), null, false) 3 -> Type(null, null, PrivateType(data), false) else -> Type(null, null, null, true) } } } } class ExternalFunctionSymbol(val hash: Long, val numberOfParameters: Int, val escapes: Int?, val pointsTo: IntArray?, val name: String?) { constructor(data: ArraySlice) : this(data.readLong(), data.readInt(), data.readNullableInt(), data.readNullable { readIntArray() }, data.readNullableString()) fun write(result: ArraySlice) { result.writeLong(hash) result.writeInt(numberOfParameters) result.writeNullableInt(escapes) result.writeNullable(pointsTo) { writeIntArray(it) } result.writeNullableString(name) } } class PublicFunctionSymbol(val hash: Long, val numberOfParameters: Int, val index: Int, val name: String?) { constructor(data: ArraySlice) : this(data.readLong(), data.readInt(), data.readInt(), data.readNullableString()) fun write(result: ArraySlice) { result.writeLong(hash) result.writeInt(numberOfParameters) result.writeInt(index) result.writeNullableString(name) } } class PrivateFunctionSymbol(val index: Int, val numberOfParameters: Int, val name: String?) { constructor(data: ArraySlice) : this(data.readInt(), data.readInt(), data.readNullableString()) fun write(result: ArraySlice) { result.writeInt(index) result.writeInt(numberOfParameters) result.writeNullableString(name) } } class FunctionSymbol(val external: ExternalFunctionSymbol?, val public: PublicFunctionSymbol?, val private: PrivateFunctionSymbol?) { fun write(result: ArraySlice) { result.writeByte( when { external != null -> 1 public != null -> 2 private != null -> 3 else -> 0 }.toByte() ) external?.write(result) public?.write(result) private?.write(result) } companion object { fun external(hash: Long, numberOfParameters: Int, escapes: Int?, pointsTo: IntArray?, name: String?) = FunctionSymbol(ExternalFunctionSymbol(hash, numberOfParameters, escapes, pointsTo, name), null, null) fun public(hash: Long, numberOfParameters: Int, index: Int, name: String?) = FunctionSymbol(null, PublicFunctionSymbol(hash, numberOfParameters, index, name), null) fun private(index: Int, numberOfParameters: Int, name: String?) = FunctionSymbol(null, null, PrivateFunctionSymbol(index, numberOfParameters, name)) fun read(data: ArraySlice): FunctionSymbol { val tag = data.readByte().toInt() return when (tag) { 1 -> FunctionSymbol(ExternalFunctionSymbol(data), null, null) 2 -> FunctionSymbol(null, PublicFunctionSymbol(data), null) 3 -> FunctionSymbol(null, null, PrivateFunctionSymbol(data)) else -> FunctionSymbol(null, null, null) } } } } class SymbolTable(val types: Array<Type>, val functionSymbols: Array<FunctionSymbol>) { constructor(data: ArraySlice) : this(data.readArray { Type.read(this) }, data.readArray { FunctionSymbol.read(this) }) fun write(result: ArraySlice) { result.writeArray(types) { it.write(this) } result.writeArray(functionSymbols) { it.write(this) } } } class Field(val type: Int?, val hash: Long, val name: String?) { constructor(data: ArraySlice) : this(data.readNullableInt(), data.readLong(), data.readNullable { readString() }) fun write(result: ArraySlice) { result.writeNullableInt(type) result.writeLong(hash) result.writeNullable(name) { writeString(it) } } } class Edge(val node: Int, val castToType: Int?) { constructor(data: ArraySlice) : this(data.readInt(), data.readNullableInt()) fun write(result: ArraySlice) { result.writeInt(node) result.writeNullableInt(castToType) } } class Parameter(val index: Int) { constructor(data: ArraySlice) : this(data.readInt()) fun write(result: ArraySlice) { result.writeInt(index) } } class Const(val type: Int) { constructor(data: ArraySlice) : this(data.readInt()) fun write(result: ArraySlice) { result.writeInt(type) } } class Call(val callee: Int, val arguments: Array<Edge>, val returnType: Int) { constructor(data: ArraySlice) : this(data.readInt(), data.readArray { Edge(this) }, data.readInt()) fun write(result: ArraySlice) { result.writeInt(callee) result.writeArray(arguments) { it.write(this) } result.writeInt(returnType) } } class StaticCall(val call: Call, val receiverType: Int?) { constructor(data: ArraySlice) : this(Call(data), data.readNullableInt()) fun write(result: ArraySlice) { call.write(result) result.writeNullableInt(receiverType) } } class NewObject(val call: Call) { constructor(data: ArraySlice) : this(Call(data)) fun write(result: ArraySlice) { call.write(result) } } class VirtualCall(val call: Call, val receiverType: Int) { constructor(data: ArraySlice) : this(Call(data), data.readInt()) fun write(result: ArraySlice) { call.write(result) result.writeInt(receiverType) } } class VtableCall(val virtualCall: VirtualCall, val calleeVtableIndex: Int) { constructor(data: ArraySlice) : this(VirtualCall(data), data.readInt()) fun write(result: ArraySlice) { virtualCall.write(result) result.writeInt(calleeVtableIndex) } } class ItableCall(val virtualCall: VirtualCall, val calleeHash: Long) { constructor(data: ArraySlice) : this(VirtualCall(data), data.readLong()) fun write(result: ArraySlice) { virtualCall.write(result) result.writeLong(calleeHash) } } class Singleton(val type: Int, val constructor: Int?) { constructor(data: ArraySlice) : this(data.readInt(), data.readNullableInt()) fun write(result: ArraySlice) { result.writeInt(type) result.writeNullableInt(constructor) } } class FieldRead(val receiver: Edge?, val field: Field) { constructor(data: ArraySlice) : this(data.readNullable { Edge(this) }, Field(data)) fun write(result: ArraySlice) { result.writeNullable(receiver) { it.write(this) } field.write(result) } } class FieldWrite(val receiver: Edge?, val field: Field, val value: Edge) { constructor(data: ArraySlice) : this(data.readNullable { Edge(this) }, Field(data), Edge(data)) fun write(result: ArraySlice) { result.writeNullable(receiver) { it.write(this) } field.write(result) value.write(result) } } class Variable(val values: Array<Edge>, val temp: Boolean) { constructor(data: ArraySlice) : this(data.readArray { Edge(this) }, data.readBoolean()) fun write(result: ArraySlice) { result.writeArray(values) { it.write(this) } result.writeBoolean(temp) } } enum class NodeType { UNKNOWN, PARAMETER, CONST, STATIC_CALL, NEW_OBJECT, VTABLE_CALL, ITABLE_CALL, SINGLETON, FIELD_READ, FIELD_WRITE, VARIABLE } class Node { var parameter : Parameter? = null var const : Const? = null var staticCall : StaticCall? = null var newObject : NewObject? = null var vtableCall : VtableCall? = null var itableCall : ItableCall? = null var singleton : Singleton? = null var fieldRead : FieldRead? = null var fieldWrite : FieldWrite? = null var variable : Variable? = null val type get() = when { parameter != null -> NodeType.PARAMETER const != null -> NodeType.CONST staticCall != null -> NodeType.STATIC_CALL newObject != null -> NodeType.NEW_OBJECT vtableCall != null -> NodeType.VTABLE_CALL itableCall != null -> NodeType.ITABLE_CALL singleton != null -> NodeType.SINGLETON fieldRead != null -> NodeType.FIELD_READ fieldWrite != null -> NodeType.FIELD_WRITE variable != null -> NodeType.VARIABLE else -> NodeType.UNKNOWN } fun write(result: ArraySlice) { result.writeByte(type.ordinal.toByte()) parameter ?.write(result) const ?.write(result) staticCall?.write(result) newObject ?.write(result) vtableCall?.write(result) itableCall?.write(result) singleton ?.write(result) fieldRead ?.write(result) fieldWrite?.write(result) variable ?.write(result) } companion object { fun parameter(index: Int) = Node().also { it.parameter = Parameter(index) } fun const(type: Int) = Node().also { it.const = Const(type) } fun staticCall(call: Call, receiverType: Int?) = Node().also { it.staticCall = StaticCall(call, receiverType) } fun newObject(call: Call) = Node().also { it.newObject = NewObject(call) } fun vtableCall(virtualCall: VirtualCall, calleeVtableIndex: Int) = Node().also { it.vtableCall = VtableCall(virtualCall, calleeVtableIndex) } fun itableCall(virtualCall: VirtualCall, calleeHash: Long) = Node().also { it.itableCall = ItableCall(virtualCall, calleeHash) } fun singleton(type: Int, constructor: Int?) = Node().also { it.singleton = Singleton(type, constructor) } fun fieldRead(receiver: Edge?, field: Field) = Node().also { it.fieldRead = FieldRead(receiver, field) } fun fieldWrite(receiver: Edge?, field: Field, value: Edge) = Node().also { it.fieldWrite = FieldWrite(receiver, field, value) } fun variable(values: Array<Edge>, temp: Boolean) = Node().also { it.variable = Variable(values, temp) } fun read(data: ArraySlice): Node { val type = enumValues<NodeType>()[data.readByte().toInt()] val result = Node() when (type) { NodeType.PARAMETER -> result.parameter = Parameter (data) NodeType.CONST -> result.const = Const (data) NodeType.STATIC_CALL -> result.staticCall = StaticCall(data) NodeType.NEW_OBJECT -> result.newObject = NewObject (data) NodeType.VTABLE_CALL -> result.vtableCall = VtableCall(data) NodeType.ITABLE_CALL -> result.itableCall = ItableCall(data) NodeType.SINGLETON -> result.singleton = Singleton (data) NodeType.FIELD_READ -> result.fieldRead = FieldRead (data) NodeType.FIELD_WRITE -> result.fieldWrite = FieldWrite(data) NodeType.VARIABLE -> result.variable = Variable (data) else -> { } } return result } } } class FunctionBody(val nodes: Array<Node>, val returns: Int, val throws: Int) { constructor(data: ArraySlice) : this(data.readArray { Node.read(this) }, data.readInt(), data.readInt()) fun write(result: ArraySlice) { result.writeArray(nodes) { it.write(this) } result.writeInt(returns) result.writeInt(throws) } } class Function(val symbol: Int, val isGlobalInitializer: Boolean, val numberOfParameters: Int, val body: FunctionBody) { constructor(data: ArraySlice) : this(data.readInt(), data.readBoolean(), data.readInt(), FunctionBody(data)) fun write(result: ArraySlice) { result.writeInt(symbol) result.writeBoolean(isGlobalInitializer) result.writeInt(numberOfParameters) body.write(result) } } class Module(val symbolTable: SymbolTable, val functions: Array<Function>) { constructor(data: ArraySlice) : this(SymbolTable(data), data.readArray { Function(this) }) fun write(result: ArraySlice) { symbolTable.write(result) result.writeArray(functions) { it.write(this) } } } private val DEBUG = 0 private inline fun DEBUG_OUTPUT(severity: Int, block: () -> Unit) { if (DEBUG > severity) block() } fun serialize(context: Context, moduleDFG: ModuleDFG) { val symbolTable = moduleDFG.symbolTable val typeMap = (symbolTable.classMap.values + DataFlowIR.Type.Virtual).distinct().withIndex().associateBy({ it.value }, { it.index }) val functionSymbolMap = symbolTable.functionMap.values.distinct().withIndex().associateBy({ it.value }, { it.index }) DEBUG_OUTPUT(1) { println("TYPES: ${typeMap.size}, " + "FUNCTIONS: ${functionSymbolMap.size}, " + "PRIVATE FUNCTIONS: ${functionSymbolMap.keys.count { it is DataFlowIR.FunctionSymbol.Private }}, " + "FUNCTION TABLE SIZE: ${symbolTable.couldBeCalledVirtuallyIndex}" ) } val types = typeMap.entries .sortedBy { it.value } .map { fun buildTypeIntestines(type: DataFlowIR.Type.Declared) = DeclaredType( type.isFinal, type.isAbstract, type.superTypes.map { typeMap[it]!! }.toIntArray(), type.vtable.map { functionSymbolMap[it]!! }.toIntArray(), type.itable.map { (hash, symbol) -> ItableSlot(hash, functionSymbolMap[symbol]!!) }.toTypedArray() ) val type = it.key when (type) { DataFlowIR.Type.Virtual -> Type.virtual() is DataFlowIR.Type.External -> Type.external(type.hash, type.name) is DataFlowIR.Type.Public -> Type.public(type.hash, buildTypeIntestines(type), type.name) is DataFlowIR.Type.Private -> Type.private(type.index, buildTypeIntestines(type), type.name) else -> error("Unknown type $type") } } .toTypedArray() val functionSymbols = functionSymbolMap.entries .sortedBy { it.value } .map { val functionSymbol = it.key val numberOfParameters = functionSymbol.numberOfParameters val name = functionSymbol.name when (functionSymbol) { is DataFlowIR.FunctionSymbol.External -> FunctionSymbol.external(functionSymbol.hash, numberOfParameters, functionSymbol.escapes, functionSymbol.pointsTo, name) is DataFlowIR.FunctionSymbol.Public -> FunctionSymbol.public(functionSymbol.hash, numberOfParameters, functionSymbol.symbolTableIndex, name) is DataFlowIR.FunctionSymbol.Private -> FunctionSymbol.private(functionSymbol.symbolTableIndex, numberOfParameters, name) else -> error("Unknown function symbol $functionSymbol") } } .toTypedArray() val functions = moduleDFG.functions.values .map { function -> val body = function.body val nodeMap = body.nodes.withIndex().associateBy({ it.value }, { it.index }) val nodes = nodeMap.entries .sortedBy { it.value } .map { val node = it.key fun buildEdge(edge: DataFlowIR.Edge) = Edge(nodeMap[edge.node]!!, edge.castToType?.let { typeMap[it]!! }) fun buildCall(call: DataFlowIR.Node.Call) = Call( functionSymbolMap[call.callee]!!, call.arguments.map { buildEdge(it) }.toTypedArray(), typeMap[call.returnType]!! ) fun buildVirtualCall(virtualCall: DataFlowIR.Node.VirtualCall) = VirtualCall(buildCall(virtualCall), typeMap[virtualCall.receiverType]!!) fun buildField(field: DataFlowIR.Field) = Field(field.type?.let { typeMap[it]!! }, field.hash, field.name) when (node) { is DataFlowIR.Node.Parameter -> Node.parameter(node.index) is DataFlowIR.Node.Const -> Node.const(typeMap[node.type]!!) is DataFlowIR.Node.StaticCall -> Node.staticCall(buildCall(node), node.receiverType?.let { typeMap[it]!! }) is DataFlowIR.Node.NewObject -> Node.newObject(buildCall(node)) is DataFlowIR.Node.VtableCall -> Node.vtableCall(buildVirtualCall(node), node.calleeVtableIndex) is DataFlowIR.Node.ItableCall -> Node.itableCall(buildVirtualCall(node), node.calleeHash) is DataFlowIR.Node.Singleton -> Node.singleton(typeMap[node.type]!!, node.constructor?.let { functionSymbolMap[it]!! }) is DataFlowIR.Node.FieldRead -> Node.fieldRead(node.receiver?.let { buildEdge(it) }, buildField(node.field)) is DataFlowIR.Node.FieldWrite -> Node.fieldWrite(node.receiver?.let { buildEdge(it) }, buildField(node.field), buildEdge(node.value)) is DataFlowIR.Node.Variable -> Node.variable(node.values.map { buildEdge(it) }.toTypedArray(), node.temp) else -> error("Unknown node $node") } } .toTypedArray() Function( functionSymbolMap[function.symbol]!!, function.isGlobalInitializer, function.numberOfParameters, FunctionBody(nodes, nodeMap[body.returns]!!, nodeMap[body.throws]!!) ) } .toTypedArray() val module = Module(SymbolTable(types, functionSymbols), functions) val writer = ArraySlice(ByteArray(1024)) writer.writeInt(VERSION) module.write(writer) writer.trim() context.dataFlowGraph = writer.array } // TODO: Deserialize functions bodies lazily. fun deserialize(context: Context, startPrivateTypeIndex: Int, startPrivateFunIndex: Int): ExternalModulesDFG { var privateTypeIndex = startPrivateTypeIndex var privateFunIndex = startPrivateFunIndex val publicTypesMap = mutableMapOf<Long, DataFlowIR.Type.Public>() val allTypes = mutableListOf<DataFlowIR.Type.Declared>() val publicFunctionsMap = mutableMapOf<Long, DataFlowIR.FunctionSymbol.Public>() val functions = mutableMapOf<DataFlowIR.FunctionSymbol, DataFlowIR.Function>() val specifics = context.config.configuration.get(CommonConfigurationKeys.LANGUAGE_VERSION_SETTINGS)!! context.librariesWithDependencies.forEach { library -> val libraryDataFlowGraph = library.dataFlowGraph DEBUG_OUTPUT(1) { println("Data flow graph size for lib '${library.libraryName}': ${libraryDataFlowGraph?.size ?: 0}") } if (libraryDataFlowGraph != null) { val module = DataFlowIR.Module(library.moduleDescriptor(specifics)) val reader = ArraySlice(libraryDataFlowGraph) val version = reader.readInt() if (version != VERSION) error("Expected version $VERSION but actual is $version") val moduleDataFlowGraph = Module(reader) val symbolTable = moduleDataFlowGraph.symbolTable val types = symbolTable.types.map { if (it.virtual) DataFlowIR.Type.Virtual else { val external = it.external val public = it.public val private = it.private when { external != null -> DataFlowIR.Type.External(external.hash, external.name) public != null -> DataFlowIR.Type.Public(public.hash, public.intestines.isFinal, public.intestines.isAbstract, public.name).also { publicTypesMap.put(it.hash, it) allTypes += it } else -> DataFlowIR.Type.Private(privateTypeIndex++, private!!.intestines.isFinal, private.intestines.isAbstract, private.name).also { allTypes += it } } } } val functionSymbols = symbolTable.functionSymbols.map { val external = it.external val public = it.public val private = it.private when { external != null -> DataFlowIR.FunctionSymbol.External(external.hash, external.numberOfParameters, external.escapes, external.pointsTo, external.name) public != null -> { val symbolTableIndex = public.index if (symbolTableIndex >= 0) ++module.numberOfFunctions DataFlowIR.FunctionSymbol.Public(public.hash, public.numberOfParameters, module, symbolTableIndex, public.name).also { publicFunctionsMap.put(it.hash, it) } } else -> { val symbolTableIndex = private!!.index if (symbolTableIndex >= 0) ++module.numberOfFunctions DataFlowIR.FunctionSymbol.Private(privateFunIndex++, private.numberOfParameters, module, symbolTableIndex, private.name) } } } DEBUG_OUTPUT(1) { println("Lib: ${library.libraryName}, types: ${types.size}, functions: ${functionSymbols.size}") } symbolTable.types.forEachIndexed { index, type -> val deserializedType = types[index] as? DataFlowIR.Type.Declared ?: return@forEachIndexed if (deserializedType == DataFlowIR.Type.Virtual) return@forEachIndexed val intestines = if (deserializedType is DataFlowIR.Type.Public) type.public!!.intestines else type.private!!.intestines deserializedType.superTypes += intestines.superTypes.map { types[it] } deserializedType.vtable += intestines.vtable.map { functionSymbols[it] } intestines.itable.forEach { deserializedType.itable.put(it.hash, functionSymbols[it.impl]) } } fun deserializeEdge(edge: Edge) = DataFlowIR.Edge(edge.castToType?.let { types[it] }) fun deserializeCall(call: Call) = DataFlowIR.Node.Call( functionSymbols[call.callee], call.arguments.map { deserializeEdge(it) }, types[call.returnType], null ) fun deserializeVirtualCall(virtualCall: VirtualCall): DataFlowIR.Node.VirtualCall { val call = deserializeCall(virtualCall.call) return DataFlowIR.Node.VirtualCall( call.callee, call.arguments, call.returnType, types[virtualCall.receiverType], null ) } fun deserializeField(field: Field) = DataFlowIR.Field(field.type?.let { types[it] }, field.hash, field.name) fun deserializeBody(body: FunctionBody): DataFlowIR.FunctionBody { val nodes = body.nodes.map { when (it.type) { NodeType.PARAMETER -> DataFlowIR.Node.Parameter(it.parameter!!.index) NodeType.CONST -> DataFlowIR.Node.Const(types[it.const!!.type]) NodeType.STATIC_CALL -> { val staticCall = it.staticCall!! val call = deserializeCall(staticCall.call) val receiverType = staticCall.receiverType?.let { types[it] } DataFlowIR.Node.StaticCall(call.callee, call.arguments, call.returnType, receiverType, null) } NodeType.NEW_OBJECT -> { val call = deserializeCall(it.newObject!!.call) DataFlowIR.Node.NewObject(call.callee, call.arguments, call.returnType, null) } NodeType.VTABLE_CALL -> { val vtableCall = it.vtableCall!! val virtualCall = deserializeVirtualCall(vtableCall.virtualCall) DataFlowIR.Node.VtableCall( virtualCall.callee, virtualCall.receiverType, vtableCall.calleeVtableIndex, virtualCall.arguments, virtualCall.returnType, virtualCall.callSite ) } NodeType.ITABLE_CALL -> { val itableCall = it.itableCall!! val virtualCall = deserializeVirtualCall(itableCall.virtualCall) DataFlowIR.Node.ItableCall( virtualCall.callee, virtualCall.receiverType, itableCall.calleeHash, virtualCall.arguments, virtualCall.returnType, virtualCall.callSite ) } NodeType.SINGLETON -> { val singleton = it.singleton!! DataFlowIR.Node.Singleton(types[singleton.type], singleton.constructor?.let { functionSymbols[it] }) } NodeType.FIELD_READ -> { val fieldRead = it.fieldRead!! val receiver = fieldRead.receiver?.let { deserializeEdge(it) } DataFlowIR.Node.FieldRead(receiver, deserializeField(fieldRead.field)) } NodeType.FIELD_WRITE -> { val fieldWrite = it.fieldWrite!! val receiver = fieldWrite.receiver?.let { deserializeEdge(it) } DataFlowIR.Node.FieldWrite(receiver, deserializeField(fieldWrite.field), deserializeEdge(fieldWrite.value)) } NodeType.VARIABLE -> { val variable = it.variable!! DataFlowIR.Node.Variable(variable.values.map { deserializeEdge(it) }, variable.temp) } else -> error("Unknown node: $it") } } body.nodes.forEachIndexed { index, node -> val deserializedNode = nodes[index] when (node.type) { NodeType.STATIC_CALL -> node.staticCall!!.call.arguments.forEachIndexed { i, arg -> (deserializedNode as DataFlowIR.Node.StaticCall).arguments[i].node = nodes[arg.node] } NodeType.NEW_OBJECT -> node.newObject!!.call.arguments.forEachIndexed { i, arg -> (deserializedNode as DataFlowIR.Node.NewObject).arguments[i].node = nodes[arg.node] } NodeType.VTABLE_CALL -> node.vtableCall!!.virtualCall.call.arguments.forEachIndexed { i, arg -> (deserializedNode as DataFlowIR.Node.VtableCall).arguments[i].node = nodes[arg.node] } NodeType.ITABLE_CALL -> node.itableCall!!.virtualCall.call.arguments.forEachIndexed { i, arg -> (deserializedNode as DataFlowIR.Node.ItableCall).arguments[i].node = nodes[arg.node] } NodeType.FIELD_READ -> node.fieldRead!!.receiver?.let { (deserializedNode as DataFlowIR.Node.FieldRead).receiver!!.node = nodes[it.node] } NodeType.FIELD_WRITE -> { val deserializedFieldWrite = deserializedNode as DataFlowIR.Node.FieldWrite val fieldWrite = node.fieldWrite!! fieldWrite.receiver?.let { deserializedFieldWrite.receiver!!.node = nodes[it.node] } deserializedFieldWrite.value.node = nodes[fieldWrite.value.node] } NodeType.VARIABLE -> node.variable!!.values.forEachIndexed { i, value -> (deserializedNode as DataFlowIR.Node.Variable).values[i].node = nodes[value.node] } else -> { } } } return DataFlowIR.FunctionBody(nodes, nodes[body.returns] as DataFlowIR.Node.Variable, nodes[body.throws] as DataFlowIR.Node.Variable) } moduleDataFlowGraph.functions.forEach { val symbol = functionSymbols[it.symbol] functions.put(symbol, DataFlowIR.Function(symbol, it.isGlobalInitializer, it.numberOfParameters, deserializeBody(it.body))) } } } return ExternalModulesDFG(allTypes, publicTypesMap, publicFunctionsMap, functions) } }
apache-2.0
1f3cc99b6f950ac27ac6a4acb282552d
41.677326
158
0.520844
5.282716
false
false
false
false
MarcinMoskala/ActivityStarter
sample/kotlinapp/src/main/java/com/marcinmoskala/kotlinapp/notification/NotificationPublisher.kt
1
1094
package com.marcinmoskala.kotlinapp.notification import activitystarter.ActivityStarter import activitystarter.Arg import android.app.Notification import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.marcinmoskala.kotlinapp.R import com.marcinmoskala.kotlinapp.notificationManager class NotificationPublisher : BroadcastReceiver() { @Arg var id: Int = -1 @Arg lateinit var time: String override fun onReceive(context: Context, intent: Intent) { ActivityStarter.fill(this, intent) val notification = createSimpleNotification(context) context.notificationManager.notify(id, notification) } fun createSimpleNotification(context: Context) = Notification.Builder(context) .setContentTitle(getTextTitle(id)) .setContentText(getTextSubtitle(time)) .setSmallIcon(R.mipmap.ic_launcher) .build()!! companion object { fun getTextTitle(id: Int) = "I am notification $id" fun getTextSubtitle(time: String) = "It is $time" } }
apache-2.0
a833d1e8c999f8e19c00b04926867ce6
32.181818
82
0.732176
4.539419
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/leguicomp/IconButton.kt
1
964
package com.cout970.modeler.gui.leguicomp import com.cout970.modeler.gui.GuiResources import org.liquidengine.legui.component.Button import org.liquidengine.legui.icon.Icon import org.liquidengine.legui.icon.ImageIcon /** * Created by cout970 on 2017/09/15. */ class IconButton( var command: String = "", var icon: String = "", posX: Float = 0f, posY: Float = 0f, sizeX: Float = 16f, sizeY: Float = 16f ) : Button("", posX, posY, sizeX, sizeY), IResourceReloadable { init { classes("icon_button") } override fun loadResources(resources: GuiResources) { if (icon.isNotBlank()) { setImage(ImageIcon(resources.getIcon(icon))) } } fun setTooltip(tooltip: String) { this.tooltip = InstantTooltip(tooltip) } fun setImage(img: Icon) { style.background.icon = img } override fun toString(): String = "IconButton(id='$command', icon='$icon')" }
gpl-3.0
1afa13018fc0a70ebf126e915503a733
25.081081
79
0.641079
3.887097
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/service/BatteryTimeService.kt
1
6218
package com.quixom.apps.deviceinfo.service import android.app.Service import android.content.Intent import android.os.IBinder import android.content.IntentFilter import android.content.BroadcastReceiver import android.content.Context import android.support.annotation.Nullable import com.quixom.apps.deviceinfo.utilities.BatteryStats import java.util.concurrent.TimeUnit /** * Created by akif on 10/6/17. */ abstract class BatteryTimeService: Service() { /** * Lists to store the tracked data for calculating charging and discharging time. */ private var batteryDischargingTimes: ArrayList<Long>? = null private var batteryChargingTimes:ArrayList<Long>? = null /** * A broadcast receiver for tracking the level changes and the battery usage. */ private val levelReceiver = object : BroadcastReceiver() { internal var oldDischargeLevel = 101 internal var oldChargeLevel = 0 internal var oldDischargeTime: Long = 0 internal var oldChargeTime: Long = 0 override fun onReceive(context: Context, intent: Intent) { val batteryStats = BatteryStats(intent) val charging = batteryStats.isCharging() val level = batteryStats.getLevel() if (!charging && level <= 100) { if (level < oldDischargeLevel) { val time = System.currentTimeMillis() if (oldDischargeTime != 0L) { val diffTime = time - oldDischargeTime batteryDischargingTimes!!.add(diffTime) publishDischargingText(level) } else { onCalculatingDischargingTime() } oldDischargeTime = time oldDischargeLevel = level } batteryChargingTimes!!.clear() oldChargeLevel = 0 oldChargeTime = 0 } if (charging) { if (oldChargeLevel < level) { val time = System.currentTimeMillis() if (oldChargeTime != 0L) { val diffTime = time - oldChargeTime batteryChargingTimes!!.add(diffTime) publishChargingText(level) } else { onCalculatingChargingTime() } oldChargeTime = time oldChargeLevel = level } if (level == 100) { onFullBattery() } batteryDischargingTimes!!.clear() oldDischargeLevel = 100 oldDischargeTime = 0 } } } /** * Method called when the charging time is calculated. * The {@param hours} and {@param mins} remaining for full charge. */ protected abstract fun onChargingTimePublish(hours: Int, mins: Int) /** * Method called when the charging time is being calculated. * Any status text indicating that "charging time is being calculated" can be used here. */ protected abstract fun onCalculatingChargingTime() /** * Method called when the charging time is calculated. * The {@param days} , {@param hours} and {@param mins} remaining for the battery to drain. */ protected abstract fun onDischargeTimePublish(days: Int, hours: Int, mins: Int) /** * Method called when the discharging time is being calculated. * Any status text indicating that "discharging time is being calculated" can be used here. */ protected abstract fun onCalculatingDischargingTime() /** * Method called when the battery is fully charged. * Called only when the device is connected to charger and battery becomes full. */ protected abstract fun onFullBattery() /** * Start the calculation when the activity is created. */ override fun onCreate() { super.onCreate() batteryDischargingTimes = ArrayList() batteryChargingTimes = ArrayList() registerReceiver(levelReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) } /** * Method to calculate the charging time based on the timely usage. */ private fun publishChargingText(level: Int) { val average: Long var sum: Long = 0 for (time in batteryChargingTimes!!) { sum += time!! } average = sum / batteryChargingTimes!!.size * (100 - level) //Since charging cannot take days //int days = (int) TimeUnit.MILLISECONDS.toDays(average); val hours = (TimeUnit.MILLISECONDS.toHours(average) % TimeUnit.DAYS.toHours(1)) as Int val mins = (TimeUnit.MILLISECONDS.toMinutes(average) % TimeUnit.HOURS.toMinutes(1)) as Int onChargingTimePublish(hours, mins) } /** * Method to calculate the discharging time based on the timely usage. */ private fun publishDischargingText(level: Int) { val average: Long var sum: Long = 0 for (time in batteryDischargingTimes!!) { sum += time } average = sum / batteryDischargingTimes!!.size * level val days = TimeUnit.MILLISECONDS.toDays(average) as Int val hours = (TimeUnit.MILLISECONDS.toHours(average) % TimeUnit.DAYS.toHours(1)) as Int val mins = (TimeUnit.MILLISECONDS.toMinutes(average) % TimeUnit.HOURS.toMinutes(1)) as Int onDischargeTimePublish(days, hours, mins) } /** * Returns START_STICKY by default. Method can be overridden to customize. */ override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { return Service.START_STICKY } /** * Unregister the level receiver onDestroy of the service to avoid leakage. */ override fun onDestroy() { super.onDestroy() unregisterReceiver(levelReceiver) } /** * Binding not required by default. Can be overridden for binding. */ @Nullable override fun onBind(intent: Intent): IBinder? { return null } }
apache-2.0
48691e19cbcc6577343fb793d9f7c473
29.787129
98
0.603088
4.96249
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/RewardsFragmentViewModel.kt
1
11312
package com.kickstarter.viewmodels import android.util.Pair import androidx.annotation.NonNull import com.kickstarter.libs.Environment import com.kickstarter.libs.FragmentViewModel import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair import com.kickstarter.libs.rx.transformers.Transformers.takeWhen import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.RewardUtils import com.kickstarter.libs.utils.extensions.isBacked import com.kickstarter.mock.factories.RewardFactory import com.kickstarter.models.Backing import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.ui.data.PledgeData import com.kickstarter.ui.data.PledgeFlowContext import com.kickstarter.ui.data.PledgeReason import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.fragments.RewardsFragment import com.kickstarter.viewmodels.usecases.ShowPledgeFragmentUseCase import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import java.util.Locale class RewardsFragmentViewModel { interface Inputs { /** Configure with current [ProjectData]. */ fun configureWith(projectData: ProjectData) /** Call when a reward is clicked. */ fun rewardClicked(reward: Reward) /** Call when the Alert button has been pressed */ fun alertButtonPressed() } interface Outputs { /** Emits the position of the backed reward. */ fun backedRewardPosition(): Observable<Int> /** Emits the current [ProjectData]. */ fun projectData(): Observable<ProjectData> /** Emits the count of the current project's rewards. */ fun rewardsCount(): Observable<Int> /** Emits when we should show the [com.kickstarter.ui.fragments.PledgeFragment]. */ fun showPledgeFragment(): Observable<Triple<PledgeData, PledgeReason, Boolean>> /** Emits when we should show the [com.kickstarter.ui.fragments.BackingAddOnsFragment]. */ fun showAddOnsFragment(): Observable<Pair<PledgeData, PledgeReason>> /** Emits if we have to show the alert in case any AddOns selection could be lost. */ fun showAlert(): Observable<Pair<PledgeData, PledgeReason>> } class ViewModel(@NonNull val environment: Environment) : FragmentViewModel<RewardsFragment>(environment), Inputs, Outputs { private val projectDataInput = PublishSubject.create<ProjectData>() private val rewardClicked = PublishSubject.create<Pair<Reward, Boolean>>() private val alertButtonPressed = PublishSubject.create<Void>() private val backedRewardPosition = PublishSubject.create<Int>() private val projectData = BehaviorSubject.create<ProjectData>() private val rewardsCount = BehaviorSubject.create<Int>() private val pledgeData = PublishSubject.create<Pair<PledgeData, PledgeReason>>() private val showPledgeFragment = PublishSubject.create<Triple<PledgeData, PledgeReason, Boolean>>() private val showAddOnsFragment = PublishSubject.create<Pair<PledgeData, PledgeReason>>() private val showAlert = PublishSubject.create<Pair<PledgeData, PledgeReason>>() // - Environment Objects private val currentUser = requireNotNull(this.environment.currentUser()?.observable()) private val optimizely = requireNotNull(this.environment.optimizely()) val inputs: Inputs = this val outputs: Outputs = this init { this.isExpanded .filter { it } .compose(combineLatestPair(this.projectDataInput)) .map { it.second } .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackRewardsCarouselViewed(it) } this.projectDataInput .map { filterOutNotStartedRewards(it) } .compose(bindToLifecycle()) .subscribe(this.projectData) val project = this.projectData .map { it.project() } project .filter { it.isBacking() } .map { indexOfBackedReward(it) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.backedRewardPosition) val backedReward = project .map { it.backing()?.let { backing -> getReward(backing) } } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } val defaultRewardClicked = Pair(Reward.builder().id(0L).minimum(0.0).build(), false) Observable .combineLatest(this.rewardClicked.startWith(defaultRewardClicked), this.projectDataInput) { rewardPair, projectData -> if (!rewardPair.second) { return@combineLatest null } else { return@combineLatest pledgeDataAndPledgeReason(projectData, rewardPair.first) } } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { val pledgeAndData = it val newRw = it.first.reward() val reason = it.second when (reason) { PledgeReason.PLEDGE -> { if (newRw.hasAddons()) this.showAddOnsFragment.onNext(pledgeAndData) else this.pledgeData.onNext(pledgeAndData) } else -> {} } this.rewardClicked.onNext(defaultRewardClicked) } Observable .combineLatest(this.rewardClicked.startWith(defaultRewardClicked), this.projectDataInput, backedReward) { rewardPair, projectData, backedReward -> if (!rewardPair.second) { return@combineLatest null } else { return@combineLatest Pair(pledgeDataAndPledgeReason(projectData, rewardPair.first), backedReward) } } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { val pledgeAndData = it.first val newRw = it.first.first.reward() val prevRw = it.second val reason = it.first.second when (reason) { PledgeReason.UPDATE_REWARD -> { if (prevRw.hasAddons() && !newRw.hasAddons()) this.showAlert.onNext(pledgeAndData) if (!prevRw.hasAddons() && !newRw.hasAddons()) this.pledgeData.onNext(pledgeAndData) if (prevRw.hasAddons() && newRw.hasAddons()) { if (differentShippingTypes(prevRw, newRw)) this.showAlert.onNext(it.first) else this.showAddOnsFragment.onNext(pledgeAndData) } if (!prevRw.hasAddons() && newRw.hasAddons()) { this.showAddOnsFragment.onNext(pledgeAndData) } } else -> {} } this.rewardClicked.onNext(defaultRewardClicked) } project .map { it.rewards()?.size ?: 0 } .compose(bindToLifecycle()) .subscribe(this.rewardsCount) this.showAlert .compose<Pair<PledgeData, PledgeReason>>(takeWhen(alertButtonPressed)) .compose(bindToLifecycle()) .subscribe { if (it.first.reward().hasAddons()) this.showAddOnsFragment.onNext(it) else this.pledgeData.onNext(it) } ShowPledgeFragmentUseCase(this.pledgeData) .data(this.currentUser, this.optimizely) .compose(bindToLifecycle()) .subscribe { this.showPledgeFragment.onNext(it) } } private fun filterOutNotStartedRewards(pData: ProjectData): ProjectData { val rewards = pData.project().rewards()?.filter { RewardUtils.hasStarted(it) } val modifiedProject = pData.project().toBuilder().rewards(rewards).build() return pData.toBuilder() .project(modifiedProject) .build() } private fun getReward(backingObj: Backing): Reward { return backingObj.reward()?.let { rw -> if (backingObj.addOns().isNullOrEmpty()) rw else rw.toBuilder().hasAddons(true).build() } ?: RewardFactory.noReward() } private fun differentShippingTypes(newRW: Reward, backedRW: Reward): Boolean { return if (newRW.id() == backedRW.id()) false else { newRW.shippingType()?.toLowerCase(Locale.getDefault()) ?: "" != backedRW.shippingType()?.toLowerCase(Locale.getDefault()) ?: "" } } private fun pledgeDataAndPledgeReason(projectData: ProjectData, reward: Reward): Pair<PledgeData, PledgeReason> { val pledgeReason = if (projectData.project().isBacking()) PledgeReason.UPDATE_REWARD else PledgeReason.PLEDGE val pledgeData = PledgeData.with(PledgeFlowContext.forPledgeReason(pledgeReason), projectData, reward) return Pair(pledgeData, pledgeReason) } private fun indexOfBackedReward(project: Project): Int { project.rewards()?.run { for ((index, reward) in withIndex()) { if (project.backing()?.isBacked(reward) == true) { return index } } } return 0 } override fun configureWith(projectData: ProjectData) { this.projectDataInput.onNext(projectData) } override fun rewardClicked(reward: Reward) { this.rewardClicked.onNext(Pair(reward, true)) } override fun alertButtonPressed() = this.alertButtonPressed.onNext(null) @NonNull override fun backedRewardPosition(): Observable<Int> = this.backedRewardPosition @NonNull override fun projectData(): Observable<ProjectData> = this.projectData @NonNull override fun rewardsCount(): Observable<Int> = this.rewardsCount @NonNull override fun showPledgeFragment(): Observable<Triple<PledgeData, PledgeReason, Boolean>> = this.showPledgeFragment @NonNull override fun showAddOnsFragment(): Observable<Pair<PledgeData, PledgeReason>> = this.showAddOnsFragment @NonNull override fun showAlert(): Observable<Pair<PledgeData, PledgeReason>> = this.showAlert } }
apache-2.0
bdb462f927aa90b24652fcbc31df41c4
41.208955
162
0.589728
5.485936
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/templates/Templates.kt
1
5820
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.utils.templates import slatekit.results.Try import slatekit.results.getOrElse /** * Handles processing of text templates with variables/substitutions inside. * * @param templates * @param variables * @param setDefaults */ class Templates( val templates: List<Template>? = null, val variables: List<Pair<String, (TemplatePart) -> String>>? = null, setDefaults: Boolean = true ) { /** * The actual variables/substitutions that map to functions to substite the values */ val subs = Subs(variables, setDefaults) val emptyParts = listOf<TemplatePart>() /** * parses the text template * * @param text * @return */ fun parse(text: String): Try<List<TemplatePart>> = TemplateParser(text).parse() /** * parses the text and returns a parsed template with individual parts. * * @param text * @return */ fun parseTemplate(name: String, text: String): Template { val result = parse(text) return Template( name = name, content = text, parsed = true, valid = result.success, status = result.desc, group = null, path = null, parts = result.getOrElse({ listOf<TemplatePart>() }) ) } /** * Processes the template with the variables supplied during creation * * @param text * @return */ fun resolve(text: String): String? = resolve(text, subs) /** * Processes the stored template associated with the name, with the variables supplied * at creation. * * @param name * @return */ fun resolveTemplate(name: String, substitutions: Subs? = null): String? { val template = templates?.filter { it.name == name }?.firstOrNull() val result = template?.let { t -> if (t.valid) resolveParts(t.parts ?: emptyParts, substitutions ?: subs) else null } return result } fun resolveTemplateWithVars(name: String, vars: Map<String, Any>): String? { val template = templates?.filter { it.name == name }?.firstOrNull() val result = template?.let { t -> if (t.valid) resolvePartsWithVars(t.parts ?: emptyParts, vars) else null } return result } /** * Processes the template with the variables supplied * * @param text * @return */ fun resolve(text: String, substitutions: Subs?): String? { val result = parse(text) // Failed parsing ? val finalResult = if (result.success) { val parts = result.getOrElse { listOf() } if (parts.isEmpty()) { text } else { resolveParts(parts, substitutions ?: subs) } } else { result.desc } return finalResult } private fun resolveParts(tokens: List<TemplatePart>, substitutions: Subs): String? { val finalText = tokens.fold("", { s, t -> when (t.subType) { TemplateConstants.TypeText -> s + t.text TemplateConstants.TypeSub -> s + substitutions.lookup(t.text) else -> s + "" } }) return finalText } private fun resolvePartsWithVars(tokens: List<TemplatePart>, vars: Map<String, Any>?): String? { val finalText = tokens.fold("", { s, t -> when (t.subType) { TemplateConstants.TypeText -> s + t.text TemplateConstants.TypeSub -> s + resolveToken(t, vars) else -> s + "" } }) return finalText } private fun resolveToken(token: TemplatePart, vars: Map<String, Any>?): Any { val result = vars?.let { v -> if (v.containsKey(token.text)) { val vr = v[token.text] vr ?: "" } else if (subs.contains(token.text)) { subs[token.text] } else { "" } } ?: "" return result } companion object { /** * Builds the templates object after parsing the given individual templates * * @param templates * @param subs * @return */ @JvmStatic fun build( templates: List<Template>, subs: List<Pair<String, (TemplatePart) -> String>>? = null ): Templates { // Each template val parsed = parse(templates) return Templates(parsed, subs) } @JvmStatic fun subs(items: List<Pair<String, (TemplatePart) -> String>>): Subs = Subs(items) @JvmStatic fun parse(templates: List<Template>): List<Template> { // Each template val parsed = templates.map { template -> // Parse the template into individual parts( plain text, variables ) val result = TemplateParser(template.content).parse() // Build the template template.copy(parsed = true, valid = result.success, parts = result.getOrElse{ listOf() } ) } return parsed } } }
apache-2.0
de7cecc35547eebd4832a7e2ce73009c
27.252427
100
0.531615
4.633758
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/protocol/protocol-reader/src/LazyCachedMethodHandler.kt
44
1650
package org.jetbrains.protocolReader import java.lang.reflect.Method /** * Basic implementation of the method that parses value on demand and store it for a future use */ internal class LazyCachedMethodHandler(private val parser: ValueReader, private val fieldBinding: VolatileFieldBinding) : MethodHandler { protected fun writeReturnTypeJava(scope: ClassScope, m: Method, out: TextOutput) { val objectValueParser = parser.asJsonTypeParser() if (objectValueParser == null) { writeJavaTypeName(m.genericReturnType, out) } else { out.append(scope.getTypeImplReference(objectValueParser.type.type!!)) } } override fun writeMethodImplementationJava(scope: ClassScope, method: Method, out: TextOutput) { out.append("override fun ") appendMethodSignatureJava(method, listOf(), out) out.append(": ") writeReturnTypeJava(scope, method, out) out.openBlock() out.append("if (") fieldBinding.writeGetExpression(out) out.append(" == null)").block { if (parser.isThrowsIOException()) { out.append("try").openBlock() } fieldBinding.writeGetExpression(out) out.append(" = ") parser.writeReadCode(scope, true, scope.output) if (parser.isThrowsIOException()) { out.closeBlock() out.newLine().append("catch (e: IOException)").openBlock() out.append("throw com.google.gson.JsonParseException(e)").closeBlock() } out.newLine().append(PENDING_INPUT_READER_NAME).append(" = null") } out.newLine().append("return ") fieldBinding.writeGetExpression(out) out.append("!!") out.closeBlock() } }
apache-2.0
b80f7530783e67b72e11951a26b9dd0b
31.352941
137
0.687273
4.263566
false
false
false
false
jagguli/intellij-community
plugins/settings-repository/testSrc/GitTest.kt
2
13328
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.configurationStore.write import com.intellij.mock.MockVirtualFileSystem import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.path import com.intellij.util.PathUtilRt import org.assertj.core.api.Assertions.assertThat import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Repository import org.jetbrains.jgit.dirCache.deletePath import org.jetbrains.jgit.dirCache.writePath import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.conflictResolver import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.commit import org.jetbrains.settingsRepository.git.computeIndexDiff import org.jetbrains.settingsRepository.git.resetHard import org.junit.ClassRule import org.junit.Test import java.io.File import java.nio.charset.StandardCharsets import java.util.Arrays import kotlin.properties.Delegates // kotlin bug, cannot be val (.NoSuchMethodError: org.jetbrains.settingsRepository.SettingsRepositoryPackage.getMARKER_ACCEPT_MY()[B) object AM { val MARKER_ACCEPT_MY: ByteArray = "__accept my__".toByteArray() val MARKER_ACCEPT_THEIRS: ByteArray = "__accept theirs__".toByteArray() } class GitTest : IcsTestCase() { companion object { @ClassRule val projectRule = ProjectRule() } private val repositoryManager: GitRepositoryManager get() = icsManager.repositoryManager as GitRepositoryManager private val repository: Repository get() = repositoryManager.repository var remoteRepository: Repository by Delegates.notNull() init { conflictResolver = { files, mergeProvider -> val mergeSession = mergeProvider.createMergeSession(files) for (file in files) { val mergeData = mergeProvider.loadRevisions(file) if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_THEIRS)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours) } else if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs) } else if (Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { file.setBinaryContent(mergeData.LAST!!) mergeProvider.conflictResolvedForFile(file) } else { throw CannotResolveConflictInTestMode() } } } } private fun addAndCommit(path: String): FileInfo { val data = """<file path="$path" />""".toByteArray() provider.write(path, data) repositoryManager.commit() return FileInfo(path, data) } @Test fun add() { provider.write(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(SAMPLE_FILE_NAME) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun addSeveral() { val addedFile = "foo.xml" val addedFile2 = "bar.xml" provider.write(addedFile, "foo") provider.write(addedFile2, "bar") val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(addedFile, addedFile2) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun delete() { fun delete(directory: Boolean) { val dir = "dir" val fullFileSpec = "$dir/file.xml" provider.write(fullFileSpec, SAMPLE_FILE_CONTENT) provider.delete(if (directory) dir else fullFileSpec) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } delete(false) delete(true) } @Test fun `set upstream`() { val url = "https://github.com/user/repo.git" repositoryManager.setUpstream(url) assertThat(repositoryManager.getUpstream()).isEqualTo(url) } @Test public fun pullToRepositoryWithoutCommits() { doPullToRepositoryWithoutCommits(null) } @Test fun pullToRepositoryWithoutCommitsAndCustomRemoteBranchName() { doPullToRepositoryWithoutCommits("customRemoteBranchName") } private fun doPullToRepositoryWithoutCommits(remoteBranchName: String?) { createLocalRepository(remoteBranchName) repositoryManager.pull() compareFiles(repository.workTree, remoteRepository.workTree) } @Test fun pullToRepositoryWithCommits() { doPullToRepositoryWithCommits(null) } @Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() { doPullToRepositoryWithCommits("customRemoteBranchName") } private fun doPullToRepositoryWithCommits(remoteBranchName: String?) { val file = createLocalRepositoryAndCommit(remoteBranchName) repositoryManager.commit() repositoryManager.pull() assertThat(FileUtil.loadFile(File(repository.getWorkTree(), file.name))).isEqualTo(String(file.data, CharsetToolkit.UTF8_CHARSET)) compareFiles(repository.workTree, remoteRepository.workTree, null, PathUtilRt.getFileName(file.name)) } private fun createLocalRepository(remoteBranchName: String? = null) { createRemoteRepository(remoteBranchName) repositoryManager.setUpstream(remoteRepository.getWorkTree().absolutePath, remoteBranchName) } private fun createLocalRepositoryAndCommit(remoteBranchName: String? = null): FileInfo { createLocalRepository(remoteBranchName) return addAndCommit("local.xml") } private fun MockVirtualFileSystem.compare() { compareFiles(repository.workTree, remoteRepository.workTree, root) } // never was merged. we reset using "merge with strategy "theirs", so, we must test - what's happen if it is not first merge? - see next test @Test fun resetToTheirsIfFirstMerge() { createLocalRepositoryAndCommit(null) sync(SyncType.OVERWRITE_LOCAL) fs().file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare() } @Test fun resetToTheirsISecondMergeIsNull() { createLocalRepositoryAndCommit(null) sync(SyncType.MERGE) restoreRemoteAfterPush() val fs = MockVirtualFileSystem() fun testRemote() { fs .file("local.xml", """<file path="local.xml" />""") .file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .compare() } testRemote() addAndCommit("_mac/local2.xml") sync(SyncType.OVERWRITE_LOCAL) fs.compare() // test: merge and push to remote after such reset sync(SyncType.MERGE) restoreRemoteAfterPush() testRemote() } @Test fun resetToMyIfFirstMerge() { createLocalRepositoryAndCommit() sync(SyncType.OVERWRITE_REMOTE) restoreRemoteAfterPush() fs().file("local.xml", """<file path="local.xml" />""").compare() } @Test fun `reset to my, second merge is null`() { createLocalRepositoryAndCommit() sync(SyncType.MERGE) restoreRemoteAfterPush() val fs = fs().file("local.xml", """<file path="local.xml" />""").file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) fs.compare() val localToFilePath = "_mac/local2.xml" addAndCommit(localToFilePath) sync(SyncType.OVERWRITE_REMOTE) restoreRemoteAfterPush() fs.file(localToFilePath, """<file path="$localToFilePath" />""") fs.compare() // test: merge to remote after such reset sync(SyncType.MERGE) restoreRemoteAfterPush() fs.compare() } @Test fun `merge - resolve conflicts to my`() { createLocalRepository() val data = AM.MARKER_ACCEPT_MY provider.write(SAMPLE_FILE_NAME, data) sync(SyncType.MERGE) restoreRemoteAfterPush() fs().file(SAMPLE_FILE_NAME, data.toString(StandardCharsets.UTF_8)).compare() } @Test fun `merge - theirs file deleted, my modified, accept theirs`() { createLocalRepository() sync(SyncType.MERGE) val data = AM.MARKER_ACCEPT_THEIRS provider.write(SAMPLE_FILE_NAME, data) repositoryManager.commit() remoteRepository.deletePath(SAMPLE_FILE_NAME) remoteRepository.commit("delete $SAMPLE_FILE_NAME") sync(SyncType.MERGE) fs().compare() } @Test fun `merge - my file deleted, theirs modified, accept my`() { createLocalRepository() sync(SyncType.MERGE) provider.delete("remote.xml") repositoryManager.commit() remoteRepository.writePath("remote.xml", AM.MARKER_ACCEPT_THEIRS) remoteRepository.commit("") sync(SyncType.MERGE) restoreRemoteAfterPush() fs().compare() } @Test fun `commit if unmerged`() { createLocalRepository() val data = "<foo />" provider.write(SAMPLE_FILE_NAME, data) try { sync(SyncType.MERGE) } catch (e: CannotResolveConflictInTestMode) { } // repository in unmerged state conflictResolver = {files, mergeProvider -> assertThat(files).hasSize(1) assertThat(files.first().path).isEqualTo(SAMPLE_FILE_NAME) val mergeSession = mergeProvider.createMergeSession(files) mergeSession.conflictResolvedForFile(files.first(), MergeSession.Resolution.AcceptedTheirs) } sync(SyncType.MERGE) fs().file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare() } // remote is uninitialized (empty - initial commit is not done) @Test fun `merge with uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.MERGE) } @Test fun `reset to my, uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE) } @Test fun `reset to theirs, uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL) } @Test fun gitignore() { createLocalRepository() provider.write(".gitignore", "*.html") sync(SyncType.MERGE) val filePaths = listOf("bar.html", "i/am/a/long/path/to/file/foo.html") for (path in filePaths) { provider.write(path, path) } val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() for (path in filePaths) { assertThat(provider.read(path)).isNull() } } private fun createRemoteRepository(branchName: String? = null, initialCommit: Boolean = true) { val repository = tempDirManager.createRepository("upstream") if (initialCommit) { repository .add(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .commit("") } if (branchName != null) { if (!initialCommit) { // jgit cannot checkout&create branch if no HEAD (no commits in our empty repository), so we create initial empty commit repository.commit("") } Git(repository).checkout().setCreateBranch(true).setName(branchName).call() } remoteRepository = repository } private fun doSyncWithUninitializedUpstream(syncType: SyncType) { createRemoteRepository(initialCommit = false) repositoryManager.setUpstream(remoteRepository.getWorkTree().absolutePath) val path = "local.xml" val data = "<application />" provider.write(path, data) sync(syncType) val fs = MockVirtualFileSystem() if (syncType != SyncType.OVERWRITE_LOCAL) { fs.file(path, data) } restoreRemoteAfterPush(); fs.compare() } private fun restoreRemoteAfterPush() { /** we must not push to non-bare repository - but we do it in test (our sync merge equals to "pull&push"), " By default, updating the current branch in a non-bare repository is denied, because it will make the index and work tree inconsistent with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD. " so, we do "git reset --hard" */ remoteRepository.resetHard() } private fun sync(syncType: SyncType) { icsManager.sync(syncType) } }
apache-2.0
58020d757e247bf22c066143702a8706
30.585308
143
0.718187
4.454545
false
true
false
false
JetBrains/kotlin-native
performance/shared/src/main/kotlin-native/posix/org/jetbrains/benchmarksLauncher/Utils.kt
4
1129
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.benchmarksLauncher import platform.posix.* import kotlinx.cinterop.* actual fun currentTime() = memScoped { val timeVal = alloc<timeval>() gettimeofday(timeVal.ptr, null) val sec = alloc<LongVar>() sec.value = timeVal.tv_sec val nowtm = localtime(sec.ptr) var timeBuffer = ByteArray(1024) strftime(timeBuffer.refTo(0), timeBuffer.size.toULong(), "%H:%M:%S", nowtm) timeBuffer.toKString() }
apache-2.0
d16e6e6ec5e0b0db9cb82210663c6cdb
33.212121
87
0.671391
4.046595
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/cache/CallSaulAction.kt
1
2684
// 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.actions.cache import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.psi.util.CachedValueProvider import com.intellij.util.SystemProperties internal class CallSaulAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) = service<Saul>().sortThingsOut(RecoveryScope.createInstance(e)) override fun update(e: AnActionEvent) { val isEnabled = e.project != null e.presentation.isEnabledAndVisible = isEnabled if (isEnabled) { val recoveryScope = RecoveryScope.createInstance(e) if (recoveryScope is FilesRecoveryScope) { e.presentation.text = ActionsBundle.message("action.CallSaul.on.file.text", recoveryScope.files.size) } } } } internal class CacheRecoveryActionGroup: ComputableActionGroup() { override fun createChildrenProvider(actionManager: ActionManager): CachedValueProvider<Array<AnAction>> { return CachedValueProvider { isPopup = ApplicationManager.getApplication().isInternal val actions = if (isSaulHere) { val baseActions = arrayListOf<AnAction>(actionManager.getAction("CallSaul")) if (isPopup) { baseActions.add(Separator.getInstance()) } (baseActions + service<Saul>().sortedActions.map { it.toAnAction() }).toTypedArray() } else emptyArray() CachedValueProvider.Result.create(actions, service<Saul>().modificationRecoveryActionTracker) } } private fun RecoveryAction.toAnAction(): AnAction { val recoveryAction = this return object: DumbAwareAction(recoveryAction.presentableName) { override fun actionPerformed(e: AnActionEvent) { val scope = RecoveryScope.createInstance(e) recoveryAction.performUnderProgress(scope,false) } override fun update(e: AnActionEvent) { if (e.project == null) { e.presentation.isEnabledAndVisible = false return } val scope = RecoveryScope.createInstance(e) e.presentation.isEnabledAndVisible = recoveryAction.canBeApplied(scope) && ApplicationManager.getApplication().isInternal } } } } private val isSaulHere: Boolean get() = ApplicationManager.getApplication().isInternal || SystemProperties.getBooleanProperty("idea.cache.recovery.enabled", true)
apache-2.0
b4694037b929146383afca1ab07e034c
37.913043
158
0.730253
4.742049
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/view/home/HomeFragment.kt
1
6378
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.view.home import android.graphics.Color import android.os.Bundle import android.support.design.widget.TabLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.zqlite.android.dclib.entiry.Node import com.zqlite.android.diycode.BR import com.zqlite.android.diycode.R import com.zqlite.android.diycode.databinding.ListitemTopicNodeItemBinding import com.zqlite.android.diycode.device.utils.TokenStore import com.zqlite.android.diycode.device.view.BaseFragment import com.zqlite.android.diycode.device.view.home.topics.TopicContract import com.zqlite.android.diycode.device.view.home.topics.TopicFragment import com.zqlite.android.diycode.device.view.home.topics.TopicPresenter import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.fragment_topic.* /** * Created by scott on 2017/8/11. */ class HomeFragment : BaseFragment(),HomeContract.View,HomeContract.CategoryCallback { private var mPresetner : HomeContract.Presenter? = null private var mTabLayout : TabLayout? = null private var mViewPager : ViewPager ? = null private var topicFragment : TopicFragment ?=null private var topicPresenter : TopicContract.Presenter ?=null private var mCurrentType : Int = -1 private var mAdapter : CategoryAdapter = CategoryAdapter() override fun setPresenter(presenter: HomeContract.Presenter) { mPresetner = presenter } override fun getLayoutId(): Int { return R.layout.fragment_home } override fun initView() { home_pager.adapter = HomePageAdapter(activity.supportFragmentManager) home_tab.setupWithViewPager(home_pager) home_tab.getTabAt(0)!!.text = "社区" val linearLayoutManager : LinearLayoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false) category.layoutManager = linearLayoutManager category.adapter = mAdapter } override fun initData() { if(!TokenStore.shouldLogin(context)){ mPresetner!!.updateDevice(TokenStore.getAccessToken(context)) } } override fun updateCategory(type: Int, categories: List<Category>) { mCurrentType = type mAdapter.updateCategoies(categories) } override fun justUpdateSelf() { mAdapter.notifyDataSetChanged() } override fun homeClicked() { val tabPositon = home_pager.currentItem when(tabPositon){ 0->{ topicPresenter!!.goTop() } } } fun getCurrentCategoryId(): Int{ return topicPresenter!!.getCurrentNodeId() } companion object Factory{ fun getInstance(bundle :Bundle?) : HomeFragment{ var hf = HomeFragment() if(bundle != null){ hf.arguments = bundle } return hf } } inner class HomePageAdapter(fm : FragmentManager) : FragmentPagerAdapter(fm){ init { topicFragment = TopicFragment.getInstance(null) topicPresenter = TopicPresenter(topicFragment!!,this@HomeFragment) } override fun getItem(position: Int): Fragment { when(position){ 0-> return topicFragment as Fragment } return TopicFragment.getInstance(null) } override fun getCount(): Int { return 1 } } inner class CategoryAdapter : RecyclerView.Adapter<CategoryItemHolder>(){ val mCategories: MutableList<Category> = mutableListOf() fun updateCategoies(categoies : List<Category>){ mCategories.clear() mCategories.addAll(categoies) notifyDataSetChanged() } override fun getItemCount(): Int { return mCategories.size } override fun onBindViewHolder(holder: CategoryItemHolder?, position: Int) { var category = mCategories[position] holder!!.bind(mCurrentType,category) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CategoryItemHolder { val inflater : LayoutInflater = LayoutInflater.from(context) val binding = ListitemTopicNodeItemBinding.inflate(inflater,parent,false) return CategoryItemHolder(binding) } } inner class CategoryItemHolder(val binding : ListitemTopicNodeItemBinding):RecyclerView.ViewHolder(binding.root){ fun bind(type:Int,category:Category){ if(type == Category.TYPE_TOPIC){ val node : Node = category.data as Node binding.setVariable(BR.node,node) binding.executePendingBindings() if(node.id == getCurrentCategoryId()){ binding.nodeText.background = resources.getDrawable(R.drawable.topic_node_bg_select) binding.nodeText.setTextColor(resources.getColor(R.color.colorPrimary)) }else{ binding.nodeText.background = resources.getDrawable(R.drawable.topic_node_bg_normal) binding.nodeText.setTextColor(Color.WHITE) } binding.root.setOnClickListener { var p : Int = adapterPosition topic_fresh_layout.isRefreshing = true topicPresenter!!.setCurrentNode(node.id,p) } } } } }
apache-2.0
8616e7f6fb0a1762ebe54de02decfd2f
33.646739
121
0.669125
4.74256
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/services/exc/mappers/JsonMappingExceptionMapperIT.kt
2
1259
package com.github.kerubistan.kerub.services.exc.mappers import com.github.kerubistan.kerub.testRestBaseUrl import org.apache.http.HttpStatus import org.apache.http.client.methods.HttpPost import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClientBuilder import org.hamcrest.CoreMatchers import org.junit.Assert import org.junit.Test import javax.ws.rs.core.MediaType class JsonMappingExceptionMapperIT { @Test fun brokenJsonFormat() { val client = HttpClientBuilder.create().build() val post = HttpPost("$testRestBaseUrl/auth/login") post.setHeader("Content-Type", MediaType.APPLICATION_JSON) post.entity = StringEntity("{username:'',password:''}") val response = client.execute(post) Assert.assertThat(response.statusLine.statusCode, CoreMatchers.`is`(HttpStatus.SC_NOT_ACCEPTABLE)) } @Test fun brokenJsonMapping() { val client = HttpClientBuilder.create().build() val post = HttpPost("$testRestBaseUrl/auth/login") post.setHeader("Content-Type", MediaType.APPLICATION_JSON) post.entity = StringEntity( """{"username__":"foo","password__":"bar"}""") val response = client.execute(post) Assert.assertThat(response.statusLine.statusCode, CoreMatchers.`is`(HttpStatus.SC_NOT_ACCEPTABLE)) } }
apache-2.0
87ae4c29ba93f46c3368024e4a6ebe0d
34
100
0.772836
3.649275
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt
1
33831
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil import com.intellij.codeInspection.* import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection import com.intellij.codeInspection.ex.EntryPointsManager import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.codeInspection.ex.EntryPointsManagerImpl import com.intellij.openapi.application.invokeLater import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.PsiSearchHelper.SearchCostResult import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.DefinitionsScopedSearch import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.safeDelete.SafeDeleteHandler import com.intellij.util.Processor import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.psi.isConstructorDeclaredProperty import org.jetbrains.kotlin.idea.base.psi.mustHaveNonEmptyPrimaryConstructor import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFindUsagesHandlerFactory; import org.jetbrains.kotlin.idea.base.searching.usages.handlers.KotlinFindClassUsagesHandler import org.jetbrains.kotlin.idea.intentions.isFinalizeMethod import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction import org.jetbrains.kotlin.idea.isMainFunction import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.search.findScriptsWithUsages import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators import org.jetbrains.kotlin.idea.search.usagesSearch.getClassNameForCompanionObject import org.jetbrains.kotlin.idea.util.hasActualsFor import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi import org.jetbrains.kotlin.resolve.isInlineClass import org.jetbrains.kotlin.resolve.isInlineClassType import org.jetbrains.kotlin.util.findCallableMemberBySignature import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import javax.swing.JComponent import javax.swing.JPanel import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class UnusedSymbolInspection : AbstractKotlinInspection() { companion object { private val javaInspection = UnusedDeclarationInspection() private val KOTLIN_ADDITIONAL_ANNOTATIONS = listOf("kotlin.test.*", "kotlin.js.JsExport") private fun KtDeclaration.hasKotlinAdditionalAnnotation() = this is KtNamedDeclaration && checkAnnotatedUsingPatterns(this, KOTLIN_ADDITIONAL_ANNOTATIONS) fun isEntryPoint(declaration: KtNamedDeclaration): Boolean = isEntryPoint(declaration, lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) }) private fun isEntryPoint(declaration: KtNamedDeclaration, isCheapEnough: Lazy<SearchCostResult>): Boolean { if (declaration.hasKotlinAdditionalAnnotation()) return true if (declaration is KtClass && declaration.declarations.any { it.hasKotlinAdditionalAnnotation() }) return true // Some of the main-function-cases are covered by 'javaInspection.isEntryPoint(lightElement)' call // but not all of them: light method for parameterless main still points to parameterless name // that is not an actual entry point from Java language point of view if (declaration.isMainFunction()) return true val lightElement: PsiElement = when (declaration) { is KtClassOrObject -> declaration.toLightClass() is KtNamedFunction, is KtSecondaryConstructor -> LightClassUtil.getLightClassMethod(declaration as KtFunction) is KtProperty, is KtParameter -> { if (declaration is KtParameter && !declaration.hasValOrVar()) return false // we may handle only annotation parameters so far if (declaration is KtParameter && isAnnotationParameter(declaration)) { val lightAnnotationMethods = LightClassUtil.getLightClassPropertyMethods(declaration).toList() for (javaParameterPsi in lightAnnotationMethods) { if (javaInspection.isEntryPoint(javaParameterPsi)) { return true } } } // can't rely on light element, check annotation ourselves val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase return checkAnnotatedUsingPatterns( declaration, entryPointsManager.additionalAnnotations + entryPointsManager.ADDITIONAL_ANNOTATIONS ) } else -> return false } ?: return false if (isCheapEnough.value == TOO_MANY_OCCURRENCES) return false return javaInspection.isEntryPoint(lightElement) } private fun isAnnotationParameter(parameter: KtParameter): Boolean { val constructor = parameter.ownerFunction as? KtConstructor<*> ?: return false return constructor.containingClassOrObject?.isAnnotation() ?: false } private fun isCheapEnoughToSearchUsages(declaration: KtNamedDeclaration): SearchCostResult { val project = declaration.project val psiSearchHelper = PsiSearchHelper.getInstance(project) if (!findScriptsWithUsages(declaration) { DefaultScriptingSupport.getInstance(project).isLoadedFromCache(it) }) { // Not all script configuration are loaded; behave like it is used return TOO_MANY_OCCURRENCES } val useScope = psiSearchHelper.getUseScope(declaration) if (useScope is GlobalSearchScope) { var zeroOccurrences = true val list = listOf(declaration.name) + declarationAccessorNames(declaration) + listOfNotNull(declaration.getClassNameForCompanionObject()) for (name in list) { if (name == null) continue when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) { ZERO_OCCURRENCES -> { } // go on, check other names FEW_OCCURRENCES -> zeroOccurrences = false TOO_MANY_OCCURRENCES -> return TOO_MANY_OCCURRENCES // searching usages is too expensive; behave like it is used } } if (zeroOccurrences) return ZERO_OCCURRENCES } return FEW_OCCURRENCES } /** * returns list of declaration accessor names e.g. pair of getter/setter for property declaration * * note: could be more than declaration.getAccessorNames() * as declaration.getAccessorNames() relies on LightClasses and therefore some of them could be not available * (as not accessible outside of class) * * e.g.: private setter w/o body is not visible outside of class and could not be used */ private fun declarationAccessorNames(declaration: KtNamedDeclaration): List<String> = when (declaration) { is KtProperty -> listOfPropertyAccessorNames(declaration) is KtParameter -> listOfParameterAccessorNames(declaration) else -> emptyList() } private fun listOfParameterAccessorNames(parameter: KtParameter): List<String> { val accessors = mutableListOf<String>() if (parameter.hasValOrVar()) { parameter.name?.let { accessors.add(JvmAbi.getterName(it)) if (parameter.isVarArg) accessors.add(JvmAbi.setterName(it)) } } return accessors } private fun listOfPropertyAccessorNames(property: KtProperty): List<String> { val accessors = mutableListOf<String>() val propertyName = property.name ?: return accessors accessors.add(property.getter?.let { getCustomAccessorName(it) } ?: JvmAbi.getterName(propertyName)) if (property.isVar) accessors.add(property.setter?.let { getCustomAccessorName(it) } ?: JvmAbi.setterName(propertyName)) return accessors } /* If the property has 'JvmName' annotation at accessor it should be used instead */ private fun getCustomAccessorName(method: KtPropertyAccessor?): String? { val customJvmNameAnnotation = method?.annotationEntries?.firstOrNull { it.shortName?.asString() == "JvmName" } ?: return null return customJvmNameAnnotation.findDescendantOfType<KtStringTemplateEntry>()?.text } private fun KtProperty.isSerializationImplicitlyUsedField(): Boolean { val ownerObject = getNonStrictParentOfType<KtClassOrObject>() if (ownerObject is KtObjectDeclaration && ownerObject.isCompanion()) { val lightClass = ownerObject.getNonStrictParentOfType<KtClass>()?.toLightClass() ?: return false return lightClass.fields.any { it.name == name && HighlightUtil.isSerializationImplicitlyUsedField(it) } } return false } private fun KtNamedFunction.isSerializationImplicitlyUsedMethod(): Boolean = toLightMethods().any { JavaHighlightUtil.isSerializationRelatedMethod(it, it.containingClass) } // variation of IDEA's AnnotationUtil.checkAnnotatedUsingPatterns() fun checkAnnotatedUsingPatterns( declaration: KtNamedDeclaration, annotationPatterns: Collection<String> ): Boolean { if (declaration.annotationEntries.isEmpty()) return false val context = declaration.analyze() val annotationsPresent = declaration.annotationEntries.mapNotNull { context[BindingContext.ANNOTATION, it]?.fqName?.asString() } if (annotationsPresent.isEmpty()) return false for (pattern in annotationPatterns) { val hasAnnotation = if (pattern.endsWith(".*")) { annotationsPresent.any { it.startsWith(pattern.dropLast(1)) } } else { pattern in annotationsPresent } if (hasAnnotation) return true } return false } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return namedDeclarationVisitor(fun(declaration) { ProgressManager.checkCanceled() val message = declaration.describe()?.let { KotlinIdeaCompletionBundle.message("inspection.message.never.used", it) } ?: return if (!RootKindFilter.projectSources.matches(declaration)) return // Simple PSI-based checks if (declaration is KtObjectDeclaration && declaration.isCompanion()) return // never mark companion object as unused (there are too many reasons it can be needed for) if (declaration is KtSecondaryConstructor && declaration.containingClass()?.isEnum() == true) return if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return if (declaration is KtProperty && declaration.isLocal) return if (declaration is KtParameter && (declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar()) ) return // More expensive, resolve-based checks val descriptor = declaration.resolveToDescriptorIfAny() ?: return if (declaration.languageVersionSettings.explicitApiEnabled && (descriptor as? DeclarationDescriptorWithVisibility)?.isEffectivelyPublicApi == true) { return } if (descriptor is FunctionDescriptor && descriptor.isOperator) return val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) } if (isEntryPoint(declaration, isCheapEnough)) return if (declaration.isFinalizeMethod(descriptor)) return if (declaration is KtProperty && declaration.isSerializationImplicitlyUsedField()) return if (declaration is KtNamedFunction && declaration.isSerializationImplicitlyUsedMethod()) return // properties can be referred by component1/component2, which is too expensive to search, don't mark them as unused if (declaration.isConstructorDeclaredProperty() && declaration.containingClass()?.mustHaveNonEmptyPrimaryConstructor() == true ) return // experimental annotations if (descriptor is ClassDescriptor && descriptor.kind == ClassKind.ANNOTATION_CLASS) { val fqName = descriptor.fqNameSafe.asString() val languageVersionSettings = declaration.languageVersionSettings if (fqName in languageVersionSettings.getFlag(AnalysisFlags.optIn)) return } // Main checks: finding reference usages && text usages if (hasNonTrivialUsages(declaration, isCheapEnough, descriptor)) return if (declaration is KtClassOrObject && classOrObjectHasTextUsages(declaration)) return val psiElement = declaration.nameIdentifier ?: (declaration as? KtConstructor<*>)?.getConstructorKeyword() ?: return val problemDescriptor = holder.manager.createProblemDescriptor( psiElement, null, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, *createQuickFixes(declaration).toTypedArray() ) holder.registerProblem(problemDescriptor) }) } private fun classOrObjectHasTextUsages(classOrObject: KtClassOrObject): Boolean { var hasTextUsages = false // Finding text usages if (classOrObject.useScope is GlobalSearchScope) { val findClassUsagesHandler = KotlinFindClassUsagesHandler(classOrObject, KotlinFindUsagesHandlerFactory(classOrObject.project)) findClassUsagesHandler.processUsagesInText( classOrObject, { hasTextUsages = true; false }, GlobalSearchScope.projectScope(classOrObject.project) ) } return hasTextUsages } private fun hasNonTrivialUsages(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor? = null): Boolean { val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) } return hasNonTrivialUsages(declaration, isCheapEnough, descriptor) } private fun hasNonTrivialUsages( declaration: KtNamedDeclaration, enoughToSearchUsages: Lazy<SearchCostResult>, descriptor: DeclarationDescriptor? = null ): Boolean { val project = declaration.project val psiSearchHelper = PsiSearchHelper.getInstance(project) val useScope = psiSearchHelper.getUseScope(declaration) val restrictedScope = if (useScope is GlobalSearchScope) { val zeroOccurrences = when (enoughToSearchUsages.value) { ZERO_OCCURRENCES -> true FEW_OCCURRENCES -> false TOO_MANY_OCCURRENCES -> return true // searching usages is too expensive; behave like it is used } if (zeroOccurrences && !declaration.hasActualModifier()) { if (declaration is KtObjectDeclaration && declaration.isCompanion()) { // go on: companion object can be used only in containing class } else { return false } } if (declaration.hasActualModifier()) { KotlinSourceFilterScope.projectSources(project.projectScope(), project) } else { KotlinSourceFilterScope.projectSources(useScope, project) } } else useScope if (declaration is KtTypeParameter) { val containingClass = declaration.containingClass() if (containingClass != null) { val isOpenClass = containingClass.isInterface() || containingClass.hasModifier(KtTokens.ABSTRACT_KEYWORD) || containingClass.hasModifier(KtTokens.SEALED_KEYWORD) || containingClass.hasModifier(KtTokens.OPEN_KEYWORD) if (isOpenClass && hasOverrides(containingClass, restrictedScope)) return true val containingClassSearchScope = GlobalSearchScope.projectScope(project) val isRequiredToCallFunction = ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, containingClassSearchScope)).any { ref -> val userType = ref.element.parent as? KtUserType ?: return@any false val typeArguments = userType.typeArguments if (typeArguments.isEmpty()) return@any false val parameter = userType.getStrictParentOfType<KtParameter>() ?: return@any false val callableDeclaration = parameter.getStrictParentOfType<KtCallableDeclaration>()?.let { if (it !is KtNamedFunction) it.containingClass() else it } ?: return@any false val typeParameters = callableDeclaration.typeParameters.map { it.name } if (typeParameters.isEmpty()) return@any false if (typeArguments.none { it.text in typeParameters }) return@any false ReferencesSearch.search(KotlinReferencesSearchParameters(callableDeclaration, containingClassSearchScope)).any { val callElement = it.element.parent as? KtCallElement callElement != null && callElement.typeArgumentList == null } } if (isRequiredToCallFunction) return true } } return (declaration is KtObjectDeclaration && declaration.isCompanion() && declaration.body?.declarations?.isNotEmpty() == true) || hasReferences(declaration, descriptor, restrictedScope) || hasOverrides(declaration, restrictedScope) || hasFakeOverrides(declaration, restrictedScope) || hasPlatformImplementations(declaration, descriptor) } private fun checkDeclaration(declaration: KtNamedDeclaration, importedDeclaration: KtNamedDeclaration): Boolean = declaration !in importedDeclaration.parentsWithSelf && !hasNonTrivialUsages(importedDeclaration) private val KtNamedDeclaration.isObjectOrEnum: Boolean get() = this is KtObjectDeclaration || this is KtClass && isEnum() private fun checkReference(ref: PsiReference, declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { ProgressManager.checkCanceled() if (declaration.isAncestor(ref.element)) return true // usages inside element's declaration are not counted if (ref.element.parent is KtValueArgumentName) return true // usage of parameter in form of named argument is not counted val import = ref.element.getParentOfType<KtImportDirective>(false) if (import != null) { if (import.aliasName != null && import.aliasName != declaration.name) { return false } // check if we import member(s) from object / nested object / enum and search for their usages val originalDeclaration = (descriptor as? TypeAliasDescriptor)?.classDescriptor?.findPsi() as? KtNamedDeclaration if (declaration is KtClassOrObject || originalDeclaration is KtClassOrObject) { if (import.isAllUnder) { val importedFrom = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtClassOrObject ?: return true return importedFrom.declarations.none { it is KtNamedDeclaration && hasNonTrivialUsages(it) } } else { if (import.importedFqName != declaration.fqName) { val importedDeclaration = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtNamedDeclaration ?: return true if (declaration.isObjectOrEnum || importedDeclaration.containingClassOrObject is KtObjectDeclaration) return checkDeclaration( declaration, importedDeclaration ) if (originalDeclaration?.isObjectOrEnum == true) return checkDeclaration( originalDeclaration, importedDeclaration ) // check type alias if (importedDeclaration.fqName == declaration.fqName) return true } } } return true } return false } private fun hasReferences( declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?, useScope: SearchScope ): Boolean { fun checkReference(ref: PsiReference): Boolean = checkReference(ref, declaration, descriptor) val searchOptions = KotlinReferencesSearchOptions(acceptCallableOverrides = declaration.hasActualModifier()) val searchParameters = KotlinReferencesSearchParameters( declaration, useScope, kotlinOptions = searchOptions ) val referenceUsed: Boolean by lazy { !ReferencesSearch.search(searchParameters).forEach(Processor { checkReference(it) }) } if (descriptor is FunctionDescriptor && DescriptorUtils.findJvmNameAnnotation(descriptor) != null) { if (referenceUsed) return true } if (declaration is KtSecondaryConstructor) { val containingClass = declaration.containingClass() if (containingClass != null && ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, useScope)).any { it.element.getStrictParentOfType<KtTypeAlias>() != null }) return true } if (declaration is KtCallableDeclaration && declaration.canBeHandledByLightMethods(descriptor)) { val lightMethods = declaration.toLightMethods() if (lightMethods.isNotEmpty()) { val lightMethodsUsed = lightMethods.any { method -> !MethodReferencesSearch.search(method).forEach(Processor { checkReference(it) }) } if (lightMethodsUsed) return true if (!declaration.hasActualModifier()) return false } } if (declaration is KtEnumEntry) { val enumClass = declaration.containingClass()?.takeIf { it.isEnum() } if (hasBuiltInEnumFunctionReference(enumClass, useScope)) return true } return referenceUsed || checkPrivateDeclaration(declaration, descriptor) } private fun hasBuiltInEnumFunctionReference(enumClass: KtClass?, useScope: SearchScope): Boolean { if (enumClass == null) return false return enumClass.anyDescendantOfType(KtExpression::isReferenceToBuiltInEnumFunction) || ReferencesSearch.search(KotlinReferencesSearchParameters(enumClass, useScope)).any(::hasBuiltInEnumFunctionReference) } private fun hasBuiltInEnumFunctionReference(reference: PsiReference): Boolean { val parent = reference.element.getParentOfTypes( true, KtTypeReference::class.java, KtQualifiedExpression::class.java, KtCallableReferenceExpression::class.java ) ?: return false return parent.isReferenceToBuiltInEnumFunction() } private fun checkPrivateDeclaration(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { if (descriptor == null || !declaration.isPrivateNestedClassOrObject) return false val set = hashSetOf<KtSimpleNameExpression>() declaration.containingKtFile.importList?.acceptChildren(simpleNameExpressionRecursiveVisitor { set += it }) return set.mapNotNull { it.referenceExpression() } .filter { descriptor in it.resolveMainReferenceToDescriptors() } .any { !checkReference(it.mainReference, declaration, descriptor) } } private fun KtCallableDeclaration.canBeHandledByLightMethods(descriptor: DeclarationDescriptor?): Boolean { return when { descriptor is ConstructorDescriptor -> { val classDescriptor = descriptor.constructedClass !classDescriptor.isInlineClass() && classDescriptor.visibility != DescriptorVisibilities.LOCAL } hasModifier(KtTokens.INTERNAL_KEYWORD) -> false descriptor !is FunctionDescriptor -> true else -> !descriptor.hasInlineClassParameters() } } private fun FunctionDescriptor.hasInlineClassParameters(): Boolean { return when { dispatchReceiverParameter?.type?.isInlineClassType() == true -> true extensionReceiverParameter?.type?.isInlineClassType() == true -> true else -> valueParameters.any { it.type.isInlineClassType() } } } private fun hasOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean = DefinitionsScopedSearch.search(declaration, useScope).findFirst() != null private fun hasFakeOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean { val ownerClass = declaration.containingClassOrObject as? KtClass ?: return false if (!ownerClass.isInheritable()) return false val descriptor = declaration.toDescriptor() as? CallableMemberDescriptor ?: return false if (descriptor.modality == Modality.ABSTRACT) return false val lightMethods = declaration.toLightMethods() return DefinitionsScopedSearch.search(ownerClass, useScope).any { element: PsiElement -> when (element) { is KtLightClass -> { val memberBySignature = (element.kotlinOrigin?.toDescriptor() as? ClassDescriptor)?.findCallableMemberBySignature(descriptor) memberBySignature != null && !memberBySignature.kind.isReal && memberBySignature.overriddenDescriptors.any { it != descriptor } } is PsiClass -> lightMethods.any { lightMethod -> val sameMethods = element.findMethodsBySignature(lightMethod, true) sameMethods.all { it.containingClass != element } && sameMethods.any { it.containingClass != lightMethod.containingClass } } else -> false } } } private fun hasPlatformImplementations(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean { if (!declaration.hasExpectModifier()) return false if (descriptor !is MemberDescriptor) return false val commonModuleDescriptor = declaration.containingKtFile.findModuleDescriptor() // TODO: Check if 'allImplementingDescriptors' should be used instead! return commonModuleDescriptor.implementingDescriptors.any { it.hasActualsFor(descriptor) } || commonModuleDescriptor.hasActualsFor(descriptor) } override fun createOptionsPanel(): JComponent = JPanel(GridBagLayout()).apply { add( EntryPointsManagerImpl.createConfigureAnnotationsButton(), GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0) ) } private fun createQuickFixes(declaration: KtNamedDeclaration): List<LocalQuickFix> { val list = ArrayList<LocalQuickFix>() list.add(SafeDeleteFix(declaration)) for (annotationEntry in declaration.annotationEntries) { val resolvedName = annotationEntry.resolveToDescriptorIfAny() ?: continue val fqName = resolvedName.fqName?.asString() ?: continue // checks taken from com.intellij.codeInspection.util.SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes if (fqName.startsWith("kotlin.") || fqName.startsWith("java.") || fqName.startsWith("javax.") || fqName.startsWith("org.jetbrains.annotations.") ) continue val intentionAction = createAddToDependencyInjectionAnnotationsFix(declaration.project, fqName) list.add(IntentionWrapper(intentionAction)) } return list } } class SafeDeleteFix(declaration: KtDeclaration) : LocalQuickFix { @Nls private val name: String = if (declaration is KtConstructor<*>) KotlinBundle.message("safe.delete.constructor") else QuickFixBundle.message("safe.delete.text", declaration.name) override fun getName() = name override fun getFamilyName() = QuickFixBundle.message("safe.delete.family") override fun startInWriteAction(): Boolean = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val declaration = descriptor.psiElement.getStrictParentOfType<KtDeclaration>() ?: return if (!FileModificationService.getInstance().prepareFileForWrite(declaration.containingFile)) return if (declaration is KtParameter && declaration.parent is KtParameterList && declaration.parent?.parent is KtFunction) { RemoveUnusedFunctionParameterFix(declaration).invoke(project, declaration.findExistingEditor(), declaration.containingKtFile) } else { val declarationPointer = declaration.createSmartPointer() invokeLater { declarationPointer.element?.let { safeDelete(project, it) } } } } } private fun safeDelete(project: Project, declaration: PsiElement) { SafeDeleteHandler.invoke(project, arrayOf(declaration), false) }
apache-2.0
a4b469409c8946750439e6940650f937
50.493151
178
0.674529
6.059645
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt
1
31003
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.configurationStore.SerializableScheme import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginManagerConfigurable import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.keymap.ex.KeymapManagerEx import com.intellij.openapi.options.ExternalizableSchemeAdapter import com.intellij.openapi.options.SchemeState import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.ui.KeyStrokeAdapter import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.mapSmart import com.intellij.util.containers.nullize import org.jdom.Element import java.util.* import java.util.concurrent.ConcurrentHashMap import javax.swing.KeyStroke import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty private const val KEY_MAP = "keymap" private const val KEYBOARD_SHORTCUT = "keyboard-shortcut" private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut" private const val KEYBOARD_GESTURE_KEY = "keystroke" private const val KEYBOARD_GESTURE_MODIFIER = "modifier" private const val KEYSTROKE_ATTRIBUTE = "keystroke" private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke" private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke" private const val ACTION = "action" private const val VERSION_ATTRIBUTE = "version" private const val PARENT_ATTRIBUTE = "parent" private const val NAME_ATTRIBUTE = "name" private const val ID_ATTRIBUTE = "id" private const val MOUSE_SHORTCUT = "mouse-shortcut" fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl { val result = KeymapImpl(dataHolder) result.name = name result.schemeState = SchemeState.UNCHANGED return result } open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null) : ExternalizableSchemeAdapter(), Keymap, SerializableScheme { @Volatile private var parent: KeymapImpl? = null private var unknownParentName: String? = null open var canModify: Boolean = true @JvmField internal var schemeState: SchemeState? = null override fun getSchemeState(): SchemeState? = schemeState private val actionIdToShortcuts = ConcurrentHashMap<String, List<Shortcut>>() get() { val dataHolder = dataHolder if (dataHolder != null) { this.dataHolder = null readExternal(dataHolder.read()) } return field } private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! } /** * @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap. */ val ownActionIds: Array<String> get() = actionIdToShortcuts.keys.toTypedArray() private fun <T> cachedShortcuts(mapper: (Shortcut) -> T?): ReadWriteProperty<Any?, Map<T, MutableList<String>>> = object : ReadWriteProperty<Any?, Map<T, MutableList<String>>> { private var cache: Map<T, MutableList<String>>? = null override fun getValue(thisRef: Any?, property: KProperty<*>): Map<T, MutableList<String>> = cache ?: mapShortcuts(mapper).also { cache = it } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Map<T, MutableList<String>>) { cache = null } private fun mapShortcuts(mapper: (Shortcut) -> T?): Map<T, MutableList<String>> { fun addActionToShortcutMap(actionId: String, map: MutableMap<T, MutableList<String>>) { for (shortcut in getOwnOrBoundShortcuts(actionId)) { mapper(shortcut)?.let { val ids = map.getOrPut(it) { SmartList() } if (!ids.contains(actionId)) { ids.add(actionId) } } } } val map = HashMap<T, MutableList<String>>() actionIdToShortcuts.keys.forEach { addActionToShortcutMap(it, map) } keymapManager.boundActions.forEach { addActionToShortcutMap(it, map) } return map } } // Accesses to these caches are non-synchronized, so must be performed // from EDT only (where all the modifications are currently done) private var keystrokeToActionIds: Map<KeyStroke, MutableList<String>> by cachedShortcuts { (it as? KeyboardShortcut)?.firstKeyStroke } private var mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>> by cachedShortcuts { it as? MouseShortcut } private var gestureToActionIds: Map<KeyboardModifierGestureShortcut, MutableList<String>> by cachedShortcuts { it as? KeyboardModifierGestureShortcut } override fun getPresentableName(): String = name override fun deriveKeymap(newName: String): KeymapImpl = if (canModify()) { val newKeymap = copy() newKeymap.name = newName newKeymap } else { val newKeymap = KeymapImpl() newKeymap.parent = this newKeymap.name = newName newKeymap } fun copy(): KeymapImpl = dataHolder?.let { KeymapImpl(name, it) } ?: copyTo(KeymapImpl()) fun copyTo(otherKeymap: KeymapImpl): KeymapImpl { otherKeymap.cleanShortcutsCache() otherKeymap.actionIdToShortcuts.clear() otherKeymap.actionIdToShortcuts.putAll(actionIdToShortcuts) // after actionIdToShortcuts (on first access we lazily read itself) otherKeymap.parent = parent otherKeymap.name = name otherKeymap.canModify = canModify() return otherKeymap } override fun getParent(): KeymapImpl? = parent final override fun canModify(): Boolean = canModify override fun addShortcut(actionId: String, shortcut: Shortcut) { addShortcut(actionId, shortcut, false) } fun addShortcut(actionId: String, shortcut: Shortcut, fromSettings: Boolean) { val boundShortcuts = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] } actionIdToShortcuts.compute(actionId) { id, list -> var result: List<Shortcut>? = list if (result == null) { result = boundShortcuts ?: parent?.getShortcutList(id)?.map { convertShortcut(it) } ?: emptyList() } if (!result.contains(shortcut)) { result = result + shortcut } if (result.areShortcutsEqualToParent(id)) null else result } cleanShortcutsCache() fireShortcutChanged(actionId, fromSettings) } private fun cleanShortcutsCache() { keystrokeToActionIds = emptyMap() mouseShortcutToActionIds = emptyMap() gestureToActionIds = emptyMap() schemeState = SchemeState.POSSIBLY_CHANGED } override fun removeAllActionShortcuts(actionId: String) { for (shortcut in getShortcuts(actionId)) { removeShortcut(actionId, shortcut) } } override fun removeShortcut(actionId: String, toDelete: Shortcut) { removeShortcut(actionId, toDelete, false) } fun removeShortcut(actionId: String, toDelete: Shortcut, fromSettings: Boolean) { val fromBinding = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] } actionIdToShortcuts.compute(actionId) { id, list -> when { list == null -> { val inherited = fromBinding ?: parent?.getShortcutList(id)?.mapSmart { convertShortcut(it) }.nullize() if (inherited == null || !inherited.contains(toDelete)) null else inherited - toDelete } !list.contains(toDelete) -> list parent == null -> if (list.size == 1) null else ContainerUtil.newUnmodifiableList(list - toDelete) else -> { val result = list - toDelete if (result.areShortcutsEqualToParent(id)) null else ContainerUtil.newUnmodifiableList(result) } } } cleanShortcutsCache() fireShortcutChanged(actionId, fromSettings) } private fun List<Shortcut>.areShortcutsEqualToParent(actionId: String) = parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getShortcutList(actionId).mapSmart { convertShortcut(it) }) } private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> { actionIdToShortcuts[actionId]?.let { return it } val result = SmartList<Shortcut>() keymapManager.getActionBinding(actionId)?.let { result.addAll(getOwnOrBoundShortcuts(it)) } return result } private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> { // first, get keystrokes from our own map val list = SmartList<String>() for ((key, value) in gestureToActionIds) { if (shortcut.startsWith(key)) { list.addAll(value) } } if (parent != null) { val ids = parent!!.getActionIds(shortcut) if (ids.isNotEmpty()) { for (id in ids) { // add actions from the parent keymap only if they are absent in this keymap if (!actionIdToShortcuts.containsKey(id)) { list.add(id) } } } } sortInRegistrationOrder(list) return list } override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> { return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToActionIds }, KeymapImpl::convertKeyStroke)) } override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> { val ids = getActionIds(firstKeyStroke) var actualBindings: MutableList<String>? = null for (id in ids) { val shortcuts = getShortcuts(id) for (shortcut in shortcuts) { if (shortcut !is KeyboardShortcut) { continue } if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) { if (actualBindings == null) { actualBindings = SmartList() } actualBindings.add(id) break } } } return ArrayUtilRt.toStringArray(actualBindings) } override fun getActionIds(shortcut: Shortcut): Array<String> { return when (shortcut) { is KeyboardShortcut -> { val first = shortcut.firstKeyStroke val second = shortcut.secondKeyStroke if (second == null) getActionIds(first) else getActionIds(first, second) } is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut)) is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut)) else -> ArrayUtilRt.EMPTY_STRING_ARRAY } } override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean { var convertedShortcut = shortcut var keymap = this do { val list = keymap.mouseShortcutToActionIds[convertedShortcut] if (list != null && list.contains(actionId)) { return true } val parent = keymap.parent ?: return false convertedShortcut = keymap.convertMouseShortcut(shortcut) keymap = parent } while (true) } override fun getActionIds(shortcut: MouseShortcut): List<String> { return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut) } @RequiresEdt private fun <T> getActionIds(shortcut: T, shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>, convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> { // first, get keystrokes from our own map var list = shortcutToActionIds(this)[shortcut] val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList() var isOriginalListInstance = list != null for (id in parentIds) { // add actions from the parent keymap only if they are absent in this keymap // do not add parent bind actions, if bind-on action is overwritten in the child if (actionIdToShortcuts.containsKey(id)) continue val key = keymapManager.getActionBinding(id) if (key != null && actionIdToShortcuts.containsKey(key)) continue if (list == null) { list = SmartList() } else if (isOriginalListInstance) { list = SmartList(list) isOriginalListInstance = false } if (!list.contains(id)) { list.add(id) } } sortInRegistrationOrder(list ?: return emptyList()) return list } fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId) override fun getShortcuts(actionId: String?): Array<Shortcut> = getShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() } private fun getShortcutList(actionId: String?): List<Shortcut> { if (actionId == null) { return emptyList() } // it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts // todo why not convert on add? why we don't need to convert our own shortcuts? return actionIdToShortcuts[actionId] ?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] } ?: parent?.getShortcutList(actionId)?.mapSmart { convertShortcut(it) } ?: emptyList() } fun getOwnShortcuts(actionId: String): Array<Shortcut> { val own = actionIdToShortcuts[actionId] ?: return Shortcut.EMPTY_ARRAY return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray() } fun hasShortcutDefined(actionId: String): Boolean = actionIdToShortcuts[actionId] != null || parent?.hasShortcutDefined(actionId) == true // you must clear `actionIdToShortcuts` before calling protected open fun readExternal(keymapElement: Element) { if (KEY_MAP != keymapElement.name) { throw InvalidDataException("unknown element: $keymapElement") } name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)!! unknownParentName = null keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName -> var parentScheme = findParentScheme(parentSchemeName) if (parentScheme == null && parentSchemeName == "Default for Mac OS X") { // https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197 parentScheme = findParentScheme("Mac OS X") } if (parentScheme == null) { logger<KeymapImpl>().warn("Cannot find parent scheme $parentSchemeName for scheme $name") unknownParentName = parentSchemeName notifyAboutMissingKeymap(parentSchemeName, IdeBundle.message("notification.content.cannot.find.parent.keymap", parentSchemeName, name), true) } else { parent = parentScheme as KeymapImpl canModify = true } } val actionIds = HashSet<String>() val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode) for (actionElement in keymapElement.children) { if (actionElement.name != ACTION) { throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name") } val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name") actionIds.add(id) val shortcuts = SmartList<Shortcut>() for (shortcutElement in actionElement.children) { if (KEYBOARD_SHORTCUT == shortcutElement.name) { // Parse first keystroke val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE) ?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name") if (skipInserts && firstKeyStrokeStr.contains("INSERT")) { continue } val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue // Parse second keystroke var secondKeyStroke: KeyStroke? = null val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE) if (secondKeyStrokeStr != null) { secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue } shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke)) } else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) { val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException( "Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name") val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER) var modifier: KeyboardGestureAction.ModifierType? = null if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) { modifier = KeyboardGestureAction.ModifierType.dblClick } else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) { modifier = KeyboardGestureAction.ModifierType.hold } if (modifier == null) { throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name") } shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke)) } else if (MOUSE_SHORTCUT == shortcutElement.name) { val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name") try { shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString)) } catch (e: InvalidDataException) { throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name") } } else { throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name") } } // creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts) actionIdToShortcuts[id] = Collections.unmodifiableList(shortcuts) } ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds) cleanShortcutsCache() } protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName) override fun writeScheme(): Element { dataHolder?.let { return it.read() } val keymapElement = Element(KEY_MAP) keymapElement.setAttribute(VERSION_ATTRIBUTE, "1") keymapElement.setAttribute(NAME_ATTRIBUTE, name) (parent?.name ?: unknownParentName)?.let { keymapElement.setAttribute(PARENT_ATTRIBUTE, it) } writeOwnActionIds(keymapElement) schemeState = SchemeState.UNCHANGED return keymapElement } private fun writeOwnActionIds(keymapElement: Element) { val ownActionIds = ownActionIds Arrays.sort(ownActionIds) for (actionId in ownActionIds) { val shortcuts = actionIdToShortcuts[actionId] ?: continue val actionElement = Element(ACTION) actionElement.setAttribute(ID_ATTRIBUTE, actionId) for (shortcut in shortcuts) { when (shortcut) { is KeyboardShortcut -> { val element = Element(KEYBOARD_SHORTCUT) element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke)) shortcut.secondKeyStroke?.let { element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it)) } actionElement.addContent(element) } is MouseShortcut -> { val element = Element(MOUSE_SHORTCUT) element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut)) actionElement.addContent(element) } is KeyboardModifierGestureShortcut -> { val element = Element(KEYBOARD_GESTURE_SHORTCUT) element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke)) element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name) actionElement.addContent(element) } else -> throw IllegalStateException("unknown shortcut class: $shortcut") } } keymapElement.addContent(actionElement) } } fun clearOwnActionsIds() { actionIdToShortcuts.clear() cleanShortcutsCache() } fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId) fun clearOwnActionsId(actionId: String) { actionIdToShortcuts.remove(actionId) cleanShortcutsCache() } override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList) override fun getActionIdList(): Set<String> { val ids = LinkedHashSet<String>() ids.addAll(actionIdToShortcuts.keys) var parent = parent while (parent != null) { ids.addAll(parent.actionIdToShortcuts.keys) parent = parent.parent } return ids } override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> { val result = HashMap<String, MutableList<KeyboardShortcut>>() for (id in getActionIds(keyboardShortcut.firstKeyStroke)) { if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) { continue } val useShortcutOf = keymapManager.getActionBinding(id) if (useShortcutOf != null && useShortcutOf == actionId) { continue } for (shortcut1 in getShortcutList(id)) { if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) { continue } if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) { continue } result.getOrPut(id) { SmartList() }.add(shortcut1) } } return result } protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut private fun fireShortcutChanged(actionId: String, fromSettings: Boolean) { ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).shortcutChanged(this, actionId, fromSettings) } override fun toString(): String = presentableName override fun equals(other: Any?): Boolean { if (other !is KeymapImpl) return false if (other === this) return true if (name != other.name) return false if (canModify != other.canModify) return false if (parent != other.parent) return false if (actionIdToShortcuts != other.actionIdToShortcuts) return false return true } override fun hashCode(): Int = name.hashCode() } private fun sortInRegistrationOrder(ids: MutableList<String>) { ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator) } // compare two lists in any order private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean { if (shortcuts1.size != shortcuts2.size) { return false } for (shortcut in shortcuts1) { if (!shortcuts2.contains(shortcut)) { return false } } return true } @Suppress("SpellCheckingInspection") private const val macOSKeymap = "com.intellij.plugins.macoskeymap" @Suppress("SpellCheckingInspection") private const val gnomeKeymap = "com.intellij.plugins.gnomekeymap" @Suppress("SpellCheckingInspection") private const val kdeKeymap = "com.intellij.plugins.kdekeymap" @Suppress("SpellCheckingInspection") private const val xwinKeymap = "com.intellij.plugins.xwinkeymap" @Suppress("SpellCheckingInspection") private const val eclipseKeymap = "com.intellij.plugins.eclipsekeymap" @Suppress("SpellCheckingInspection") private const val emacsKeymap = "com.intellij.plugins.emacskeymap" @Suppress("SpellCheckingInspection") private const val netbeansKeymap = "com.intellij.plugins.netbeanskeymap" @Suppress("SpellCheckingInspection") private const val qtcreatorKeymap = "com.intellij.plugins.qtcreatorkeymap" @Suppress("SpellCheckingInspection") private const val resharperKeymap = "com.intellij.plugins.resharperkeymap" @Suppress("SpellCheckingInspection") private const val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap" @Suppress("SpellCheckingInspection") private const val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap" private const val visualStudio2022Keymap = "com.intellij.plugins.visualstudio2022keymap" @Suppress("SpellCheckingInspection") private const val xcodeKeymap = "com.intellij.plugins.xcodekeymap" @Suppress("SpellCheckingInspection") private const val visualAssistKeymap = "com.intellij.plugins.visualassistkeymap" @Suppress("SpellCheckingInspection") private const val riderKeymap = "com.intellij.plugins.riderkeymap" @Suppress("SpellCheckingInspection") private const val vsCodeKeymap = "com.intellij.plugins.vscodekeymap" @Suppress("SpellCheckingInspection") private const val vsForMacKeymap = "com.intellij.plugins.vsformackeymap" internal fun notifyAboutMissingKeymap(keymapName: String, @NlsContexts.NotificationContent message: String, isParent: Boolean) { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(project: Project) { connection.disconnect() ApplicationManager.getApplication().invokeLater( { // TODO remove when PluginAdvertiser implements that val pluginId = when (keymapName) { "Mac OS X", "Mac OS X 10.5+" -> macOSKeymap "Default for GNOME" -> gnomeKeymap "Default for KDE" -> kdeKeymap "Default for XWin" -> xwinKeymap "Eclipse", "Eclipse (Mac OS X)" -> eclipseKeymap "Emacs" -> emacsKeymap "NetBeans 6.5" -> netbeansKeymap "QtCreator", "QtCreator OSX" -> qtcreatorKeymap "ReSharper", "ReSharper OSX" -> resharperKeymap "Sublime Text", "Sublime Text (Mac OS X)" -> sublimeKeymap "Visual Studio", "Visual Studio OSX" -> visualStudioKeymap "Visual Studio 2022" -> visualStudio2022Keymap "Visual Assist", "Visual Assist OSX" -> visualAssistKeymap "Xcode" -> xcodeKeymap "Visual Studio for Mac" -> vsForMacKeymap "Rider", "Rider OSX"-> riderKeymap "VSCode", "VSCode OSX"-> vsCodeKeymap else -> null } val action: AnAction = when (pluginId) { null -> object : NotificationAction(IdeBundle.message("action.text.search.for.keymap", keymapName)) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { //TODO enableSearch("$keymapName /tag:Keymap")?.run() ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java) } } else -> object : NotificationAction(IdeBundle.message("action.text.install.keymap", keymapName)) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { val connect = ApplicationManager.getApplication().messageBus.connect() connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener { override fun keymapAdded(keymap: Keymap) { ApplicationManager.getApplication().invokeLater { if (keymap.name == keymapName) { connect.disconnect() val successMessage = if (isParent) IdeBundle.message("notification.content.keymap.successfully.installed", keymapName) else { KeymapManagerEx.getInstanceEx().activeKeymap = keymap IdeBundle.message("notification.content.keymap.successfully.activated", keymapName) } Notification("KeymapInstalled", successMessage, NotificationType.INFORMATION).notify(e.project) } } } }) val plugins = mutableSetOf(PluginId.getId(pluginId)) when (pluginId) { gnomeKeymap, kdeKeymap -> plugins += PluginId.getId(xwinKeymap) resharperKeymap -> plugins += PluginId.getId(visualStudioKeymap) visualAssistKeymap -> plugins += PluginId.getId(visualStudioKeymap) visualStudio2022Keymap -> plugins += PluginId.getId(visualStudioKeymap) xcodeKeymap, vsForMacKeymap -> plugins += PluginId.getId(macOSKeymap) } installAndEnable(project, plugins) { } notification.expire() } } } Notification("KeymapMissing", IdeBundle.message("notification.group.missing.keymap"), message, NotificationType.ERROR) .addAction(action) .notify(project) }, ModalityState.NON_MODAL) } }) }
apache-2.0
eaad3821deabd4ab6f9f72f90ad29da2
40.670699
158
0.690836
5.237878
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeViewAccessibilityDelegateCompat.android.kt
3
126484
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.accessibilityservice.AccessibilityServiceInfo import android.content.Context import android.graphics.RectF import android.graphics.Region import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log import android.view.MotionEvent import android.view.View import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener import android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener import android.view.accessibility.AccessibilityNodeInfo import android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH import android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX import android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY import android.view.accessibility.AccessibilityNodeProvider import androidx.annotation.DoNotInline import androidx.annotation.IntRange import androidx.annotation.RequiresApi import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.Companion.PRIVATE import androidx.collection.ArraySet import androidx.collection.SparseArrayCompat import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.R import androidx.compose.ui.fastJoinToString import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.toAndroidRect import androidx.compose.ui.graphics.toComposeRect import androidx.compose.ui.layout.boundsInParent import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.node.HitTestResult import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.node.OwnerScope import androidx.compose.ui.node.SemanticsModifierNode import androidx.compose.ui.node.collapsedSemanticsConfiguration import androidx.compose.ui.node.requireLayoutNode import androidx.compose.ui.platform.accessibility.hasCollectionInfo import androidx.compose.ui.platform.accessibility.setCollectionInfo import androidx.compose.ui.platform.accessibility.setCollectionItemInfo import androidx.compose.ui.semantics.AccessibilityAction import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.ProgressBarRangeInfo import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.ScrollAxisRange import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsActions.CustomActions import androidx.compose.ui.semantics.SemanticsConfiguration import androidx.compose.ui.semantics.SemanticsNode import androidx.compose.ui.semantics.SemanticsOwner import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.semantics.SemanticsPropertiesAndroid import androidx.compose.ui.semantics.getOrNull import androidx.compose.ui.semantics.outerSemantics import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.InternalTextApi import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.platform.toAccessibilitySpannableString import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.toSize import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastForEachIndexed import androidx.core.view.AccessibilityDelegateCompat import androidx.core.view.ViewCompat import androidx.core.view.ViewCompat.ACCESSIBILITY_LIVE_REGION_ASSERTIVE import androidx.core.view.ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE import androidx.core.view.accessibility.AccessibilityEventCompat import androidx.core.view.accessibility.AccessibilityNodeInfoCompat import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat import androidx.core.view.accessibility.AccessibilityNodeProviderCompat import androidx.lifecycle.Lifecycle import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt import kotlin.math.sign private fun LayoutNode.findClosestParentNode(selector: (LayoutNode) -> Boolean): LayoutNode? { var currentParent = this.parent while (currentParent != null) { if (selector(currentParent)) { return currentParent } else { currentParent = currentParent.parent } } return null } internal class AndroidComposeViewAccessibilityDelegateCompat(val view: AndroidComposeView) : AccessibilityDelegateCompat() { companion object { /** Virtual node identifier value for invalid nodes. */ const val InvalidId = Integer.MIN_VALUE const val ClassName = "android.view.View" const val LogTag = "AccessibilityDelegate" const val ExtraDataTestTagKey = "androidx.compose.ui.semantics.testTag" /** * Intent size limitations prevent sending over a megabyte of data. Limit * text length to 100K characters - 200KB. */ const val ParcelSafeTextLength = 100000 /** * The undefined cursor position. */ const val AccessibilityCursorPositionUndefined = -1 // 20 is taken from AbsSeekbar.java. const val AccessibilitySliderStepsCount = 20 /** * Delay before dispatching a recurring accessibility event in milliseconds. * This delay guarantees that a recurring event will be send at most once * during the [SendRecurringAccessibilityEventsIntervalMillis] time * frame. */ const val SendRecurringAccessibilityEventsIntervalMillis: Long = 100 /** * Timeout to determine whether a text selection changed event and the pending text * traversed event could be resulted from the same traverse action. */ const val TextTraversedEventTimeoutMillis: Long = 1000 private val AccessibilityActionsResourceIds = intArrayOf( R.id.accessibility_custom_action_0, R.id.accessibility_custom_action_1, R.id.accessibility_custom_action_2, R.id.accessibility_custom_action_3, R.id.accessibility_custom_action_4, R.id.accessibility_custom_action_5, R.id.accessibility_custom_action_6, R.id.accessibility_custom_action_7, R.id.accessibility_custom_action_8, R.id.accessibility_custom_action_9, R.id.accessibility_custom_action_10, R.id.accessibility_custom_action_11, R.id.accessibility_custom_action_12, R.id.accessibility_custom_action_13, R.id.accessibility_custom_action_14, R.id.accessibility_custom_action_15, R.id.accessibility_custom_action_16, R.id.accessibility_custom_action_17, R.id.accessibility_custom_action_18, R.id.accessibility_custom_action_19, R.id.accessibility_custom_action_20, R.id.accessibility_custom_action_21, R.id.accessibility_custom_action_22, R.id.accessibility_custom_action_23, R.id.accessibility_custom_action_24, R.id.accessibility_custom_action_25, R.id.accessibility_custom_action_26, R.id.accessibility_custom_action_27, R.id.accessibility_custom_action_28, R.id.accessibility_custom_action_29, R.id.accessibility_custom_action_30, R.id.accessibility_custom_action_31 ) } /** Virtual view id for the currently hovered logical item. */ internal var hoveredVirtualViewId = InvalidId @VisibleForTesting internal val accessibilityManager: AccessibilityManager = view.context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager internal var accessibilityForceEnabledForTesting = false @VisibleForTesting internal val enabledStateListener: AccessibilityStateChangeListener = AccessibilityStateChangeListener { enabled -> enabledServices = if (enabled) { accessibilityManager.getEnabledAccessibilityServiceList( AccessibilityServiceInfo.FEEDBACK_ALL_MASK ) } else { emptyList() } } @VisibleForTesting internal val touchExplorationStateListener: TouchExplorationStateChangeListener = TouchExplorationStateChangeListener { enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( AccessibilityServiceInfo.FEEDBACK_ALL_MASK ) } private var enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( AccessibilityServiceInfo.FEEDBACK_ALL_MASK ) /** * True if any accessibility service enabled in the system, except the UIAutomator (as it * doesn't appear in the list of enabled services) */ @VisibleForTesting internal val isEnabled: Boolean get() { // checking the list allows us to filter out the UIAutomator which doesn't appear in it return accessibilityForceEnabledForTesting || accessibilityManager.isEnabled && enabledServices.isNotEmpty() } /** * True if accessibility service with the touch exploration (e.g. Talkback) is enabled in the * system. * Note that UIAutomator doesn't request touch exploration therefore returns false */ private val isTouchExplorationEnabled get() = accessibilityForceEnabledForTesting || accessibilityManager.isEnabled && accessibilityManager.isTouchExplorationEnabled private val handler = Handler(Looper.getMainLooper()) private var nodeProvider: AccessibilityNodeProviderCompat = AccessibilityNodeProviderCompat(MyNodeProvider()) private var focusedVirtualViewId = InvalidId // For actionIdToId and labelToActionId, the keys are the virtualViewIds. The value of // actionIdToLabel holds assigned custom action id to custom action label mapping. The // value of labelToActionId holds custom action label to assigned custom action id mapping. private var actionIdToLabel = SparseArrayCompat<SparseArrayCompat<CharSequence>>() private var labelToActionId = SparseArrayCompat<Map<CharSequence, Int>>() private var accessibilityCursorPosition = AccessibilityCursorPositionUndefined // We hold this node id to reset the [accessibilityCursorPosition] to undefined when // traversal with granularity switches to the next node private var previousTraversedNode: Int? = null private val subtreeChangedLayoutNodes = ArraySet<LayoutNode>() private val boundsUpdateChannel = Channel<Unit>(Channel.CONFLATED) private var currentSemanticsNodesInvalidated = true private class PendingTextTraversedEvent( val node: SemanticsNode, val action: Int, val granularity: Int, val fromIndex: Int, val toIndex: Int, val traverseTime: Long ) private var pendingTextTraversedEvent: PendingTextTraversedEvent? = null /** * Up to date semantics nodes in pruned semantics tree. It always reflects the current * semantics tree. They key is the virtual view id(the root node has a key of * AccessibilityNodeProviderCompat.HOST_VIEW_ID and other node has a key of its id). */ private var currentSemanticsNodes: Map<Int, SemanticsNodeWithAdjustedBounds> = mapOf() get() { if (currentSemanticsNodesInvalidated) { // first instance of retrieving all nodes currentSemanticsNodesInvalidated = false field = view.semanticsOwner.getAllUncoveredSemanticsNodesToMap() setTraversalValues() } return field } private var paneDisplayed = ArraySet<Int>() private var idToBeforeMap = HashMap<Int, Int>() private val EXTRA_DATA_TEST_TRAVERSALBEFORE_VAL = "android.view.accessibility.extra.EXTRA_DATA_TEST_TRAVERSALBEFORE_VAL" /** * A snapshot of the semantics node. The children here is fixed and are taken from the time * this node is constructed. While a SemanticsNode always contains the up-to-date children. */ @VisibleForTesting internal class SemanticsNodeCopy( semanticsNode: SemanticsNode, currentSemanticsNodes: Map<Int, SemanticsNodeWithAdjustedBounds> ) { val unmergedConfig = semanticsNode.unmergedConfig val children: MutableSet<Int> = mutableSetOf() init { semanticsNode.replacedChildren.fastForEach { child -> if (currentSemanticsNodes.contains(child.id)) { children.add(child.id) } } } fun hasPaneTitle() = unmergedConfig.contains(SemanticsProperties.PaneTitle) } // previousSemanticsNodes holds the previous pruned semantics tree so that we can compare the // current and previous trees in onSemanticsChange(). We use SemanticsNodeCopy here because // SemanticsNode's children are dynamically generated and always reflect the current children. // We need to keep a copy of its old structure for comparison. @VisibleForTesting internal var previousSemanticsNodes: MutableMap<Int, SemanticsNodeCopy> = mutableMapOf() private var previousSemanticsRoot = SemanticsNodeCopy(view.semanticsOwner.unmergedRootSemanticsNode, mapOf()) private var checkingForSemanticsChanges = false init { // Remove callbacks that rely on view being attached to a window when we become detached. view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(view: View) { accessibilityManager.addAccessibilityStateChangeListener(enabledStateListener) accessibilityManager.addTouchExplorationStateChangeListener( touchExplorationStateListener ) } override fun onViewDetachedFromWindow(view: View) { handler.removeCallbacks(semanticsChangeChecker) accessibilityManager.removeAccessibilityStateChangeListener(enabledStateListener) accessibilityManager.removeTouchExplorationStateChangeListener( touchExplorationStateListener ) } }) } /** * Returns true if there is any semantics node in the tree that can scroll in the given * [orientation][vertical] and [direction] at the given [position] in the view associated with * this delegate. * * @param direction The direction to check for scrolling: <0 means scrolling left or up, >0 * means scrolling right or down. * @param position The position in the view to check in view-local coordinates. */ internal fun canScroll( vertical: Boolean, direction: Int, position: Offset ): Boolean = canScroll(currentSemanticsNodes.values, vertical, direction, position) @VisibleForTesting(otherwise = PRIVATE) internal fun canScroll( currentSemanticsNodes: Collection<SemanticsNodeWithAdjustedBounds>, vertical: Boolean, direction: Int, position: Offset ): Boolean { // No down event has occurred yet which gives us a location to hit test. if (position == Offset.Unspecified || !position.isValid()) return false val scrollRangeProperty = when (vertical) { true -> SemanticsProperties.VerticalScrollAxisRange false -> SemanticsProperties.HorizontalScrollAxisRange } return currentSemanticsNodes.any { node -> // Only consider nodes that are under the touch event. Checks the adjusted bounds to // avoid overlapping siblings. Because position is a float (touch event can happen in- // between pixels), convert the int-based Android Rect to a float-based Compose Rect // before doing the comparison. if (!node.adjustedBounds.toComposeRect().contains(position)) { return@any false } val scrollRange = node.semanticsNode.config.getOrNull(scrollRangeProperty) ?: return@any false // A node simply having scrollable semantics doesn't mean it's necessarily scrollable // in the given direction – it must also not be scrolled to its limit in that direction. var actualDirection = if (scrollRange.reverseScrolling) -direction else direction if (direction == 0 && scrollRange.reverseScrolling) { // The View implementation of canScroll* treat zero as a positive direction, so // this code should do the same. That means if scrolling is reversed, zero should be // a negative direction. The actual number doesn't matter, just its sign. actualDirection = -1 } if (actualDirection < 0) scrollRange.value() > 0 else scrollRange.value() < scrollRange.maxValue() } } private fun createNodeInfo(virtualViewId: Int): AccessibilityNodeInfo? { if (view.viewTreeOwners?.lifecycleOwner?.lifecycle?.currentState == Lifecycle.State.DESTROYED ) { return null } val info: AccessibilityNodeInfoCompat = AccessibilityNodeInfoCompat.obtain() val semanticsNodeWithAdjustedBounds = currentSemanticsNodes[virtualViewId] if (semanticsNodeWithAdjustedBounds == null) { return null } val semanticsNode: SemanticsNode = semanticsNodeWithAdjustedBounds.semanticsNode if (virtualViewId == AccessibilityNodeProviderCompat.HOST_VIEW_ID) { info.setParent(ViewCompat.getParentForAccessibility(view) as? View) } else { if (semanticsNode.parent != null) { var parentId = semanticsNode.parent!!.id if (parentId == view.semanticsOwner.unmergedRootSemanticsNode.id) { parentId = AccessibilityNodeProviderCompat.HOST_VIEW_ID } info.setParent(view, parentId) } else { throw IllegalStateException("semanticsNode $virtualViewId has null parent") } } info.setSource(view, virtualViewId) val boundsInRoot = semanticsNodeWithAdjustedBounds.adjustedBounds val topLeftInScreen = view.localToScreen(Offset(boundsInRoot.left.toFloat(), boundsInRoot.top.toFloat())) val bottomRightInScreen = view.localToScreen(Offset(boundsInRoot.right.toFloat(), boundsInRoot.bottom.toFloat())) info.setBoundsInScreen( android.graphics.Rect( floor(topLeftInScreen.x).toInt(), floor(topLeftInScreen.y).toInt(), ceil(bottomRightInScreen.x).toInt(), ceil(bottomRightInScreen.y).toInt() ) ) populateAccessibilityNodeInfoProperties(virtualViewId, info, semanticsNode) return info.unwrap() } private fun setTraversalValues() { idToBeforeMap.clear() var idToCoordinatesList = mutableListOf<Pair<Int, Rect>>() fun depthFirstSearch(currNode: SemanticsNode) { if (currNode.parent?.layoutNode?.innerCoordinator?.isAttached == true && currNode.layoutNode.innerCoordinator.isAttached ) { idToCoordinatesList.add( Pair( currNode.id, currNode.layoutNode.coordinates.boundsInWindow() ) ) } // This retrieves the children in the order that we want (respecting child/parent // hierarchies) currNode.replacedChildrenSortedByBounds.fastForEach { child -> depthFirstSearch(child) } } currentSemanticsNodes[AccessibilityNodeProviderCompat.HOST_VIEW_ID]?.semanticsNode ?.replacedChildrenSortedByBounds?.fastForEach { node -> depthFirstSearch(node) } // Iterate through our ordered list, and creating a mapping of current node to next node ID // We'll later read through this and set traversal order with IdToBeforeMap for (i in 1..idToCoordinatesList.lastIndex) { val prevId = idToCoordinatesList[i - 1].first val currId = idToCoordinatesList[i].first idToBeforeMap[prevId] = currId } return } @VisibleForTesting @OptIn(ExperimentalComposeUiApi::class) fun populateAccessibilityNodeInfoProperties( virtualViewId: Int, info: AccessibilityNodeInfoCompat, semanticsNode: SemanticsNode ) { val isUnmergedLeafNode = !semanticsNode.isFake && semanticsNode.replacedChildren.isEmpty() && semanticsNode.layoutNode.findClosestParentNode { it.outerSemantics ?.collapsedSemanticsConfiguration() ?.isMergingSemanticsOfDescendants == true } == null // set classname info.className = ClassName val role = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.Role) role?.let { if (semanticsNode.isFake || semanticsNode.replacedChildren.isEmpty()) { if (role == Role.Tab) { info.roleDescription = view.context.resources.getString(R.string.tab) } else if (role == Role.Switch) { info.roleDescription = view.context.resources.getString(R.string.switch_role) } else { val className = when (it) { Role.Button -> "android.widget.Button" Role.Checkbox -> "android.widget.CheckBox" Role.RadioButton -> "android.widget.RadioButton" Role.Image -> "android.widget.ImageView" else -> null } // Images are often minor children of larger widgets, so we only want to // announce the Image role when the image itself is focusable. if (role != Role.Image || isUnmergedLeafNode || semanticsNode.unmergedConfig.isMergingSemanticsOfDescendants ) { info.className = className } } } } if (semanticsNode.isTextField) { info.className = "android.widget.EditText" } if (semanticsNode.config.contains(SemanticsProperties.Text)) { info.className = "android.widget.TextView" } info.packageName = view.context.packageName // This property exists to distinguish semantically meaningful nodes from purely structural // or decorative UI elements. In Compose, LayoutNodes without semantics are simply omitted // from the AccessibilityNodeInfo tree. Therefore, every AccessibilityNodeInfo qualifies as // "important". info.isImportantForAccessibility = true semanticsNode.replacedChildren.fastForEach { child -> if (currentSemanticsNodes.contains(child.id)) { val holder = view.androidViewsHandler.layoutNodeToHolder[child.layoutNode] if (holder != null) { info.addChild(holder) } else { info.addChild(view, child.id) } } } // Manage internal accessibility focus state. if (focusedVirtualViewId == virtualViewId) { info.isAccessibilityFocused = true info.addAction(AccessibilityActionCompat.ACTION_CLEAR_ACCESSIBILITY_FOCUS) } else { info.isAccessibilityFocused = false info.addAction(AccessibilityActionCompat.ACTION_ACCESSIBILITY_FOCUS) } setText(semanticsNode, info) setContentInvalid(semanticsNode, info) info.stateDescription = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.StateDescription) val toggleState = semanticsNode.unmergedConfig.getOrNull( SemanticsProperties.ToggleableState ) toggleState?.let { info.isCheckable = true when (it) { ToggleableState.On -> { info.isChecked = true // Unfortunately, talback has a bug of using "checked", so we set state // description here if (role == Role.Switch && info.stateDescription == null) { info.stateDescription = view.context.resources.getString(R.string.on) } } ToggleableState.Off -> { info.isChecked = false // Unfortunately, talkback has a bug of using "not checked", so we set state // description here if (role == Role.Switch && info.stateDescription == null) { info.stateDescription = view.context.resources.getString(R.string.off) } } ToggleableState.Indeterminate -> { if (info.stateDescription == null) { info.stateDescription = view.context.resources.getString(R.string.indeterminate) } } } } semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.Selected)?.let { if (role == Role.Tab) { // Tab in native android uses selected property info.isSelected = it } else { info.isCheckable = true info.isChecked = it if (info.stateDescription == null) { // If a radio entry (radio button + text) is selectable, it won't have the role // RadioButton, so if we use info.isCheckable/info.isChecked, talkback will say // "checked/not checked" instead "selected/note selected". info.stateDescription = if (it) { view.context.resources.getString(R.string.selected) } else { view.context.resources.getString(R.string.not_selected) } } } } if (!semanticsNode.unmergedConfig.isMergingSemanticsOfDescendants || // we don't emit fake nodes for nodes without children, therefore we should assign // content description for such nodes semanticsNode.replacedChildren.isEmpty() ) { info.contentDescription = semanticsNode.unmergedConfig.getOrNull( SemanticsProperties.ContentDescription )?.firstOrNull() } // Map testTag to resourceName if testTagsAsResourceId == true (which can be set by an ancestor) val testTag = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.TestTag) if (testTag != null) { var testTagsAsResourceId = false var current: SemanticsNode? = semanticsNode while (current != null) { if (current.unmergedConfig.contains( SemanticsPropertiesAndroid.TestTagsAsResourceId )) { testTagsAsResourceId = current.unmergedConfig.get( SemanticsPropertiesAndroid.TestTagsAsResourceId ) break } else { current = current.parent } } if (testTagsAsResourceId) { info.viewIdResourceName = testTag } } semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.Heading)?.let { info.isHeading = true } info.isPassword = semanticsNode.isPassword // Note editable is not added to semantics properties api. info.isEditable = semanticsNode.isTextField info.isEnabled = semanticsNode.enabled() info.isFocusable = semanticsNode.unmergedConfig.contains(SemanticsProperties.Focused) if (info.isFocusable) { info.isFocused = semanticsNode.unmergedConfig[SemanticsProperties.Focused] if (info.isFocused) { info.addAction(AccessibilityNodeInfoCompat.ACTION_CLEAR_FOCUS) } else { info.addAction(AccessibilityNodeInfoCompat.ACTION_FOCUS) } } // Mark invisible nodes val wrapperToCheckTransparency = if (semanticsNode.isFake) { // when node is fake, its parent that is the original semantics node should define the // alpha value semanticsNode.parent?.findCoordinatorToGetBounds() } else { semanticsNode.findCoordinatorToGetBounds() } val isTransparent = wrapperToCheckTransparency?.isTransparent() ?: false info.isVisibleToUser = !isTransparent && semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.InvisibleToUser) == null semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.LiveRegion)?.let { info.liveRegion = when (it) { LiveRegionMode.Polite -> ACCESSIBILITY_LIVE_REGION_POLITE LiveRegionMode.Assertive -> ACCESSIBILITY_LIVE_REGION_ASSERTIVE else -> ACCESSIBILITY_LIVE_REGION_POLITE } } info.isClickable = false semanticsNode.unmergedConfig.getOrNull(SemanticsActions.OnClick)?.let { // Selectable items that are already selected should not announce it again val isSelected = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.Selected) == true info.isClickable = !isSelected if (semanticsNode.enabled() && !isSelected) { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_CLICK, it.label ) ) } } info.isLongClickable = false semanticsNode.unmergedConfig.getOrNull(SemanticsActions.OnLongClick)?.let { info.isLongClickable = true if (semanticsNode.enabled()) { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_LONG_CLICK, it.label ) ) } } // The config will contain this action only if there is a text selection at the moment. semanticsNode.unmergedConfig.getOrNull(SemanticsActions.CopyText)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_COPY, it.label ) ) } if (semanticsNode.enabled()) { semanticsNode.unmergedConfig.getOrNull(SemanticsActions.SetText)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_SET_TEXT, it.label ) ) } // The config will contain this action only if there is a text selection at the moment. semanticsNode.unmergedConfig.getOrNull(SemanticsActions.CutText)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_CUT, it.label ) ) } // The config will contain the action anyway, therefore we check the clipboard text to // decide whether to add the action to the node or not. semanticsNode.unmergedConfig.getOrNull(SemanticsActions.PasteText)?.let { if (info.isFocused && view.clipboardManager.hasText()) { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_PASTE, it.label ) ) } } } val text = getIterableTextForAccessibility(semanticsNode) if (!text.isNullOrEmpty()) { info.setTextSelection( getAccessibilitySelectionStart(semanticsNode), getAccessibilitySelectionEnd(semanticsNode) ) val setSelectionAction = semanticsNode.unmergedConfig.getOrNull(SemanticsActions.SetSelection) // ACTION_SET_SELECTION should be provided even when SemanticsActions.SetSelection // semantics action is not provided by the component info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_SET_SELECTION, setSelectionAction?.label ) ) info.addAction(AccessibilityNodeInfoCompat.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) info.addAction(AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY) info.movementGranularities = AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_CHARACTER or AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_WORD or AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_PARAGRAPH // We only traverse the text when contentDescription is not set. val contentDescription = semanticsNode.unmergedConfig.getOrNull( SemanticsProperties.ContentDescription ) if (contentDescription.isNullOrEmpty() && semanticsNode.unmergedConfig.contains(SemanticsActions.GetTextLayoutResult) && // Talkback does not handle below granularities for text field (which includes // label/hint) when text field is not in focus !semanticsNode.excludeLineAndPageGranularities() ) { info.movementGranularities = info.movementGranularities or AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_LINE or AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_PAGE } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val extraDataKeys: MutableList<String> = mutableListOf() if (!info.text.isNullOrEmpty() && semanticsNode.unmergedConfig.contains(SemanticsActions.GetTextLayoutResult) ) { extraDataKeys.add(EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY) } if (semanticsNode.unmergedConfig.contains(SemanticsProperties.TestTag)) { extraDataKeys.add(ExtraDataTestTagKey) } if (!extraDataKeys.isEmpty()) { AccessibilityNodeInfoVerificationHelperMethods.setAvailableExtraData( info.unwrap(), extraDataKeys ) } } val rangeInfo = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.ProgressBarRangeInfo) if (rangeInfo != null) { if (semanticsNode.unmergedConfig.contains(SemanticsActions.SetProgress)) { info.className = "android.widget.SeekBar" } else { info.className = "android.widget.ProgressBar" } if (rangeInfo !== ProgressBarRangeInfo.Indeterminate) { info.rangeInfo = AccessibilityNodeInfoCompat.RangeInfoCompat.obtain( AccessibilityNodeInfoCompat.RangeInfoCompat.RANGE_TYPE_FLOAT, rangeInfo.range.start, rangeInfo.range.endInclusive, rangeInfo.current ) // let's set state description here and use state description change events. // otherwise, we need to send out type_view_selected event, as the old android // versions do. But the support for type_view_selected event for progress bars // maybe deprecated in talkback in the future. if (info.stateDescription == null) { val valueRange = rangeInfo.range val progress = ( if (valueRange.endInclusive - valueRange.start == 0f) 0f else (rangeInfo.current - valueRange.start) / (valueRange.endInclusive - valueRange.start) ).coerceIn(0f, 1f) // We only display 0% or 100% when it is exactly 0% or 100%. val percent = when (progress) { 0f -> 0 1f -> 100 else -> (progress * 100).roundToInt().coerceIn(1, 99) } info.stateDescription = view.context.resources.getString(R.string.template_percent, percent) } } else if (info.stateDescription == null) { info.stateDescription = view.context.resources.getString(R.string.in_progress) } if (semanticsNode.unmergedConfig.contains(SemanticsActions.SetProgress) && semanticsNode.enabled() ) { if (rangeInfo.current < rangeInfo.range.endInclusive.coerceAtLeast(rangeInfo.range.start) ) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_FORWARD) } if (rangeInfo.current > rangeInfo.range.start.coerceAtMost(rangeInfo.range.endInclusive) ) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_BACKWARD) } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Api24Impl.addSetProgressAction(info, semanticsNode) } setCollectionInfo(semanticsNode, info) setCollectionItemInfo(semanticsNode, info) // Will the scrollable scroll when ACTION_SCROLL_FORWARD is performed? fun ScrollAxisRange.canScrollForward(): Boolean { return value() < maxValue() && !reverseScrolling || value() > 0f && reverseScrolling } // Will the scrollable scroll when ACTION_SCROLL_BACKWARD is performed? fun ScrollAxisRange.canScrollBackward(): Boolean { return value() > 0f && !reverseScrolling || value() < maxValue() && reverseScrolling } val xScrollState = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.HorizontalScrollAxisRange) val scrollAction = semanticsNode.unmergedConfig.getOrNull(SemanticsActions.ScrollBy) if (xScrollState != null && scrollAction != null) { // Talkback defines SCROLLABLE_ROLE_FILTER_FOR_DIRECTION_NAVIGATION, so we need to // assign a role for auto scroll to work. Node with collectionInfo resolved by // Talkback to ROLE_LIST and supports autoscroll too if (!semanticsNode.hasCollectionInfo()) { info.className = "android.widget.HorizontalScrollView" } if (xScrollState.maxValue() > 0f) { info.isScrollable = true } if (semanticsNode.enabled()) { if (xScrollState.canScrollForward()) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_FORWARD) info.addAction( if (!semanticsNode.isRtl) { AccessibilityActionCompat.ACTION_SCROLL_RIGHT } else { AccessibilityActionCompat.ACTION_SCROLL_LEFT } ) } if (xScrollState.canScrollBackward()) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_BACKWARD) info.addAction( if (!semanticsNode.isRtl) { AccessibilityActionCompat.ACTION_SCROLL_LEFT } else { AccessibilityActionCompat.ACTION_SCROLL_RIGHT } ) } } } val yScrollState = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.VerticalScrollAxisRange) if (yScrollState != null && scrollAction != null) { // Talkback defines SCROLLABLE_ROLE_FILTER_FOR_DIRECTION_NAVIGATION, so we need to // assign a role for auto scroll to work. Node with collectionInfo resolved by // Talkback to ROLE_LIST and supports autoscroll too if (!semanticsNode.hasCollectionInfo()) { info.className = "android.widget.ScrollView" } if (yScrollState.maxValue() > 0f) { info.isScrollable = true } if (semanticsNode.enabled()) { if (yScrollState.canScrollForward()) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_FORWARD) info.addAction(AccessibilityActionCompat.ACTION_SCROLL_DOWN) } if (yScrollState.canScrollBackward()) { info.addAction(AccessibilityActionCompat.ACTION_SCROLL_BACKWARD) info.addAction(AccessibilityActionCompat.ACTION_SCROLL_UP) } } } info.paneTitle = semanticsNode.unmergedConfig.getOrNull(SemanticsProperties.PaneTitle) if (semanticsNode.enabled()) { semanticsNode.unmergedConfig.getOrNull(SemanticsActions.Expand)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_EXPAND, it.label ) ) } semanticsNode.unmergedConfig.getOrNull(SemanticsActions.Collapse)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_COLLAPSE, it.label ) ) } semanticsNode.unmergedConfig.getOrNull(SemanticsActions.Dismiss)?.let { info.addAction( AccessibilityActionCompat( AccessibilityNodeInfoCompat.ACTION_DISMISS, it.label ) ) } if (semanticsNode.unmergedConfig.contains(CustomActions)) { val customActions = semanticsNode.unmergedConfig[CustomActions] if (customActions.size >= AccessibilityActionsResourceIds.size) { throw IllegalStateException( "Can't have more than " + "${AccessibilityActionsResourceIds.size} custom actions for one widget" ) } val currentActionIdToLabel = SparseArrayCompat<CharSequence>() val currentLabelToActionId = mutableMapOf<CharSequence, Int>() // If this virtual node had custom action id assignment before, we try to keep the id // unchanged for the same action (identified by action label). This way, we can // minimize the influence of custom action change between custom actions are // presented to the user and actually performed. if (labelToActionId.containsKey(virtualViewId)) { val oldLabelToActionId = labelToActionId[virtualViewId] val availableIds = AccessibilityActionsResourceIds.toMutableList() val unassignedActions = mutableListOf<CustomAccessibilityAction>() customActions.fastForEach { action -> if (oldLabelToActionId!!.contains(action.label)) { val actionId = oldLabelToActionId[action.label] currentActionIdToLabel.put(actionId!!, action.label) currentLabelToActionId[action.label] = actionId availableIds.remove(actionId) info.addAction(AccessibilityActionCompat(actionId, action.label)) } else { unassignedActions.add(action) } } unassignedActions.fastForEachIndexed { index, action -> val actionId = availableIds[index] currentActionIdToLabel.put(actionId, action.label) currentLabelToActionId[action.label] = actionId info.addAction(AccessibilityActionCompat(actionId, action.label)) } } else { customActions.fastForEachIndexed { index, action -> val actionId = AccessibilityActionsResourceIds[index] currentActionIdToLabel.put(actionId, action.label) currentLabelToActionId[action.label] = actionId info.addAction(AccessibilityActionCompat(actionId, action.label)) } } actionIdToLabel.put(virtualViewId, currentActionIdToLabel) labelToActionId.put(virtualViewId, currentLabelToActionId) } } val isSpeakingNode = info.contentDescription != null || info.text != null || info.hintText != null || info.stateDescription != null || info.isCheckable info.isScreenReaderFocusable = semanticsNode.unmergedConfig.isMergingSemanticsOfDescendants || isUnmergedLeafNode && isSpeakingNode if (idToBeforeMap[virtualViewId] != null) { idToBeforeMap[virtualViewId]?.let { info.setTraversalBefore(view, it) } addExtraDataToAccessibilityNodeInfoHelper( virtualViewId, info.unwrap(), EXTRA_DATA_TEST_TRAVERSALBEFORE_VAL, null) } } /** Set the error text for this node */ private fun setContentInvalid(node: SemanticsNode, info: AccessibilityNodeInfoCompat) { if (node.unmergedConfig.contains(SemanticsProperties.Error)) { info.isContentInvalid = true info.error = node.unmergedConfig.getOrNull(SemanticsProperties.Error) } } @OptIn(InternalTextApi::class) private fun setText( node: SemanticsNode, info: AccessibilityNodeInfoCompat, ) { val fontFamilyResolver: FontFamily.Resolver = view.fontFamilyResolver val editableTextToAssign = trimToSize( node.unmergedConfig.getTextForTextField() ?.toAccessibilitySpannableString(density = view.density, fontFamilyResolver), ParcelSafeTextLength ) val textToAssign = trimToSize( node.unmergedConfig.getOrNull(SemanticsProperties.Text)?.firstOrNull() ?.toAccessibilitySpannableString(density = view.density, fontFamilyResolver), ParcelSafeTextLength ) info.text = editableTextToAssign ?: textToAssign } /** * Returns whether this virtual view is accessibility focused. * * @return True if the view is accessibility focused. */ private fun isAccessibilityFocused(virtualViewId: Int): Boolean { return (focusedVirtualViewId == virtualViewId) } /** * Attempts to give accessibility focus to a virtual view. * <p> * A virtual view will not actually take focus if * {@link AccessibilityManager#isEnabled()} returns false, * {@link AccessibilityManager#isTouchExplorationEnabled()} returns false, * or the view already has accessibility focus. * * @param virtualViewId The id of the virtual view on which to place * accessibility focus. * @return Whether this virtual view actually took accessibility focus. */ private fun requestAccessibilityFocus(virtualViewId: Int): Boolean { if (!isTouchExplorationEnabled) { return false } // TODO: Check virtual view visibility. if (!isAccessibilityFocused(virtualViewId)) { // Clear focus from the previously focused view, if applicable. if (focusedVirtualViewId != InvalidId) { sendEventForVirtualView( focusedVirtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED ) } // Set focus on the new view. focusedVirtualViewId = virtualViewId view.invalidate() sendEventForVirtualView( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED ) return true } return false } /** * Populates an event of the specified type with information about an item * and attempts to send it up through the view hierarchy. * <p> * You should call this method after performing a user action that normally * fires an accessibility event, such as clicking on an item. * * <pre>public performItemClick(T item) { * ... * sendEventForVirtualView(item.id, AccessibilityEvent.TYPE_VIEW_CLICKED) * } * </pre> * * @param virtualViewId The virtual view id for which to send an event. * @param eventType The type of event to send. * @param contentChangeType The contentChangeType of this event. * @param contentDescription Content description of this event. * @return true if the event was sent successfully. */ private fun sendEventForVirtualView( virtualViewId: Int, eventType: Int, contentChangeType: Int? = null, contentDescription: List<String>? = null ): Boolean { if (virtualViewId == InvalidId || !isEnabled) { return false } val event: AccessibilityEvent = createEvent(virtualViewId, eventType) if (contentChangeType != null) { event.contentChangeTypes = contentChangeType } if (contentDescription != null) { event.contentDescription = contentDescription.fastJoinToString(",") } return sendEvent(event) } /** * Send an accessibility event. * * @param event The accessibility event to send. * @return true if the event was sent successfully. */ private fun sendEvent(event: AccessibilityEvent): Boolean { // only send an event if there's an enabled service listening for events of this type if (!isEnabled) { return false } return view.parent.requestSendAccessibilityEvent(view, event) } /** * Constructs and returns an {@link AccessibilityEvent} populated with * information about the specified item. * * @param virtualViewId The virtual view id for the item for which to * construct an event. * @param eventType The type of event to construct. * @return An {@link AccessibilityEvent} populated with information about * the specified item. */ @Suppress("DEPRECATION") @VisibleForTesting internal fun createEvent(virtualViewId: Int, eventType: Int): AccessibilityEvent { val event: AccessibilityEvent = AccessibilityEvent.obtain(eventType) event.isEnabled = true event.className = ClassName // Don't allow the client to override these properties. event.packageName = view.context.packageName event.setSource(view, virtualViewId) // populate additional information from the node currentSemanticsNodes[virtualViewId]?.let { event.isPassword = it.semanticsNode.isPassword } return event } private fun createTextSelectionChangedEvent( virtualViewId: Int, fromIndex: Int?, toIndex: Int?, itemCount: Int?, text: String? ): AccessibilityEvent { return createEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED ).apply { fromIndex?.let { this.fromIndex = it } toIndex?.let { this.toIndex = it } itemCount?.let { this.itemCount = it } text?.let { this.text.add(it) } } } /** * Attempts to clear accessibility focus from a virtual view. * * @param virtualViewId The id of the virtual view from which to clear * accessibility focus. * @return Whether this virtual view actually cleared accessibility focus. */ private fun clearAccessibilityFocus(virtualViewId: Int): Boolean { if (isAccessibilityFocused(virtualViewId)) { focusedVirtualViewId = InvalidId view.invalidate() sendEventForVirtualView( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED ) return true } return false } private fun performActionHelper( virtualViewId: Int, action: Int, arguments: Bundle? ): Boolean { val node = currentSemanticsNodes[virtualViewId]?.semanticsNode ?: return false // Actions can be performed when disabled. when (action) { AccessibilityNodeInfoCompat.ACTION_ACCESSIBILITY_FOCUS -> return requestAccessibilityFocus(virtualViewId) AccessibilityNodeInfoCompat.ACTION_CLEAR_ACCESSIBILITY_FOCUS -> return clearAccessibilityFocus(virtualViewId) AccessibilityNodeInfoCompat.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY -> { if (arguments != null) { val granularity = arguments.getInt( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT ) val extendSelection = arguments.getBoolean( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN ) return traverseAtGranularity( node, granularity, action == AccessibilityNodeInfoCompat.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, extendSelection ) } return false } AccessibilityNodeInfoCompat.ACTION_SET_SELECTION -> { val start = arguments?.getInt( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SELECTION_START_INT, -1 ) ?: -1 val end = arguments?.getInt( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SELECTION_END_INT, -1 ) ?: -1 // Note: This is a little different from current android framework implementation. val success = setAccessibilitySelection(node, start, end, false) // Text selection changed event already updates the cache. so this may not be // necessary. if (success) { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(node.id), AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED ) } return success } AccessibilityNodeInfoCompat.ACTION_COPY -> { return node.unmergedConfig.getOrNull( SemanticsActions.CopyText )?.action?.invoke() ?: false } } if (!node.enabled()) { return false } // Actions can't be performed when disabled. when (action) { AccessibilityNodeInfoCompat.ACTION_CLICK -> { val result = node.unmergedConfig.getOrNull(SemanticsActions.OnClick)?.action?.invoke() sendEventForVirtualView(virtualViewId, AccessibilityEvent.TYPE_VIEW_CLICKED) return result ?: false } AccessibilityNodeInfoCompat.ACTION_LONG_CLICK -> { return node.unmergedConfig.getOrNull(SemanticsActions.OnLongClick)?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD, AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD, android.R.id.accessibilityActionScrollDown, android.R.id.accessibilityActionScrollUp, android.R.id.accessibilityActionScrollRight, android.R.id.accessibilityActionScrollLeft -> { // Introduce a few shorthands: val scrollForward = action == AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD val scrollBackward = action == AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD val scrollLeft = action == android.R.id.accessibilityActionScrollLeft val scrollRight = action == android.R.id.accessibilityActionScrollRight val scrollUp = action == android.R.id.accessibilityActionScrollUp val scrollDown = action == android.R.id.accessibilityActionScrollDown val scrollHorizontal = scrollLeft || scrollRight || scrollForward || scrollBackward val scrollVertical = scrollUp || scrollDown || scrollForward || scrollBackward if (scrollForward || scrollBackward) { val rangeInfo = node.unmergedConfig.getOrNull(SemanticsProperties.ProgressBarRangeInfo) val setProgressAction = node.unmergedConfig.getOrNull(SemanticsActions.SetProgress) if (rangeInfo != null && setProgressAction != null) { val max = rangeInfo.range.endInclusive.coerceAtLeast(rangeInfo.range.start) val min = rangeInfo.range.start.coerceAtMost(rangeInfo.range.endInclusive) var increment = if (rangeInfo.steps > 0) { (max - min) / (rangeInfo.steps + 1) } else { (max - min) / AccessibilitySliderStepsCount } if (scrollBackward) { increment = -increment } return setProgressAction.action?.invoke(rangeInfo.current + increment) ?: false } } // Will the scrollable scroll when ScrollBy is invoked with the given [amount]? fun ScrollAxisRange.canScroll(amount: Float): Boolean { return amount < 0 && value() > 0 || amount > 0 && value() < maxValue() } val viewport = node.layoutInfo.coordinates.boundsInParent().size val scrollAction = node.unmergedConfig.getOrNull(SemanticsActions.ScrollBy) ?: return false val xScrollState = node.unmergedConfig.getOrNull(SemanticsProperties.HorizontalScrollAxisRange) if (xScrollState != null && scrollHorizontal) { var amountToScroll = viewport.width if (scrollLeft || scrollBackward) { amountToScroll = -amountToScroll } if (xScrollState.reverseScrolling) { amountToScroll = -amountToScroll } if (node.isRtl && (scrollLeft || scrollRight)) { amountToScroll = -amountToScroll } if (xScrollState.canScroll(amountToScroll)) { return scrollAction.action?.invoke(amountToScroll, 0f) ?: false } } val yScrollState = node.unmergedConfig.getOrNull(SemanticsProperties.VerticalScrollAxisRange) if (yScrollState != null && scrollVertical) { var amountToScroll = viewport.height if (scrollUp || scrollBackward) { amountToScroll = -amountToScroll } if (yScrollState.reverseScrolling) { amountToScroll = -amountToScroll } if (yScrollState.canScroll(amountToScroll)) { return scrollAction.action?.invoke(0f, amountToScroll) ?: false } } return false } android.R.id.accessibilityActionSetProgress -> { if (arguments == null || !arguments.containsKey( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_PROGRESS_VALUE ) ) { return false } return node.unmergedConfig.getOrNull(SemanticsActions.SetProgress)?.action?.invoke( arguments.getFloat(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_PROGRESS_VALUE) ) ?: false } AccessibilityNodeInfoCompat.ACTION_FOCUS -> { return node.unmergedConfig.getOrNull(SemanticsActions.RequestFocus) ?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_CLEAR_FOCUS -> { return if (node.unmergedConfig.getOrNull(SemanticsProperties.Focused) == true) { view.focusManager.clearFocus() true } else { false } } AccessibilityNodeInfoCompat.ACTION_SET_TEXT -> { val text = arguments?.getString( AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE ) return node.unmergedConfig.getOrNull(SemanticsActions.SetText) ?.action?.invoke(AnnotatedString(text ?: "")) ?: false } AccessibilityNodeInfoCompat.ACTION_PASTE -> { return node.unmergedConfig.getOrNull( SemanticsActions.PasteText )?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_CUT -> { return node.unmergedConfig.getOrNull( SemanticsActions.CutText )?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_EXPAND -> { return node.unmergedConfig.getOrNull( SemanticsActions.Expand )?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_COLLAPSE -> { return node.unmergedConfig.getOrNull( SemanticsActions.Collapse )?.action?.invoke() ?: false } AccessibilityNodeInfoCompat.ACTION_DISMISS -> { return node.unmergedConfig.getOrNull( SemanticsActions.Dismiss )?.action?.invoke() ?: false } android.R.id.accessibilityActionShowOnScreen -> { // TODO(b/190865803): Consider scrolling nested containers instead of only the first one. var scrollableAncestor: SemanticsNode? = node.parent var scrollAction = scrollableAncestor?.config?.getOrNull(SemanticsActions.ScrollBy) while (scrollableAncestor != null) { if (scrollAction != null) { break } scrollableAncestor = scrollableAncestor.parent scrollAction = scrollableAncestor?.config?.getOrNull(SemanticsActions.ScrollBy) } if (scrollableAncestor == null) { return false } // TalkBack expects the minimum amount of movement to fully reveal the node. // First, get the viewport and the target bounds in root coordinates val viewportInParent = scrollableAncestor.layoutInfo.coordinates.boundsInParent() val parentInRoot = scrollableAncestor.layoutInfo.coordinates .parentLayoutCoordinates?.positionInRoot() ?: Offset.Zero val viewport = viewportInParent.translate(parentInRoot) val target = Rect(node.positionInRoot, node.size.toSize()) val xScrollState = scrollableAncestor.unmergedConfig .getOrNull(SemanticsProperties.HorizontalScrollAxisRange) val yScrollState = scrollableAncestor.unmergedConfig .getOrNull(SemanticsProperties.VerticalScrollAxisRange) // Given the desired scroll value to align either side of the target with the // viewport, what delta should we go with? // If we need to scroll in opposite directions for both sides, don't scroll at all. // Otherwise, take the delta that scrolls the least amount. fun scrollDelta(a: Float, b: Float): Float = if (sign(a) == sign(b)) if (abs(a) < abs(b)) a else b else 0f // Get the desired delta X var dx = scrollDelta(target.left - viewport.left, target.right - viewport.right) // And adjust for reversing properties if (xScrollState?.reverseScrolling == true) dx = -dx if (node.isRtl) dx = -dx // Get the desired delta Y var dy = scrollDelta(target.top - viewport.top, target.bottom - viewport.bottom) // And adjust for reversing properties if (yScrollState?.reverseScrolling == true) dy = -dy return scrollAction?.action?.invoke(dx, dy) ?: false } // TODO: handling for other system actions else -> { val label = actionIdToLabel[virtualViewId]?.get(action) ?: return false val customActions = node.unmergedConfig.getOrNull(CustomActions) ?: return false customActions.fastForEach { customAction -> if (customAction.label == label) { return customAction.action() } } return false } } } private fun addExtraDataToAccessibilityNodeInfoHelper( virtualViewId: Int, info: AccessibilityNodeInfo, extraDataKey: String, arguments: Bundle? ) { val node = currentSemanticsNodes[virtualViewId]?.semanticsNode ?: return val text = getIterableTextForAccessibility(node) // This extra is just for testing: needed a way to retrieve `traversalBefore` from // non-sealed instance of ANI if (extraDataKey == EXTRA_DATA_TEST_TRAVERSALBEFORE_VAL) { idToBeforeMap[virtualViewId]?.let { info.extras.putInt(extraDataKey, it) } } else if (node.unmergedConfig.contains(SemanticsActions.GetTextLayoutResult) && arguments != null && extraDataKey == EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY ) { val positionInfoStartIndex = arguments.getInt( EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX, -1 ) val positionInfoLength = arguments.getInt( EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH, -1 ) if ((positionInfoLength <= 0) || (positionInfoStartIndex < 0) || (positionInfoStartIndex >= text?.length ?: Int.MAX_VALUE) ) { Log.e(LogTag, "Invalid arguments for accessibility character locations") return } val textLayoutResults = mutableListOf<TextLayoutResult>() // Note now it only works for single Text/TextField until we fix b/157474582. val getLayoutResult = node.unmergedConfig[SemanticsActions.GetTextLayoutResult] .action?.invoke(textLayoutResults) val textLayoutResult: TextLayoutResult if (getLayoutResult == true) { textLayoutResult = textLayoutResults[0] } else { return } val boundingRects = mutableListOf<RectF?>() for (i in 0 until positionInfoLength) { // This is a workaround until we fix the merging issue in b/157474582. if (positionInfoStartIndex + i >= textLayoutResult.layoutInput.text.length) { boundingRects.add(null) continue } val bounds = textLayoutResult.getBoundingBox(positionInfoStartIndex + i) val boundsOnScreen = toScreenCoords(node, bounds) boundingRects.add(boundsOnScreen) } info.extras.putParcelableArray(extraDataKey, boundingRects.toTypedArray()) } else if (node.unmergedConfig.contains(SemanticsProperties.TestTag) && arguments != null && extraDataKey == ExtraDataTestTagKey ) { val testTag = node.unmergedConfig.getOrNull(SemanticsProperties.TestTag) if (testTag != null) { info.extras.putCharSequence(extraDataKey, testTag) } } } private fun toScreenCoords(textNode: SemanticsNode?, bounds: Rect): RectF? { if (textNode == null) return null val boundsInRoot = bounds.translate(textNode.positionInRoot) val textNodeBoundsInRoot = textNode.boundsInRoot // Only visible or partially visible locations are used. val visibleBounds = if (boundsInRoot.overlaps(textNodeBoundsInRoot)) { boundsInRoot.intersect(textNodeBoundsInRoot) } else { null } return if (visibleBounds != null) { val topLeftInScreen = view.localToScreen(Offset(visibleBounds.left, visibleBounds.top)) val bottomRightInScreen = view.localToScreen(Offset(visibleBounds.right, visibleBounds.bottom)) RectF( topLeftInScreen.x, topLeftInScreen.y, bottomRightInScreen.x, bottomRightInScreen.y ) } else { null } } /** * Dispatches hover {@link android.view.MotionEvent}s to the virtual view hierarchy when * the Explore by Touch feature is enabled. * <p> * This method should be called by overriding * {@link View#dispatchHoverEvent}: * * <pre>&#64;Override * public boolean dispatchHoverEvent(MotionEvent event) { * if (mHelper.dispatchHoverEvent(this, event) { * return true; * } * return super.dispatchHoverEvent(event); * } * </pre> * * @param event The hover event to dispatch to the virtual view hierarchy. * @return Whether the hover event was handled. */ fun dispatchHoverEvent(event: MotionEvent): Boolean { if (!isTouchExplorationEnabled) { return false } when (event.action) { MotionEvent.ACTION_HOVER_MOVE, MotionEvent.ACTION_HOVER_ENTER -> { val virtualViewId = hitTestSemanticsAt(event.x, event.y) // The android views could be view groups, so the event must be dispatched to the // views. Android ViewGroup.java will take care of synthesizing hover enter/exit // actions from hover moves. // Note that this should be before calling "updateHoveredVirtualView" so that in // the corner case of overlapped nodes, the final hover enter event is sent from // the node/view that we want to focus. val handled = view.androidViewsHandler.dispatchGenericMotionEvent(event) updateHoveredVirtualView(virtualViewId) return if (virtualViewId == InvalidId) handled else true } MotionEvent.ACTION_HOVER_EXIT -> { return when { hoveredVirtualViewId != InvalidId -> { updateHoveredVirtualView(InvalidId) true } else -> { view.androidViewsHandler.dispatchGenericMotionEvent(event) } } } else -> { return false } } } /** * Hit test the layout tree for semantics wrappers. * The return value is a virtual view id, or InvalidId if an embedded Android View was hit. */ @OptIn(ExperimentalComposeUiApi::class) @VisibleForTesting internal fun hitTestSemanticsAt(x: Float, y: Float): Int { view.measureAndLayout() val hitSemanticsEntities = HitTestResult<SemanticsModifierNode>() view.root.hitTestSemantics( pointerPosition = Offset(x, y), hitSemanticsEntities = hitSemanticsEntities ) val wrapper = hitSemanticsEntities.lastOrNull()?.requireLayoutNode()?.outerSemantics var virtualViewId = InvalidId if (wrapper != null) { // The node below is not added to the tree; it's a wrapper around outer semantics to // use the methods available to the SemanticsNode val semanticsNode = SemanticsNode(wrapper, false) val wrapperToCheckAlpha = semanticsNode.findCoordinatorToGetBounds() // Do not 'find' invisible nodes when exploring by touch. This will prevent us from // sending events for invisible nodes if (!semanticsNode.unmergedConfig.contains(SemanticsProperties.InvisibleToUser) && !wrapperToCheckAlpha.isTransparent() ) { val layoutNode = wrapper.requireLayoutNode() val androidView = view .androidViewsHandler .layoutNodeToHolder[layoutNode] if (androidView == null) { virtualViewId = semanticsNodeIdToAccessibilityVirtualNodeId( layoutNode.semanticsId ) } } } return virtualViewId } /** * Sets the currently hovered item, sending hover accessibility events as * necessary to maintain the correct state. * * @param virtualViewId The virtual view id for the item currently being * hovered, or {@link #InvalidId} if no item is hovered within * the parent view. */ private fun updateHoveredVirtualView(virtualViewId: Int) { if (hoveredVirtualViewId == virtualViewId) { return } val previousVirtualViewId: Int = hoveredVirtualViewId hoveredVirtualViewId = virtualViewId /* Stay consistent with framework behavior by sending ENTER/EXIT pairs in reverse order. This is accurate as of API 18. */ sendEventForVirtualView(virtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER) sendEventForVirtualView(previousVirtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT) } override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProviderCompat { return nodeProvider } /** * Trims the text to [size] length. Returns the string as it is if the length is * smaller than [size]. If chars at [size] - 1 and [size] is a surrogate * pair, returns a CharSequence of length [size] - 1. * * @param size length of the result, should be greater than 0 */ private fun <T : CharSequence> trimToSize(text: T?, @IntRange(from = 1) size: Int): T? { require(size > 0) var len = size if (text.isNullOrEmpty() || text.length <= size) return text if (Character.isHighSurrogate(text[size - 1]) && Character.isLowSurrogate(text[size])) { len = size - 1 } @Suppress("UNCHECKED_CAST") return text.subSequence(0, len) as T } // TODO (in a separate cl): Called when the SemanticsNode with id semanticsNodeId disappears. // fun clearNode(semanticsNodeId: Int) { // clear the actionIdToId and labelToActionId nodes } private val semanticsChangeChecker = Runnable { view.measureAndLayout() checkForSemanticsChanges() checkingForSemanticsChanges = false } internal fun onSemanticsChange() { // When accessibility is turned off, we still want to keep // currentSemanticsNodesInvalidated up to date so that when accessibility is turned on // later, we can refresh currentSemanticsNodes if currentSemanticsNodes is stale. currentSemanticsNodesInvalidated = true if (isEnabled && !checkingForSemanticsChanges) { checkingForSemanticsChanges = true handler.post(semanticsChangeChecker) } } /** * This suspend function loops for the entire lifetime of the Compose instance: it consumes * recent layout changes and sends events to the accessibility framework in batches separated * by a 100ms delay. */ suspend fun boundsUpdatesEventLoop() { try { val subtreeChangedSemanticsNodesIds = ArraySet<Int>() for (notification in boundsUpdateChannel) { if (isEnabled) { for (i in subtreeChangedLayoutNodes.indices) { @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") sendSubtreeChangeAccessibilityEvents( subtreeChangedLayoutNodes.valueAt(i)!!, subtreeChangedSemanticsNodesIds ) } subtreeChangedSemanticsNodesIds.clear() // When the bounds of layout nodes change, we will not always get semantics // change notifications because bounds is not part of semantics. And bounds // change from a layout node without semantics will affect the global bounds // of it children which has semantics. Bounds change will affect which nodes // are covered and which nodes are not, so the currentSemanticsNodes is not // up to date anymore. // After the subtree events are sent, accessibility services will get the // current visible/invisible state. We also try to do semantics tree diffing // to send out the proper accessibility events and update our copy here so that // our incremental changes (represented by accessibility events) are consistent // with accessibility services. That is: change - notify - new change - // notify, if we don't do the tree diffing and update our copy here, we will // combine old change and new change, which is missing finer-grained // notification. if (!checkingForSemanticsChanges) { checkingForSemanticsChanges = true handler.post(semanticsChangeChecker) } } subtreeChangedLayoutNodes.clear() delay(SendRecurringAccessibilityEventsIntervalMillis) } } finally { subtreeChangedLayoutNodes.clear() } } internal fun onLayoutChange(layoutNode: LayoutNode) { // When accessibility is turned off, we still want to keep // currentSemanticsNodesInvalidated up to date so that when accessibility is turned on // later, we can refresh currentSemanticsNodes if currentSemanticsNodes is stale. currentSemanticsNodesInvalidated = true if (!isEnabled) { return } // The layout change of a LayoutNode will also affect its children, so even if it doesn't // have semantics attached, we should process it. notifySubtreeAccessibilityStateChangedIfNeeded(layoutNode) } private fun notifySubtreeAccessibilityStateChangedIfNeeded(layoutNode: LayoutNode) { if (subtreeChangedLayoutNodes.add(layoutNode)) { boundsUpdateChannel.trySend(Unit) } } @OptIn(ExperimentalComposeUiApi::class) private fun sendSubtreeChangeAccessibilityEvents( layoutNode: LayoutNode, subtreeChangedSemanticsNodesIds: ArraySet<Int> ) { // The node may be no longer available while we were waiting so check // again. if (!layoutNode.isAttached) { return } // Android Views will send proper events themselves. if (view.androidViewsHandler.layoutNodeToHolder.contains(layoutNode)) { return } // When we finally send the event, make sure it is an accessibility-focusable node. var semanticsWrapper = layoutNode.outerSemantics ?: layoutNode.findClosestParentNode { it.outerSemantics != null } ?.outerSemantics ?: return if (!semanticsWrapper.collapsedSemanticsConfiguration().isMergingSemanticsOfDescendants) { layoutNode.findClosestParentNode { it.outerSemantics ?.collapsedSemanticsConfiguration() ?.isMergingSemanticsOfDescendants == true }?.outerSemantics?.let { semanticsWrapper = it } } val id = semanticsWrapper.requireLayoutNode().semanticsId if (!subtreeChangedSemanticsNodesIds.add(id)) { return } sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE ) } private fun checkForSemanticsChanges() { // Structural change sendSemanticsStructureChangeEvents( view.semanticsOwner.unmergedRootSemanticsNode, previousSemanticsRoot ) // Property change sendSemanticsPropertyChangeEvents(currentSemanticsNodes) updateSemanticsNodesCopyAndPanes() } private fun updateSemanticsNodesCopyAndPanes() { // TODO(b/172606324): removed this compose specific fix when talkback has a proper solution. for (id in paneDisplayed) { val currentNode = currentSemanticsNodes[id]?.semanticsNode if (currentNode == null || !currentNode.hasPaneTitle()) { paneDisplayed.remove(id) sendPaneChangeEvents( id, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED, previousSemanticsNodes[id]?.unmergedConfig?.getOrNull( SemanticsProperties.PaneTitle ) ) } } previousSemanticsNodes.clear() for (entry in currentSemanticsNodes.entries) { if (entry.value.semanticsNode.hasPaneTitle() && paneDisplayed.add(entry.key)) { sendPaneChangeEvents( entry.key, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_PANE_APPEARED, entry.value.semanticsNode.unmergedConfig[SemanticsProperties.PaneTitle] ) } previousSemanticsNodes[entry.key] = SemanticsNodeCopy(entry.value.semanticsNode, currentSemanticsNodes) } previousSemanticsRoot = SemanticsNodeCopy(view.semanticsOwner.unmergedRootSemanticsNode, currentSemanticsNodes) } @VisibleForTesting internal fun sendSemanticsPropertyChangeEvents( newSemanticsNodes: Map<Int, SemanticsNodeWithAdjustedBounds> ) { val oldScrollObservationScopes = ArrayList(scrollObservationScopes) scrollObservationScopes.clear() for (id in newSemanticsNodes.keys) { // We do doing this search because the new configuration is set as a whole, so we // can't indicate which property is changed when setting the new configuration. val oldNode = previousSemanticsNodes[id] ?: continue val newNode = newSemanticsNodes[id]?.semanticsNode var propertyChanged = false for (entry in newNode!!.unmergedConfig) { var newlyObservingScroll = false if (entry.key == SemanticsProperties.HorizontalScrollAxisRange || entry.key == SemanticsProperties.VerticalScrollAxisRange ) { newlyObservingScroll = registerScrollingId(id, oldScrollObservationScopes) } if (!newlyObservingScroll && entry.value == oldNode.unmergedConfig.getOrNull(entry.key) ) { continue } @Suppress("UNCHECKED_CAST") when (entry.key) { SemanticsProperties.PaneTitle -> { val paneTitle = entry.value as String // If oldNode doesn't have pane title, it will be handled in // updateSemanticsNodesCopyAndPanes(). if (oldNode.hasPaneTitle()) { sendPaneChangeEvents( id, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_PANE_TITLE, paneTitle ) } } SemanticsProperties.StateDescription, SemanticsProperties.ToggleableState -> { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION ) // Temporary(b/192295060) fix, sending CONTENT_CHANGE_TYPE_UNDEFINED to // force ViewRootImpl to update its accessibility-focused virtual-node. // If we have an androidx fix, we can remove this event. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED ) } SemanticsProperties.ProgressBarRangeInfo -> { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION ) // Temporary(b/192295060) fix, sending CONTENT_CHANGE_TYPE_UNDEFINED to // force ViewRootImpl to update its accessibility-focused virtual-node. // If we have an androidx fix, we can remove this event. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED ) } SemanticsProperties.Selected -> { // The assumption is among widgets using SemanticsProperties.Selected, only // Tab is using AccessibilityNodeInfo#isSelected, and all others are using // AccessibilityNodeInfo#isChekable and setting // AccessibilityNodeInfo#stateDescription in this delegate. if (newNode.config.getOrNull(SemanticsProperties.Role) == Role.Tab) { if (newNode.config.getOrNull(SemanticsProperties.Selected) == true) { val event = createEvent( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_VIEW_SELECTED ) // Here we use the merged node @OptIn(ExperimentalComposeUiApi::class) val mergedNode = SemanticsNode(newNode.outerSemanticsNode, true) val contentDescription = mergedNode.config.getOrNull( SemanticsProperties.ContentDescription )?.fastJoinToString(",") val text = mergedNode.config.getOrNull(SemanticsProperties.Text) ?.fastJoinToString(",") contentDescription?.let { event.contentDescription = it } text?.let { event.text.add(it) } sendEvent(event) } else { // Send this event to match View.java. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED ) } } else { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION ) // Temporary(b/192295060) fix, sending CONTENT_CHANGE_TYPE_UNDEFINED to // force ViewRootImpl to update its accessibility-focused virtual-node. // If we have an androidx fix, we can remove this event. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED ) } } SemanticsProperties.ContentDescription -> { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION, entry.value as List<String> ) } SemanticsProperties.EditableText -> { // TODO(b/160184953) Add test for SemanticsProperty Text change event if (newNode.isTextField) { val oldText = oldNode.unmergedConfig.getTextForTextField() ?: "" val newText = newNode.unmergedConfig.getTextForTextField() ?: "" var startCount = 0 // endCount records how many characters are the same from the end. var endCount = 0 val oldTextLen = oldText.length val newTextLen = newText.length val minLength = oldTextLen.coerceAtMost(newTextLen) while (startCount < minLength) { if (oldText[startCount] != newText[startCount]) { break } startCount++ } // abcdabcd vs // abcd while (endCount < minLength - startCount) { if (oldText[oldTextLen - 1 - endCount] != newText[newTextLen - 1 - endCount] ) { break } endCount++ } val removedCount = oldTextLen - endCount - startCount val addedCount = newTextLen - endCount - startCount val textChangeEvent = createEvent( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED ) textChangeEvent.fromIndex = startCount textChangeEvent.removedCount = removedCount textChangeEvent.addedCount = addedCount textChangeEvent.beforeText = oldText textChangeEvent.text.add(trimToSize(newText, ParcelSafeTextLength)) sendEvent(textChangeEvent) } else { sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT ) } } // do we need to overwrite TextRange equals? SemanticsProperties.TextSelectionRange -> { val newText = newNode.unmergedConfig.getTextForTextField()?.text ?: "" val textRange = newNode.unmergedConfig[SemanticsProperties.TextSelectionRange] val event = createTextSelectionChangedEvent( semanticsNodeIdToAccessibilityVirtualNodeId(id), textRange.start, textRange.end, newText.length, trimToSize(newText, ParcelSafeTextLength) ) sendEvent(event) sendPendingTextTraversedAtGranularityEvent(newNode.id) } SemanticsProperties.HorizontalScrollAxisRange, SemanticsProperties.VerticalScrollAxisRange -> { // TODO(yingleiw): Add throttling for scroll/state events. notifySubtreeAccessibilityStateChangedIfNeeded(newNode.layoutNode) val scope = scrollObservationScopes.findById(id)!! scope.horizontalScrollAxisRange = newNode.unmergedConfig.getOrNull( SemanticsProperties.HorizontalScrollAxisRange ) scope.verticalScrollAxisRange = newNode.unmergedConfig.getOrNull( SemanticsProperties.VerticalScrollAxisRange ) sendScrollEventIfNeeded(scope) } SemanticsProperties.Focused -> { if (entry.value as Boolean) { sendEvent( createEvent( semanticsNodeIdToAccessibilityVirtualNodeId(newNode.id), AccessibilityEvent.TYPE_VIEW_FOCUSED ) ) } // In View.java this window event is sent for unfocused view. But we send // it for focused too so that TalkBack invalidates its cache. Otherwise // PasteText edit option is not displayed properly on some OS versions. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(newNode.id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED ) } CustomActions -> { val actions = newNode.unmergedConfig[CustomActions] val oldActions = oldNode.unmergedConfig.getOrNull(CustomActions) if (oldActions != null) { // Suppose actions with the same label should be deduped. val labels = mutableSetOf<String>() actions.fastForEach { action -> labels.add(action.label) } val oldLabels = mutableSetOf<String>() oldActions.fastForEach { action -> oldLabels.add(action.label) } propertyChanged = !(labels.containsAll(oldLabels) && oldLabels.containsAll(labels)) } else if (actions.isNotEmpty()) { propertyChanged = true } } // TODO(b/151840490) send the correct events for certain properties, like view // selected. else -> { if (entry.value is AccessibilityAction<*>) { propertyChanged = !(entry.value as AccessibilityAction<*>) .accessibilityEquals(oldNode.unmergedConfig.getOrNull(entry.key)) } else { propertyChanged = true } } } } if (!propertyChanged) { propertyChanged = newNode.propertiesDeleted(oldNode) } if (propertyChanged) { // TODO(b/176105563): throttle the window content change events and merge different // sub types. We can use the subtreeChangedLayoutNodes with sub types. sendEventForVirtualView( semanticsNodeIdToAccessibilityVirtualNodeId(id), AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED ) } } } // List of visible scrollable nodes (which are observing scroll state snapshot writes). private val scrollObservationScopes = mutableListOf<ScrollObservationScope>() /* * Lambda to store in scrolling snapshot observer, which must never be recreated because * the snapshot system makes use of lambda reference comparisons. * (Note that recent versions of the Kotlin compiler do maintain a persistent * object for most lambda expressions, so this is just for the purpose of explicitness.) */ private val sendScrollEventIfNeededLambda: (ScrollObservationScope) -> Unit = { this.sendScrollEventIfNeeded(it) } private fun registerScrollingId( id: Int, oldScrollObservationScopes: List<ScrollObservationScope> ): Boolean { var newlyObservingScroll = false val oldScope = oldScrollObservationScopes.findById(id) val newScope = if (oldScope != null) { oldScope } else { newlyObservingScroll = true ScrollObservationScope( semanticsNodeId = id, allScopes = scrollObservationScopes, oldXValue = null, oldYValue = null, horizontalScrollAxisRange = null, verticalScrollAxisRange = null ) } scrollObservationScopes.add(newScope) return newlyObservingScroll } private fun sendScrollEventIfNeeded(scrollObservationScope: ScrollObservationScope) { if (!scrollObservationScope.isValid) { return } view.snapshotObserver.observeReads(scrollObservationScope, sendScrollEventIfNeededLambda) { val newXState = scrollObservationScope.horizontalScrollAxisRange val newYState = scrollObservationScope.verticalScrollAxisRange val oldXValue = scrollObservationScope.oldXValue val oldYValue = scrollObservationScope.oldYValue val deltaX = if (newXState != null && oldXValue != null) { newXState.value() - oldXValue } else { 0f } val deltaY = if (newYState != null && oldYValue != null) { newYState.value() - oldYValue } else { 0f } if (deltaX != 0f || deltaY != 0f) { val virtualNodeId = semanticsNodeIdToAccessibilityVirtualNodeId( scrollObservationScope.semanticsNodeId ) // View System sends a content changed event before each scroll event. TalkBack // uses the content changed event to synchronize the focus rect along with touch // scroll, and uses the scroll event to hear feedback that the app reacted to scroll // actions that it initiated. sendEventForVirtualView( virtualNodeId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE ) val event = createEvent( virtualNodeId, AccessibilityEvent.TYPE_VIEW_SCROLLED ) if (newXState != null) { event.scrollX = newXState.value().toInt() event.maxScrollX = newXState.maxValue().toInt() } if (newYState != null) { event.scrollY = newYState.value().toInt() event.maxScrollY = newYState.maxValue().toInt() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { Api28Impl.setScrollEventDelta(event, deltaX.toInt(), deltaY.toInt()) } sendEvent(event) } if (newXState != null) { scrollObservationScope.oldXValue = newXState.value() } if (newYState != null) { scrollObservationScope.oldYValue = newYState.value() } } } private fun sendPaneChangeEvents( semanticsNodeId: Int, contentChangeType: Int, title: String? ) { val event = createEvent( semanticsNodeIdToAccessibilityVirtualNodeId(semanticsNodeId), AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED ) event.contentChangeTypes = contentChangeType if (title != null) { event.text.add(title) } sendEvent(event) } private fun sendSemanticsStructureChangeEvents( newNode: SemanticsNode, oldNode: SemanticsNodeCopy ) { val newChildren: MutableSet<Int> = mutableSetOf() // If any child is added, clear the subtree rooted at this node and return. newNode.replacedChildren.fastForEach { child -> if (currentSemanticsNodes.contains(child.id)) { if (!oldNode.children.contains(child.id)) { notifySubtreeAccessibilityStateChangedIfNeeded(newNode.layoutNode) return } newChildren.add(child.id) } } // If any child is deleted, clear the subtree rooted at this node and return. for (child in oldNode.children) { if (!newChildren.contains(child)) { notifySubtreeAccessibilityStateChangedIfNeeded(newNode.layoutNode) return } } newNode.replacedChildren.fastForEach { child -> if (currentSemanticsNodes.contains(child.id)) { sendSemanticsStructureChangeEvents(child, previousSemanticsNodes[child.id]!!) } } } private fun semanticsNodeIdToAccessibilityVirtualNodeId(id: Int): Int { if (id == view.semanticsOwner.unmergedRootSemanticsNode.id) { return AccessibilityNodeProviderCompat.HOST_VIEW_ID } return id } private fun traverseAtGranularity( node: SemanticsNode, granularity: Int, forward: Boolean, extendSelection: Boolean ): Boolean { if (node.id != previousTraversedNode) { accessibilityCursorPosition = AccessibilityCursorPositionUndefined previousTraversedNode = node.id } val text = getIterableTextForAccessibility(node) if (text.isNullOrEmpty()) { return false } val iterator = getIteratorForGranularity(node, granularity) ?: return false var current = getAccessibilitySelectionEnd(node) if (current == AccessibilityCursorPositionUndefined) { current = if (forward) 0 else text.length } val range = (if (forward) iterator.following(current) else iterator.preceding(current)) ?: return false val segmentStart = range[0] val segmentEnd = range[1] var selectionStart: Int val selectionEnd: Int if (extendSelection && isAccessibilitySelectionExtendable(node)) { selectionStart = getAccessibilitySelectionStart(node) if (selectionStart == AccessibilityCursorPositionUndefined) { selectionStart = if (forward) segmentStart else segmentEnd } selectionEnd = if (forward) segmentEnd else segmentStart } else { selectionStart = if (forward) segmentEnd else segmentStart selectionEnd = selectionStart } val action = if (forward) AccessibilityNodeInfoCompat.ACTION_NEXT_AT_MOVEMENT_GRANULARITY else AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY pendingTextTraversedEvent = PendingTextTraversedEvent( node, action, granularity, segmentStart, segmentEnd, SystemClock.uptimeMillis() ) setAccessibilitySelection(node, selectionStart, selectionEnd, true) return true } private fun sendPendingTextTraversedAtGranularityEvent(semanticsNodeId: Int) { pendingTextTraversedEvent?.let { // not the same node, do nothing. Don't set pendingTextTraversedEvent to null either. if (semanticsNodeId != it.node.id) { return } if (SystemClock.uptimeMillis() - it.traverseTime <= TextTraversedEventTimeoutMillis) { val event = createEvent( semanticsNodeIdToAccessibilityVirtualNodeId(it.node.id), AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY ) event.fromIndex = it.fromIndex event.toIndex = it.toIndex event.action = it.action event.movementGranularity = it.granularity event.text.add(getIterableTextForAccessibility(it.node)) sendEvent(event) } } pendingTextTraversedEvent = null } private fun setAccessibilitySelection( node: SemanticsNode, start: Int, end: Int, traversalMode: Boolean ): Boolean { // Any widget which has custom action_set_selection needs to provide cursor // positions, so events will be sent when cursor position change. // When the node is disabled, only the default/virtual set selection can performed. if (node.unmergedConfig.contains(SemanticsActions.SetSelection) && node.enabled()) { // Hide all selection controllers used for adjusting selection // since we are doing so explicitly by other means and these // controllers interact with how selection behaves. From TextView.java. return node.unmergedConfig[SemanticsActions.SetSelection].action?.invoke( start, end, traversalMode ) ?: false } if (start == end && end == accessibilityCursorPosition) { return false } val text = getIterableTextForAccessibility(node) ?: return false accessibilityCursorPosition = if (start >= 0 && start == end && end <= text.length) { start } else { AccessibilityCursorPositionUndefined } val nonEmptyText = text.isNotEmpty() val event = createTextSelectionChangedEvent( semanticsNodeIdToAccessibilityVirtualNodeId(node.id), if (nonEmptyText) accessibilityCursorPosition else null, if (nonEmptyText) accessibilityCursorPosition else null, if (nonEmptyText) text.length else null, text ) sendEvent(event) sendPendingTextTraversedAtGranularityEvent(node.id) return true } /** Returns selection start and end indices in original text */ private fun getAccessibilitySelectionStart(node: SemanticsNode): Int { // If there is ContentDescription, it will be used instead of text during traversal. if (!node.unmergedConfig.contains(SemanticsProperties.ContentDescription) && node.unmergedConfig.contains(SemanticsProperties.TextSelectionRange) ) { return node.unmergedConfig[SemanticsProperties.TextSelectionRange].start } return accessibilityCursorPosition } private fun getAccessibilitySelectionEnd(node: SemanticsNode): Int { // If there is ContentDescription, it will be used instead of text during traversal. if (!node.unmergedConfig.contains(SemanticsProperties.ContentDescription) && node.unmergedConfig.contains(SemanticsProperties.TextSelectionRange) ) { return node.unmergedConfig[SemanticsProperties.TextSelectionRange].end } return accessibilityCursorPosition } private fun isAccessibilitySelectionExtendable(node: SemanticsNode): Boolean { // Currently only TextField is extendable. Static text may become extendable later. return !node.unmergedConfig.contains(SemanticsProperties.ContentDescription) && node.unmergedConfig.contains(SemanticsProperties.EditableText) } private fun getIteratorForGranularity( node: SemanticsNode?, granularity: Int ): AccessibilityIterators.TextSegmentIterator? { if (node == null) return null val text = getIterableTextForAccessibility(node) if (text.isNullOrEmpty()) { return null } // TODO(b/160190186) Make sure locale is right in AccessibilityIterators. val iterator: AccessibilityIterators.AbstractTextSegmentIterator @Suppress("DEPRECATION") when (granularity) { AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_CHARACTER -> { iterator = AccessibilityIterators.CharacterTextSegmentIterator.getInstance( view.context.resources.configuration.locale ) iterator.initialize(text) } AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_WORD -> { iterator = AccessibilityIterators.WordTextSegmentIterator.getInstance( view.context.resources.configuration.locale ) iterator.initialize(text) } AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_PARAGRAPH -> { iterator = AccessibilityIterators.ParagraphTextSegmentIterator.getInstance() iterator.initialize(text) } AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_LINE, AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_PAGE -> { // Line and page granularity are only for static text or text field. if (!node.unmergedConfig.contains(SemanticsActions.GetTextLayoutResult)) { return null } // TODO(b/157474582): Note now it only works for single Text/TextField until we // fix the merging issue. val textLayoutResults = mutableListOf<TextLayoutResult>() val textLayoutResult: TextLayoutResult val getLayoutResult = node.unmergedConfig[SemanticsActions.GetTextLayoutResult] .action?.invoke(textLayoutResults) if (getLayoutResult == true) { textLayoutResult = textLayoutResults[0] } else { return null } if (granularity == AccessibilityNodeInfoCompat.MOVEMENT_GRANULARITY_LINE) { iterator = AccessibilityIterators.LineTextSegmentIterator.getInstance() iterator.initialize(text, textLayoutResult) } else { iterator = AccessibilityIterators.PageTextSegmentIterator.getInstance() // TODO: the node should be text/textfield node instead of the current node. iterator.initialize(text, textLayoutResult, node) } } else -> return null } return iterator } /** * Gets the text reported for accessibility purposes. If a text node has a content description * in the unmerged config, it will be used instead of the text. * * This function is basically prioritising the content description over the text or editable * text of the text and text field nodes. */ private fun getIterableTextForAccessibility(node: SemanticsNode?): String? { if (node == null) { return null } // Note in android framework, TextView set this to its text. This is changed to // prioritize content description, even for Text. if (node.unmergedConfig.contains(SemanticsProperties.ContentDescription)) { return node.unmergedConfig[SemanticsProperties.ContentDescription] .fastJoinToString(",") } if (node.isTextField) { return node.unmergedConfig.getTextForTextField()?.text } return node.unmergedConfig.getOrNull(SemanticsProperties.Text)?.firstOrNull()?.text } private fun SemanticsConfiguration.getTextForTextField(): AnnotatedString? { return getOrNull(SemanticsProperties.EditableText) } // TODO(b/160820721): use AccessibilityNodeProviderCompat instead of AccessibilityNodeProvider inner class MyNodeProvider : AccessibilityNodeProvider() { override fun createAccessibilityNodeInfo(virtualViewId: Int): AccessibilityNodeInfo? { return createNodeInfo(virtualViewId) } override fun performAction( virtualViewId: Int, action: Int, arguments: Bundle? ): Boolean { return performActionHelper(virtualViewId, action, arguments) } override fun addExtraDataToAccessibilityNodeInfo( virtualViewId: Int, info: AccessibilityNodeInfo, extraDataKey: String, arguments: Bundle? ) { addExtraDataToAccessibilityNodeInfoHelper(virtualViewId, info, extraDataKey, arguments) } } @RequiresApi(Build.VERSION_CODES.N) private object Api24Impl { @DoNotInline @JvmStatic fun addSetProgressAction( info: AccessibilityNodeInfoCompat, semanticsNode: SemanticsNode ) { if (semanticsNode.enabled()) { semanticsNode.unmergedConfig.getOrNull(SemanticsActions.SetProgress)?.let { info.addAction( AccessibilityActionCompat( android.R.id.accessibilityActionSetProgress, it.label ) ) } } } } @RequiresApi(Build.VERSION_CODES.P) private object Api28Impl { @JvmStatic @DoNotInline fun setScrollEventDelta(event: AccessibilityEvent, deltaX: Int, deltaY: Int) { event.scrollDeltaX = deltaX event.scrollDeltaY = deltaY } } } private fun SemanticsNode.enabled() = (config.getOrNull(SemanticsProperties.Disabled) == null) private fun SemanticsNode.propertiesDeleted( oldNode: AndroidComposeViewAccessibilityDelegateCompat.SemanticsNodeCopy ): Boolean { for (entry in oldNode.unmergedConfig) { if (!config.contains(entry.key)) { return true } } return false } private fun SemanticsNode.hasPaneTitle() = config.contains(SemanticsProperties.PaneTitle) private val SemanticsNode.isPassword: Boolean get() = config.contains(SemanticsProperties.Password) private val SemanticsNode.isTextField get() = this.unmergedConfig.contains(SemanticsActions.SetText) private val SemanticsNode.isRtl get() = layoutInfo.layoutDirection == LayoutDirection.Rtl @OptIn(ExperimentalComposeUiApi::class) private fun SemanticsNode.excludeLineAndPageGranularities(): Boolean { // text field that is not in focus if (isTextField && unmergedConfig.getOrNull(SemanticsProperties.Focused) != true) return true // text nodes that are part of the 'merged' text field, for example hint or label. val ancestor = layoutNode.findClosestParentNode { // looking for text field merging node val ancestorSemanticsConfiguration = it.outerSemantics?.collapsedSemanticsConfiguration() ancestorSemanticsConfiguration?.isMergingSemanticsOfDescendants == true && ancestorSemanticsConfiguration.contains(SemanticsActions.SetText) } return ancestor != null && ancestor.outerSemantics ?.collapsedSemanticsConfiguration() ?.getOrNull(SemanticsProperties.Focused) != true } private fun AccessibilityAction<*>.accessibilityEquals(other: Any?): Boolean { if (this === other) return true if (other !is AccessibilityAction<*>) return false if (label != other.label) return false if (action == null && other.action != null) return false if (action != null && other.action == null) return false return true } /** * Semantics node with adjusted bounds for the uncovered(by siblings) part. */ internal class SemanticsNodeWithAdjustedBounds( val semanticsNode: SemanticsNode, val adjustedBounds: android.graphics.Rect ) /** * Finds pruned [SemanticsNode]s in the tree owned by this [SemanticsOwner]. A semantics node * completely covered by siblings drawn on top of it will be pruned. Return the results in a * map. */ internal fun SemanticsOwner .getAllUncoveredSemanticsNodesToMap(): Map<Int, SemanticsNodeWithAdjustedBounds> { val root = unmergedRootSemanticsNode val nodes = mutableMapOf<Int, SemanticsNodeWithAdjustedBounds>() if (!root.layoutNode.isPlaced || !root.layoutNode.isAttached) { return nodes } val unaccountedSpace = Region().also { it.set(root.boundsInRoot.toAndroidRect()) } fun findAllSemanticNodesRecursive(currentNode: SemanticsNode) { val notAttachedOrPlaced = !currentNode.layoutNode.isPlaced || !currentNode.layoutNode.isAttached if ((unaccountedSpace.isEmpty && currentNode.id != root.id) || (notAttachedOrPlaced && !currentNode.isFake) ) { return } val boundsInRoot = currentNode.touchBoundsInRoot.toAndroidRect() val region = Region().also { it.set(boundsInRoot) } val virtualViewId = if (currentNode.id == root.id) { AccessibilityNodeProviderCompat.HOST_VIEW_ID } else { currentNode.id } if (region.op(unaccountedSpace, region, Region.Op.INTERSECT)) { nodes[virtualViewId] = SemanticsNodeWithAdjustedBounds(currentNode, region.bounds) // Children could be drawn outside of parent, but we are using clipped bounds for // accessibility now, so let's put the children recursion inside of this if. If later // we decide to support children drawn outside of parent, we can move it out of the // if block. val children = currentNode.replacedChildren for (i in children.size - 1 downTo 0) { findAllSemanticNodesRecursive(children[i]) } unaccountedSpace.op(boundsInRoot, unaccountedSpace, Region.Op.REVERSE_DIFFERENCE) } else { if (currentNode.isFake) { val parentNode = currentNode.parent // use parent bounds for fake node val boundsForFakeNode = if (parentNode?.layoutInfo?.isPlaced == true) { parentNode.boundsInRoot } else { Rect(0f, 0f, 10f, 10f) } nodes[virtualViewId] = SemanticsNodeWithAdjustedBounds( currentNode, boundsForFakeNode.toAndroidRect() ) } else if (virtualViewId == AccessibilityNodeProviderCompat.HOST_VIEW_ID) { // Root view might have WRAP_CONTENT layout params in which case it will have zero // bounds if there is no other content with semantics. But we need to always send the // root view info as there are some other apps (e.g. Google Assistant) that depend // on accessibility info nodes[virtualViewId] = SemanticsNodeWithAdjustedBounds(currentNode, region.bounds) } } } findAllSemanticNodesRecursive(root) return nodes } /** * This class is here to ensure that the classes that use this API will get verified and can be * AOT compiled. It is expected that this class will soft-fail verification, but the classes * which use this method will pass. */ @RequiresApi(Build.VERSION_CODES.O) internal object AccessibilityNodeInfoVerificationHelperMethods { @RequiresApi(Build.VERSION_CODES.O) @DoNotInline fun setAvailableExtraData(node: AccessibilityNodeInfo, data: List<String>) { node.availableExtraData = data } } /** * These objects are used as snapshot observation scopes for the purpose of sending accessibility * scroll events whenever the scroll offset changes. There is one per scroller and their lifecycle * is the same as the scroller's lifecycle in the semantics tree. */ internal class ScrollObservationScope( val semanticsNodeId: Int, val allScopes: List<ScrollObservationScope>, var oldXValue: Float?, var oldYValue: Float?, var horizontalScrollAxisRange: ScrollAxisRange?, var verticalScrollAxisRange: ScrollAxisRange? ) : OwnerScope { override val isValid get() = allScopes.contains(this) } internal fun List<ScrollObservationScope>.findById(id: Int): ScrollObservationScope? { for (index in indices) { if (this[index].semanticsNodeId == id) { return this[index] } } return null }
apache-2.0
7e5cb4c85fd19586f8f9311d427ba2af
44.710878
106
0.599753
5.594816
false
false
false
false