repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/common/CommentsMapperTest.kt | 1 | 9561 | package org.wordpress.android.fluxc.common
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.wordpress.android.fluxc.model.CommentModel
import org.wordpress.android.fluxc.model.CommentStatus.APPROVED
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.comments.CommentsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentParent
import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentWPComRestResponse
import org.wordpress.android.fluxc.persistence.comments.CommentEntityList
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.utils.DateTimeUtilsWrapper
import java.util.Date
class CommentsMapperTest {
private val dateTimeUtilsWrapper: DateTimeUtilsWrapper = mock()
private val mapper = CommentsMapper(dateTimeUtilsWrapper)
@Test
fun `xmlrpc dto is converted to entity`() {
val comment = getDefaultComment(false).copy(
authorProfileImageUrl = null,
datePublished = "2021-07-29T21:29:27+00:00"
)
val site = SiteModel().apply {
id = comment.localSiteId
selfHostedSiteId = comment.remoteSiteId
}
val xmlRpcDto = comment.toXmlRpcDto()
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp)
whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(comment.datePublished)
val mappedEntity = mapper.commentXmlRpcDTOToEntity(xmlRpcDto, site)
assertThat(mappedEntity).isEqualTo(comment)
}
@Test
fun `xmlrpc dto list is converted to entity list`() {
val commentList = getDefaultCommentList(false).map { it.copy(id = 0, authorProfileImageUrl = null) }
val site = SiteModel().apply {
id = commentList.first().localSiteId
selfHostedSiteId = commentList.first().remoteSiteId
}
val xmlRpcDtoList = commentList.map { it.toXmlRpcDto() }
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(commentList.first().publishedTimestamp)
whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(commentList.first().datePublished)
val mappedEntityList = mapper.commentXmlRpcDTOToEntityList(xmlRpcDtoList.toTypedArray(), site)
assertThat(mappedEntityList).isEqualTo(commentList)
}
@Test
fun `dto is converted to entity`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val site = SiteModel().apply {
id = comment.localSiteId
siteId = comment.remoteSiteId
}
val commentDto = comment.toDto()
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp)
val mappedEntity = mapper.commentDtoToEntity(commentDto, site)
assertThat(mappedEntity).isEqualTo(comment)
}
@Test
fun `entity is converted to model`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val commentModel = comment.toModel()
val mappedModel = mapper.commentEntityToLegacyModel(comment)
assertModelsEqual(mappedModel, commentModel)
}
@Test
fun `model is converted to entity`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val commentModel = comment.toModel()
val mappedEntity = mapper.commentLegacyModelToEntity(commentModel)
assertThat(mappedEntity).isEqualTo(comment)
}
@Suppress("ComplexMethod")
private fun assertModelsEqual(mappedModel: CommentModel, commentModel: CommentModel): Boolean {
return mappedModel.id == commentModel.id &&
mappedModel.remoteCommentId == commentModel.remoteCommentId &&
mappedModel.remotePostId == commentModel.remotePostId &&
mappedModel.authorId == commentModel.authorId &&
mappedModel.localSiteId == commentModel.localSiteId &&
mappedModel.remoteSiteId == commentModel.remoteSiteId &&
mappedModel.authorUrl == commentModel.authorUrl &&
mappedModel.authorName == commentModel.authorName &&
mappedModel.authorEmail == commentModel.authorEmail &&
mappedModel.authorProfileImageUrl == commentModel.authorProfileImageUrl &&
mappedModel.postTitle == commentModel.postTitle &&
mappedModel.status == commentModel.status &&
mappedModel.datePublished == commentModel.datePublished &&
mappedModel.publishedTimestamp == commentModel.publishedTimestamp &&
mappedModel.content == commentModel.content &&
mappedModel.url == commentModel.url &&
mappedModel.hasParent == commentModel.hasParent &&
mappedModel.parentId == commentModel.parentId &&
mappedModel.iLike == commentModel.iLike
}
private fun CommentEntity.toDto(): CommentWPComRestResponse {
val entity = this
return CommentWPComRestResponse().apply {
ID = entity.remoteCommentId
URL = entity.url
author = Author().apply {
ID = entity.authorId
URL = entity.authorUrl
avatar_URL = entity.authorProfileImageUrl
email = entity.authorEmail
name = entity.authorName
}
content = entity.content
date = entity.datePublished
i_like = entity.iLike
parent = CommentParent().apply {
ID = entity.parentId
}
post = Post().apply {
type = "post"
title = entity.postTitle
link = "https://public-api.wordpress.com/rest/v1.1/sites/185464053/posts/85"
ID = entity.remotePostId
}
status = entity.status
}
}
private fun CommentEntity.toModel(): CommentModel {
val entity = this
return CommentModel().apply {
id = entity.id.toInt()
remoteCommentId = entity.remoteCommentId
remotePostId = entity.remotePostId
authorId = entity.authorId
localSiteId = entity.localSiteId
remoteSiteId = entity.remoteSiteId
authorUrl = entity.authorUrl
authorName = entity.authorName
authorEmail = entity.authorEmail
authorProfileImageUrl = entity.authorProfileImageUrl
postTitle = entity.postTitle
status = entity.status
datePublished = entity.datePublished
publishedTimestamp = entity.publishedTimestamp
content = entity.content
url = entity.authorProfileImageUrl
hasParent = entity.hasParent
parentId = entity.parentId
iLike = entity.iLike
}
}
private fun CommentEntity.toXmlRpcDto(): HashMap<*, *> {
return hashMapOf<String, Any?>(
"parent" to this.parentId.toString(),
"post_title" to this.postTitle,
"author" to this.authorName,
"link" to this.url,
"date_created_gmt" to Date(),
"comment_id" to this.remoteCommentId.toString(),
"content" to this.content,
"author_url" to this.authorUrl,
"post_id" to this.remotePostId,
"user_id" to this.authorId,
"author_email" to this.authorEmail,
"status" to this.status
)
}
private fun getDefaultComment(allowNulls: Boolean): CommentEntity {
return CommentEntity(
id = 0,
remoteCommentId = 10,
remotePostId = 100,
authorId = 44,
localSiteId = 10_000,
remoteSiteId = 100_000,
authorUrl = if (allowNulls) null else "https://test-debug-site.wordpress.com",
authorName = if (allowNulls) null else "authorname",
authorEmail = if (allowNulls) null else "[email protected]",
authorProfileImageUrl = if (allowNulls) null else "https://gravatar.com/avatar/111222333",
postTitle = if (allowNulls) null else "again",
status = APPROVED.toString(),
datePublished = if (allowNulls) null else "2021-05-12T15:10:40+02:00",
publishedTimestamp = 1_000_000,
content = if (allowNulls) null else "content example",
url = if (allowNulls) null else "https://test-debug-site.wordpress.com/2021/02/25/again/#comment-137",
hasParent = true,
parentId = 1_000L,
iLike = false
)
}
private fun getDefaultCommentList(allowNulls: Boolean): CommentEntityList {
val comment = getDefaultComment(allowNulls)
return listOf(
comment.copy(id = 1, remoteCommentId = 10, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 2, remoteCommentId = 20, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 3, remoteCommentId = 30, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 4, remoteCommentId = 40, datePublished = "2021-07-24T00:51:43+02:00")
)
}
}
| gpl-2.0 | bbc7fc1f396cad8b31ed82cb5f45815e | 42.459091 | 118 | 0.643134 | 4.98748 | false | false | false | false |
ursjoss/scipamato | public/public-web/src/test/kotlin/ch/difty/scipamato/publ/ScipamatoPublicApplicationTest.kt | 2 | 1902 | package ch.difty.scipamato.publ
import ch.difty.scipamato.common.logger
import ch.difty.scipamato.publ.config.ScipamatoPublicProperties
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Test
private val log = logger()
class ScipamatoPublicApplicationTest {
@Test
fun withCommercialFontEnabled_willOutputLog() {
val properties = mockk<ScipamatoPublicProperties> {
every { isCommercialFontPresent } returns true
every { isResponsiveIframeSupportEnabled } returns false
}
val app = ScipamatoPublicApplication(properties)
log.info { "We should see single log about commercial font being enabled" }
app.logSpecialConfiguration()
// visually assert the respective log is on console (no automatic assertion)
log.info { "----" }
}
@Test
fun withPymEnabled_willOutputLog() {
val properties = mockk<ScipamatoPublicProperties> {
every { isCommercialFontPresent } returns false
every { isResponsiveIframeSupportEnabled } returns true
}
val app = ScipamatoPublicApplication(properties)
log.info("We should see single log about pym being enabled")
app.logSpecialConfiguration()
// visually assert the respective log is on console (no automatic assertion)
log.info("----")
}
@Test
fun withPropertiesDisabled_willNotOutputLogs() {
val properties = mockk<ScipamatoPublicProperties> {
every { isCommercialFontPresent } returns false
every { isResponsiveIframeSupportEnabled } returns false
}
val app = ScipamatoPublicApplication(properties)
log.info { "We should see no logs (about commercial fonts or pym)" }
app.logSpecialConfiguration()
// visually assert no logs are on console
log.info { "----" }
}
}
| bsd-3-clause | e193b4a4776f1377a7164434ec782ecd | 30.7 | 84 | 0.677182 | 5.045093 | false | true | false | false |
hbb20/CountryCodePickerProject | app/src/main/java/in/hbb20/countrycodepickerproject/CustomMasterFragment.kt | 1 | 2401 | package `in`.hbb20.countrycodepickerproject
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.hbb20.CountryCodePicker
/**
* A simple [Fragment] subclass.
* create an instance of this fragment.
*/
class CustomMasterFragment: Fragment() {
private lateinit var editTextCountryCustomMaster: EditText
private lateinit var buttonSetCustomMaster: Button
private lateinit var ccp: CountryCodePicker
private lateinit var buttonNext: Button
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_custom_master_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
assignViews()
editTextWatcher()
addClickListeners()
}
private fun addClickListeners() {
buttonSetCustomMaster.setOnClickListener {
val customMasterCountries: String
try {
customMasterCountries = editTextCountryCustomMaster.text.toString()
ccp.setCustomMasterCountries(customMasterCountries)
Toast.makeText(activity, "Master list has been changed. Tap on ccp to see the changes.", Toast.LENGTH_LONG).show()
} catch (ex: Exception) {
}
}
buttonNext.setOnClickListener { (activity as ExampleActivity).viewPager.currentItem = (activity as ExampleActivity).viewPager.currentItem + 1 }
}
private fun editTextWatcher() {
editTextCountryCustomMaster.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
buttonSetCustomMaster.text = "set '$s' as Custom Master List."
}
override fun afterTextChanged(s: Editable) {
}
})
}
private fun assignViews() {
editTextCountryCustomMaster = view!!.findViewById(R.id.editText_countryPreference)
ccp = view!!.findViewById(R.id.ccp)
buttonSetCustomMaster = view!!.findViewById(R.id.button_setCustomMaster)
buttonNext = view!!.findViewById(R.id.button_next)
}
}
| apache-2.0 | 5936747b4268b1ced7b1aabca298b3c8 | 31.445946 | 145 | 0.774677 | 4.076401 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/MainApplication.kt | 1 | 10725 | package com.lasthopesoftware.bluewater
import android.annotation.SuppressLint
import android.app.Application
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Environment
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.Configuration
import androidx.work.WorkManager
import ch.qos.logback.classic.AsyncAppender
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.android.LogcatAppender
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy
import ch.qos.logback.core.util.StatusPrinter
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.UpdatePlayStatsOnCompleteRegistration
import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.request.read.StorageReadPermissionsRequestNotificationBuilder
import com.lasthopesoftware.bluewater.client.browsing.library.request.read.StorageReadPermissionsRequestedBroadcaster
import com.lasthopesoftware.bluewater.client.browsing.library.request.write.StorageWritePermissionsRequestNotificationBuilder
import com.lasthopesoftware.bluewater.client.browsing.library.request.write.StorageWritePermissionsRequestedBroadcaster
import com.lasthopesoftware.bluewater.client.connection.receivers.SessionConnectionRegistrationsMaintainer
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionSettingsChangeReceiver
import com.lasthopesoftware.bluewater.client.connection.session.ConnectionSessionManager
import com.lasthopesoftware.bluewater.client.connection.session.ConnectionSessionSettingsChangeReceiver
import com.lasthopesoftware.bluewater.client.connection.settings.changes.ObservableConnectionSettingsLibraryStorage
import com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.pebble.PebbleFileChangedNotificationRegistration
import com.lasthopesoftware.bluewater.client.playback.service.receivers.scrobble.PlaybackFileStartedScrobblerRegistration
import com.lasthopesoftware.bluewater.client.playback.service.receivers.scrobble.PlaybackFileStoppedScrobblerRegistration
import com.lasthopesoftware.bluewater.client.stored.library.items.files.StoredFileAccess
import com.lasthopesoftware.bluewater.client.stored.library.items.files.system.uri.MediaFileUriProvider
import com.lasthopesoftware.bluewater.client.stored.sync.SyncScheduler
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.exceptions.LoggerUncaughtExceptionHandler
import com.lasthopesoftware.compilation.DebugFlag
import com.namehillsoftware.handoff.promises.Promise
import org.slf4j.LoggerFactory
import java.io.File
open class MainApplication : Application() {
companion object {
private var isWorkManagerInitialized = false
}
private val notificationManagerLazy by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }
private val storageReadPermissionsRequestNotificationBuilderLazy by lazy { StorageReadPermissionsRequestNotificationBuilder(this) }
private val storageWritePermissionsRequestNotificationBuilderLazy by lazy { StorageWritePermissionsRequestNotificationBuilder(this) }
private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) }
private val applicationSettings by lazy { getApplicationSettingsRepository() }
@SuppressLint("DefaultLocale")
override fun onCreate() {
super.onCreate()
initializeLogging()
Thread.setDefaultUncaughtExceptionHandler(LoggerUncaughtExceptionHandler)
Promise.Rejections.setUnhandledRejectionsReceiver(LoggerUncaughtExceptionHandler)
registerAppBroadcastReceivers()
if (!isWorkManagerInitialized) {
WorkManager.initialize(this, Configuration.Builder().build())
isWorkManagerInitialized = true
}
SyncScheduler
.promiseIsScheduled(this)
.then { isScheduled -> if (!isScheduled) SyncScheduler.scheduleSync(this) }
}
private fun registerAppBroadcastReceivers() {
messageBus.registerReceiver(object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val libraryId = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundFileKey, -1)
if (libraryId < 0) return
val fileKey = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundFileKey, -1)
if (fileKey == -1) return
val mediaFileId = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundMediaId, -1)
if (mediaFileId == -1) return
val mediaFilePath = intent.getStringExtra(MediaFileUriProvider.mediaFileFoundPath)
if (mediaFilePath.isNullOrEmpty()) return
LibraryRepository(context)
.getLibrary(LibraryId(libraryId))
.then { library ->
if (library != null) {
val storedFileAccess = StoredFileAccess(
context
)
storedFileAccess.addMediaFile(library, ServiceFile(fileKey), mediaFileId, mediaFilePath)
}
}
}
}, IntentFilter(MediaFileUriProvider.mediaFileFoundEvent))
messageBus.registerReceiver(object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val libraryId = intent.getIntExtra(StorageReadPermissionsRequestedBroadcaster.ReadPermissionsLibraryId, -1)
if (libraryId < 0) return
notificationManagerLazy.notify(
336,
storageReadPermissionsRequestNotificationBuilderLazy
.buildReadPermissionsRequestNotification(libraryId))
}
}, IntentFilter(StorageReadPermissionsRequestedBroadcaster.ReadPermissionsNeeded))
messageBus.registerReceiver(object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val libraryId = intent.getIntExtra(StorageWritePermissionsRequestedBroadcaster.WritePermissionsLibraryId, -1)
if (libraryId < 0) return
notificationManagerLazy.notify(
396,
storageWritePermissionsRequestNotificationBuilderLazy
.buildWritePermissionsRequestNotification(libraryId))
}
}, IntentFilter(StorageWritePermissionsRequestedBroadcaster.WritePermissionsNeeded))
messageBus.registerReceiver(
ConnectionSessionSettingsChangeReceiver(ConnectionSessionManager.get(this)),
IntentFilter(ObservableConnectionSettingsLibraryStorage.connectionSettingsUpdated)
)
messageBus.registerReceiver(
SelectedConnectionSettingsChangeReceiver(
SelectedBrowserLibraryIdentifierProvider(applicationSettings),
messageBus),
IntentFilter(ObservableConnectionSettingsLibraryStorage.connectionSettingsUpdated)
)
val connectionDependentReceiverRegistrations = listOf(
UpdatePlayStatsOnCompleteRegistration(),
PlaybackFileStartedScrobblerRegistration(),
PlaybackFileStoppedScrobblerRegistration(),
PebbleFileChangedNotificationRegistration())
messageBus.registerReceiver(
SessionConnectionRegistrationsMaintainer(messageBus, connectionDependentReceiverRegistrations),
IntentFilter(SelectedConnection.buildSessionBroadcast))
}
private fun initializeLogging() {
val lc = LoggerFactory.getILoggerFactory() as LoggerContext
lc.reset()
// setup LogcatAppender
val logcatEncoder = PatternLayoutEncoder()
logcatEncoder.context = lc
logcatEncoder.pattern = "[%thread] %msg%n"
logcatEncoder.start()
val logcatAppender = LogcatAppender()
logcatAppender.context = lc
logcatAppender.encoder = logcatEncoder
logcatAppender.start()
// add the newly created appenders to the root logger;
// qualify Logger to disambiguate from org.slf4j.Logger
val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger
rootLogger.level = Level.WARN
rootLogger.addAppender(logcatAppender)
if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && getExternalFilesDir(null) != null) {
val asyncAppender = AsyncAppender()
asyncAppender.context = lc
asyncAppender.name = "ASYNC"
val externalFilesDir = getExternalFilesDir(null)
if (externalFilesDir != null) {
val logDir = File(externalFilesDir.path + File.separator + "logs")
if (!logDir.exists()) logDir.mkdirs()
val filePle = PatternLayoutEncoder()
filePle.pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
filePle.context = lc
filePle.start()
val rollingFileAppender = RollingFileAppender<ILoggingEvent>()
rollingFileAppender.lazy = true
rollingFileAppender.isAppend = true
rollingFileAppender.context = lc
rollingFileAppender.encoder = filePle
val rollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>()
rollingPolicy.fileNamePattern = File(logDir, "%d{yyyy-MM-dd}.log").absolutePath
rollingPolicy.maxHistory = 30
rollingPolicy.setParent(rollingFileAppender) // parent and context required!
rollingPolicy.context = lc
rollingPolicy.start()
rollingFileAppender.rollingPolicy = rollingPolicy
rollingFileAppender.start()
asyncAppender.addAppender(rollingFileAppender)
}
// UNCOMMENT TO TWEAK OPTIONAL SETTINGS
// excluding caller data (used for stack traces) improves appender's performance
asyncAppender.isIncludeCallerData = !DebugFlag.isDebugCompilation
asyncAppender.start()
rootLogger.addAppender(asyncAppender)
StatusPrinter.print(lc)
}
val logger = LoggerFactory.getLogger(javaClass)
logger.info("Uncaught exceptions logging to custom uncaught exception handler.")
if (!DebugFlag.isDebugCompilation) return
rootLogger.level = Level.DEBUG
logger.info("DEBUG_MODE active")
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build())
StrictMode.setVmPolicy(VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.build())
}
}
| lgpl-3.0 | 9b8de18bc842cb273a7899f1e15a1cbe | 44.444915 | 144 | 0.821352 | 4.828906 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/ui/browser/MediaScrapingBrowserTvFragment.kt | 1 | 6828 | /*
* ************************************************************************
* MoviepediaBrowserTvFragment.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.television.ui.browser
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.moviepedia.database.models.MediaMetadataType
import org.videolan.moviepedia.database.models.MediaMetadataWithImages
import org.videolan.moviepedia.provider.MediaScrapingProvider
import org.videolan.resources.CATEGORY
import org.videolan.resources.CATEGORY_VIDEOS
import org.videolan.resources.HEADER_MOVIES
import org.videolan.resources.HEADER_TV_SHOW
import org.videolan.resources.util.getFromMl
import org.videolan.television.ui.*
import org.videolan.television.viewmodel.MediaScrapingBrowserViewModel
import org.videolan.television.viewmodel.getMoviepediaBrowserModel
import org.videolan.vlc.R
import org.videolan.vlc.gui.view.EmptyLoadingState
import org.videolan.vlc.interfaces.IEventsHandler
import java.util.*
@UseExperimental(ObsoleteCoroutinesApi::class)
@ExperimentalCoroutinesApi
class MediaScrapingBrowserTvFragment : BaseBrowserTvFragment<MediaMetadataWithImages>() {
override fun provideAdapter(eventsHandler: IEventsHandler<MediaMetadataWithImages>, itemSize: Int): TvItemAdapter {
return MediaScrapingTvItemAdapter((viewModel as MediaScrapingBrowserViewModel).category, this, itemSize)
}
override fun getDisplayPrefId() = "display_tv_moviepedia_${(viewModel as MediaScrapingBrowserViewModel).category}"
override lateinit var adapter: TvItemAdapter
override fun getTitle() = when ((viewModel as MediaScrapingBrowserViewModel).category) {
HEADER_TV_SHOW -> getString(R.string.header_tvshows)
HEADER_MOVIES -> getString(R.string.header_movies)
else -> getString(R.string.video)
}
override fun getCategory(): Long = (viewModel as MediaScrapingBrowserViewModel).category
override fun getColumnNumber() = when ((viewModel as MediaScrapingBrowserViewModel).category) {
CATEGORY_VIDEOS -> resources.getInteger(R.integer.tv_videos_col_count)
else -> resources.getInteger(R.integer.tv_songs_col_count)
}
companion object {
fun newInstance(type: Long) =
MediaScrapingBrowserTvFragment().apply {
arguments = Bundle().apply {
this.putLong(CATEGORY, type)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = getMoviepediaBrowserModel(arguments?.getLong(CATEGORY, HEADER_MOVIES)
?: HEADER_MOVIES)
(viewModel.provider as MediaScrapingProvider).pagedList.observe(this, Observer { items ->
binding.emptyLoading.post {
submitList(items)
binding.emptyLoading.state = if (items.isEmpty()) EmptyLoadingState.EMPTY else EmptyLoadingState.NONE
//headers
val nbColumns = if ((viewModel as MediaScrapingBrowserViewModel).sort == Medialibrary.SORT_ALPHA || (viewModel as MediaScrapingBrowserViewModel).sort == Medialibrary.SORT_DEFAULT) 9 else 1
binding.headerList.layoutManager = GridLayoutManager(requireActivity(), nbColumns)
headerAdapter.sortType = (viewModel as MediaScrapingBrowserViewModel).sort
val headerItems = ArrayList<String>()
viewModel.provider.headers.run {
for (i in 0 until size()) {
headerItems.add(valueAt(i))
}
}
headerAdapter.items = headerItems
headerAdapter.notifyDataSetChanged()
}
})
(viewModel.provider as MediaScrapingProvider).loading.observe(this, Observer {
if (it) binding.emptyLoading.state = EmptyLoadingState.LOADING
})
(viewModel.provider as MediaScrapingProvider).liveHeaders.observe(this, Observer {
headerAdapter.notifyDataSetChanged()
})
}
override fun onClick(v: View, position: Int, item: MediaMetadataWithImages) {
when (item.metadata.type) {
MediaMetadataType.TV_SHOW -> {
val intent = Intent(activity, MediaScrapingTvshowDetailsActivity::class.java)
intent.putExtra(TV_SHOW_ID, item.metadata.moviepediaId)
requireActivity().startActivity(intent)
}
else -> {
item.metadata.mlId?.let {
lifecycleScope.launchWhenStarted {
val media = requireActivity().getFromMl { getMedia(it) }
TvUtil.showMediaDetail(requireActivity(), media)
}
}
}
}
}
override fun onLongClick(v: View, position: Int, item: MediaMetadataWithImages): Boolean {
when (item.metadata.type) {
MediaMetadataType.TV_SHOW -> {
val intent = Intent(activity, MediaScrapingTvshowDetailsActivity::class.java)
intent.putExtra(TV_SHOW_ID, item.metadata.moviepediaId)
requireActivity().startActivity(intent)
}
else -> {
item.metadata.mlId?.let {
lifecycleScope.launchWhenStarted {
val media = requireActivity().getFromMl { getMedia(it) }
TvUtil.showMediaDetail(requireActivity(), media)
}
}
}
}
return true
}
}
| gpl-2.0 | 9ded9b155834dd9cca65c256740b9b32 | 42.484076 | 204 | 0.6549 | 5.375591 | false | false | false | false |
mastrgamr/rettiwt | app/src/main/java/net/mastrgamr/rettiwt/views/activities/LoginActivity.kt | 1 | 2747 | package net.mastrgamr.rettiwt.views.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.twitter.sdk.android.core.Callback
import com.twitter.sdk.android.core.Result
import com.twitter.sdk.android.core.TwitterException
import com.twitter.sdk.android.core.TwitterSession
import com.twitter.sdk.android.core.identity.TwitterLoginButton
import es.dmoral.prefs.Prefs
import net.mastrgamr.rettiwt.R
/*
* Documentation: https://docs.fabric.io/android/twitter/log-in-with-twitter.html
*/
class LoginActivity : Activity() {
private val TAG = javaClass.simpleName
private var logBtn: TwitterLoginButton? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//if an access token is defined in the preferences
//skip the login flow altogether and start the main app
if(Prefs.with(this).read("access_token").isNotEmpty()){
Log.d(TAG, "Token found, start Main app.")
startActivity(Intent(this, MainActivity::class.java))
finish()
}
logBtn = findViewById(R.id.login_button) as TwitterLoginButton
logBtn!!.callback = object : Callback<TwitterSession>() {
override fun success(result: Result<TwitterSession>) {
// Do something with result, which provides a TwitterSession for making API calls
Log.d(TAG, result.data.userName)
// Write the tokens to Preferences
// WARNING: Usually not too safe, but this is an open source app. You know what you signed up for.
Prefs.with(this@LoginActivity).write("access_token", result.data.authToken.token)
Prefs.with(this@LoginActivity).write("secret", result.data.authToken.secret)
}
override fun failure(exception: TwitterException) { }
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Pass the activity result to the login button.
logBtn!!.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "Result Code: " + resultCode)
if(resultCode == -1) { //on successful login -- P.S. WTF is the TwitterAPI Enum code for this!?
startActivity(Intent(this, MainActivity::class.java))
finish()
}
// Example of static Auth Session
// val session = Twitter.getSessionManager().activeSession
// val authToken = session.authToken
// val token = authToken.token
// val secret = authToken.secret
}
}
| apache-2.0 | 784742f151082e8ce8aed14d6fde51e9 | 38.811594 | 114 | 0.675646 | 4.38118 | false | false | false | false |
pgutkowski/KGraphQL | src/main/kotlin/com/github/pgutkowski/kgraphql/request/Variables.kt | 1 | 3031 | package com.github.pgutkowski.kgraphql.request
import com.github.pgutkowski.kgraphql.ExecutionException
import com.github.pgutkowski.kgraphql.RequestException
import com.github.pgutkowski.kgraphql.getIterableElementType
import com.github.pgutkowski.kgraphql.isIterable
import com.github.pgutkowski.kgraphql.schema.structure2.LookupSchema
import kotlin.reflect.KClass
import kotlin.reflect.KType
@Suppress("UNCHECKED_CAST")
data class Variables(
private val typeDefinitionProvider: LookupSchema,
private val variablesJson: VariablesJson,
private val variables: List<OperationVariable>?
) {
/**
* map and return object of requested class
*/
fun <T : Any> get(kClass: KClass<T>, kType: KType, key: String, transform: (value: String) -> Any?): T? {
val variable = variables?.find { key == it.name }
?: throw IllegalArgumentException("Variable '$key' was not declared for this operation")
val isIterable = kClass.isIterable()
validateVariable(typeDefinitionProvider.typeReference(kType), variable)
var value = variablesJson.get(kClass, kType, key.substring(1))
if(value == null && variable.defaultValue != null){
value = transformDefaultValue(transform, variable.defaultValue, kClass)
}
value?.let {
if (isIterable && kType.getIterableElementType()?.isMarkedNullable == false) {
for (element in value as Iterable<*>) {
if (element == null) {
throw RequestException(
"Invalid argument value $value from variable $key, expected list with non null arguments"
)
}
}
}
}
return value
}
private fun <T : Any> transformDefaultValue(transform: (value: String) -> Any?, defaultValue: String, kClass: KClass<T>): T? {
val transformedDefaultValue = transform.invoke(defaultValue)
when {
transformedDefaultValue == null -> return null
kClass.isInstance(transformedDefaultValue) -> return transformedDefaultValue as T?
else -> {
throw ExecutionException("Invalid transform function returned ")
}
}
}
fun validateVariable(expectedType: TypeReference, variable: OperationVariable){
val variableType = variable.type
val invalidName = expectedType.name != variableType.name
val invalidIsList = expectedType.isList != variableType.isList
val invalidNullability = !expectedType.isNullable && variableType.isNullable && variable.defaultValue == null
val invalidElementNullability = !expectedType.isElementNullable && variableType.isElementNullable
if(invalidName || invalidIsList || invalidNullability || invalidElementNullability){
throw RequestException("Invalid variable ${variable.name} argument type $variableType, expected $expectedType")
}
}
} | mit | 29912a610da769f158275ef1f3bb57c4 | 41.704225 | 130 | 0.661168 | 5.308231 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/examples/kotlin/TestHopfield.kt | 1 | 5241 | /* The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.examples.kotlin
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.Hopfield
import org.neuroph.nnet.learning.BackPropagation
import java.io.*
import java.util.*
object TestHopfield {
@JvmStatic
var inputSize = 8
@JvmStatic
var outputSize = 1
@JvmStatic
var network: NeuralNetwork? = null
@JvmStatic
var trainingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var testingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var layers = arrayOf(8, 8, 1)
@JvmStatic
fun loadNetwork() {
network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TestHopfield.nnet")
}
@JvmStatic
fun trainNetwork() {
val list = ArrayList<Int>()
for (layer in layers) {
list.add(layer)
}
network = Hopfield(inputSize + outputSize)
trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize)
trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val learningRule = BackPropagation()
(network as NeuralNetwork).learningRule = learningRule
(network as NeuralNetwork).learn(trainingSet)
(network as NeuralNetwork).save("D:/GitHub/Neuroph-Intellij-Plugin/TestHopfield.nnet")
}
@JvmStatic
fun testNetwork() {
var input = ""
val fromKeyboard = BufferedReader(InputStreamReader(System.`in`))
val testValues = ArrayList<Double>()
var testValuesDouble: DoubleArray
do {
try {
println("Enter test values or \"\": ")
input = fromKeyboard.readLine()
if (input == "") {
break
}
input = input.replace(" ", "")
val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
testValues.clear()
for (`val` in stringVals) {
testValues.add(java.lang.Double.parseDouble(`val`))
}
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
} catch (nfe: NumberFormatException) {
nfe.printStackTrace(System.err)
}
testValuesDouble = DoubleArray(testValues.size)
for (t in testValuesDouble.indices) {
testValuesDouble[t] = testValues[t].toDouble()
}
network?.setInput(*testValuesDouble)
network?.calculate()
} while (input != "")
}
@JvmStatic
fun testNetworkAuto(setPath: String) {
var total: Double = 0.0
val list = ArrayList<Int>()
val outputLine = ArrayList<String>()
for (layer in layers) {
list.add(layer)
}
testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val count: Int = testingSet?.elements()?.size!!
var averageDeviance = 0.0
var resultString = ""
try {
val file = File("Results " + setPath)
val fw = FileWriter(file)
val bw = BufferedWriter(fw)
for (i in 0..testingSet?.elements()?.size!! - 1) {
val expected: Double
val calculated: Double
network?.setInput(*testingSet?.elementAt(i)!!.input)
network?.calculate()
calculated = network?.output!![0]
expected = testingSet?.elementAt(i)?.idealArray!![0]
println("Calculated Output: " + calculated)
println("Expected Output: " + expected)
println("Deviance: " + (calculated - expected))
averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected))
total += network?.output!![0]
resultString = ""
for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) {
resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", "
}
for (t in 0..network?.output!!.size - 1) {
resultString += network?.output!![t].toString() + ", "
}
resultString = resultString.substring(0, resultString.length - 2)
resultString += ""
bw.write(resultString)
bw.flush()
println()
println("Average: " + (total / count).toString())
println("Average Deviance % : " + (averageDeviance / count * 100).toString())
bw.flush()
bw.close()
}
} catch (ex: IOException) {
ex.printStackTrace()
}
}
}
| mit | 51876edc7aa5a26a6852da2992e4ae75 | 32.382166 | 174 | 0.711124 | 3.908277 | false | true | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/labels/Label.kt | 1 | 1010 | package net.nemerosa.ontrack.model.labels
import net.nemerosa.ontrack.common.toRGBColor
open class Label(
val id: Int,
val category: String?,
val name: String,
val description: String?,
val color: String,
val computedBy: LabelProviderDescription?
) {
/**
* Foreground colour
*/
val foregroundColor: String get() = color.toRGBColor().toBlackOrWhite().toString()
/**
* Representation
*/
fun getDisplay() = if (category != null) {
"$category:$name"
} else {
name
}
companion object {
fun categoryAndNameFromDisplay(display: String): Pair<String?, String> {
val index = display.indexOf(':')
return if (index >= 0) {
val category = display.substring(0, index).trim().takeIf { it.isNotBlank() }
val name = display.substring(index + 1).trim()
category to name
} else {
null to display
}
}
}
}
| mit | 7f1173dc47a4f2d158a0498e3e1a851f | 24.897436 | 92 | 0.562376 | 4.469027 | false | false | false | false |
Kotlin/kotlinx-cli | core/commonMain/src/ArgParser.kt | 1 | 28747 | /*
* Copyright 2010-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 kotlinx.cli
import kotlin.reflect.KProperty
internal expect fun exitProcess(status: Int): Nothing
/**
* Queue of arguments descriptors.
* Arguments can have several values, so one descriptor can be returned several times.
*/
internal class ArgumentsQueue(argumentsDescriptors: List<ArgDescriptor<*, *>>) {
/**
* Map of arguments descriptors and their current usage number.
*/
private val argumentsUsageNumber = linkedMapOf(*argumentsDescriptors.map { it to 0 }.toTypedArray())
/**
* Get next descriptor from queue.
*/
fun pop(): String? {
if (argumentsUsageNumber.isEmpty())
return null
val (currentDescriptor, usageNumber) = argumentsUsageNumber.iterator().next()
currentDescriptor.number?.let {
// Parse all arguments for current argument description.
if (usageNumber + 1 >= currentDescriptor.number) {
// All needed arguments were provided.
argumentsUsageNumber.remove(currentDescriptor)
} else {
argumentsUsageNumber[currentDescriptor] = usageNumber + 1
}
}
return currentDescriptor.fullName
}
}
/**
* A property delegate that provides access to the argument/option value.
*/
interface ArgumentValueDelegate<T> {
/**
* The value of an option or argument parsed from command line.
*
* Accessing this value before [ArgParser.parse] method is called will result in an exception.
*
* @see CLIEntity.value
*/
var value: T
/** Provides the value for the delegated property getter. Returns the [value] property.
* @throws IllegalStateException in case of accessing the value before [ArgParser.parse] method is called.
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
/** Sets the [value] to the [ArgumentValueDelegate.value] property from the delegated property setter.
* This operation is possible only after command line arguments were parsed with [ArgParser.parse]
* @throws IllegalStateException in case of resetting value before command line arguments are parsed.
*/
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
/**
* Abstract base class for subcommands.
*/
@ExperimentalCli
abstract class Subcommand(val name: String, val actionDescription: String): ArgParser(name) {
/**
* Execute action if subcommand was provided.
*/
abstract fun execute()
val helpMessage: String
get() = " $name - $actionDescription\n"
}
/**
* Argument parsing result.
* Contains name of subcommand which was called.
*
* @property commandName name of command which was called.
*/
class ArgParserResult(val commandName: String)
/**
* Arguments parser.
*
* @property programName the name of the current program.
* @property useDefaultHelpShortName specifies whether to register "-h" option for printing the usage information.
* @property prefixStyle the style of option prefixing.
* @property skipExtraArguments specifies whether the extra unmatched arguments in a command line string
* can be skipped without producing an error message.
*/
open class ArgParser(
val programName: String,
var useDefaultHelpShortName: Boolean = true,
var prefixStyle: OptionPrefixStyle = OptionPrefixStyle.LINUX,
var skipExtraArguments: Boolean = false,
var strictSubcommandOptionsOrder: Boolean = false
) {
/**
* Map of options: key - full name of option, value - pair of descriptor and parsed values.
*/
private val options = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Map of arguments: key - full name of argument, value - pair of descriptor and parsed values.
*/
private val arguments = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Map with declared options.
*/
private val declaredOptions = mutableListOf<CLIEntityWrapper>()
/**
* Map with declared arguments.
*/
private val declaredArguments = mutableListOf<CLIEntityWrapper>()
/**
* State of parser. Stores last parsing result or null.
*/
private var parsingState: ArgParserResult? = null
/**
* Map of subcommands.
*/
@OptIn(ExperimentalCli::class)
protected val subcommands = mutableMapOf<String, Subcommand>()
/**
* Mapping for short options names for quick search.
*/
private val shortNames = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Used prefix form for full option form.
*/
protected val optionFullFormPrefix = if (prefixStyle == OptionPrefixStyle.JVM) "-" else "--"
/**
* Used prefix form for short option form.
*/
protected val optionShortFromPrefix = "-"
/**
* Name with all commands that should be executed.
*/
protected val fullCommandName = mutableListOf(programName)
/**
* Flag to recognize if CLI entities can be treated as options.
*/
protected var treatAsOption = true
/**
* Arguments which should be parsed with subcommands.
*/
private val subcommandsArguments = mutableListOf<String>()
/**
* Options which should be parsed with subcommands.
*/
private val subcommandsOptions = mutableListOf<String>()
/**
* Subcommand used in commmand line arguments.
*/
private var usedSubcommand: Subcommand? = null
internal var outputAndTerminate: (message: String, exitCode: Int) -> Nothing = { message, exitCode ->
println(message)
exitProcess(exitCode)
}
/**
* The way an option/argument has got its value.
*/
enum class ValueOrigin {
/* The value was parsed from command line arguments. */
SET_BY_USER,
/* The value was missing in command line, therefore the default value was used. */
SET_DEFAULT_VALUE,
/* The value is not initialized by command line values or by default values. */
UNSET,
/* The value was redefined after parsing manually (usually with the property setter). */
REDEFINED,
/* The value is undefined, because parsing wasn't called. */
UNDEFINED
}
/**
* The style of option prefixing.
*/
enum class OptionPrefixStyle {
/* Linux style: the full name of an option is prefixed with two hyphens "--" and the short name — with one "-". */
LINUX,
/* JVM style: both full and short names are prefixed with one hyphen "-". */
JVM,
/* GNU style: the full name of an option is prefixed with two hyphens "--" and "=" between options and value
and the short name — with one "-".
Detailed information https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
*/
GNU
}
@Deprecated("OPTION_PREFIX_STYLE is deprecated. Please, use OptionPrefixStyle.",
ReplaceWith("OptionPrefixStyle", "kotlinx.cli.OptionPrefixStyle"))
@Suppress("TOPLEVEL_TYPEALIASES_ONLY")
typealias OPTION_PREFIX_STYLE = OptionPrefixStyle
/**
* Declares a named option and returns an object which can be used to access the option value
* after all arguments are parsed or to delegate a property for accessing the option value to.
*
* By default, the option supports only a single value, is optional, and has no default value,
* therefore its value's type is `T?`.
*
* You can alter the option properties by chaining extensions for the option type on the returned object:
* - [AbstractSingleOption.default] to provide a default value that is used when the option is not specified;
* - [SingleNullableOption.required] to make the option non-optional;
* - [AbstractSingleOption.delimiter] to allow specifying multiple values in one command line argument with a delimiter;
* - [AbstractSingleOption.multiple] to allow specifying the option several times.
*
* @param type The type describing how to parse an option value from a string,
* an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice].
* @param fullName the full name of the option, can be omitted if the option name is inferred
* from the name of a property delegated to this option.
* @param shortName the short name of the option, `null` if the option cannot be specified in a short form.
* @param description the description of the option used when rendering the usage information.
* @param deprecatedWarning the deprecation message for the option.
* Specifying anything except `null` makes this option deprecated. The message is rendered in a help message and
* issued as a warning when the option is encountered when parsing command line arguments.
*/
fun <T : Any> option(
type: ArgType<T>,
fullName: String? = null,
shortName: String ? = null,
description: String? = null,
deprecatedWarning: String? = null
): SingleNullableOption<T> {
if (prefixStyle == OptionPrefixStyle.GNU && shortName != null)
require(shortName.length == 1) {
"""
GNU standard for options allow to use short form which consists of one character.
For more information, please, see https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
""".trimIndent()
}
val option = SingleNullableOption(OptionDescriptor(optionFullFormPrefix, optionShortFromPrefix, type,
fullName, shortName, description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper())
option.owner.entity = option
declaredOptions.add(option.owner)
return option
}
/**
* Check usage of required property for arguments.
* Make sense only for several last arguments.
*/
private fun inspectRequiredAndDefaultUsage() {
var previousArgument: ParsingValue<*, *>? = null
arguments.forEach { (_, currentArgument) ->
previousArgument?.let { previous ->
// Previous argument has default value.
if (previous.descriptor.defaultValueSet) {
if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) {
error("Default value of argument ${previous.descriptor.fullName} will be unused, " +
"because next argument ${currentArgument.descriptor.fullName} is always required and has no default value.")
}
}
// Previous argument is optional.
if (!previous.descriptor.required) {
if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) {
error("Argument ${previous.descriptor.fullName} will be always required, " +
"because next argument ${currentArgument.descriptor.fullName} is always required.")
}
}
}
previousArgument = currentArgument
}
}
/**
* Declares an argument and returns an object which can be used to access the argument value
* after all arguments are parsed or to delegate a property for accessing the argument value to.
*
* By default, the argument supports only a single value, is required, and has no default value,
* therefore its value's type is `T`.
*
* You can alter the argument properties by chaining extensions for the argument type on the returned object:
* - [AbstractSingleArgument.default] to provide a default value that is used when the argument is not specified;
* - [SingleArgument.optional] to allow omitting the argument;
* - [AbstractSingleArgument.multiple] to require the argument to have exactly the number of values specified;
* - [AbstractSingleArgument.vararg] to allow specifying an unlimited number of values for the _last_ argument.
*
* @param type The type describing how to parse an option value from a string,
* an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice].
* @param fullName the full name of the argument, can be omitted if the argument name is inferred
* from the name of a property delegated to this argument.
* @param description the description of the argument used when rendering the usage information.
* @param deprecatedWarning the deprecation message for the argument.
* Specifying anything except `null` makes this argument deprecated. The message is rendered in a help message and
* issued as a warning when the argument is encountered when parsing command line arguments.
*/
fun <T : Any> argument(
type: ArgType<T>,
fullName: String? = null,
description: String? = null,
deprecatedWarning: String? = null
) : SingleArgument<T, DefaultRequiredType.Required> {
val argument = SingleArgument<T, DefaultRequiredType.Required>(ArgDescriptor(type, fullName, 1,
description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper())
argument.owner.entity = argument
declaredArguments.add(argument.owner)
return argument
}
/**
* Registers one or more subcommands.
*
* @param subcommandsList subcommands to add.
*/
@ExperimentalCli
fun subcommands(vararg subcommandsList: Subcommand) {
subcommandsList.forEach {
if (it.name in subcommands) {
error("Subcommand with name ${it.name} was already defined.")
}
// Set same settings as main parser.
it.prefixStyle = prefixStyle
it.useDefaultHelpShortName = useDefaultHelpShortName
it.strictSubcommandOptionsOrder = strictSubcommandOptionsOrder
fullCommandName.forEachIndexed { index, namePart ->
it.fullCommandName.add(index, namePart)
}
it.outputAndTerminate = outputAndTerminate
subcommands[it.name] = it
}
}
/**
* Outputs an error message adding the usage information after it.
*
* @param message error message.
*/
private fun printError(message: String): Nothing {
outputAndTerminate("$message\n${makeUsage()}", 127)
}
/**
* Save value as argument value.
*
* @param arg string with argument value.
* @param argumentsQueue queue with active argument descriptors.
*/
private fun saveAsArg(arg: String, argumentsQueue: ArgumentsQueue): Boolean {
// Find next uninitialized arguments.
val name = argumentsQueue.pop()
name?.let {
val argumentValue = arguments[name]!!
argumentValue.descriptor.deprecatedWarning?.let { printWarning(it) }
argumentValue.addValue(arg)
return true
}
return false
}
/**
* Treat value as argument value.
*
* @param arg string with argument value.
* @param argumentsQueue queue with active argument descriptors.
*/
private fun treatAsArgument(arg: String, argumentsQueue: ArgumentsQueue) {
if (!saveAsArg(arg, argumentsQueue)) {
usedSubcommand?.let {
(if (treatAsOption) subcommandsOptions else subcommandsArguments).add(arg)
} ?: printError("Too many arguments! Couldn't process argument $arg!")
}
}
/**
* Save value as option value.
*/
private fun <T : Any, U: Any> saveAsOption(parsingValue: ParsingValue<T, U>, value: String) {
parsingValue.addValue(value)
}
/**
* Try to recognize and save command line element as full form of option.
*
* @param candidate string with candidate in options.
* @param argIterator iterator over command line arguments.
*/
private fun recognizeAndSaveOptionFullForm(candidate: String, argIterator: Iterator<String>): Boolean {
if (prefixStyle == OptionPrefixStyle.GNU && candidate == optionFullFormPrefix) {
// All other arguments after `--` are treated as non-option arguments.
treatAsOption = false
return false
}
if (!candidate.startsWith(optionFullFormPrefix))
return false
val optionString = candidate.substring(optionFullFormPrefix.length)
val argValue = if (prefixStyle == OptionPrefixStyle.GNU) null else options[optionString]
if (argValue != null) {
saveStandardOptionForm(argValue, argIterator)
return true
} else {
// Check GNU style of options.
if (prefixStyle == OptionPrefixStyle.GNU) {
// Option without a parameter.
if (options[optionString]?.descriptor?.type?.hasParameter == false) {
saveOptionWithoutParameter(options[optionString]!!)
return true
}
// Option with parameters.
val optionParts = optionString.split('=', limit = 2)
if (optionParts.size != 2)
return false
if (options[optionParts[0]] != null) {
saveAsOption(options[optionParts[0]]!!, optionParts[1])
return true
}
}
}
return false
}
/**
* Save option without parameter.
*
* @param argValue argument value with all information about option.
*/
internal fun saveOptionWithoutParameter(argValue: ParsingValue<*, *>) {
// Boolean flags.
if (argValue.descriptor.fullName == "help") {
usedSubcommand?.let {
it.parse(listOf("${it.optionFullFormPrefix}${argValue.descriptor.fullName}"))
}
outputAndTerminate(makeUsage(), 0)
}
saveAsOption(argValue, "true")
}
/**
* Save option described with standard separated form `--name value`.
*
* @param argValue argument value with all information about option.
* @param argIterator iterator over command line arguments.
*/
private fun saveStandardOptionForm(argValue: ParsingValue<*, *>, argIterator: Iterator<String>) {
if (argValue.descriptor.type.hasParameter) {
if (argIterator.hasNext()) {
saveAsOption(argValue, argIterator.next())
} else {
// An error, option with value without value.
printError("No value for ${argValue.descriptor.textDescription}")
}
} else {
saveOptionWithoutParameter(argValue)
}
}
/**
* Try to recognize and save command line element as short form of option.
*
* @param candidate string with candidate in options.
* @param argIterator iterator over command line arguments.
*/
private fun recognizeAndSaveOptionShortForm(candidate: String, argIterator: Iterator<String>): Boolean {
if (!candidate.startsWith(optionShortFromPrefix) ||
optionFullFormPrefix != optionShortFromPrefix && candidate.startsWith(optionFullFormPrefix)) return false
// Try to find exact match.
val option = candidate.substring(optionShortFromPrefix.length)
val argValue = shortNames[option]
if (argValue != null) {
saveStandardOptionForm(argValue, argIterator)
} else {
if (prefixStyle != OptionPrefixStyle.GNU || option.isEmpty())
return false
// Try to find collapsed form.
val firstOption = shortNames["${option[0]}"] ?: return false
// Form with value after short form without separator.
if (firstOption.descriptor.type.hasParameter) {
saveAsOption(firstOption, option.substring(1))
} else {
// Form with several short forms as one string.
val otherBooleanOptions = option.substring(1)
saveOptionWithoutParameter(firstOption)
for (opt in otherBooleanOptions) {
shortNames["$opt"]?.let {
if (it.descriptor.type.hasParameter) {
printError(
"Option $optionShortFromPrefix$opt can't be used in option combination $candidate, " +
"because parameter value of type ${it.descriptor.type.description} should be " +
"provided for current option."
)
}
}?: printError("Unknown option $optionShortFromPrefix$opt in option combination $candidate.")
saveOptionWithoutParameter(shortNames["$opt"]!!)
}
}
}
return true
}
/**
* Parses the provided array of command line arguments.
* After a successful parsing, the options and arguments declared in this parser get their values and can be accessed
* with the properties delegated to them.
*
* @param args the array with command line arguments.
*
* @return an [ArgParserResult] if all arguments were parsed successfully.
* Otherwise, prints the usage information and terminates the program execution.
* @throws IllegalStateException in case of attempt of calling parsing several times.
*/
fun parse(args: Array<String>): ArgParserResult = parse(args.asList())
protected fun parse(args: List<String>): ArgParserResult {
check(parsingState == null) { "Parsing of command line options can be called only once." }
// Add help option.
val helpDescriptor = if (useDefaultHelpShortName) OptionDescriptor<Boolean, Boolean>(
optionFullFormPrefix,
optionShortFromPrefix, ArgType.Boolean,
"help", "h", "Usage info"
)
else OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix,
ArgType.Boolean, "help", description = "Usage info"
)
val helpOption = SingleNullableOption(helpDescriptor, CLIEntityWrapper())
helpOption.owner.entity = helpOption
declaredOptions.add(helpOption.owner)
// Add default list with arguments if there can be extra free arguments.
if (skipExtraArguments) {
argument(ArgType.String, "").vararg()
}
// Clean options and arguments maps.
options.clear()
arguments.clear()
// Map declared options and arguments to maps.
declaredOptions.forEachIndexed { index, option ->
val value = option.entity?.delegate as ParsingValue<*, *>
value.descriptor.fullName?.let {
// Add option.
if (options.containsKey(it)) {
error("Option with full name $it was already added.")
}
with(value.descriptor as OptionDescriptor) {
if (shortName != null && shortNames.containsKey(shortName)) {
error("Option with short name ${shortName} was already added.")
}
shortName?.let {
shortNames[it] = value
}
}
options[it] = value
} ?: error("Option was added, but unnamed. Added option under №${index + 1}")
}
declaredArguments.forEachIndexed { index, argument ->
val value = argument.entity?.delegate as ParsingValue<*, *>
value.descriptor.fullName?.let {
// Add option.
if (arguments.containsKey(it)) {
error("Argument with full name $it was already added.")
}
arguments[it] = value
} ?: error("Argument was added, but unnamed. Added argument under №${index + 1}")
}
// Make inspections for arguments.
inspectRequiredAndDefaultUsage()
listOf(arguments, options).forEach {
it.forEach { (_, value) ->
value.valueOrigin = ValueOrigin.UNSET
}
}
val argumentsQueue = ArgumentsQueue(arguments.map { it.value.descriptor as ArgDescriptor<*, *> })
usedSubcommand = null
subcommandsOptions.clear()
subcommandsArguments.clear()
val argIterator = args.listIterator()
try {
while (argIterator.hasNext()) {
val arg = argIterator.next()
// Check for subcommands.
if (arg !in subcommands) {
// Parse arguments from command line.
if (treatAsOption && arg.startsWith('-')) {
// Candidate in being option.
// Option is found.
if (!(recognizeAndSaveOptionShortForm(arg, argIterator) ||
recognizeAndSaveOptionFullForm(arg, argIterator))
) {
// State is changed so next options are arguments.
if (!treatAsOption) {
// Argument is found.
treatAsArgument(argIterator.next(), argumentsQueue)
} else {
usedSubcommand?.let { subcommandsOptions.add(arg) } ?: run {
// Try save as argument.
if (!saveAsArg(arg, argumentsQueue)) {
printError("Unknown option $arg")
}
}
}
}
} else {
// Argument is found.
treatAsArgument(arg, argumentsQueue)
}
} else {
usedSubcommand = subcommands[arg]
if (strictSubcommandOptionsOrder) {
break
}
}
}
// Postprocess results of parsing.
options.values.union(arguments.values).forEach { value ->
// Not inited, append default value if needed.
if (value.isEmpty()) {
value.addDefaultValue()
}
if (value.valueOrigin != ValueOrigin.SET_BY_USER && value.descriptor.required) {
printError("Value for ${value.descriptor.textDescription} should be always provided in command line.")
}
}
// Parse arguments for subcommand.
usedSubcommand?.let {
if (strictSubcommandOptionsOrder) {
it.parse(args.slice(argIterator.nextIndex() until args.size))
} else {
it.parse(subcommandsOptions + listOfNotNull("--".takeUnless { treatAsOption }) + subcommandsArguments)
}
it.execute()
parsingState = ArgParserResult(it.name)
return parsingState!!
}
} catch (exception: ParsingException) {
printError(exception.message!!)
}
parsingState = ArgParserResult(programName)
return parsingState!!
}
/**
* Creates a message with the usage information.
*/
internal fun makeUsage(): String {
val result = StringBuilder()
result.append("Usage: ${fullCommandName.joinToString(" ")} options_list\n")
if (subcommands.isNotEmpty()) {
result.append("Subcommands: \n")
subcommands.forEach { (_, subcommand) ->
result.append(subcommand.helpMessage)
}
result.append("\n")
}
if (arguments.isNotEmpty()) {
result.append("Arguments: \n")
arguments.forEach {
result.append(it.value.descriptor.helpMessage)
}
}
if (options.isNotEmpty()) {
result.append("Options: \n")
options.forEach {
result.append(it.value.descriptor.helpMessage)
}
}
return result.toString()
}
}
/**
* Output warning.
*
* @param message warning message.
*/
internal fun printWarning(message: String) {
println("WARNING $message")
}
| apache-2.0 | 0c1dd7b0c1e1b36bc3841943688eeecb | 39.764539 | 140 | 0.606389 | 5.315147 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/customView/PlayerControls.kt | 1 | 6556 | package be.florien.anyflow.feature.customView
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import be.florien.anyflow.R
import kotlin.math.absoluteValue
import kotlin.math.min
/**
* Created by florien on 8/01/18.
*/
class PlayerControls
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: View(context, attrs, defStyleAttr) {
/**
* Attributes
*/
private val playPauseIconAnimator: PlayPauseIconAnimator = PlayPauseIconAnimator(context)
private val previousIconAnimator: PreviousIconAnimator = PreviousIconAnimator(context)
private val playPlayerPainter: PlayPlayerPainter = PlayPlayerPainter(context, playPauseIconAnimator, previousIconAnimator)
private val scrollPlayerPainter: ScrollPlayerPainter = ScrollPlayerPainter(context, playPauseIconAnimator, previousIconAnimator)
private var currentPlayerPainter: PlayerPainter = playPlayerPainter
set(value) {
field.onValuesComputed = {}
value.onValuesComputed = {
invalidate()
}
field = value
field.currentState = field.currentState
}
// Variable changing due to usage
var shouldShowBuffering: Boolean = false
var hasPrevious: Boolean
get() = currentPlayerPainter.hasPrevious
set(value) {
playPlayerPainter.hasPrevious = value
scrollPlayerPainter.hasPrevious = value
}
var hasNext: Boolean
get() = currentPlayerPainter.hasNext
set(value) {
playPlayerPainter.hasNext = value
scrollPlayerPainter.hasNext = value
}
// Variables that can be configured by XML attributes
var currentDuration: Int
set(value) {
playPlayerPainter.playingDuration = value
}
get() = playPlayerPainter.playingDuration
var state = PlayPauseIconAnimator.STATE_PLAY_PAUSE_PAUSE
set(value) {
currentPlayerPainter.currentState = value
field = value
}
var actionListener: OnActionListener? = null
var totalDuration: Int = 0
set(value) {
field = if (value == 0) Int.MAX_VALUE else value
scrollPlayerPainter.totalDuration = field
playPlayerPainter.totalDuration = field
}
private var progressAnimDuration: Int = 10000
// Calculations
private var lastDownEventX = 0f
/**
* Constructor
*/
init {
if (attrs != null) {
val typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.PlayerControls)
currentDuration = typedArray.getInt(R.styleable.PlayerControls_currentDuration, currentDuration)
totalDuration = typedArray.getInt(R.styleable.PlayerControls_totalDuration, totalDuration)
progressAnimDuration = typedArray.getInt(R.styleable.PlayerControls_progressAnimDuration, progressAnimDuration)
state = typedArray.getInteger(R.styleable.PlayerControls_state, PlayPauseIconAnimator.STATE_PLAY_PAUSE_PAUSE)
playPlayerPainter.retrieveLayoutProperties(typedArray)
scrollPlayerPainter.retrieveLayoutProperties(typedArray)
typedArray.recycle()
}
currentPlayerPainter = playPlayerPainter
}
/**
* Overridden methods
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val idealButtonSize = currentPlayerPainter.smallestButtonWidth
val desiredWidth = when (widthMode) {
MeasureSpec.AT_MOST -> widthSize
MeasureSpec.EXACTLY -> widthSize
MeasureSpec.UNSPECIFIED -> idealButtonSize
else -> idealButtonSize
}
val desiredHeight = when (heightMode) {
MeasureSpec.AT_MOST -> min(heightSize, idealButtonSize)
MeasureSpec.EXACTLY -> heightSize
MeasureSpec.UNSPECIFIED -> idealButtonSize
else -> idealButtonSize
}
setMeasuredDimension(desiredWidth, desiredHeight)
playPlayerPainter.measure(desiredWidth, desiredHeight)
scrollPlayerPainter.measure(desiredWidth, desiredHeight)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
currentPlayerPainter.computePreviousIcon()
}
override fun onDraw(canvas: Canvas) {
currentPlayerPainter.draw(canvas, width, height)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
lastDownEventX = event.x
scrollPlayerPainter.durationOnTouchStart = currentDuration
}
MotionEvent.ACTION_MOVE -> {
scrollPlayerPainter.scrollOffset = (event.x - lastDownEventX)
if (scrollPlayerPainter.scrollOffset.absoluteValue > playPlayerPainter.smallestButtonWidth && currentPlayerPainter != scrollPlayerPainter) {
currentPlayerPainter = scrollPlayerPainter
}
}
MotionEvent.ACTION_UP -> {
when (currentPlayerPainter.getButtonClicked(lastDownEventX.toInt(), event.x.toInt())) {
PlayerPainter.CLICK_PREVIOUS -> actionListener?.onPreviousClicked()
PlayerPainter.CLICK_PLAY_PAUSE -> actionListener?.onPlayPauseClicked()
PlayerPainter.CLICK_NEXT -> actionListener?.onNextClicked()
else -> {
actionListener?.onCurrentDurationChanged(scrollPlayerPainter.duration.toLong())
}
}
lastDownEventX = 0f
currentPlayerPainter = playPlayerPainter
}
else -> return super.onTouchEvent(event)
}
return true
}
/**
* Listeners
*/
interface OnActionListener {
fun onPreviousClicked()
fun onNextClicked()
fun onPlayPauseClicked()
fun onCurrentDurationChanged(newDuration: Long)
}
companion object {
const val NO_VALUE = -15
}
} | gpl-3.0 | d7a57a9753b26c3458c3e61d8aa04e15 | 36.045198 | 156 | 0.656803 | 5.781305 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/widget/WidgetWebViewFactory.kt | 1 | 2612 | package treehou.se.habit.ui.widget
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.services.IServerHandler
import treehou.se.habit.R
import treehou.se.habit.ui.adapter.WidgetAdapter
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class WidgetWebViewFactory @Inject constructor() : WidgetFactory {
@Inject lateinit var logger: Logger
@Inject lateinit var server: OHServer
@Inject lateinit var page: OHLinkedPage
@Inject lateinit var serverHandler: IServerHandler
override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.widget_web_view, parent, false)
return WebWidgetViewHolder(view)
}
inner class WebWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) {
private var webView: WebView = view as WebView
init {
setupWebView()
}
override fun bind(itemWidget: WidgetAdapter.WidgetItem) {
super.bind(itemWidget)
val lp = webView.layoutParams
val heightInRows = widget.height
val desiredHeightPixels = if (heightInRows is Int && heightInRows > 0) (heightInRows * context.resources.getDimension(R.dimen.webview_row_height)).toInt() else ViewGroup.LayoutParams.WRAP_CONTENT
if (lp.height != desiredHeightPixels) {
lp.height = desiredHeightPixels
webView.layoutParams = lp
}
if (widget.url != null) {
webView.loadUrl(widget.url)
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() {
val client = WebViewClient()
webView.webViewClient = client
val settings = webView.settings
settings.javaScriptEnabled = true
settings.javaScriptCanOpenWindowsAutomatically = true
webView.isFocusableInTouchMode = true
settings.cacheMode = WebSettings.LOAD_NO_CACHE
settings.domStorageEnabled = true
settings.databaseEnabled = true
settings.setAppCacheEnabled(true)
}
}
companion object {
const val TAG = "WidgetSwitchFactory"
}
} | epl-1.0 | a2ab6ed9888e78086df3f41b93208c01 | 34.310811 | 207 | 0.691041 | 4.965779 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mcp/gradle/datahandler/McpModelFG2Handler.kt | 1 | 2041 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.gradle.datahandler
import com.demonwav.mcdev.platform.mcp.McpModuleSettings
import com.demonwav.mcdev.platform.mcp.gradle.McpModelData
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2
import com.demonwav.mcdev.platform.mcp.srg.SrgType
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
object McpModelFG2Handler : McpModelDataHandler {
override fun build(
gradleModule: IdeaModule,
node: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val data = resolverCtx.getExtraProject(gradleModule, McpModelFG2::class.java) ?: return
val state = McpModuleSettings.State(
data.minecraftVersion,
data.mcpVersion,
data.mappingFiles.find { it.endsWith("mcp-srg.srg") },
SrgType.SRG
)
val modelData = McpModelData(
node.data,
state,
null,
null
)
node.createChild(
McpModelData.KEY,
McpModelData(
node.data,
McpModuleSettings.State(
data.minecraftVersion,
data.mcpVersion,
data.mappingFiles.find { it.endsWith("mcp-srg.srg") },
SrgType.SRG
),
null,
null
)
)
for (child in node.children) {
val childData = child.data
if (childData is GradleSourceSetData) {
child.createChild(McpModelData.KEY, modelData.copy(module = childData))
}
}
}
}
| mit | 9a6ad4ae2bbfd8436603ac69a16bc03b | 29.014706 | 95 | 0.622734 | 4.576233 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/models/dao/base/BaseDao.kt | 1 | 1853 | package de.xikolo.models.dao.base
import androidx.lifecycle.LiveData
import de.xikolo.extensions.asLiveData
import io.realm.Realm
import io.realm.RealmObject
import io.realm.RealmQuery
import io.realm.Sort
import kotlin.reflect.KClass
/**
* The base class for data access objects.
*
* Inherit this class to implement a data access object for a certain model class.
* Subclasses should be the only ones in the project who implement Realm-specific code,
* like database queries. We agreed on some conventions:
* - single entity request methods begin with `find`, collection requests begin with `all`
* - managed requests with results wrapped as `LiveData` are implemented as instance methods
* - unmanaged requests with plain object/list results are implemented in an `Unmanaged` object
*
* @param T the type of the model this class belongs to.
* @property clazz the model's class.
* @realm realm the managed Realm instance for managed requests.
*/
open class BaseDao<T : RealmObject>(private val clazz: KClass<T>, val realm: Realm) {
var defaultSort: Pair<String, Sort>? = null
fun query(): RealmQuery<T> = realm.where(clazz.java)
open val unmanaged = object { }
open fun find(id: String?): LiveData<T> =
query()
.equalTo("id", id)
.findFirstAsync()
.asLiveData()
fun all(vararg equalToClauses: Pair<String, Any?>): LiveData<List<T>> {
val query = query()
for (equalTo in equalToClauses) {
val value = equalTo.second
when (value) {
is String -> query.equalTo(equalTo.first, value)
is Boolean -> query.equalTo(equalTo.first, value)
}
}
defaultSort?.let {
query.sort(it.first, it.second)
}
return query.findAllAsync().asLiveData()
}
}
| bsd-3-clause | 4072c4949a4896103e2764ef94d3073a | 31.508772 | 95 | 0.668645 | 4.279446 | false | false | false | false |
samtstern/quickstart-android | mlkit-langid/app/src/main/java/com/google/firebase/samples/apps/mlkit/languageid/kotlin/MainActivity.kt | 1 | 3698 | package com.google.firebase.samples.apps.mlkit.languageid.kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage
import com.google.firebase.samples.apps.mlkit.languageid.R
import com.google.firebase.samples.apps.mlkit.languageid.databinding.ActivityMainBinding
import java.util.ArrayList
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
with(binding) {
buttonIdLanguage.setOnClickListener {
val input = inputText.text?.toString()
input?.let {
inputText.text?.clear()
identifyLanguage(it)
}
}
buttonIdAll.setOnClickListener {
val input = inputText.text?.toString()
input?.let {
inputText.text?.clear()
identifyPossibleLanguages(input)
}
}
}
}
private fun identifyPossibleLanguages(inputText: String) {
val languageIdentification = FirebaseNaturalLanguage
.getInstance().languageIdentification
languageIdentification
.identifyPossibleLanguages(inputText)
.addOnSuccessListener(this@MainActivity) { identifiedLanguages ->
val detectedLanguages = ArrayList<String>(identifiedLanguages.size)
for (language in identifiedLanguages) {
detectedLanguages.add(
String.format(
Locale.US,
"%s (%3f)",
language.languageCode,
language.confidence
)
)
}
binding.outputText.append(
String.format(
Locale.US,
"\n%s - [%s]",
inputText,
TextUtils.join(", ", detectedLanguages)
)
)
}
.addOnFailureListener(this@MainActivity) { e ->
Log.e(TAG, "Language identification error", e)
Toast.makeText(
this@MainActivity, R.string.language_id_error,
Toast.LENGTH_SHORT
).show()
}
}
private fun identifyLanguage(inputText: String) {
val languageIdentification = FirebaseNaturalLanguage
.getInstance().languageIdentification
languageIdentification
.identifyLanguage(inputText)
.addOnSuccessListener(this@MainActivity) { s ->
binding.outputText.append(
String.format(
Locale.US,
"\n%s - %s",
inputText,
s
)
)
}
.addOnFailureListener(this@MainActivity) { e ->
Log.e(TAG, "Language identification error", e)
Toast.makeText(
this@MainActivity, R.string.language_id_error,
Toast.LENGTH_SHORT
).show()
}
}
companion object {
private const val TAG = "MainActivity"
}
}
| apache-2.0 | fc47946d8e210cf4ce68200851505d23 | 34.902913 | 88 | 0.533261 | 5.814465 | false | false | false | false |
apixandru/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyClosurePattern.kt | 13 | 2076 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.patterns
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.psi.PsiMethod
import com.intellij.util.ProcessingContext
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
class GroovyClosurePattern : GroovyExpressionPattern<GrClosableBlock, GroovyClosurePattern>(GrClosableBlock::class.java) {
fun inMethod(methodPattern: ElementPattern<out PsiMethod>) = with(object : PatternCondition<GrClosableBlock>("closureInMethod") {
override fun accepts(closure: GrClosableBlock, context: ProcessingContext?): Boolean {
val parent = closure.parent
val call = when (parent) {
is GrCall -> {
if (closure !in parent.closureArguments) return false
parent
}
is GrArgumentList -> {
val grandParent = parent.parent as? GrCall ?: return false
if (grandParent.closureArguments.isNotEmpty()) return false
if (grandParent.expressionArguments.lastOrNull() != closure) return false
grandParent
}
else -> return false
}
context?.put(closureCallKey, call)
val method = call.resolveMethod() ?: return false
return methodPattern.accepts(method)
}
})
} | apache-2.0 | 401ff7bef518b6efa8c72a8263b071db | 40.54 | 131 | 0.736031 | 4.623608 | false | false | false | false |
cashapp/sqldelight | dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/grammar/mixins/MySqlBinaryEqualityExpr.kt | 1 | 564 | package app.cash.sqldelight.dialects.mysql.grammar.mixins
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.impl.SqlBinaryEqualityExprImpl
import com.intellij.lang.ASTNode
internal class MySqlBinaryEqualityExpr(node: ASTNode) : SqlBinaryEqualityExprImpl(node) {
override fun annotate(annotationHolder: SqlAnnotationHolder) {
if (node.getChildren(null).getOrNull(2)?.text == "==") {
annotationHolder.createErrorAnnotation(this, "Expected '=' but got '=='.")
}
super.annotate(annotationHolder)
}
}
| apache-2.0 | f5d702ced1793158106f050264c8c3a6 | 39.285714 | 89 | 0.77305 | 4.147059 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/stylesheets/StyleSheetTests.kt | 1 | 10053 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.css.stylesheets
import o.katydid.css.colors.*
import o.katydid.css.measurements.pt
import o.katydid.css.measurements.px
import o.katydid.css.styles.builders.*
import o.katydid.css.styles.makeStyle
import o.katydid.css.stylesheets.KatydidStyleSheet
import o.katydid.css.stylesheets.makeStyleSheet
import o.katydid.css.types.EFontStyle
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
@Suppress("RemoveRedundantBackticks")
class StyleSheetTests {
private fun checkStyle(
expectedCss: String,
build: KatydidStyleSheet.() -> Unit
) {
assertEquals(expectedCss, makeStyleSheet(build).toString())
}
@Test
fun `A simple style sheet can be constructed from selectors and styles`() {
val css = """
|div {
| height: 23px;
| width: 30px;
|}
|
|div.wider {
| width: 45px;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"div" {
height(23.px)
width(30.px)
}
"div.wider" {
width(45.px)
}
}
}
@Test
fun `A nested style sheet can be constructed from selectors and styles`() {
val css = """
|div {
| height: 23px;
| width: 30px;
|}
|
|div.wider {
| width: 45px;
|}
|
|div.wider span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"div" {
height(23.px)
width(30.px)
"&.wider" {
width(45.px)
"span" {
color(green)
}
}
}
}
}
@Test
fun `Nested styles can reference the parent selector after the nested selector`() {
val css = """
|a {
| color: honeydew;
|}
|
|a:hover {
| color: aquamarine;
|}
|
|td a {
| color: chartreuse;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"a" {
color(honeydew)
"&:hover" {
color(aquamarine)
}
"td &" {
color(chartreuse)
}
}
}
}
@Test
fun `Comma-separated selectors are handled`() {
val css = """
|td,
|th,
|div {
| font-size: 10pt;
| font-style: italic;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
" td,th, div " {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
}
}
}
@Test
fun `Selectors can be combined with the or operator`() {
val css = """
|td,
|th,
|div {
| font-size: 10pt;
| font-style: italic;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"td" or "th" or "div" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
}
}
}
@Test
fun `Nesting works with the or operator inside the nesting`() {
val css = """
|td {
| font-size: 10pt;
| font-style: italic;
|}
|
|td div,
|td span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"td" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
"div" or "span" {
color(green)
}
}
}
}
@Test
fun `Nesting works with the or operator outside the nesting`() {
val css = """
|td,
|th {
| font-size: 10pt;
| font-style: italic;
|}
|
|td div,
|th div {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"td" or "th" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
"div" {
color(green)
}
}
}
}
@Test
fun `Nesting works with the or operator at both levels`() {
val css = """
|nav,
|td,
|th {
| font-size: 10pt;
| font-style: italic;
|}
|
|nav div,
|nav span,
|td div,
|td span,
|th div,
|th span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"nav" or "td" or "th" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
"div" or "span" {
color(green)
}
}
}
}
@Test
fun `Three layers of nesting works with the or operator`() {
val css = """
|nav,
|td,
|th {
| font-size: 10pt;
| font-style: italic;
|}
|
|nav.quirky,
|td.quirky,
|th.quirky {
| max-width: 45px;
|}
|
|nav.quirky div,
|nav.quirky span,
|td.quirky div,
|td.quirky span,
|th.quirky div,
|th.quirky span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"nav" or "td" or "th" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
"&.quirky" {
maxWidth(45.px)
"div" or "span" {
color(green)
}
}
}
}
}
@Test
fun `Three layers of nesting works when the top level has no styles`() {
val css = """
|nav.quirky,
|td.quirky,
|th.quirky {
| max-width: 45px;
|}
|
|nav.quirky div,
|nav.quirky span,
|td.quirky div,
|td.quirky span,
|th.quirky div,
|th.quirky span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"nav" or "td" or "th" {
"&.quirky" {
maxWidth(45.px)
"div" or "span" {
color(green)
}
}
}
}
}
@Test
fun `Three layers of nesting works when the middle level has no styles`() {
val css = """
|nav,
|td,
|th {
| font-size: 10pt;
| font-style: italic;
|}
|
|nav.quirky div,
|nav.quirky span,
|td.quirky div,
|td.quirky span,
|th.quirky div,
|th.quirky span {
| color: green;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
"nav" or "td" or "th" {
fontSize(10.pt)
fontStyle(EFontStyle.italic)
"&.quirky" {
"div" or "span" {
color(green)
}
}
}
}
}
@Test
fun `Style blocks can include other styles`() {
val css = """
|div {
| height: 23px;
| background-color: gray;
| color: blue;
| width: 30px;
|}
|
|div.wider {
| width: 45px;
|}
|
""".trimMargin() + "\n"
checkStyle(css) {
val commonColors = makeStyle {
backgroundColor(gray)
color(blue)
}
"div" {
height(23.px)
include(commonColors)
width(30.px)
"&.wider" {
width(45.px)
}
}
}
}
@Test
fun `One style sheet can include another`() {
val css = """
|div,
|span {
| background-color: gray;
| color: blue;
|}
|
|div {
| height: 23px;
| width: 30px;
|}
|
|div.wider {
| width: 45px;
|}
|
""".trimMargin() + "\n"
val commonColors = makeStyleSheet {
"div" or "span" {
backgroundColor(gray)
color(blue)
}
}
checkStyle(css) {
include(commonColors)
"div" {
height(23.px)
width(30.px)
"&.wider" {
width(45.px)
}
}
}
}
@Test
fun `An empty style rule results in no output`() {
val css = ""
checkStyle(css) {
".stuff" {}
".morestuff" {}
}
}
}
| apache-2.0 | fafea24c75f386642e3ade69af2a985b | 17.896617 | 87 | 0.346563 | 4.622069 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/util/StringUtil.kt | 1 | 10035 | package org.wikipedia.util
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.icu.text.CompactDecimalFormat
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.IntRange
import androidx.core.text.parseAsHtml
import androidx.core.text.toSpanned
import okio.ByteString.Companion.encodeUtf8
import org.wikipedia.R
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.page.PageTitle
import org.wikipedia.staticdata.UserAliasData
import java.nio.charset.StandardCharsets
import java.text.Collator
import java.text.Normalizer
import java.util.*
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
object StringUtil {
private const val CSV_DELIMITER = ","
fun listToCsv(list: List<String?>): String {
return list.joinToString(CSV_DELIMITER)
}
fun csvToList(csv: String): List<String> {
return delimiterStringToList(csv, CSV_DELIMITER)
}
fun delimiterStringToList(delimitedString: String,
delimiter: String): List<String> {
return delimitedString.split(delimiter).filter { it.isNotBlank() }
}
fun md5string(s: String): String {
return s.encodeUtf8().md5().hex()
}
fun strip(str: CharSequence?): CharSequence {
// TODO: remove this function once Kotlin conversion of consumers is complete.
return if (str.isNullOrEmpty()) "" else str.trim()
}
fun intToHexStr(i: Int): String {
return String.format("x%08x", i)
}
fun addUnderscores(text: String?): String {
return text.orEmpty().replace(" ", "_")
}
fun removeUnderscores(text: String?): String {
return text.orEmpty().replace("_", " ")
}
fun dbNameToLangCode(wikiDbName: String): String {
return (if (wikiDbName.endsWith("wiki")) wikiDbName.substring(0, wikiDbName.length - "wiki".length) else wikiDbName)
.replace("_", "-")
}
fun removeSectionAnchor(text: String?): String {
text.orEmpty().let {
return if (it.contains("#")) it.substring(0, it.indexOf("#")) else it
}
}
fun removeNamespace(text: String): String {
return if (text.length > text.indexOf(":")) {
text.substring(text.indexOf(":") + 1)
} else {
text
}
}
fun removeHTMLTags(text: String?): String {
return fromHtml(text).toString()
}
fun removeStyleTags(text: String): String {
return text.replace("<style.*?</style>".toRegex(), "")
}
fun removeCiteMarkup(text: String): String {
return text.replace("<cite.*?>".toRegex(), "").replace("</cite>".toRegex(), "")
}
fun sanitizeAbuseFilterCode(code: String): String {
return code.replace("[⧼⧽]".toRegex(), "")
}
fun normalizedEquals(str1: String?, str2: String?): Boolean {
return if (str1 == null || str2 == null) {
str1 == null && str2 == null
} else (Normalizer.normalize(str1, Normalizer.Form.NFC)
== Normalizer.normalize(str2, Normalizer.Form.NFC))
}
fun fromHtml(source: String?): Spanned {
var sourceStr = source ?: return "".toSpanned()
if ("<" !in sourceStr && "&" !in sourceStr) {
// If the string doesn't contain any hints of HTML entities, then skip the expensive
// processing that fromHtml() performs.
return sourceStr.toSpanned()
}
sourceStr = sourceStr.replace("‎", "\u200E")
.replace("‏", "\u200F")
.replace("&", "&")
// HACK: We don't want to display "images" in the html string, because they will just show
// up as a green square. Therefore, let's just disable the parsing of images by renaming
// <img> tags to something that the native Html parser doesn't recognize.
// This automatically covers both <img></img> and <img /> variations.
sourceStr = sourceStr.replace("<img ", "<figure ").replace("</img>", "</figure>")
return sourceStr.parseAsHtml()
}
fun highlightEditText(editText: EditText, parentText: String, highlightText: String) {
val words = highlightText.split("\\s".toRegex()).filter { it.isNotBlank() }
var pos = 0
var firstPos = 0
for (word in words) {
pos = parentText.indexOf(word, pos)
if (pos == -1) {
break
} else if (firstPos == 0) {
firstPos = pos
}
}
if (pos == -1) {
pos = parentText.indexOf(words.last())
firstPos = pos
}
if (pos >= 0) {
editText.setSelection(firstPos, pos + words.last().length)
}
}
fun boldenKeywordText(textView: TextView, parentText: String, searchQuery: String?) {
var parentTextStr = parentText
val startIndex = indexOf(parentTextStr, searchQuery)
if (startIndex >= 0 && !isIndexInsideHtmlTag(parentTextStr, startIndex)) {
parentTextStr = (parentTextStr.substring(0, startIndex) + "<strong>" +
parentTextStr.substring(startIndex, startIndex + searchQuery!!.length) + "</strong>" +
parentTextStr.substring(startIndex + searchQuery.length))
}
textView.text = fromHtml(parentTextStr)
}
fun highlightAndBoldenText(textView: TextView, input: String?, shouldBolden: Boolean, highlightColor: Int) {
if (!input.isNullOrEmpty()) {
val spannableString = SpannableString(textView.text)
val caseInsensitiveSpannableString = SpannableString(textView.text.toString().lowercase())
var indexOfKeyword = caseInsensitiveSpannableString.toString().lowercase().indexOf(input.lowercase())
while (indexOfKeyword >= 0) {
spannableString.setSpan(BackgroundColorSpan(highlightColor), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableString.setSpan(ForegroundColorSpan(Color.BLACK), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
if (shouldBolden) {
spannableString.setSpan(StyleSpan(Typeface.BOLD), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
indexOfKeyword = caseInsensitiveSpannableString.indexOf(input.lowercase(), indexOfKeyword + input.length)
}
textView.text = spannableString
}
}
private fun isIndexInsideHtmlTag(text: String, index: Int): Boolean {
var tagStack = 0
for (i in text.indices) {
if (text[i] == '<') { tagStack++ } else if (text[i] == '>') { tagStack-- }
if (i == index) { break }
}
return tagStack > 0
}
// case insensitive indexOf, also more lenient with similar chars, like chars with accents
private fun indexOf(original: String, search: String?): Int {
if (!search.isNullOrEmpty()) {
val collator = Collator.getInstance()
collator.strength = Collator.PRIMARY
for (i in 0..original.length - search.length) {
if (collator.equals(search, original.substring(i, i + search.length))) {
return i
}
}
}
return -1
}
fun getBase26String(@IntRange(from = 1) number: Int): String {
var num = number
val base = 26
var str = ""
while (--num >= 0) {
str = ('A' + num % base) + str
num /= base
}
return str
}
fun utf8Indices(s: String): IntArray {
val indices = IntArray(s.toByteArray(StandardCharsets.UTF_8).size)
var ptr = 0
var count = 0
for (i in s.indices) {
val c = s.codePointAt(i)
when {
c <= 0x7F -> count = 1
c <= 0x7FF -> count = 2
c <= 0xFFFF -> count = 3
c <= 0x1FFFFF -> count = 4
}
for (j in 0 until count) {
if (ptr < indices.size) {
indices[ptr++] = i
}
}
}
return indices
}
fun userPageTitleFromName(userName: String, wiki: WikiSite): PageTitle {
return PageTitle(UserAliasData.valueFor(wiki.languageCode), userName, wiki)
}
fun getPageViewText(context: Context, pageViews: Long): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val primaryLocale = context.resources.configuration.locales[0]
val decimalFormat = CompactDecimalFormat.getInstance(primaryLocale, CompactDecimalFormat.CompactStyle.SHORT)
return decimalFormat.format(pageViews)
}
return when {
pageViews < 1000 -> pageViews.toString()
pageViews < 1000000 -> {
context.getString(
R.string.view_top_read_card_pageviews_k_suffix,
(pageViews / 1000f).roundToInt()
)
}
else -> {
context.getString(
R.string.view_top_read_card_pageviews_m_suffix,
(pageViews / 1000000f).roundToInt()
)
}
}
}
fun getDiffBytesText(context: Context, diffSize: Int): String {
return context.resources.getQuantityString(R.plurals.edit_diff_bytes, diffSize.absoluteValue, if (diffSize > 0) "+$diffSize" else diffSize.toString())
}
fun capitalize(str: String?): String? {
return str?.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
}
}
| apache-2.0 | dd5644b2057c98ea831bcc4545845c4f | 36.569288 | 158 | 0.601635 | 4.547144 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/navigation/CameraPermissionDeniedFragment.kt | 1 | 4053 | package com.stripe.android.identity.navigation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.stripe.android.camera.AppSettingsOpenable
import com.stripe.android.identity.R
import com.stripe.android.identity.analytics.IdentityAnalyticsRequestFactory.Companion.SCREEN_NAME_ERROR
import com.stripe.android.identity.networking.models.CollectedDataParam
import com.stripe.android.identity.ui.ErrorScreen
import com.stripe.android.identity.ui.ErrorScreenButton
import com.stripe.android.identity.utils.navigateToUploadFragment
/**
* Fragment to show user denies camera permission.
*/
internal class CameraPermissionDeniedFragment(
private val appSettingsOpenable: AppSettingsOpenable,
identityViewModelFactory: ViewModelProvider.Factory
) : BaseErrorFragment(identityViewModelFactory) {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
val scanType = arguments?.getSerializable(ARG_SCAN_TYPE) as? CollectedDataParam.Type
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
ErrorScreen(
title = stringResource(id = R.string.camera_permission),
message1 = stringResource(id = R.string.grant_camera_permission_text),
message2 = scanType?.let {
stringResource(R.string.upload_file_text, it.getDisplayName())
},
topButton = scanType?.let {
ErrorScreenButton(
buttonText = stringResource(id = R.string.file_upload)
) {
identityViewModel.screenTracker.screenTransitionStart(SCREEN_NAME_ERROR)
navigateToUploadFragment(
it.toUploadDestinationId(),
shouldShowTakePhoto = false,
shouldShowChoosePhoto = true
)
}
},
bottomButton = ErrorScreenButton(
buttonText = stringResource(id = R.string.app_settings)
) {
appSettingsOpenable.openAppSettings()
// navigate back to DocSelectFragment, so that when user is back to the app from settings
// the camera permission check can be triggered again from there.
findNavController().navigate(R.id.action_cameraPermissionDeniedFragment_to_docSelectionFragment)
}
)
}
}
private fun CollectedDataParam.Type.getDisplayName() =
when (this) {
CollectedDataParam.Type.IDCARD -> {
getString(R.string.id_card)
}
CollectedDataParam.Type.DRIVINGLICENSE -> {
getString(R.string.driver_license)
}
CollectedDataParam.Type.PASSPORT -> {
getString(R.string.passport)
}
}
internal companion object {
const val ARG_SCAN_TYPE = "scanType"
@IdRes
private fun CollectedDataParam.Type.toUploadDestinationId() =
when (this) {
CollectedDataParam.Type.IDCARD ->
R.id.action_cameraPermissionDeniedFragment_to_IDUploadFragment
CollectedDataParam.Type.DRIVINGLICENSE ->
R.id.action_cameraPermissionDeniedFragment_to_driverLicenseUploadFragment
CollectedDataParam.Type.PASSPORT ->
R.id.action_cameraPermissionDeniedFragment_to_passportUploadFragment
}
}
}
| mit | fad7408c2d9aceedbef7e5ecc38b66bf | 42.580645 | 116 | 0.646681 | 5.574966 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/brightness/BrightnessModule.kt | 2 | 7594 | package abi43_0_0.expo.modules.brightness
import abi43_0_0.expo.modules.core.ExportedModule
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.ModuleRegistryDelegate
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.errors.InvalidArgumentException
import abi43_0_0.expo.modules.core.interfaces.ActivityProvider
import abi43_0_0.expo.modules.interfaces.permissions.Permissions
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
import android.Manifest
import android.app.Activity
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.view.WindowManager
import java.lang.Exception
import kotlin.math.roundToInt
class BrightnessModule(
reactContext: Context?,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(reactContext) {
private val permissionModule: Permissions by moduleRegistry()
private val activityProvider: ActivityProvider by moduleRegistry()
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun getName(): String {
return "ExpoBrightness"
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
}
@ExpoMethod
fun requestPermissionsAsync(promise: Promise?) {
Permissions.askForPermissionsWithPermissionsManager(permissionModule, promise, Manifest.permission.WRITE_SETTINGS)
}
@ExpoMethod
fun getPermissionsAsync(promise: Promise?) {
Permissions.getPermissionsWithPermissionsManager(permissionModule, promise, Manifest.permission.WRITE_SETTINGS)
}
@ExpoMethod
fun setBrightnessAsync(brightnessValue: Float, promise: Promise) {
val activity = currentActivity
activity.runOnUiThread {
try {
val lp = activity.window.attributes
lp.screenBrightness = brightnessValue
activity.window.attributes = lp // must be done on UI thread
promise.resolve(null)
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS", "Failed to set the current screen brightness", e)
}
}
}
@ExpoMethod
fun getBrightnessAsync(promise: Promise) {
val activity = currentActivity
activity.runOnUiThread {
val lp = activity.window.attributes
if (lp.screenBrightness == WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) {
// system brightness is not overridden by the current activity, so just resolve with it
getSystemBrightnessAsync(promise)
} else {
promise.resolve(lp.screenBrightness)
}
}
}
@ExpoMethod
fun getSystemBrightnessAsync(promise: Promise) {
try {
val brightnessMode = Settings.System.getInt(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE
)
if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
val brightness = Settings.System.getFloat(
currentActivity.contentResolver, // https://stackoverflow.com/questions/29349153/change-adaptive-brightness-level-programatically
// this setting cannot be changed starting in targetSdkVersion 23, but it can still be read
"screen_auto_brightness_adj"
)
promise.resolve((brightness + 1.0f) / 2)
} else {
val brightness = Settings.System.getString(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS
)
promise.resolve(brightness.toInt() / 255f)
}
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS_SYSTEM", "Failed to get the system brightness value", e)
}
}
@ExpoMethod
fun setSystemBrightnessAsync(brightnessValue: Float, promise: Promise) {
try {
// we have to just check this every time
// if we try to store a value for this permission, there is no way to know if the user has changed it
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(currentActivity)) {
promise.reject("ERR_BRIGHTNESS_PERMISSIONS_DENIED", "WRITE_SETTINGS permission has not been granted")
return
}
// manual mode must be set in order to change system brightness (sets the automatic mode off)
Settings.System.putInt(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
Settings.System.putInt(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS,
(brightnessValue * 255).roundToInt()
)
promise.resolve(null)
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS_SYSTEM", "Failed to set the system brightness value", e)
}
}
@ExpoMethod
fun useSystemBrightnessAsync(promise: Promise) {
val activity = currentActivity
activity.runOnUiThread {
try {
val lp = activity.window.attributes
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
activity.window.attributes = lp // must be done on UI thread
promise.resolve(null)
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS", "Failed to set the brightness of the current screen", e)
}
}
}
@ExpoMethod
fun isUsingSystemBrightnessAsync(promise: Promise) {
val activity = currentActivity
activity.runOnUiThread {
val lp = activity.window.attributes
promise.resolve(lp.screenBrightness == WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE)
}
}
@ExpoMethod
fun getSystemBrightnessModeAsync(promise: Promise) {
try {
val brightnessMode = Settings.System.getInt(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE
)
promise.resolve(brightnessModeNativeToJS(brightnessMode))
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS_MODE", "Failed to get the system brightness mode", e)
}
}
@ExpoMethod
fun setSystemBrightnessModeAsync(brightnessMode: Int, promise: Promise) {
try {
// we have to just check this every time
// if we try to store a value for this permission, there is no way to know if the user has changed it
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(currentActivity)) {
promise.reject("ERR_BRIGHTNESS_PERMISSIONS_DENIED", "WRITE_SETTINGS permission has not been granted")
return
}
Settings.System.putInt(
currentActivity.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
brightnessModeJSToNative(brightnessMode)
)
promise.resolve(null)
} catch (e: InvalidArgumentException) {
promise.reject(e)
} catch (e: Exception) {
promise.reject("ERR_BRIGHTNESS_MODE", "Failed to set the system brightness mode", e)
}
}
private fun brightnessModeNativeToJS(nativeValue: Int): Int {
return when (nativeValue) {
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC -> 1
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL -> 2
else -> 0
}
}
@Throws(InvalidArgumentException::class)
private fun brightnessModeJSToNative(jsValue: Int): Int {
return when (jsValue) {
1 -> Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
2 -> Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
else -> throw InvalidArgumentException("Unsupported brightness mode $jsValue")
}
}
private val currentActivity: Activity
get() = activityProvider.currentActivity
}
| bsd-3-clause | 70e8f198e62b018f38dcda419b76c7b9 | 35.334928 | 139 | 0.713458 | 4.627666 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopRenderProcessGoneEvent.kt | 2 | 826 | package abi42_0_0.host.exp.exponent.modules.api.components.webview.events
import abi42_0_0.com.facebook.react.bridge.WritableMap
import abi42_0_0.com.facebook.react.uimanager.events.Event
import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter
/**
* Event emitted when the WebView's process has crashed or
was killed by the OS.
*/
class TopRenderProcessGoneEvent(viewId: Int, private val mEventData: WritableMap) :
Event<TopRenderProcessGoneEvent>(viewId) {
companion object {
const val EVENT_NAME = "topRenderProcessGone"
}
override fun getEventName(): String = EVENT_NAME
override fun canCoalesce(): Boolean = false
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) =
rctEventEmitter.receiveEvent(viewTag, eventName, mEventData)
}
| bsd-3-clause | 4d47ad29b9aee54dd7736995cc7d915e | 32.04 | 83 | 0.77845 | 4.009709 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/TextFieldDelegateTest.kt | 3 | 9750 | /*
* 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.foundation.text
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.MultiParagraphIntrinsics
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.EditProcessor
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.text.input.TextInputSession
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextDecoration
import com.google.common.truth.Truth.assertThat
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(InternalFoundationTextApi::class)
@RunWith(JUnit4::class)
class TextFieldDelegateTest {
private lateinit var canvas: Canvas
private lateinit var mDelegate: TextDelegate
private lateinit var processor: EditProcessor
private lateinit var onValueChange: (TextFieldValue) -> Unit
private lateinit var onEditorActionPerformed: (Any) -> Unit
private lateinit var textInputService: TextInputService
private lateinit var layoutCoordinates: LayoutCoordinates
private lateinit var multiParagraphIntrinsics: MultiParagraphIntrinsics
private lateinit var textLayoutResultProxy: TextLayoutResultProxy
private lateinit var textLayoutResult: TextLayoutResult
/**
* Test implementation of offset map which doubles the offset in transformed text.
*/
private val skippingOffsetMap = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int = offset * 2
override fun transformedToOriginal(offset: Int): Int = offset / 2
}
@Before
fun setup() {
mDelegate = mock()
canvas = mock()
processor = mock()
onValueChange = mock()
onEditorActionPerformed = mock()
textInputService = mock()
layoutCoordinates = mock()
multiParagraphIntrinsics = mock()
textLayoutResult = mock()
textLayoutResultProxy = mock()
whenever(textLayoutResultProxy.value).thenReturn(textLayoutResult)
}
@Test
fun test_setCursorOffset() {
val position = Offset(100f, 200f)
val offset = 10
val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1))
whenever(processor.toTextFieldValue()).thenReturn(editorState)
whenever(textLayoutResultProxy.getOffsetForPosition(position)).thenReturn(offset)
TextFieldDelegate.setCursorOffset(
position,
textLayoutResultProxy,
processor,
OffsetMapping.Identity,
onValueChange
)
verify(onValueChange, times(1)).invoke(
eq(TextFieldValue(text = editorState.text, selection = TextRange(offset)))
)
}
@Test
fun on_focus() {
val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1))
val imeOptions = ImeOptions(
singleLine = true,
capitalization = KeyboardCapitalization.Sentences,
keyboardType = KeyboardType.Phone,
imeAction = ImeAction.Search
)
val textInputSession: TextInputSession = mock()
whenever(
textInputService.startInput(
eq(editorState),
eq(imeOptions),
any(),
eq(onEditorActionPerformed)
)
).thenReturn(textInputSession)
val actual = TextFieldDelegate.onFocus(
textInputService = textInputService,
value = editorState,
editProcessor = processor,
imeOptions = imeOptions,
onValueChange = onValueChange,
onImeActionPerformed = onEditorActionPerformed
)
verify(textInputService).startInput(
eq(
TextFieldValue(
text = editorState.text,
selection = editorState.selection
)
),
eq(imeOptions),
any(),
eq(onEditorActionPerformed)
)
assertThat(actual).isEqualTo(textInputSession)
}
@Test
fun on_blur_with_hiding() {
val editorState = TextFieldValue(
text = "Hello, World",
selection = TextRange(1),
composition = TextRange(3, 5)
)
whenever(processor.toTextFieldValue()).thenReturn(editorState)
val textInputSession = mock<TextInputSession>()
TextFieldDelegate.onBlur(textInputSession, processor, onValueChange)
inOrder(textInputSession) {
verify(textInputSession).dispose()
}
verify(onValueChange, times(1)).invoke(
eq(editorState.copy(composition = null))
)
}
@Test
fun check_setCursorOffset_uses_offset_map() {
val position = Offset(100f, 200f)
val offset = 10
val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1))
whenever(processor.toTextFieldValue()).thenReturn(editorState)
whenever(textLayoutResultProxy.getOffsetForPosition(position)).thenReturn(offset)
TextFieldDelegate.setCursorOffset(
position,
textLayoutResultProxy,
processor,
skippingOffsetMap,
onValueChange
)
verify(onValueChange, times(1)).invoke(
eq(TextFieldValue(text = editorState.text, selection = TextRange(offset / 2)))
)
}
@Test
fun use_identity_mapping_if_none_visual_transformation() {
val transformedText = VisualTransformation.None.filter(
AnnotatedString(text = "Hello, World")
)
val visualText = transformedText.text
val offsetMapping = transformedText.offsetMapping
assertThat(visualText.text).isEqualTo("Hello, World")
for (i in 0..visualText.text.length) {
// Identity mapping returns if no visual filter is provided.
assertThat(offsetMapping.originalToTransformed(i)).isEqualTo(i)
assertThat(offsetMapping.transformedToOriginal(i)).isEqualTo(i)
}
}
@Test
fun apply_composition_decoration() {
val identityOffsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int = offset
override fun transformedToOriginal(offset: Int): Int = offset
}
val input = TransformedText(
text = AnnotatedString.Builder().apply {
pushStyle(SpanStyle(color = Color.Red))
append("Hello, World")
}.toAnnotatedString(),
offsetMapping = identityOffsetMapping
)
val result = TextFieldDelegate.applyCompositionDecoration(
compositionRange = TextRange(3, 6),
transformed = input
)
assertThat(result.text.text).isEqualTo(input.text.text)
assertThat(result.text.spanStyles.size).isEqualTo(2)
assertThat(result.text.spanStyles).contains(
AnnotatedString.Range(SpanStyle(textDecoration = TextDecoration.Underline), 3, 6)
)
}
@Test
fun apply_composition_decoration_with_offsetmap() {
val offsetAmount = 5
val offsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int = offsetAmount + offset
override fun transformedToOriginal(offset: Int): Int = offset - offsetAmount
}
val input = TransformedText(
text = AnnotatedString.Builder().apply {
append(" ".repeat(offsetAmount))
append("Hello World")
}.toAnnotatedString(),
offsetMapping = offsetMapping
)
val range = TextRange(0, 2)
val result = TextFieldDelegate.applyCompositionDecoration(
compositionRange = range,
transformed = input
)
assertThat(result.text.spanStyles.size).isEqualTo(1)
assertThat(result.text.spanStyles).contains(
AnnotatedString.Range(
SpanStyle(textDecoration = TextDecoration.Underline),
range.start + offsetAmount,
range.end + offsetAmount
)
)
}
} | apache-2.0 | e6d1273263af7b0f58216d1cac9a9035 | 34.98155 | 93 | 0.666051 | 5.147835 | false | false | false | false |
riaektiv/fdp | fdp-service/src/main/java/com/riaektiv/fdp/endpoint/RabbitMQEndpointCallbackActor.kt | 1 | 1376 | package com.riaektiv.fdp.endpoint
import com.riaektiv.fdp.common.messages.MessageHeader
import com.riaektiv.fdp.proxy.messages.Response
import org.springframework.amqp.rabbit.core.RabbitTemplate
/**
* Created: 1/28/2018, 5:07 PM Eastern Time
*
* @author Sergey Chuykov
*/
class RabbitMQEndpointCallbackActor<RES : Response> : ActorFactory<EndpointCallback<*>, RabbitMQEndpointCallbackActor<*>>(), EndpointCallback<RES> {
private var rabbitTemplate: RabbitTemplate? = null
fun setRabbitTemplate(rabbitTemplate: RabbitTemplate) {
this.rabbitTemplate = rabbitTemplate
}
override fun getActorType(): Class<EndpointCallback<*>> {
return EndpointCallback::class.java
}
override fun onResponse(response: RES, header: MessageHeader) {
try {
logger.info("< {} replyTo={} correlationId={}", response, header.replyTo, header.correlationId)
rabbitTemplate!!.convertAndSend("fdp.main", "fdp.reply", response) { message ->
val correlationId = header.correlationId
if (correlationId != null) {
@Suppress("DEPRECATION")
message.messageProperties.correlationId = correlationId.toByteArray()
}
message
}
} catch (e: Exception) {
logger.error(e.message, e)
}
}
}
| apache-2.0 | 73d24de6d1d122be496ebf4d0647ec8a | 32.560976 | 148 | 0.649709 | 4.82807 | false | false | false | false |
twilio/video-quickstart-android | exampleAdvancedCameraCapturer/src/main/java/com/twilio/video/examples/advancedcameracapturer/AdvancedCameraCapturerActivity.kt | 1 | 6118 | package com.twilio.video.examples.advancedcameracapturer
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.hardware.Camera
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import com.twilio.video.CameraCapturer
import com.twilio.video.CameraParameterUpdater
import com.twilio.video.LocalVideoTrack
import com.twilio.video.VideoView
import tvi.webrtc.Camera1Enumerator
/**
* This example demonstrates advanced use cases of [com.twilio.video.CameraCapturer]. Current
* use cases shown are as follows:
*
* 1. Setting Custom [android.hardware.Camera.Parameters]
* 2. Taking a picture while capturing
*/
class AdvancedCameraCapturerActivity : Activity() {
private lateinit var videoView: VideoView
private lateinit var toggleFlashButton: Button
private lateinit var takePictureButton: Button
private lateinit var pictureImageView: ImageView
private lateinit var pictureDialog: AlertDialog
private val backCameraId by lazy {
val camera1Enumerator = Camera1Enumerator()
val cameraId = camera1Enumerator.deviceNames.find { camera1Enumerator.isBackFacing(it) }
requireNotNull(cameraId)
}
private val cameraCapturer by lazy {
CameraCapturer(this, backCameraId)
}
private val localVideoTrack by lazy {
LocalVideoTrack.create(this, true, cameraCapturer)
}
private var flashOn = false
private val toggleFlashButtonClickListener = View.OnClickListener { toggleFlash() }
private val takePictureButtonClickListener = View.OnClickListener { takePicture() }
/**
* An example of a [CameraParameterUpdater] that shows how to toggle the flash of a
* camera if supported by the device.
*/
@Suppress("DEPRECATION")
private val flashToggler =
CameraParameterUpdater { parameters: Camera.Parameters ->
if (parameters.flashMode != null) {
val flashMode =
if (flashOn) Camera.Parameters.FLASH_MODE_OFF else Camera.Parameters.FLASH_MODE_TORCH
parameters.flashMode = flashMode
flashOn = !flashOn
} else {
Toast.makeText(
this@AdvancedCameraCapturerActivity,
R.string.flash_not_supported,
Toast.LENGTH_LONG
).show()
}
}
/**
* An example of a [tvi.webrtc.VideoProcessor] that decodes the preview image to a [Bitmap]
* and shows the result in an alert dialog.
*/
private val photographer by lazy { Photographer(videoView) }
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_advanced_camera_capturer)
videoView = findViewById<View>(R.id.video_view) as VideoView
toggleFlashButton = findViewById<View>(R.id.toggle_flash_button) as Button
takePictureButton = findViewById<View>(R.id.take_picture_button) as Button
pictureImageView = layoutInflater.inflate(
R.layout.picture_image_view,
findViewById(android.R.id.content),
false
) as ImageView
pictureDialog = AlertDialog.Builder(this)
.setView(pictureImageView)
.setTitle(null)
.setPositiveButton(
R.string.close
) { dialog: DialogInterface, _: Int -> dialog.dismiss() }.create()
if (!checkPermissionForCamera()) {
requestPermissionForCamera()
} else {
addCameraVideo()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
var cameraPermissionGranted = true
for (grantResult in grantResults) {
cameraPermissionGranted =
cameraPermissionGranted and (grantResult == PackageManager.PERMISSION_GRANTED)
}
if (cameraPermissionGranted) {
addCameraVideo()
} else {
Toast.makeText(
this,
R.string.permissions_needed,
Toast.LENGTH_LONG
).show()
finish()
}
}
}
override fun onDestroy() {
localVideoTrack?.removeSink(videoView)
localVideoTrack?.release()
super.onDestroy()
}
private fun checkPermissionForCamera(): Boolean {
val resultCamera =
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
return resultCamera == PackageManager.PERMISSION_GRANTED
}
private fun requestPermissionForCamera() {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.CAMERA),
CAMERA_PERMISSION_REQUEST_CODE
)
}
private fun addCameraVideo() {
localVideoTrack?.videoSource?.setVideoProcessor(photographer)
toggleFlashButton.setOnClickListener(toggleFlashButtonClickListener)
takePictureButton.setOnClickListener(takePictureButtonClickListener)
}
private fun toggleFlash() {
// Request an update to camera parameters with flash toggler
cameraCapturer.updateCameraParameters(flashToggler)
}
private fun takePicture() {
photographer.takePicture { bitmap: Bitmap? ->
bitmap?.let {
runOnUiThread { showPicture(it) }
}
}
}
private fun showPicture(bitmap: Bitmap) {
pictureImageView.setImageBitmap(bitmap)
pictureDialog.show()
}
companion object {
private const val CAMERA_PERMISSION_REQUEST_CODE = 100
}
}
| mit | 49211359c766d6893de57ba3105ba9b5 | 34.16092 | 105 | 0.659202 | 5.077178 | false | false | false | false |
satamas/fortran-plugin | src/main/java/org/jetbrains/fortran/lang/psi/mixin/FortranSeparateModuleSubprogramImplMixin.kt | 1 | 1703 | package org.jetbrains.fortran.lang.psi.mixin
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.fortran.lang.psi.*
import org.jetbrains.fortran.lang.psi.ext.FortranNamedElement
import org.jetbrains.fortran.lang.psi.impl.FortranProgramUnitImpl
import org.jetbrains.fortran.lang.stubs.FortranProgramUnitStub
abstract class FortranSeparateModuleSubprogramImplMixin : FortranProgramUnitImpl, FortranNamedElement, FortranSeparateModuleSubprogram {
constructor(node: ASTNode) : super(node)
constructor(stub: FortranProgramUnitStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getNameIdentifier(): PsiElement? = mpSubprogramStmt.entityDecl
override val variables: List<FortranNamedElement>
get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranTypeDeclarationStmt::class.java)
.flatMap { PsiTreeUtil.getStubChildrenOfTypeAsList(it, FortranEntityDecl::class.java) }
override val unit: FortranNamedElement?
get() = PsiTreeUtil.getStubChildOfType(
PsiTreeUtil.getStubChildOfType(this, FortranMpSubprogramStmt::class.java),
FortranEntityDecl::class.java
)
override val usedModules: List<FortranDataPath>
get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranUseStmt::class.java)
.mapNotNull { it.dataPath }
override val types: List<FortranNamedElement>
get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranDerivedTypeDef::class.java)
.mapNotNull { it.derivedTypeStmt.typeDecl }
} | apache-2.0 | b299794ccf4808353c2232f6a36a6037 | 45.054054 | 136 | 0.765708 | 4.783708 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/EditTag.kt | 1 | 3208 | /*
* Copyright (c) 2017-2019 Yui
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package moe.kyubey.akatsuki.commands
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.annotations.Alias
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Arguments
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.db.schema.Tags
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.I18n
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.update
@Load
@Arguments(
Argument("name", "string"),
Argument("content", "string")
)
@Alias("editpasta", "editahh")
class EditTag : Command() {
override val desc = "Edit tags"
override fun run(ctx: Context) {
val name = ctx.args["name"] as String
val content = ctx.args["content"] as String
asyncTransaction(Akatsuki.pool) {
val tag = Tags.select { Tags.tagName.eq(name) }.firstOrNull()
?: return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("tag_not_found"),
mapOf("username" to ctx.author.name)
)
)
if (tag[Tags.ownerId] != ctx.author.idLong) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("tag_not_owner"),
mapOf("username" to ctx.author.name)
)
)
}
Tags.update({
Tags.tagName.eq(name)
}) {
it[tagContent] = content
}
ctx.send(
I18n.parse(
ctx.lang.getString("tag_edited"),
mapOf("name" to name)
)
)
}.execute()
}
} | mit | f2774d623468b281710afbcc107b2a06 | 35.885057 | 73 | 0.610349 | 4.443213 | false | false | false | false |
Flipkart/stag-java | stag-library-compiler/src/test/java/com/vimeo/stag/processor/Utils.kt | 1 | 3844 | /*
* The MIT License (MIT)
* <p/>
* Copyright (c) 2016 Vimeo
* <p/>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p/>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p/>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.vimeo.stag.processor
import com.vimeo.stag.processor.dummy.DummyGenericClass
import com.vimeo.stag.processor.utils.Preconditions
import org.junit.Assert.assertTrue
import java.lang.reflect.InvocationTargetException
import javax.lang.model.element.TypeElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
internal object Utils {
internal lateinit var elements: Elements
internal lateinit var types: Types
private fun safeTypes(): Types {
Preconditions.checkNotNull(types)
return types
}
@Throws(Exception::class)
fun <T> testZeroArgumentConstructorFinalClass(clazz: Class<T>) {
var exceptionThrown = false
try {
val constructor = clazz.getDeclaredConstructor()
constructor.isAccessible = true
constructor.newInstance()
} catch (e: InvocationTargetException) {
if (e.cause is UnsupportedOperationException) {
exceptionThrown = true
}
}
assertTrue(exceptionThrown)
}
/**
* Gets the parameterized class with the given parameters.
*
* @param clazz the class to parameterize.
* @param parameters the parameters to use.
* @return the declared type mirror with the correct type parameters.
*/
fun getParameterizedClass(clazz: Class<*>, vararg parameters: Class<*>): DeclaredType {
val rootType = elements.getTypeElement(clazz.name)
val params = parameters.map { elements.getTypeElement(it.name).asType() }.toTypedArray()
return safeTypes().getDeclaredType(rootType, *params)
}
fun getElementFromClass(clazz: Class<*>): TypeElement = elements.getTypeElement(clazz.name)
fun getTypeMirrorFromClass(clazz: Class<*>): TypeMirror {
val element = getElementFromClass(clazz)
return element.asType()
}
fun getElementFromObject(`object`: Any): TypeElement = elements.getTypeElement(`object`.javaClass.name)
fun getTypeMirrorFromObject(`object`: Any): TypeMirror {
val element = getElementFromObject(`object`)
return element.asType()
}
fun getGenericVersionOfClass(clazz: Class<*>): TypeMirror {
val params = elements.getTypeElement(clazz.name).typeParameters
val genericTypes = arrayOfNulls<TypeMirror>(params.size)
for (n in genericTypes.indices) {
genericTypes[n] = params[n].asType()
}
return safeTypes().getDeclaredType(elements.getTypeElement(DummyGenericClass::class.java.name),
*genericTypes)
}
}
| mit | 84aaea1b576303b060bd7c205413f741 | 37.44 | 107 | 0.707336 | 4.728167 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt | 2 | 61177 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.infer
import com.intellij.openapi.project.Project
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.*
import org.rust.lang.core.resolve.ref.MethodResolveVariant
import org.rust.lang.core.resolve.ref.pathPsiSubst
import org.rust.lang.core.resolve.ref.resolvePathRaw
import org.rust.lang.core.types.*
import org.rust.lang.core.types.consts.*
import org.rust.lang.core.types.infer.TypeError.ConstMismatch
import org.rust.lang.core.types.infer.TypeError.TypeMismatch
import org.rust.lang.core.types.regions.Region
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.ty.Mutability.IMMUTABLE
import org.rust.lang.core.types.ty.Mutability.MUTABLE
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.snapshot.CombinedSnapshot
import org.rust.lang.utils.snapshot.Snapshot
import org.rust.openapiext.Testmark
import org.rust.openapiext.recursionGuard
import org.rust.openapiext.testAssert
import org.rust.stdext.*
import org.rust.stdext.RsResult.Err
import org.rust.stdext.RsResult.Ok
fun inferTypesIn(element: RsInferenceContextOwner): RsInferenceResult {
val items = element.knownItems
val paramEnv = if (element is RsItemElement) ParamEnv.buildFor(element) else ParamEnv.EMPTY
val lookup = ImplLookup(element.project, element.containingCrate, items, paramEnv)
return recursionGuard(element, { lookup.ctx.infer(element) }, memoize = false)
?: error("Can not run nested type inference")
}
sealed class Adjustment: TypeFoldable<Adjustment> {
abstract val target: Ty
override fun superVisitWith(visitor: TypeVisitor): Boolean = target.visitWith(visitor)
class NeverToAny(override val target: Ty) : Adjustment() {
override fun superFoldWith(folder: TypeFolder): Adjustment = NeverToAny(target.foldWith(folder))
}
class Deref(
override val target: Ty,
/** Non-null if dereference has been done using Deref/DerefMut trait */
val overloaded: Mutability?
) : Adjustment() {
override fun superFoldWith(folder: TypeFolder): Adjustment = Deref(target.foldWith(folder), overloaded)
}
class BorrowReference(
override val target: TyReference
) : Adjustment() {
val region: Region = target.region
val mutability: Mutability = target.mutability
override fun superFoldWith(folder: TypeFolder): Adjustment = BorrowReference(target.foldWith(folder) as TyReference)
}
class BorrowPointer(
override val target: TyPointer,
) : Adjustment() {
val mutability: Mutability = target.mutability
override fun superFoldWith(folder: TypeFolder): Adjustment = BorrowPointer(target.foldWith(folder) as TyPointer)
}
class MutToConstPointer(override val target: TyPointer) : Adjustment() {
override fun superFoldWith(folder: TypeFolder): Adjustment = MutToConstPointer(target.foldWith(folder) as TyPointer)
}
class Unsize(override val target: Ty) : Adjustment() {
override fun superFoldWith(folder: TypeFolder): Adjustment = Unsize(target.foldWith(folder))
}
}
interface RsInferenceData {
fun getExprAdjustments(expr: RsElement): List<Adjustment>
fun getExprType(expr: RsExpr): Ty
fun getExpectedExprType(expr: RsExpr): ExpectedType
fun getPatType(pat: RsPat): Ty
fun getPatFieldType(patField: RsPatField): Ty
fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath>
fun isOverloadedOperator(expr: RsExpr): Boolean
fun getBindingType(binding: RsPatBinding): Ty =
when (val parent = binding.parent) {
is RsPat -> getPatType(parent)
is RsPatField -> getPatFieldType(parent)
else -> TyUnknown // impossible
}
fun getExprTypeAdjusted(expr: RsExpr): Ty = getExprAdjustments(expr).lastOrNull()?.target ?: getExprType(expr)
}
/**
* [RsInferenceResult] is an immutable per-function map
* from expressions to their types.
*/
class RsInferenceResult(
val exprTypes: Map<RsExpr, Ty>,
val patTypes: Map<RsPat, Ty>,
val patFieldTypes: Map<RsPatField, Ty>,
private val expectedExprTypes: Map<RsExpr, ExpectedType>,
private val resolvedPaths: Map<RsPathExpr, List<ResolvedPath>>,
private val resolvedMethods: Map<RsMethodCall, InferredMethodCallInfo>,
private val resolvedFields: Map<RsFieldLookup, List<RsElement>>,
private val adjustments: Map<RsElement, List<Adjustment>>,
private val overloadedOperators: Set<RsElement>,
val diagnostics: List<RsDiagnostic>
) : RsInferenceData {
private val timestamp: Long = System.nanoTime()
override fun getExprAdjustments(expr: RsElement): List<Adjustment> =
adjustments[expr] ?: emptyList()
override fun getExprType(expr: RsExpr): Ty =
exprTypes[expr] ?: TyUnknown
override fun getPatType(pat: RsPat): Ty =
patTypes[pat] ?: TyUnknown
override fun getPatFieldType(patField: RsPatField): Ty =
patFieldTypes[patField] ?: TyUnknown
override fun getExpectedExprType(expr: RsExpr): ExpectedType =
expectedExprTypes[expr] ?: ExpectedType.UNKNOWN
override fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath> =
resolvedPaths[expr] ?: emptyList()
override fun isOverloadedOperator(expr: RsExpr): Boolean = expr in overloadedOperators
fun getResolvedMethod(call: RsMethodCall): List<MethodResolveVariant> =
resolvedMethods[call]?.resolveVariants ?: emptyList()
fun getResolvedMethodType(call: RsMethodCall): TyFunction? =
resolvedMethods[call]?.type
fun getResolvedMethodSubst(call: RsMethodCall): Substitution =
resolvedMethods[call]?.subst ?: emptySubstitution
fun getResolvedField(call: RsFieldLookup): List<RsElement> =
resolvedFields[call] ?: emptyList()
@TestOnly
fun isExprTypeInferred(expr: RsExpr): Boolean =
expr in exprTypes
@TestOnly
fun getTimestamp(): Long = timestamp
companion object {
@JvmStatic
val EMPTY: RsInferenceResult = RsInferenceResult(
emptyMap(),
emptyMap(),
emptyMap(),
emptyMap(),
emptyMap(),
emptyMap(),
emptyMap(),
emptyMap(),
emptySet(),
emptyList(),
)
}
}
/**
* A mutable object, which is filled while we walk function body top down.
*/
class RsInferenceContext(
val project: Project,
val lookup: ImplLookup,
val items: KnownItems
) : RsInferenceData {
val fulfill: FulfillmentContext = FulfillmentContext(this, lookup)
private val exprTypes: MutableMap<RsExpr, Ty> = hashMapOf()
private val patTypes: MutableMap<RsPat, Ty> = hashMapOf()
private val patFieldTypes: MutableMap<RsPatField, Ty> = hashMapOf()
private val expectedExprTypes: MutableMap<RsExpr, ExpectedType> = hashMapOf()
private val resolvedPaths: MutableMap<RsPathExpr, List<ResolvedPath>> = hashMapOf()
private val resolvedMethods: MutableMap<RsMethodCall, InferredMethodCallInfo> = hashMapOf()
private val resolvedFields: MutableMap<RsFieldLookup, List<RsElement>> = hashMapOf()
private val pathRefinements: MutableList<Pair<RsPathExpr, TraitRef>> = mutableListOf()
private val methodRefinements: MutableList<Pair<RsMethodCall, TraitRef>> = mutableListOf()
private val adjustments: MutableMap<RsElement, MutableList<Adjustment>> = hashMapOf()
private val overloadedOperators: MutableSet<RsElement> = hashSetOf()
val diagnostics: MutableList<RsDiagnostic> = mutableListOf()
private val intUnificationTable: UnificationTable<TyInfer.IntVar, TyInteger> = UnificationTable()
private val floatUnificationTable: UnificationTable<TyInfer.FloatVar, TyFloat> = UnificationTable()
private val varUnificationTable: UnificationTable<TyInfer.TyVar, Ty> = UnificationTable()
private val constUnificationTable: UnificationTable<CtInferVar, Const> = UnificationTable()
private val projectionCache: ProjectionCache = ProjectionCache()
fun startSnapshot(): Snapshot = CombinedSnapshot(
intUnificationTable.startSnapshot(),
floatUnificationTable.startSnapshot(),
varUnificationTable.startSnapshot(),
constUnificationTable.startSnapshot(),
projectionCache.startSnapshot()
)
inline fun <T> probe(action: () -> T): T {
val snapshot = startSnapshot()
try {
return action()
} finally {
snapshot.rollback()
}
}
inline fun <T : Any> commitIfNotNull(action: () -> T?): T? {
val snapshot = startSnapshot()
val result = action()
if (result == null) snapshot.rollback() else snapshot.commit()
return result
}
fun infer(element: RsInferenceContextOwner): RsInferenceResult {
when (element) {
is RsFunction -> {
val retTy = normalizeAssociatedTypesIn(element.rawReturnType).value
val fctx = RsTypeInferenceWalker(this, retTy)
fctx.extractParameterBindings(element)
element.block?.let { fctx.inferFnBody(it) }
}
is RsReplCodeFragment -> {
element.context.inference?.let {
patTypes.putAll(it.patTypes)
patFieldTypes.putAll(it.patFieldTypes)
exprTypes.putAll(it.exprTypes)
}
RsTypeInferenceWalker(this, TyUnknown).inferReplCodeFragment(element)
}
is RsPath -> {
val declaration = resolvePathRaw(element, lookup).singleOrNull()?.element as? RsGenericDeclaration
if (declaration != null) {
val constParameters = mutableListOf<RsConstParameter>()
val constArguments = mutableListOf<RsElement>()
for ((param, value) in pathPsiSubst(element, declaration).constSubst) {
if (value is RsPsiSubstitution.Value.Present) {
constParameters += param
constArguments += value.value
}
}
RsTypeInferenceWalker(this, TyUnknown).inferConstArgumentTypes(constParameters, constArguments)
}
}
else -> {
val (retTy, expr) = when (element) {
is RsConstant -> element.typeReference?.rawType to element.expr
is RsConstParameter -> element.typeReference?.rawType to element.expr
is RsArrayType -> TyInteger.USize.INSTANCE to element.expr
is RsVariantDiscriminant -> {
val enum = element.contextStrict<RsEnumItem>()
enum?.reprType to element.expr
}
is RsExpressionCodeFragment -> {
element.context.inference?.let {
patTypes.putAll(it.patTypes)
patFieldTypes.putAll(it.patFieldTypes)
exprTypes.putAll(it.exprTypes)
}
null to element.expr
}
else -> error(
"Type inference is not implemented for PSI element of type " +
"`${element.javaClass}` that implement `RsInferenceContextOwner`"
)
}
if (expr != null) {
RsTypeInferenceWalker(this, retTy ?: TyUnknown).inferLambdaBody(expr)
}
}
}
fulfill.selectWherePossible()
fallbackUnresolvedTypeVarsIfPossible()
fulfill.selectWherePossible()
exprTypes.replaceAll { _, ty -> fullyResolve(ty) }
expectedExprTypes.replaceAll { _, ty -> fullyResolveWithOrigins(ty) }
patTypes.replaceAll { _, ty -> fullyResolve(ty) }
patFieldTypes.replaceAll { _, ty -> fullyResolve(ty) }
// replace types in diagnostics for better quick fixes
diagnostics.replaceAll { if (it is RsDiagnostic.TypeError) fullyResolve(it) else it }
adjustments.replaceAll { _, it -> it.mapToMutableList { fullyResolve(it) } }
performPathsRefinement(lookup)
resolvedPaths.values.asSequence().flatten()
.forEach { it.subst = it.subst.foldValues(fullTypeWithOriginsResolver) }
resolvedMethods.replaceAll { _, ty -> fullyResolveWithOrigins(ty) }
return RsInferenceResult(
exprTypes,
patTypes,
patFieldTypes,
expectedExprTypes,
resolvedPaths,
resolvedMethods,
resolvedFields,
adjustments,
overloadedOperators,
diagnostics
)
}
private fun fallbackUnresolvedTypeVarsIfPossible() {
val allTypes = exprTypes.values.asSequence() + patTypes.values.asSequence() +
patFieldTypes.values.asSequence() + expectedExprTypes.values.asSequence().map { it.ty }
for (ty in allTypes) {
ty.visitInferTys { tyInfer ->
val rty = shallowResolve(tyInfer)
if (rty is TyInfer) {
fallbackIfPossible(rty)
}
false
}
}
}
private fun fallbackIfPossible(ty: TyInfer) {
when (ty) {
is TyInfer.IntVar -> intUnificationTable.unifyVarValue(ty, TyInteger.DEFAULT)
is TyInfer.FloatVar -> floatUnificationTable.unifyVarValue(ty, TyFloat.DEFAULT)
is TyInfer.TyVar -> Unit
}
}
private fun performPathsRefinement(lookup: ImplLookup) {
for ((path, traitRef) in pathRefinements) {
val variant = resolvedPaths[path]?.firstOrNull() ?: continue
val fnName = (variant.element as? RsFunction)?.name
val impl = lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()?.impl as? RsImplItem ?: continue
val fn = impl.expandedMembers.functions.find { it.name == fnName } ?: continue
val source = RsCachedImplItem.forImpl(impl).explicitImpl
val result = ResolvedPath.AssocItem(fn, source)
result.subst = variant.subst // TODO remap subst
resolvedPaths[path] = listOf(result)
}
for ((call, traitRef) in methodRefinements) {
val info = resolvedMethods[call] ?: continue
val variant = info.resolveVariants.firstOrNull() ?: continue
val impl = lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()?.impl as? RsImplItem ?: continue
val fn = impl.expandedMembers.functions.find { it.name == variant.name } ?: continue
val source = RsCachedImplItem.forImpl(impl).explicitImpl
// TODO remap subst
resolvedMethods[call] = info.copy(resolveVariants = listOf(variant.copy(element = fn, source = source)))
}
}
override fun getExprAdjustments(expr: RsElement): List<Adjustment> {
return adjustments[expr] ?: emptyList()
}
override fun getExprType(expr: RsExpr): Ty {
return exprTypes[expr] ?: TyUnknown
}
override fun getPatType(pat: RsPat): Ty {
return patTypes[pat] ?: TyUnknown
}
override fun getPatFieldType(patField: RsPatField): Ty {
return patFieldTypes[patField] ?: TyUnknown
}
override fun getExpectedExprType(expr: RsExpr): ExpectedType {
return expectedExprTypes[expr] ?: ExpectedType.UNKNOWN
}
override fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath> {
return resolvedPaths[expr] ?: emptyList()
}
override fun isOverloadedOperator(expr: RsExpr): Boolean = expr in overloadedOperators
fun isTypeInferred(expr: RsExpr): Boolean {
return exprTypes.containsKey(expr)
}
fun writeExprTy(psi: RsExpr, ty: Ty) {
exprTypes[psi] = ty
}
fun writePatTy(psi: RsPat, ty: Ty) {
patTypes[psi] = ty
}
fun writePatFieldTy(psi: RsPatField, ty: Ty) {
patFieldTypes[psi] = ty
}
fun writeExpectedExprTy(psi: RsExpr, ty: Ty) {
expectedExprTypes[psi] = ExpectedType(ty)
}
fun writeExpectedExprTyCoercable(psi: RsExpr) {
expectedExprTypes.computeIfPresent(psi) { _, v -> v.copy(coercable = true) }
}
fun writePath(path: RsPathExpr, resolved: List<ResolvedPath>) {
resolvedPaths[path] = resolved
}
fun writePathSubst(path: RsPathExpr, subst: Substitution) {
resolvedPaths[path]?.singleOrNull()?.subst = subst
}
fun writeResolvedMethod(call: RsMethodCall, resolvedTo: List<MethodResolveVariant>) {
resolvedMethods[call] = InferredMethodCallInfo(resolvedTo)
}
fun writeResolvedMethodSubst(call: RsMethodCall, subst: Substitution, ty: TyFunction) {
resolvedMethods[call]?.let {
it.subst = subst
it.type = ty
}
}
fun writeResolvedField(lookup: RsFieldLookup, resolvedTo: List<RsElement>) {
resolvedFields[lookup] = resolvedTo
}
fun registerPathRefinement(path: RsPathExpr, traitRef: TraitRef) {
pathRefinements.add(Pair(path, traitRef))
}
private fun registerMethodRefinement(path: RsMethodCall, traitRef: TraitRef) {
methodRefinements.add(Pair(path, traitRef))
}
fun addDiagnostic(diagnostic: RsDiagnostic) {
if (diagnostic.element.containingFile.isPhysical) {
diagnostics.add(diagnostic)
}
}
fun applyAdjustment(expr: RsElement, adjustment: Adjustment) {
applyAdjustments(expr, listOf(adjustment))
}
fun applyAdjustments(expr: RsElement, adjustment: List<Adjustment>) {
if (adjustment.isEmpty()) return
val unwrappedExpr = if (expr is RsExpr) {
unwrapParenExprs(expr)
} else {
expr
}
val isAutoborrowMut = adjustment.any { it is Adjustment.BorrowReference && it.mutability == MUTABLE }
adjustments.getOrPut(unwrappedExpr) { mutableListOf() }.addAll(adjustment)
if (isAutoborrowMut && unwrappedExpr is RsExpr) {
convertPlaceDerefsToMutable(unwrappedExpr)
}
}
fun writeOverloadedOperator(expr: RsExpr) {
overloadedOperators += expr
}
fun reportTypeMismatch(element: RsElement, expected: Ty, actual: Ty) {
addDiagnostic(RsDiagnostic.TypeError(element, expected, actual))
}
@Suppress("MemberVisibilityCanBePrivate")
fun canCombineTypes(ty1: Ty, ty2: Ty): Boolean {
return probe { combineTypes(ty1, ty2).isOk }
}
private fun combineTypesIfOk(ty1: Ty, ty2: Ty): Boolean {
return combineTypesIfOkResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesIfOkResolved(ty1: Ty, ty2: Ty): Boolean {
val snapshot = startSnapshot()
val res = combineTypesResolved(ty1, ty2).isOk
if (res) {
snapshot.commit()
} else {
snapshot.rollback()
}
return res
}
fun combineTypes(ty1: Ty, ty2: Ty): RelateResult {
return combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesResolved(ty1: Ty, ty2: Ty): RelateResult {
return when {
ty1 is TyInfer.TyVar -> combineTyVar(ty1, ty2)
ty2 is TyInfer.TyVar -> combineTyVar(ty2, ty1)
else -> when {
ty1 is TyInfer -> combineIntOrFloatVar(ty1, ty2)
ty2 is TyInfer -> combineIntOrFloatVar(ty2, ty1)
else -> combineTypesNoVars(ty1, ty2)
}
}
}
private fun combineTyVar(ty1: TyInfer.TyVar, ty2: Ty): RelateResult {
when (ty2) {
is TyInfer.TyVar -> varUnificationTable.unifyVarVar(ty1, ty2)
else -> {
val ty1r = varUnificationTable.findRoot(ty1)
val isTy2ContainsTy1 = ty2.visitWith(object : TypeVisitor {
override fun visitTy(ty: Ty): Boolean = when {
ty is TyInfer.TyVar && varUnificationTable.findRoot(ty) == ty1r -> true
ty.hasTyInfer -> ty.superVisitWith(this)
else -> false
}
})
if (isTy2ContainsTy1) {
// "E0308 cyclic type of infinite size"
TypeInferenceMarks.CyclicType.hit()
varUnificationTable.unifyVarValue(ty1r, TyUnknown)
} else {
varUnificationTable.unifyVarValue(ty1r, ty2)
}
}
}
return Ok(Unit)
}
private fun combineIntOrFloatVar(ty1: TyInfer, ty2: Ty): RelateResult {
when (ty1) {
is TyInfer.IntVar -> when (ty2) {
is TyInfer.IntVar -> intUnificationTable.unifyVarVar(ty1, ty2)
is TyInteger -> intUnificationTable.unifyVarValue(ty1, ty2)
else -> return Err(TypeMismatch(ty1, ty2))
}
is TyInfer.FloatVar -> when (ty2) {
is TyInfer.FloatVar -> floatUnificationTable.unifyVarVar(ty1, ty2)
is TyFloat -> floatUnificationTable.unifyVarValue(ty1, ty2)
else -> return Err(TypeMismatch(ty1, ty2))
}
is TyInfer.TyVar -> error("unreachable")
}
return Ok(Unit)
}
fun combineTypesNoVars(ty1: Ty, ty2: Ty): RelateResult =
when {
ty1 === ty2 -> Ok(Unit)
ty1 is TyPrimitive && ty2 is TyPrimitive && ty1.javaClass == ty2.javaClass -> Ok(Unit)
ty1 is TyTypeParameter && ty2 is TyTypeParameter && ty1 == ty2 -> Ok(Unit)
ty1 is TyProjection && ty2 is TyProjection && ty1.target == ty2.target && combineBoundElements(ty1.trait, ty2.trait) -> {
combineTypes(ty1.type, ty2.type)
}
ty1 is TyReference && ty2 is TyReference && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyPointer && ty2 is TyPointer && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyArray && ty2 is TyArray && (ty1.size == null || ty2.size == null || ty1.size == ty2.size) ->
combineTypes(ty1.base, ty2.base).and { combineConsts(ty1.const, ty2.const) }
ty1 is TySlice && ty2 is TySlice -> combineTypes(ty1.elementType, ty2.elementType)
ty1 is TyTuple && ty2 is TyTuple && ty1.types.size == ty2.types.size -> {
combineTypePairs(ty1.types.zip(ty2.types))
}
ty1 is TyFunction && ty2 is TyFunction && ty1.paramTypes.size == ty2.paramTypes.size -> {
combineTypePairs(ty1.paramTypes.zip(ty2.paramTypes))
.and { combineTypes(ty1.retType, ty2.retType) }
}
ty1 is TyAdt && ty2 is TyAdt && ty1.item == ty2.item -> {
combineTypePairs(ty1.typeArguments.zip(ty2.typeArguments))
.and { combineConstPairs(ty1.constArguments.zip(ty2.constArguments)) }
}
ty1 is TyTraitObject && ty2 is TyTraitObject &&
// TODO: Use all trait bounds
combineBoundElements(ty1.traits.first(), ty2.traits.first()) -> Ok(Unit)
ty1 is TyAnon && ty2 is TyAnon && ty1.definition != null && ty1.definition == ty2.definition -> Ok(Unit)
ty1 is TyNever || ty2 is TyNever -> Ok(Unit)
else -> Err(TypeMismatch(ty1, ty2))
}
fun combineConsts(const1: Const, const2: Const): RelateResult {
return combineConstsResolved(shallowResolve(const1), shallowResolve(const2))
}
private fun combineConstsResolved(const1: Const, const2: Const): RelateResult =
when {
const1 is CtInferVar -> combineConstVar(const1, const2)
const2 is CtInferVar -> combineConstVar(const2, const1)
else -> combineConstsNoVars(const1, const2)
}
private fun combineConstVar(const1: CtInferVar, const2: Const): RelateResult {
if (const2 is CtInferVar) {
constUnificationTable.unifyVarVar(const1, const2)
} else {
val const1r = constUnificationTable.findRoot(const1)
constUnificationTable.unifyVarValue(const1r, const2)
}
return Ok(Unit)
}
private fun combineConstsNoVars(const1: Const, const2: Const): RelateResult =
when {
const1 === const2 -> Ok(Unit)
const1 is CtUnknown || const2 is CtUnknown -> Ok(Unit)
const1 is CtUnevaluated || const2 is CtUnevaluated -> Ok(Unit)
const1 == const2 -> Ok(Unit)
else -> Err(ConstMismatch(const1, const2))
}
fun combineTypePairs(pairs: List<Pair<Ty, Ty>>): RelateResult = combinePairs(pairs, ::combineTypes)
fun combineConstPairs(pairs: List<Pair<Const, Const>>): RelateResult = combinePairs(pairs, ::combineConsts)
private fun <T : Kind> combinePairs(pairs: List<Pair<T, T>>, combine: (T, T) -> RelateResult): RelateResult {
var canUnify: RelateResult = Ok(Unit)
for ((k1, k2) in pairs) {
canUnify = combine(k1, k2).and { canUnify }
}
return canUnify
}
fun combineTraitRefs(ref1: TraitRef, ref2: TraitRef): Boolean =
ref1.trait.element == ref2.trait.element &&
combineTypes(ref1.selfTy, ref2.selfTy).isOk &&
ref1.trait.subst.zipTypeValues(ref2.trait.subst).all { (a, b) ->
combineTypes(a, b).isOk
} &&
ref1.trait.subst.zipConstValues(ref2.trait.subst).all { (a, b) ->
combineConsts(a, b).isOk
}
fun <T : RsElement> combineBoundElements(be1: BoundElement<T>, be2: BoundElement<T>): Boolean =
be1.element == be2.element &&
combineTypePairs(be1.subst.zipTypeValues(be2.subst)).isOk &&
combineConstPairs(be1.subst.zipConstValues(be2.subst)).isOk &&
combineTypePairs(zipValues(be1.assoc, be2.assoc)).isOk
fun tryCoerce(inferred: Ty, expected: Ty): CoerceResult {
if (inferred === expected) {
return Ok(CoerceOk())
}
if (inferred == TyNever) {
return Ok(CoerceOk(adjustments = listOf(Adjustment.NeverToAny(expected))))
}
if (inferred is TyInfer.TyVar) {
return combineTypes(inferred, expected).into()
}
val unsize = commitIfNotNull { coerceUnsized(inferred, expected) }
if (unsize != null) {
return Ok(unsize)
}
return when {
// Coerce reference to pointer
inferred is TyReference && expected is TyPointer &&
coerceMutability(inferred.mutability, expected.mutability) -> {
combineTypes(inferred.referenced, expected.referenced).map {
CoerceOk(
adjustments = listOf(
Adjustment.Deref(inferred.referenced, overloaded = null),
Adjustment.BorrowPointer(expected)
)
)
}
}
// Coerce mutable pointer to const pointer
inferred is TyPointer && inferred.mutability.isMut
&& expected is TyPointer && !expected.mutability.isMut -> {
combineTypes(inferred.referenced, expected.referenced).map {
CoerceOk(adjustments = listOf(Adjustment.MutToConstPointer(expected)))
}
}
// Coerce references
inferred is TyReference && expected is TyReference &&
coerceMutability(inferred.mutability, expected.mutability) -> {
coerceReference(inferred, expected)
}
else -> combineTypes(inferred, expected).into()
}
}
// &[T; n] or &mut [T; n] -> &[T]
// or &mut [T; n] -> &mut [T]
// or &Concrete -> &Trait, etc.
// Mirrors rustc's `coerce_unsized`
// https://github.com/rust-lang/rust/blob/97d48bec2d/compiler/rustc_typeck/src/check/coercion.rs#L486
private fun coerceUnsized(source: Ty, target: Ty): CoerceOk? {
if (source is TyInfer.TyVar || target is TyInfer.TyVar) return null
// Optimization: return early if unsizing is not needed to match types
if (target.isScalar || canCombineTypes(source, target)) return null
val unsizeTrait = items.Unsize ?: return null
val coerceUnsizedTrait = items.CoerceUnsized ?: return null
val traits = listOf(unsizeTrait, coerceUnsizedTrait)
val reborrow = when {
source is TyReference && target is TyReference -> {
if (!coerceMutability(source.mutability, target.mutability)) return null
Pair(
Adjustment.Deref(source.referenced, overloaded = null),
Adjustment.BorrowReference(TyReference(source.referenced, target.mutability))
)
}
source is TyReference && target is TyPointer -> {
if (!coerceMutability(source.mutability, target.mutability)) return null
Pair(
Adjustment.Deref(source.referenced, overloaded = null),
Adjustment.BorrowPointer(TyPointer(source.referenced, target.mutability))
)
}
else -> null
}
val coerceSource = reborrow?.second?.target ?: source
val adjustments = listOfNotNull(
reborrow?.first,
reborrow?.second,
Adjustment.Unsize(target)
)
val resultObligations = mutableListOf<Obligation>()
val queue = dequeOf(Obligation(Predicate.Trait(TraitRef(coerceSource, coerceUnsizedTrait.withSubst(target)))))
while (!queue.isEmpty()) {
val obligation = queue.removeFirst()
val predicate = resolveTypeVarsIfPossible(obligation.predicate)
if (predicate is Predicate.Trait && predicate.trait.trait.element in traits) {
when (val selection = lookup.select(predicate.trait, obligation.recursionDepth)) {
SelectionResult.Err -> return null
is SelectionResult.Ok -> queue += selection.result.nestedObligations
SelectionResult.Ambiguous -> if (predicate.trait.trait.element == unsizeTrait) {
val selfTy = predicate.trait.selfTy
val unsizeTy = predicate.trait.trait.singleParamValue
if (selfTy is TyInfer.TyVar && unsizeTy is TyTraitObject && typeVarIsSized(selfTy)) {
resultObligations += obligation
} else {
return null
}
} else {
return null
}
}
} else {
resultObligations += obligation
continue
}
}
return CoerceOk(adjustments, resultObligations)
}
private fun typeVarIsSized(ty: TyInfer.TyVar): Boolean {
return fulfill.pendingObligations
.mapNotNull { it.obligation.predicate as? Predicate.Trait }
.any { it.trait.selfTy == ty && it.trait.trait.element == items.Sized }
}
private fun coerceMutability(from: Mutability, to: Mutability): Boolean =
from == to || from.isMut && !to.isMut
/**
* Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
* To match `A` with `B`, autoderef will be performed
*/
private fun coerceReference(inferred: TyReference, expected: TyReference): CoerceResult {
val autoderef = lookup.coercionSequence(inferred)
for (derefTy in autoderef.drop(1)) {
// TODO proper handling of lifetimes
val derefTyRef = TyReference(derefTy, expected.mutability, expected.region)
if (combineTypesIfOk(derefTyRef, expected)) {
// Deref `&a` to `a` and then reborrow as `&a`. No-op. See rustc's `coerce_borrowed_pointer`
val isTrivialReborrow = autoderef.stepCount() == 1
&& inferred.mutability == expected.mutability
&& !expected.mutability.isMut
if (!isTrivialReborrow) {
val adjustments = autoderef.steps().toAdjustments(items) +
listOf(Adjustment.BorrowReference(derefTyRef))
return Ok(CoerceOk(adjustments))
}
return Ok(CoerceOk())
}
}
return Err(TypeMismatch(inferred, expected))
}
fun <T : TypeFoldable<T>> shallowResolve(value: T): T = value.foldWith(shallowResolver)
private inner class ShallowResolver : TypeFolder {
override fun foldTy(ty: Ty): Ty = shallowResolve(ty)
override fun foldConst(const: Const): Const =
if (const is CtInferVar) {
constUnificationTable.findValue(const) ?: const
} else {
const
}
private fun shallowResolve(ty: Ty): Ty {
if (ty !is TyInfer) return ty
return when (ty) {
is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: ty
is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: ty
is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(this::shallowResolve) ?: ty
}
}
}
private val shallowResolver: ShallowResolver = ShallowResolver()
fun <T : TypeFoldable<T>> resolveTypeVarsIfPossible(value: T): T = value.foldWith(opportunisticVarResolver)
private inner class OpportunisticVarResolver : TypeFolder {
override fun foldTy(ty: Ty): Ty {
if (!ty.needsInfer) return ty
val res = shallowResolve(ty)
return res.superFoldWith(this)
}
override fun foldConst(const: Const): Const {
if (!const.hasCtInfer) return const
val res = shallowResolve(const)
return res.superFoldWith(this)
}
}
private val opportunisticVarResolver: OpportunisticVarResolver = OpportunisticVarResolver()
/**
* Full type resolution replaces all type and const variables with their concrete results.
*/
fun <T : TypeFoldable<T>> fullyResolve(value: T): T {
val resolved = value.foldWith(fullTypeResolver)
testAssert { !resolved.hasTyPlaceholder }
return resolved
}
private inner class FullTypeResolver : TypeFolder {
override fun foldTy(ty: Ty): Ty {
if (!ty.needsInfer) return ty
val res = shallowResolve(ty)
return if (res is TyInfer) TyUnknown else res.superFoldWith(this)
}
override fun foldConst(const: Const): Const =
if (const is CtInferVar) {
constUnificationTable.findValue(const) ?: CtUnknown
} else {
const
}
}
private val fullTypeResolver: FullTypeResolver = FullTypeResolver()
/**
* Similar to [fullyResolve], but replaces unresolved [TyInfer.TyVar] to its [TyInfer.TyVar.origin]
* instead of [TyUnknown]
*/
fun <T : TypeFoldable<T>> fullyResolveWithOrigins(value: T): T {
return value.foldWith(fullTypeWithOriginsResolver)
}
private inner class FullTypeWithOriginsResolver : TypeFolder {
override fun foldTy(ty: Ty): Ty {
if (!ty.needsInfer) return ty
return when (val res = shallowResolve(ty)) {
is TyUnknown -> (ty as? TyInfer.TyVar)?.origin as? TyTypeParameter ?: TyUnknown
is TyInfer.TyVar -> res.origin as? TyTypeParameter ?: TyUnknown
is TyInfer -> TyUnknown
else -> res.superFoldWith(this)
}
}
override fun foldConst(const: Const): Const =
if (const is CtInferVar) {
constUnificationTable.findValue(const) ?: CtUnknown
} else {
const
}
}
private val fullTypeWithOriginsResolver: FullTypeWithOriginsResolver = FullTypeWithOriginsResolver()
fun typeVarForParam(ty: TyTypeParameter): Ty = TyInfer.TyVar(ty)
fun constVarForParam(const: CtConstParameter): Const = CtInferVar(const)
fun <T : TypeFoldable<T>> fullyNormalizeAssociatedTypesIn(ty: T): T {
val (normalizedTy, obligations) = normalizeAssociatedTypesIn(ty)
obligations.forEach(fulfill::registerPredicateObligation)
fulfill.selectWherePossible()
return fullyResolve(normalizedTy)
}
/** Deeply normalize projection types. See [normalizeProjectionType] */
fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T, recursionDepth: Int = 0): TyWithObligations<T> {
val obligations = mutableListOf<Obligation>()
val normTy = ty.foldTyProjectionWith {
val normTy = normalizeProjectionType(it, recursionDepth)
obligations += normTy.obligations
normTy.value
}
return TyWithObligations(normTy, obligations)
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* If ambiguity arises, which implies that
* there are unresolved type variables in the projection, we will
* substitute a fresh type variable `$X` and generate a new
* obligation `<T as Trait>::Item == $X` for later.
*/
private fun normalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty> {
return optNormalizeProjectionType(projectionTy, recursionDepth) ?: run {
val tyVar = TyInfer.TyVar(projectionTy)
val obligation = Obligation(recursionDepth + 1, Predicate.Projection(projectionTy, tyVar))
TyWithObligations(tyVar, listOf(obligation))
}
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* Returns `null` in the case of ambiguity, which indicates that there
* are unbound type variables.
*/
fun optNormalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? =
optNormalizeProjectionTypeResolved(resolveTypeVarsIfPossible(projectionTy) as TyProjection, recursionDepth)
/** See [optNormalizeProjectionType] */
private fun optNormalizeProjectionTypeResolved(
projectionTy: TyProjection,
recursionDepth: Int
): TyWithObligations<Ty>? {
if (projectionTy.type is TyInfer.TyVar) return null
return when (val cacheResult = projectionCache.tryStart(projectionTy)) {
ProjectionCacheEntry.Ambiguous -> {
// If we found ambiguity the last time, that generally
// means we will continue to do so until some type in the
// key changes (and we know it hasn't, because we just
// fully resolved it).
// TODO rustc has an exception for closure types here
null
}
ProjectionCacheEntry.InProgress -> {
// While normalized A::B we are asked to normalize A::B.
TypeInferenceMarks.RecursiveProjectionNormalization.hit()
TyWithObligations(TyUnknown)
}
ProjectionCacheEntry.Error -> {
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is ProjectionCacheEntry.NormalizedTy -> {
var ty = cacheResult.ty
// If we find the value in the cache, then return it along
// with the obligations that went along with it. Note
// that, when using a fulfillment context, these
// obligations could in principle be ignored: they have
// already been registered when the cache entry was
// created (and hence the new ones will quickly be
// discarded as duplicated). But when doing trait
// evaluation this is not the case.
// (See rustc's https://github.com/rust-lang/rust/issues/43132 )
if (!hasUnresolvedTypeVars(ty.value)) {
// Once we have inferred everything we need to know, we
// can ignore the `obligations` from that point on.
ty = TyWithObligations(ty.value)
projectionCache.putTy(projectionTy, ty)
}
ty
}
null -> {
when (val selResult = lookup.selectProjection(projectionTy, recursionDepth)) {
is SelectionResult.Ok -> {
val result = selResult.result ?: TyWithObligations(projectionTy)
projectionCache.putTy(projectionTy, pruneCacheValueObligations(result))
result
}
is SelectionResult.Err -> {
projectionCache.error(projectionTy)
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is SelectionResult.Ambiguous -> {
projectionCache.ambiguous(projectionTy)
null
}
}
}
}
}
/**
* If there are unresolved type variables, then we need to include
* any subobligations that bind them, at least until those type
* variables are fully resolved.
*/
private fun pruneCacheValueObligations(ty: TyWithObligations<Ty>): TyWithObligations<Ty> {
if (!hasUnresolvedTypeVars(ty.value)) return TyWithObligations(ty.value)
// I don't completely understand why we leave the only projection
// predicates here, but here is the comment from rustc about it
//
// If we found a `T: Foo<X = U>` predicate, let's check
// if `U` references any unresolved type
// variables. In principle, we only care if this
// projection can help resolve any of the type
// variables found in `result.value` -- but we just
// check for any type variables here, for fear of
// indirect obligations (e.g., we project to `?0`,
// but we have `T: Foo<X = ?1>` and `?1: Bar<X =
// ?0>`).
//
// We are only interested in `T: Foo<X = U>` predicates, where
// `U` references one of `unresolved_type_vars`.
val obligations = ty.obligations
.filter { it.predicate is Predicate.Projection && hasUnresolvedTypeVars(it.predicate) }
return TyWithObligations(ty.value, obligations)
}
private fun <T : TypeFoldable<T>> hasUnresolvedTypeVars(_ty: T): Boolean = _ty.visitWith(object : TypeVisitor {
override fun visitTy(ty: Ty): Boolean {
val resolvedTy = shallowResolve(ty)
return when {
resolvedTy is TyInfer -> true
resolvedTy.hasTyInfer -> resolvedTy.superVisitWith(this)
else -> false
}
}
})
fun <T : TypeFoldable<T>> hasResolvableTypeVars(ty: T): Boolean =
ty.visitInferTys { it != shallowResolve(it) }
/** Return true if [ty] was instantiated or unified with another type variable */
fun isTypeVarAffected(ty: TyInfer.TyVar): Boolean =
varUnificationTable.findRoot(ty) != ty || varUnificationTable.findValue(ty) != null
fun instantiateBounds(
bounds: List<Predicate>,
subst: Substitution = emptySubstitution,
recursionDepth: Int = 0
): Sequence<Obligation> {
return bounds.asSequence()
.map { it.substitute(subst) }
.map { normalizeAssociatedTypesIn(it, recursionDepth) }
.flatMap { it.obligations.asSequence() + Obligation(recursionDepth, it.value) }
}
fun instantiateBounds(
element: RsGenericDeclaration,
selfTy: Ty? = null,
subst: Substitution = emptySubstitution
): Substitution {
val map = run {
val typeSubst = element
.generics
.associateWith { typeVarForParam(it) }
.let { if (selfTy != null) it + (TyTypeParameter.self() to selfTy) else it }
val constSubst = element
.constGenerics
.associateWith { constVarForParam(it) }
subst + Substitution(typeSubst = typeSubst, constSubst = constSubst)
}
instantiateBounds(element.predicates, map).forEach(fulfill::registerPredicateObligation)
return map
}
/** Checks that [selfTy] satisfies all trait bounds of the [source] */
fun canEvaluateBounds(source: TraitImplSource, selfTy: Ty): Boolean {
return when (source) {
is TraitImplSource.ExplicitImpl -> canEvaluateBounds(source.value, selfTy)
is TraitImplSource.Derived, is TraitImplSource.Builtin -> {
if (source.value.typeParameters.isNotEmpty()) return true
lookup.canSelect(TraitRef(selfTy, BoundElement(source.value as RsTraitItem)))
}
else -> return true
}
}
/** Checks that [selfTy] satisfies all trait bounds of the [impl] */
private fun canEvaluateBounds(impl: RsImplItem, selfTy: Ty): Boolean {
val ff = FulfillmentContext(this, lookup)
val subst = Substitution(
typeSubst = impl.generics.associateWith { typeVarForParam(it) },
constSubst = impl.constGenerics.associateWith { constVarForParam(it) }
)
return probe {
instantiateBounds(impl.predicates, subst).forEach(ff::registerPredicateObligation)
impl.typeReference?.rawType?.substitute(subst)?.let { combineTypes(selfTy, it) }
ff.selectUntilError()
}
}
fun instantiateMethodOwnerSubstitution(
callee: AssocItemScopeEntryBase<*>,
methodCall: RsMethodCall? = null
): Substitution = instantiateMethodOwnerSubstitution(callee.source, callee.selfTy, callee.element, methodCall)
fun instantiateMethodOwnerSubstitution(
callee: MethodPick,
methodCall: RsMethodCall? = null
): Substitution = instantiateMethodOwnerSubstitution(callee.source, callee.formalSelfTy, callee.element, methodCall)
private fun instantiateMethodOwnerSubstitution(
source: TraitImplSource,
selfTy: Ty,
element: RsAbstractable,
methodCall: RsMethodCall? = null
): Substitution = when (source) {
is TraitImplSource.ExplicitImpl -> {
val impl = source.value
val typeParameters = instantiateBounds(impl)
source.type?.substitute(typeParameters)?.let { combineTypes(selfTy, it) }
if (element.owner is RsAbstractableOwner.Trait) {
source.implementedTrait?.substitute(typeParameters)?.subst ?: emptySubstitution
} else {
typeParameters
}
}
is TraitImplSource.TraitBound -> lookup.getEnvBoundTransitivelyFor(selfTy)
.find { it.element == source.value }?.subst ?: emptySubstitution
is TraitImplSource.ProjectionBound -> {
val ty = selfTy as TyProjection
val subst = ty.trait.subst + mapOf(TyTypeParameter.self() to ty.type).toTypeSubst()
val bound = ty.trait.element.bounds
.find { it.trait.element == source.value && probe { combineTypes(it.selfTy.substitute(subst), ty) }.isOk }
bound?.trait?.subst?.substituteInValues(subst) ?: emptySubstitution
}
is TraitImplSource.Derived -> emptySubstitution
is TraitImplSource.Object -> when (selfTy) {
is TyAnon -> selfTy.getTraitBoundsTransitively()
.find { it.element == source.value }?.subst ?: emptySubstitution
is TyTraitObject -> selfTy.getTraitBoundsTransitively()
.find { it.element == source.value }?.subst ?: emptySubstitution
else -> emptySubstitution
}
is TraitImplSource.Collapsed, is TraitImplSource.Builtin -> {
// Method has been resolved to a trait, so we should add a predicate
// `Self : Trait<Args>` to select args and also refine method path if possible.
// Method path refinement needed if there are multiple impls of the same trait to the same type
val trait = source.value as RsTraitItem
val typeParameters = instantiateBounds(trait)
val subst = Substitution(
typeSubst = trait.generics.associateBy { it },
constSubst = trait.constGenerics.associateBy { it }
)
val boundTrait = BoundElement(trait, subst).substitute(typeParameters)
val traitRef = TraitRef(selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
if (methodCall != null) {
registerMethodRefinement(methodCall, traitRef)
}
typeParameters
}
is TraitImplSource.Trait -> {
// It's possible in type-qualified UFCS paths (like `<A as Trait>::Type`) during completion
emptySubstitution
}
}
/**
* Convert auto-derefs, indices, etc of an expression from `Deref` and `Index`
* into `DerefMut` and `IndexMut` respectively.
*/
fun convertPlaceDerefsToMutable(receiver: RsExpr) {
val exprs = mutableListOf(receiver)
while (true) {
exprs += when (val expr = exprs.last()) {
is RsIndexExpr -> expr.containerExpr
is RsUnaryExpr -> if (expr.isDereference) expr.expr else null
is RsDotExpr -> if (expr.fieldLookup != null) expr.expr else null
is RsParenExpr -> expr.expr
else -> null
} ?: break
}
for (expr in exprs.asReversed()) {
val exprAdjustments = adjustments[expr]
exprAdjustments?.forEachIndexed { i, adjustment ->
if (adjustment is Adjustment.Deref && adjustment.overloaded == IMMUTABLE) {
exprAdjustments[i] = Adjustment.Deref(adjustment.target, MUTABLE)
}
}
val base = unwrapParenExprs(
when (expr) {
is RsIndexExpr -> expr.containerExpr
is RsUnaryExpr -> if (expr.isDereference) expr.expr else null
else -> null
} ?: continue
)
val baseAdjustments = adjustments[base] ?: continue
baseAdjustments.forEachIndexed { i, adjustment ->
if (adjustment is Adjustment.BorrowReference && adjustment.mutability == IMMUTABLE) {
baseAdjustments[i] = Adjustment.BorrowReference(adjustment.target.copy(mutability = MUTABLE))
}
}
val lastAdjustment = baseAdjustments.lastOrNull()
if (lastAdjustment is Adjustment.Unsize
&& baseAdjustments.getOrNull(baseAdjustments.lastIndex - 1) is Adjustment.BorrowReference
&& lastAdjustment.target is TyReference) {
baseAdjustments[baseAdjustments.lastIndex] =
Adjustment.Unsize((lastAdjustment.target as TyReference).copy(mutability = MUTABLE))
}
}
}
}
val RsGenericDeclaration.generics: List<TyTypeParameter>
get() = typeParameters.map { TyTypeParameter.named(it) }
val RsGenericDeclaration.constGenerics: List<CtConstParameter>
get() = constParameters.map { CtConstParameter(it) }
val RsGenericDeclaration.bounds: List<TraitRef>
get() = predicates.mapNotNull { (it as? Predicate.Trait)?.trait }
val RsGenericDeclaration.predicates: List<Predicate>
get() = CachedValuesManager.getCachedValue(this) {
CachedValueProvider.Result.create(
doGetPredicates(),
rustStructureOrAnyPsiModificationTracker
)
}
private fun RsGenericDeclaration.doGetPredicates(): List<Predicate> {
val whereBounds = whereClause?.wherePredList.orEmpty().asSequence()
.flatMap {
val selfTy = it.typeReference?.rawType ?: return@flatMap emptySequence<PsiPredicate>()
it.typeParamBounds?.polyboundList.toPredicates(selfTy)
}
val bounds = typeParameters.asSequence().flatMap {
val selfTy = TyTypeParameter.named(it)
it.typeParamBounds?.polyboundList.toPredicates(selfTy)
}
val assocTypes = if (this is RsTraitItem) {
expandedMembers.types.map { TyProjection.valueOf(it) }
} else {
emptyList()
}
val assocTypeBounds = assocTypes.asSequence().flatMap { it.target.typeParamBounds?.polyboundList.toPredicates(it) }
val explicitPredicates = (bounds + whereBounds + assocTypeBounds).toList()
val sized = knownItems.Sized
val implicitPredicates = if (sized != null) {
val sizedBounds = explicitPredicates.mapNotNullToSet {
when (it) {
is PsiPredicate.Unbound -> it.selfTy
is PsiPredicate.Bound -> if (it.predicate is Predicate.Trait && it.predicate.trait.trait.element == sized) {
it.predicate.trait.selfTy
} else {
null
}
}
}
(generics.asSequence() + assocTypes.asSequence())
.filter { it !in sizedBounds }
.map { Predicate.Trait(TraitRef(it, sized.withSubst())) }
} else {
emptySequence()
}
return explicitPredicates.mapNotNull { (it as? PsiPredicate.Bound)?.predicate } + implicitPredicates
}
private fun List<RsPolybound>?.toPredicates(selfTy: Ty): Sequence<PsiPredicate> = orEmpty().asSequence()
.flatMap { bound ->
if (bound.hasQ) { // ?Sized
return@flatMap sequenceOf(PsiPredicate.Unbound(selfTy))
}
val traitRef = bound.bound.traitRef ?: return@flatMap emptySequence<PsiPredicate>()
val boundTrait = traitRef.resolveToBoundTrait() ?: return@flatMap emptySequence<PsiPredicate>()
val assocTypeBounds = traitRef.path.assocTypeBindings.asSequence()
.flatMap nestedFlatMap@{
val assoc = it.path.reference?.resolve() as? RsTypeAlias
?: return@nestedFlatMap emptySequence<PsiPredicate>()
val projectionTy = TyProjection.valueOf(selfTy, assoc)
val typeRef = it.typeReference
if (typeRef != null) {
// T: Iterator<Item = Foo>
// ~~~~~~~~~~ expands to predicate `T::Item = Foo`
sequenceOf(PsiPredicate.Bound(Predicate.Equate(projectionTy, typeRef.rawType)))
} else {
// T: Iterator<Item: Debug>
// ~~~~~~~~~~~ equivalent to `T::Item: Debug`
it.polyboundList.toPredicates(projectionTy)
}
}
val constness = if (bound.hasConst) {
BoundConstness.ConstIfConst
} else {
BoundConstness.NotConst
}
sequenceOf(PsiPredicate.Bound(Predicate.Trait(TraitRef(selfTy, boundTrait), constness))) + assocTypeBounds
}
private sealed class PsiPredicate {
data class Bound(val predicate: Predicate) : PsiPredicate()
data class Unbound(val selfTy: Ty) : PsiPredicate()
}
data class TyWithObligations<out T>(
val value: T,
val obligations: List<Obligation> = emptyList()
)
fun <T> TyWithObligations<T>.withObligations(addObligations: List<Obligation>) =
TyWithObligations(value, obligations + addObligations)
sealed class ResolvedPath {
abstract val element: RsElement
var subst: Substitution = emptySubstitution
class Item(override val element: RsElement, val isVisible: Boolean) : ResolvedPath()
class AssocItem(
override val element: RsAbstractable,
val source: TraitImplSource
) : ResolvedPath()
companion object {
fun from(entry: ScopeEntry, context: RsElement): ResolvedPath? {
return if (entry is AssocItemScopeEntry) {
AssocItem(entry.element, entry.source)
} else {
entry.element?.let {
val isVisible = entry.isVisibleFrom(context.containingMod)
Item(it, isVisible)
}
}
}
fun from(entry: AssocItemScopeEntry): ResolvedPath =
AssocItem(entry.element, entry.source)
}
}
data class InferredMethodCallInfo(
val resolveVariants: List<MethodResolveVariant>,
var subst: Substitution = emptySubstitution,
var type: TyFunction? = null,
) : TypeFoldable<InferredMethodCallInfo> {
override fun superFoldWith(folder: TypeFolder): InferredMethodCallInfo = InferredMethodCallInfo(
resolveVariants,
subst.foldValues(folder),
type?.foldWith(folder) as? TyFunction
)
override fun superVisitWith(visitor: TypeVisitor): Boolean {
val type = type
return subst.visitValues(visitor) || type != null && type.visitWith(visitor)
}
}
data class MethodPick(
val element: RsFunction,
/** A type that should be unified with `Self` type of the `impl` */
val formalSelfTy: Ty,
/** An actual type of `self` inside the method. Can differ from [formalSelfTy] because of `&mut self`, etc */
val methodSelfTy: Ty,
val derefCount: Int,
val source: TraitImplSource,
val derefSteps: List<Autoderef.AutoderefStep>,
val autorefOrPtrAdjustment: AutorefOrPtrAdjustment?,
val isValid: Boolean
) {
fun toMethodResolveVariant(): MethodResolveVariant =
MethodResolveVariant(element.name!!, element, formalSelfTy, derefCount, source)
sealed class AutorefOrPtrAdjustment {
data class Autoref(val mutability: Mutability, val unsize: Boolean) : AutorefOrPtrAdjustment()
object ToConstPtr : AutorefOrPtrAdjustment()
}
companion object {
fun from(
m: MethodResolveVariant,
methodSelfTy: Ty,
derefSteps: List<Autoderef.AutoderefStep>,
autorefOrPtrAdjustment: AutorefOrPtrAdjustment?
) = MethodPick(m.element, m.selfTy, methodSelfTy, m.derefCount, m.source, derefSteps, autorefOrPtrAdjustment, true)
fun from(m: MethodResolveVariant) =
MethodPick(m.element, m.selfTy, TyUnknown, m.derefCount, m.source, emptyList(), null, false)
}
}
typealias RelateResult = RsResult<Unit, TypeError>
private inline fun RelateResult.and(rhs: () -> RelateResult): RelateResult = if (isOk) rhs() else this
sealed class TypeError {
class TypeMismatch(val ty1: Ty, val ty2: Ty) : TypeError()
class ConstMismatch(val const1: Const, val const2: Const) : TypeError()
}
typealias CoerceResult = RsResult<CoerceOk, TypeError>
data class CoerceOk(
val adjustments: List<Adjustment> = emptyList(),
val obligations: List<Obligation> = emptyList()
)
fun RelateResult.into(): CoerceResult = map { CoerceOk() }
data class ExpectedType(val ty: Ty, val coercable: Boolean = false) : TypeFoldable<ExpectedType> {
override fun superFoldWith(folder: TypeFolder): ExpectedType = copy(ty = ty.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean = ty.visitWith(visitor)
companion object {
val UNKNOWN: ExpectedType = ExpectedType(TyUnknown)
}
}
object TypeInferenceMarks {
object CyclicType : Testmark()
object RecursiveProjectionNormalization : Testmark()
object QuestionOperator : Testmark()
object MethodPickTraitScope : Testmark()
object MethodPickTraitsOutOfScope : Testmark()
object MethodPickCheckBounds : Testmark()
object MethodPickDerefOrder : Testmark()
object MethodPickCollapseTraits : Testmark()
object WinnowSpecialization : Testmark()
object WinnowParamCandidateWins : Testmark()
object WinnowParamCandidateLoses : Testmark()
object WinnowObjectOrProjectionCandidateWins : Testmark()
object TraitSelectionOverflow : Testmark()
object MacroExprDepthLimitReached : Testmark()
object UnsizeToTraitObject : Testmark()
object UnsizeArrayToSlice : Testmark()
object UnsizeStruct : Testmark()
object UnsizeTuple : Testmark()
}
| mit | e5b6486ffd5419a96a878181055a6608 | 40.816131 | 133 | 0.621966 | 4.947194 | false | false | false | false |
google/dokka | core/src/main/kotlin/Locations/Location.kt | 2 | 2261 | package org.jetbrains.dokka
import java.io.File
interface Location {
val path: String get
fun relativePathTo(other: Location, anchor: String? = null): String
}
/**
* Represents locations in the documentation in the form of [path](File).
*
* $file: [File] for this location
* $path: [String] representing path of this location
*/
data class FileLocation(val file: File) : Location {
override val path: String
get() = file.path
override fun relativePathTo(other: Location, anchor: String?): String {
if (other !is FileLocation) {
throw IllegalArgumentException("$other is not a FileLocation")
}
if (file.path.substringBeforeLast(".") == other.file.path.substringBeforeLast(".") && anchor == null) {
return "./${file.name}"
}
val ownerFolder = file.parentFile!!
val relativePath = ownerFolder.toPath().relativize(other.file.toPath()).toString().replace(File.separatorChar, '/')
return if (anchor == null) relativePath else relativePath + "#" + anchor
}
}
fun relativePathToNode(qualifiedName: List<String>, hasMembers: Boolean): String {
val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() }
return if (!hasMembers) {
// leaf node, use file in owner's folder
parts.joinToString("/")
} else {
parts.joinToString("/") + (if (parts.none()) "" else "/") + "index"
}
}
fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any())
fun identifierToFilename(path: String): String {
val escaped = path.replace('<', '-').replace('>', '-')
val lowercase = escaped.replace("[A-Z]".toRegex()) { matchResult -> "-" + matchResult.value.toLowerCase() }
return if (lowercase == "index") "--index--" else lowercase
}
fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String {
return location(owner).relativePathTo(location(node), null)
}
fun NodeLocationAwareGenerator.relativePathToRoot(from: Location): File {
val file = File(from.path).parentFile
return root.relativeTo(file)
}
fun File.toUnixString() = toString().replace(File.separatorChar, '/')
| apache-2.0 | a0f034ddea61b48e28da0789eddf37da | 36.065574 | 123 | 0.673153 | 4.25 | false | false | false | false |
rwinch/spring-security | config/src/test/kotlin/org/springframework/security/config/web/server/ServerOAuth2ClientDslTests.kt | 1 | 10887 | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.verify
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository
import org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository
import org.springframework.security.oauth2.client.web.server.WebSessionOAuth2ServerAuthorizationRequestRepository
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames
import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.reactive.config.EnableWebFlux
import reactor.core.publisher.Mono
/**
* Tests for [ServerOAuth2ClientDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class ServerOAuth2ClientDslTests {
@JvmField
val spring = SpringTestContext(this)
private lateinit var client: WebTestClient
@Autowired
fun setup(context: ApplicationContext) {
this.client = WebTestClient
.bindToApplicationContext(context)
.configureClient()
.build()
}
@Test
fun `OAuth2 client when custom client registration repository then bean is not required`() {
this.spring.register(ClientRepoConfig::class.java).autowire()
}
@EnableWebFluxSecurity
@EnableWebFlux
open class ClientRepoConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
oauth2Client {
clientRegistrationRepository = InMemoryReactiveClientRegistrationRepository(
CommonOAuth2Provider.GOOGLE
.getBuilder("google").clientId("clientId").clientSecret("clientSecret")
.build()
)
}
}
}
}
@Test
fun `OAuth2 client when authorization request repository configured then custom repository used`() {
this.spring.register(AuthorizationRequestRepositoryConfig::class.java, ClientConfig::class.java).autowire()
mockkObject(AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY)
every {
AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any())
} returns Mono.empty()
this.client.get()
.uri {
it.path("/")
.queryParam(OAuth2ParameterNames.CODE, "code")
.queryParam(OAuth2ParameterNames.STATE, "state")
.build()
}
.exchange()
verify(exactly = 1) {
AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any())
}
}
@EnableWebFluxSecurity
@EnableWebFlux
open class AuthorizationRequestRepositoryConfig {
companion object {
val AUTHORIZATION_REQUEST_REPOSITORY : ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository()
}
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
oauth2Client {
authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY
}
}
}
}
@Test
fun `OAuth2 client when authentication converter configured then custom converter used`() {
this.spring.register(AuthenticationConverterConfig::class.java, ClientConfig::class.java).autowire()
mockkObject(AuthenticationConverterConfig.AUTHORIZATION_REQUEST_REPOSITORY)
mockkObject(AuthenticationConverterConfig.AUTHENTICATION_CONVERTER)
every {
AuthenticationConverterConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any())
} returns Mono.just(OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("https://example.com/login/oauth/authorize")
.clientId("clientId")
.redirectUri("/authorize/oauth2/code/google")
.build())
every {
AuthenticationConverterConfig.AUTHENTICATION_CONVERTER.convert(any())
} returns Mono.empty()
this.client.get()
.uri {
it.path("/authorize/oauth2/code/google")
.queryParam(OAuth2ParameterNames.CODE, "code")
.queryParam(OAuth2ParameterNames.STATE, "state")
.build()
}
.exchange()
verify(exactly = 1) { AuthenticationConverterConfig.AUTHENTICATION_CONVERTER.convert(any()) }
}
@EnableWebFluxSecurity
@EnableWebFlux
open class AuthenticationConverterConfig {
companion object {
val AUTHORIZATION_REQUEST_REPOSITORY: ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository()
val AUTHENTICATION_CONVERTER: ServerAuthenticationConverter = ServerBearerTokenAuthenticationConverter()
}
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
oauth2Client {
authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY
authenticationConverter = AUTHENTICATION_CONVERTER
}
}
}
}
@Test
fun `OAuth2 client when authentication manager configured then custom manager used`() {
this.spring.register(AuthenticationManagerConfig::class.java, ClientConfig::class.java).autowire()
mockkObject(AuthenticationManagerConfig.AUTHORIZATION_REQUEST_REPOSITORY)
mockkObject(AuthenticationManagerConfig.AUTHENTICATION_CONVERTER)
mockkObject(AuthenticationManagerConfig.AUTHENTICATION_MANAGER)
every {
AuthenticationManagerConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any())
} returns Mono.just(OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("https://example.com/login/oauth/authorize")
.clientId("clientId")
.redirectUri("/authorize/oauth2/code/google")
.build())
every {
AuthenticationManagerConfig.AUTHENTICATION_CONVERTER.convert(any())
} returns Mono.just(TestingAuthenticationToken("a", "b", "c"))
every {
AuthenticationManagerConfig.AUTHENTICATION_MANAGER.authenticate(any())
} returns Mono.empty()
this.client.get()
.uri {
it.path("/authorize/oauth2/code/google")
.queryParam(OAuth2ParameterNames.CODE, "code")
.queryParam(OAuth2ParameterNames.STATE, "state")
.build()
}
.exchange()
verify(exactly = 1) { AuthenticationManagerConfig.AUTHENTICATION_MANAGER.authenticate(any()) }
}
@EnableWebFluxSecurity
@EnableWebFlux
open class AuthenticationManagerConfig {
companion object {
val AUTHORIZATION_REQUEST_REPOSITORY: ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository()
val AUTHENTICATION_CONVERTER: ServerAuthenticationConverter = ServerBearerTokenAuthenticationConverter()
val AUTHENTICATION_MANAGER: ReactiveAuthenticationManager = NoopReactiveAuthenticationManager()
}
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
oauth2Client {
authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY
authenticationConverter = AUTHENTICATION_CONVERTER
authenticationManager = AUTHENTICATION_MANAGER
}
}
}
}
class NoopReactiveAuthenticationManager: ReactiveAuthenticationManager {
override fun authenticate(authentication: Authentication?): Mono<Authentication> {
return Mono.empty()
}
}
@Configuration
open class ClientConfig {
@Bean
open fun clientRegistrationRepository(): ReactiveClientRegistrationRepository {
return InMemoryReactiveClientRegistrationRepository(
CommonOAuth2Provider.GOOGLE
.getBuilder("google").clientId("clientId").clientSecret("clientSecret")
.build()
)
}
}
}
| apache-2.0 | e678c7b9301ba2cf2491880e489f5e00 | 42.202381 | 172 | 0.686966 | 5.926511 | false | true | false | false |
androidx/androidx | lifecycle/lifecycle-compiler/src/main/kotlin/androidx/lifecycle/transformation.kt | 3 | 5734 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.lifecycle
import androidx.lifecycle.model.AdapterClass
import androidx.lifecycle.model.EventMethod
import androidx.lifecycle.model.EventMethodCall
import androidx.lifecycle.model.InputModel
import androidx.lifecycle.model.LifecycleObserverInfo
import com.google.common.collect.HashMultimap
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.TypeElement
import javax.tools.Diagnostic
private fun mergeAndVerifyMethods(
processingEnv: ProcessingEnvironment,
type: TypeElement,
classMethods: List<EventMethod>,
parentMethods: List<EventMethod>
): List<EventMethod> {
// need to update parent methods like that because:
// 1. visibility can be expanded
// 2. we want to preserve order
val updatedParentMethods = parentMethods.map { parentMethod ->
val overrideMethod = classMethods.find { (method) ->
processingEnv.elementUtils.overrides(method, parentMethod.method, type)
}
if (overrideMethod != null) {
if (overrideMethod.onLifecycleEvent != parentMethod.onLifecycleEvent) {
processingEnv.messager.printMessage(
Diagnostic.Kind.ERROR,
ErrorMessages.INVALID_STATE_OVERRIDE_METHOD, overrideMethod.method
)
}
overrideMethod
} else {
parentMethod
}
}
return updatedParentMethods + classMethods.filterNot { updatedParentMethods.contains(it) }
}
fun flattenObservers(
processingEnv: ProcessingEnvironment,
world: Map<TypeElement, LifecycleObserverInfo>
): List<LifecycleObserverInfo> {
val flattened: MutableMap<LifecycleObserverInfo, LifecycleObserverInfo> = mutableMapOf()
fun traverse(observer: LifecycleObserverInfo) {
if (observer in flattened) {
return
}
if (observer.parents.isEmpty()) {
flattened[observer] = observer
return
}
observer.parents.forEach(::traverse)
val methods = observer.parents
.map(flattened::get)
.fold(emptyList<EventMethod>()) { list, parentObserver ->
mergeAndVerifyMethods(
processingEnv, observer.type,
parentObserver!!.methods, list
)
}
flattened[observer] = LifecycleObserverInfo(
observer.type,
mergeAndVerifyMethods(processingEnv, observer.type, observer.methods, methods)
)
}
world.values.forEach(::traverse)
return flattened.values.toList()
}
private fun needsSyntheticAccess(type: TypeElement, eventMethod: EventMethod): Boolean {
val executable = eventMethod.method
return type.getPackageQName() != eventMethod.packageName() &&
(executable.isPackagePrivate() || executable.isProtected())
}
private fun validateMethod(
processingEnv: ProcessingEnvironment,
world: InputModel,
type: TypeElement,
eventMethod: EventMethod
): Boolean {
if (!needsSyntheticAccess(type, eventMethod)) {
// no synthetic calls - no problems
return true
}
if (world.isRootType(eventMethod.type)) {
// we will generate adapters for them, so we can generate all accessors
return true
}
if (world.hasSyntheticAccessorFor(eventMethod)) {
// previously generated adapter already has synthetic
return true
}
processingEnv.messager.printMessage(
Diagnostic.Kind.WARNING,
ErrorMessages.failedToGenerateAdapter(type, eventMethod), type
)
return false
}
fun transformToOutput(
processingEnv: ProcessingEnvironment,
world: InputModel
): List<AdapterClass> {
val flatObservers = flattenObservers(processingEnv, world.observersInfo)
val syntheticMethods = HashMultimap.create<TypeElement, EventMethodCall>()
val adapterCalls = flatObservers
// filter out everything that arrived from jars
.filter { (type) -> world.isRootType(type) }
// filter out if it needs SYNTHETIC access and we can't generate adapter for it
.filter { (type, methods) ->
methods.all { eventMethod ->
validateMethod(processingEnv, world, type, eventMethod)
}
}
.map { (type, methods) ->
val calls = methods.map { eventMethod ->
if (needsSyntheticAccess(type, eventMethod)) {
EventMethodCall(eventMethod, eventMethod.type)
} else {
EventMethodCall(eventMethod)
}
}
calls.filter { it.syntheticAccess != null }.forEach { eventMethod ->
syntheticMethods.put(eventMethod.method.type, eventMethod)
}
type to calls
}.toMap()
return adapterCalls
.map { (type, calls) ->
val methods = syntheticMethods.get(type) ?: emptySet()
val synthetic = methods.map { eventMethod -> eventMethod!!.method.method }.toSet()
AdapterClass(type, calls, synthetic)
}
}
| apache-2.0 | 47b706544025999e268d053d1d42211b | 34.8375 | 94 | 0.660446 | 5.021016 | false | false | false | false |
paulalewis/agl | src/main/kotlin/com/castlefrog/agl/domains/backgammon/BackgammonState.kt | 1 | 3651 | package com.castlefrog.agl.domains.backgammon
import com.castlefrog.agl.State
/**
* Represents a backgammon state as an array of byte locations.
* @param locations each location is 0 if no pieces are at that location and positive for
* the number of pieces player 1 has there and negative for the number of
* pieces player 2 has there.
* @param dice two values in range 0-5 that represent die faces 1 to 6 each; order does not matter
* @param agentTurn current players turn
*/
class BackgammonState(
val locations: ByteArray = byteArrayOf(
0,
2,
0,
0,
0,
0,
-5,
0,
-3,
0,
0,
0,
5,
-5,
0,
0,
0,
3,
0,
5,
0,
0,
0,
0,
-2,
0
),
val dice: ByteArray = ByteArray(N_DICE),
var agentTurn: Int = 0
) : State<BackgammonState> {
override fun copy(): BackgammonState {
val locations = ByteArray(N_LOCATIONS)
System.arraycopy(this.locations, 0, locations, 0, N_LOCATIONS)
val dice = ByteArray(N_DICE)
System.arraycopy(this.dice, 0, dice, 0, N_DICE)
return BackgammonState(locations, dice, agentTurn)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is BackgammonState) {
return false
}
return locations.contentEquals(other.locations) &&
((dice[0] == other.dice[0] && dice[1] == other.dice[1]) ||
(dice[0] == other.dice[1] && dice[1] == other.dice[0])) &&
agentTurn == other.agentTurn
}
override fun hashCode(): Int {
val dice = if (dice[0] < dice[1]) {
intArrayOf(dice[1].toInt(), dice[0].toInt())
} else {
intArrayOf(dice[0].toInt(), dice[1].toInt())
}
return (agentTurn * 11 + locations.contentHashCode()) * 17 + dice.contentHashCode()
}
override fun toString(): String {
val output = StringBuilder(" ").append(agentTurn).append(" - ")
val dice = if (dice[0] < dice[1]) {
intArrayOf(dice[1].toInt(), dice[0].toInt())
} else {
intArrayOf(dice[0].toInt(), dice[1].toInt())
}
output.append("[").append(dice[0] + 1).append("][").append(dice[1] + 1).append("]\n")
for (i in 12 downTo 7) {
if (locations[i] >= 0) {
output.append(" ")
}
output.append(locations[i].toInt())
}
output.append("|")
for (i in 6 downTo 1) {
if (locations[i] >= 0) {
output.append(" ")
}
output.append(locations[i].toInt())
}
output.append(" [").append(locations[0].toInt()).append("]\n")
output.append("------------|------------\n")
for (i in 13..18) {
if (locations[i] >= 0) {
output.append(" ")
}
output.append(locations[i].toInt())
}
output.append("|")
var i = 19
while (i < 25) {
if (locations[i] >= 0) {
output.append(" ")
}
output.append(locations[i].toInt())
i += 1
}
output.append(" [").append(locations[25].toInt()).append("]")
return output.toString()
}
companion object {
const val N_PLAYERS = 2
const val N_DICE = 2
const val N_DIE_FACES = 6
const val N_LOCATIONS = 26
}
}
| mit | de08404c5ef8e8888ff5ec7b732fd87f | 28.443548 | 98 | 0.489455 | 3.977124 | false | false | false | false |
jooby-project/jooby | jooby/src/main/kotlin/io/jooby/CoroutineRouter.kt | 1 | 2977 | /*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby
import io.jooby.Router.DELETE
import io.jooby.Router.GET
import io.jooby.Router.HEAD
import io.jooby.Router.OPTIONS
import io.jooby.Router.PATCH
import io.jooby.Router.POST
import io.jooby.Router.PUT
import io.jooby.Router.TRACE
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
internal class RouterCoroutineScope(override val coroutineContext: CoroutineContext) :
CoroutineScope
class CoroutineRouter(val coroutineStart: CoroutineStart, val router: Router) {
val coroutineScope: CoroutineScope by lazy {
RouterCoroutineScope(router.worker.asCoroutineDispatcher())
}
private var extraCoroutineContextProvider: HandlerContext.() -> CoroutineContext = {
EmptyCoroutineContext
}
fun launchContext(provider: HandlerContext.() -> CoroutineContext) {
extraCoroutineContextProvider = provider
}
@RouterDsl
fun get(pattern: String, handler: suspend HandlerContext.() -> Any) = route(GET, pattern, handler)
@RouterDsl
fun post(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(POST, pattern, handler)
@RouterDsl
fun put(pattern: String, handler: suspend HandlerContext.() -> Any) = route(PUT, pattern, handler)
@RouterDsl
fun delete(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(DELETE, pattern, handler)
@RouterDsl
fun patch(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(PATCH, pattern, handler)
@RouterDsl
fun head(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(HEAD, pattern, handler)
@RouterDsl
fun trace(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(TRACE, pattern, handler)
@RouterDsl
fun options(pattern: String, handler: suspend HandlerContext.() -> Any) =
route(OPTIONS, pattern, handler)
fun route(method: String, pattern: String, handler: suspend HandlerContext.() -> Any): Route =
router
.route(method, pattern) { ctx ->
val handlerContext = HandlerContext(ctx)
launch(handlerContext) {
val result = handler(handlerContext)
if (result != ctx) {
ctx.render(result)
}
}
}
.setHandle(handler)
.attribute("coroutine", true)
internal fun launch(handlerContext: HandlerContext, block: suspend CoroutineScope.() -> Unit) {
val exceptionHandler = CoroutineExceptionHandler { _, x -> handlerContext.ctx.sendError(x) }
val coroutineContext = exceptionHandler + handlerContext.extraCoroutineContextProvider()
coroutineScope.launch(coroutineContext, coroutineStart, block)
}
}
| apache-2.0 | b3641db218bfafc02c3511913fefcf45 | 32.449438 | 100 | 0.735304 | 4.62986 | false | false | false | false |
pyamsoft/power-manager | powermanager-manage/src/main/java/com/pyamsoft/powermanager/manage/ManageModule.kt | 1 | 7287 | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.manage
import com.pyamsoft.powermanager.manage.ManageTargets.AIRPLANE
import com.pyamsoft.powermanager.manage.ManageTargets.BLUETOOTH
import com.pyamsoft.powermanager.manage.ManageTargets.DATA
import com.pyamsoft.powermanager.manage.ManageTargets.DATA_SAVER
import com.pyamsoft.powermanager.manage.ManageTargets.DOZE
import com.pyamsoft.powermanager.manage.ManageTargets.SYNC
import com.pyamsoft.powermanager.manage.ManageTargets.WIFI
import com.pyamsoft.powermanager.manage.bus.ManageBus
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import javax.inject.Named
@Module class ManageModule {
@Provides @Named("manage_wifi") internal fun provideWifi(
@Named("manage_wifi_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = WIFI
}
}
@Provides @Named("manage_data") internal fun provideData(
@Named("manage_data_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DATA
}
}
@Provides @Named("manage_bluetooth") internal fun provideBluetooth(
@Named("manage_bluetooth_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = BLUETOOTH
}
}
@Provides @Named("manage_sync") internal fun provideSync(
@Named("manage_sync_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = SYNC
}
}
@Provides @Named("manage_airplane") internal fun provideAirplane(
@Named("manage_airplane_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = AIRPLANE
}
}
@Provides @Named("manage_doze") internal fun provideDoze(
@Named("manage_doze_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DOZE
}
}
@Provides @Named("manage_data_saver") internal fun provideDataSaver(
@Named("manage_data_saver_interactor") interactor: ManageInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ManagePresenter {
return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DATA_SAVER
}
}
@Provides @Named("exception_wifi") internal fun provideWifiException(
@Named("exception_wifi_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = WIFI
}
}
@Provides @Named("exception_data") internal fun provideDataException(
@Named("exception_data_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DATA
}
}
@Provides @Named("exception_bluetooth") internal fun provideBluetoothException(
@Named("exception_bluetooth_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = BLUETOOTH
}
}
@Provides @Named("exception_sync") internal fun provideSyncException(
@Named("exception_sync_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = SYNC
}
}
@Provides @Named("exception_airplane") internal fun provideAirplaneException(
@Named("exception_airplane_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = AIRPLANE
}
}
@Provides @Named("exception_doze") internal fun provideDozeException(
@Named("exception_doze_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DOZE
}
}
@Provides @Named("exception_data_saver") internal fun provideDataSaverException(
@Named("exception_data_saver_interactor") interactor: ExceptionInteractor,
@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler,
bus: ManageBus): ExceptionPresenter {
return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) {
override val target: ManageTargets
get() = DATA_SAVER
}
}
}
| apache-2.0 | 3e6536e71e9b5c7e3c444ac78ada336d | 41.121387 | 85 | 0.719775 | 4.858 | false | false | false | false |
google/android-auto-companion-android | calendarsync/tests/unit/src/com/google/android/libraries/car/calendarsync/feature/CalendarSyncManagerTest.kt | 1 | 16185 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.calendarsync.feature
import android.Manifest.permission
import android.content.Context
import android.provider.CalendarContract
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.GrantPermissionRule
import com.google.android.connecteddevice.calendarsync.proto.Calendar
import com.google.android.connecteddevice.calendarsync.proto.Calendars
import com.google.android.connecteddevice.calendarsync.proto.TimeZone
import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.KEY_CALENDAR_IDS
import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.KEY_ENABLED
import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.key
import com.google.android.libraries.car.calendarsync.feature.repository.CalendarRepository
import com.google.android.libraries.car.trustagent.Car
import com.google.common.collect.ImmutableSet
import com.google.common.time.ZoneIds
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import java.time.Clock
import java.time.Instant
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import java.util.UUID
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowContentResolver
import org.robolectric.shadows.ShadowLooper
@RunWith(AndroidJUnit4::class)
class CalendarSyncManagerTest {
private val zoneId = ZoneIds.googleZoneId()
private val zonedDateTime = ZonedDateTime.of(2020, 3, 10, 11, 12, 13, 14, zoneId)
private val fixedTimeClock = Clock.fixed(zonedDateTime.toInstant(), zoneId)
private val context = ApplicationProvider.getApplicationContext<Context>()
private val carId = UUID.randomUUID()
private val mockCar: Car = mock {
on { deviceId } doReturn carId
}
private val calendarId1 = "111"
private val calendarId2 = "222"
// Create a dummy value that contains a unique field we can use to recognize its bytes.
private val calendars = Calendars.newBuilder()
.setDeviceTimeZone(TimeZone.newBuilder().setName("DummyTimeZone")).build()
private lateinit var calendarSyncManager: CalendarSyncManager
private lateinit var mockCalendarRepository: CalendarRepository
private val sharedPreferences by lazy {
context.getSharedPreferences("CalendarSyncManagerTest", Context.MODE_PRIVATE)
}
@get:Rule
val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant(
permission.READ_CALENDAR
)
@Before
fun setUp() {
mockCalendarRepository = mock()
// Make sure something is returned whenever we do not care about the returned content.
whenever(
mockCalendarRepository.getCalendars(any(), any(), any())
) doReturn calendars
whenever(
mockCalendarRepository.getCalendars(any(), any())
) doReturn calendars
calendarSyncManager = CalendarSyncManager(
context,
mockCalendarRepository,
fixedTimeClock,
sharedPreferences
)
}
@Test
fun onCarConnected_enabled_withIds_queriesCalendarsFromStartOfDay() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId)
calendarSyncManager.notifyCarConnected(mockCar)
val expectedCalendarIds = setOf(Integer.parseInt(calendarId1), Integer.parseInt(calendarId2))
val expectedStartInstant = zonedDateTime.truncatedTo(ChronoUnit.DAYS).toInstant()
argumentCaptor<Instant>().apply {
verify(mockCalendarRepository).getCalendars(eq(expectedCalendarIds), capture(), capture())
assertThat(firstValue).isEqualTo(expectedStartInstant)
assertThat(firstValue).isLessThan(secondValue)
}
}
@Test
fun onCarConnected_enabled_withIds_doesSync() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.notifyCarConnected(mockCar)
verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID)
}
@Test
fun onCarConnected_enabled_emptyIds_doesNotSync() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.notifyCarConnected(mockCar)
verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull())
}
@Test
fun onCarConnected_disabled_doesNotSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.notifyCarConnected(mockCar)
verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull())
}
@Test
fun onCarConnected_syncsOnNextDay() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.notifyCarConnected(mockCar)
var foundScheduledTaskTomorrow = false
val loopers = ShadowLooper.getAllLoopers()
for (looper in loopers) {
val shadowLooper: ShadowLooper = shadowOf(looper)
val tomorrowDateTime = zonedDateTime.plusDays(1).truncatedTo(ChronoUnit.DAYS)
if (zonedDateTime.plus(shadowLooper.nextScheduledTaskTime) >= tomorrowDateTime) {
foundScheduledTaskTomorrow = true
// Run tomorrows task so we can assert it caused a sync.
shadowLooper.runOneTask()
}
}
assertThat(foundScheduledTaskTomorrow).isTrue()
verify(mockCar, times(2))
.sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID)
}
fun onCarDisassociated_disablesCalendarSync() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.onCarDisassociated(carId)
assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse()
}
@Test
fun onCarDisassociated_removesCarPreferences() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
// Another car
calendarSyncManager.enableCar(UUID.randomUUID())
calendarSyncManager.onCarDisassociated(carId)
assertThat(sharedPreferences.contains(key(KEY_CALENDAR_IDS, carId))).isFalse()
assertThat(sharedPreferences.contains(key(KEY_ENABLED, carId))).isFalse()
assertThat(sharedPreferences.all).isNotEmpty()
}
@Test
fun onAllCarsDisassociated_disablesCalendarSync() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.onAllCarsDisassociated()
assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse()
}
@Test
fun onAllCarsDisassociated_clearsAllPreferences() {
sharedPreferences.edit().putString("key", "value").apply()
calendarSyncManager.onAllCarsDisassociated()
assertThat(sharedPreferences.all).isEmpty()
}
@Test
fun enableCar_storesValue() {
calendarSyncManager.enableCar(carId)
assertThat(
sharedPreferences.getBoolean(
key(CalendarSyncManager.KEY_ENABLED, carId),
false
)
).isTrue()
}
@Test
fun enableCar_withoutStoredCalendarIds_doesNotSync() {
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.enableCar(carId)
verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID))
}
@Test
fun enableCar_withStoredCalendarIds_doesSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.enableCar(carId)
verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID)
}
@Test
fun enableCar_disconnected_withStoredCalendarIds_doesNotSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.enableCar(carId)
verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID))
}
@Test
fun disableCar_storesValue() {
calendarSyncManager.disableCar(carId)
assertThat(
sharedPreferences.getBoolean(
key(CalendarSyncManager.KEY_ENABLED, carId),
true
)
).isFalse()
}
@Test
fun disableCar_withStoredCalendarIds_doesSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.disableCar(carId)
verify(mockCar).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID))
}
@Test
fun disableCar_withoutStoredCalendarIds_doesNotSync() {
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.disableCar(carId)
verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID))
}
@Test
fun disableCar_disconnected_withStoredCalendarIds_doesNotSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
calendarSyncManager.disableCar(carId)
verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID))
}
@Test
fun isCarEnabled_noStoredPreferences_returnFalse() {
assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse()
}
@Test
fun getCalendarIdsToSync_calendarsInRepository_returnsCalendars() {
val calendarIds = setOf("first", "second", "third")
whenever(
mockCalendarRepository.getCalendars(any(), any())
) doReturn generateEmptyCalendars(calendarIds)
assertThat(calendarSyncManager.getCalendarIdsToSync(carId)).isEqualTo(calendarIds)
}
@Test
fun getCalendarIdsToSync_noCalendarsInRepository_returnEmptyList() {
assertThat(calendarSyncManager.getCalendarIdsToSync(carId)).isEmpty()
}
@Test
fun getCalendarIdsToSync() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId)
assertThat(calendarSyncManager.getCalendarIdsToSync(carId))
.containsExactly(calendarId1, calendarId2)
assertThat(calendarSyncManager.getCalendarIdsToSync(UUID.randomUUID())).isEmpty()
}
@Test
fun setCalendarIdsToSync_storesValue() {
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId)
val storedCalendars = sharedPreferences.getStringSet(
key(CalendarSyncManager.KEY_CALENDAR_IDS, carId), ImmutableSet.of()
)!!
assertThat(storedCalendars).containsExactly(calendarId1, calendarId2)
}
@Test
fun setCalendarIdsToSync_doesSyncNewCalendar() {
calendarSyncManager.notifyCarConnected(mockCar)
configureCarPreferences(
carId, enable = true, calendarIds = setOf(calendarId1, calendarId2)
)
val newCalendarId = "333"
calendarSyncManager.setCalendarIdsToSync(
setOf(calendarId1, calendarId2, newCalendarId), carId
)
verify(mockCalendarRepository)
.getCalendars(eq(setOf(Integer.parseInt(newCalendarId))), any(), any())
verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID)
}
@Test
fun setCalendarIdsToSync_doesSyncRemovedCalendar() {
calendarSyncManager.notifyCarConnected(mockCar)
configureCarPreferences(
carId, enable = true, calendarIds = setOf(calendarId1, calendarId2)
)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
val calendarsToRemove = generateEmptyCalendars(setOf(calendarId2))
verify(mockCar)
.sendMessage(calendarsToRemove.toByteArray(), CalendarSyncManager.FEATURE_ID)
verify(mockCalendarRepository, never()).getCalendars(any(), any(), any())
}
@Test
fun setCalendarIdsToSync_onDisabledCar_doesNotSync() {
calendarSyncManager.notifyCarConnected(mockCar)
configureCarPreferences(carId, enable = false, calendarIds = setOf())
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId)
verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull())
}
@Test
fun carsConnected_registersCalendarObserver() {
calendarSyncManager.enableCar(carId)
// Register another car which should not start another observer.
val carId2 = UUID.randomUUID()
val mockCar2: Car = mock {
on { deviceId } doReturn carId2
}
calendarSyncManager.enableCar(carId2)
val contentResolver: ShadowContentResolver = shadowOf(context.contentResolver)
assertThat(contentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI))
.isEmpty()
// Connect the cars.
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.notifyCarConnected(mockCar2)
assertThat(contentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI))
.hasSize(1)
}
@Test
fun carsDisconnected_unregistersCalendarObserver() {
calendarSyncManager.enableCar(carId)
// Register another car which should not start another observer.
val carId2 = UUID.randomUUID()
val mockCar2: Car = mock {
on { deviceId } doReturn carId2
}
calendarSyncManager.enableCar(carId2)
// Connect the cars.
calendarSyncManager.notifyCarConnected(mockCar)
calendarSyncManager.notifyCarConnected(mockCar2)
val shadowContentResolver = shadowOf(context.contentResolver)
assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI))
.isNotEmpty()
// Disconnect the first car to remove it and trigger onCarDisconnected.
argumentCaptor<Car.Callback>().apply {
verify(mockCar).setCallback(capture(), eq(CalendarSyncManager.FEATURE_ID))
firstValue.onDisconnected()
assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI))
.isNotEmpty()
}
// Only removing the last car should stop observing the calendar event instances.
argumentCaptor<Car.Callback>().apply {
verify(mockCar2).setCallback(capture(), eq(CalendarSyncManager.FEATURE_ID))
firstValue.onDisconnected()
assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI))
.isEmpty()
}
}
@Test
fun eventsChanged_syncToCar() {
calendarSyncManager.enableCar(carId)
calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId)
calendarSyncManager.notifyCarConnected(mockCar)
idleAllLoopers()
val shadowContentResolver = shadowOf(context.contentResolver)
val observer =
shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI).first()
observer.dispatchChange(false, null)
idleAllLoopers()
// The first sync will occur on connection, the second due to the changed events.
verify(mockCar, times(2))
.sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID)
}
/** Creates a [Calendars] proto with the given calendar ids. */
private fun generateEmptyCalendars(calendarIds: Set<String>): Calendars {
val calendarList = calendarIds.map { Calendar.newBuilder().setUuid(it).build() }
return Calendars.newBuilder().addAllCalendar(calendarList).build()
}
/** Configure preferences for the given carId. */
private fun configureCarPreferences(
carId: UUID,
enable: Boolean,
calendarIds: Set<String>
) {
sharedPreferences.edit()
.clear()
.putBoolean(key(KEY_ENABLED, carId), enable)
.putStringSet(key(KEY_CALENDAR_IDS, carId), calendarIds)
.apply()
}
private fun idleAllLoopers() = ShadowLooper.getAllLoopers().forEach { shadowOf(it).idle() }
}
| apache-2.0 | cbb93d355e421441ea08e39b69446583 | 33.14557 | 107 | 0.765462 | 4.945005 | false | true | false | false |
Hentioe/BloggerMini | app/src/main/kotlin/io/bluerain/tweets/fragment/ArticleFragment.kt | 1 | 5203 | package io.bluerain.tweets.fragment
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import io.bluerain.tweets.R
import io.bluerain.tweets.adapter.BaseRecyclerViewAdapter
import io.bluerain.tweets.adapter.BaseRecyclerViewHolder
import io.bluerain.tweets.base.BaseFragment
import io.bluerain.tweets.data.models.ArticleModel
import io.bluerain.tweets.data.models.isNormal
import io.bluerain.tweets.data.models.isTop
import io.bluerain.tweets.data.models.statusToString
import io.bluerain.tweets.fragment.ArticlesFragment.Companion.LIST_DATA
import io.bluerain.tweets.presenter.BlogPresenter
import io.bluerain.tweets.ui.ArticleInfoActivity
import io.bluerain.tweets.ui.ShowCommentsActivity
import io.bluerain.tweets.view.IBlogView
import kotlinx.android.synthetic.main.fragment_article_main.*
/**
* Created by hentioe on 17-4-26.
* 博客列表页面
*/
class ArticlesFragment : BaseFragment<BlogPresenter, IBlogView>(), IBlogView {
override fun providePresenter(): BlogPresenter {
return BlogPresenter()
}
override fun initEvent() {
refresh_blog.setOnRefreshListener {
initListView(ArrayList<ArticleModel>())
presenter.updateList()
}
}
companion object {
var LIST_DATA: List<ArticleModel> = ArrayList()
}
override fun stopRefreshing() {
refresh_blog.isRefreshing = false
}
override fun initListView(list: List<ArticleModel>) {
updateArticleList(list)
LIST_DATA = list
}
fun updateArticleList(list: List<ArticleModel>) {
simple_list_view_blog.setHasFixedSize(true)
simple_list_view_blog.layoutManager = LinearLayoutManager(context)
simple_list_view_blog.adapter = ArticleRecyclerAdapter(list, this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_article_main, container, false)
}
}
class ArticleRecyclerViewHolder(items: View) : BaseRecyclerViewHolder(items) {
val titleView = find(R.id.recycler_item_article_title) as TextView
val commentTotalView = find(R.id.recycler_item_article_comment_total) as TextView
val moreView = find(R.id.recycler_item_article_more) as ImageView
val statusView = find(R.id.article_comment_status_recycler_item) as TextView
val topView = find(R.id.article_comment_top_recycler_item) as TextView
}
class ArticleRecyclerAdapter(items: List<ArticleModel>, val fragment: ArticlesFragment) :
BaseRecyclerViewAdapter<ArticleRecyclerViewHolder, ArticleModel>(items, R.layout.recycler_item_article) {
override fun onCreateViewHolderByView(itemView: View): ArticleRecyclerViewHolder {
return ArticleRecyclerViewHolder(itemView)
}
override fun onBindViewHolder(holder: ArticleRecyclerViewHolder, position: Int) {
val model = getModel(position)
holder.titleView.text = model.title
holder.commentTotalView.text = "${model.commentTotal} 评论"
if (!model.isNormal()) {
holder.statusView.text = model.statusToString()
holder.statusView.visibility = View.VISIBLE
} else {
holder.statusView.visibility = View.GONE
}
if (model.isTop())
holder.topView.visibility = View.VISIBLE
else
holder.topView.visibility = View.GONE
super.onBindViewHolder(holder, position)
}
override fun onBindEvent(holder: ArticleRecyclerViewHolder, position: Int) {
val article = LIST_DATA[position]
holder.titleView.setOnClickListener {
ArticleInfoActivity.launch(fragment.activity, article.query)
}
val popupMenu = PopupMenu(fragment.context, holder.moreView)
popupMenu.menuInflater.inflate(R.menu.popup_menu_admin_article_more, popupMenu.menu)
holder.moreView.setOnClickListener {
popupMenu.show()
}
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.admin_article_popup_menu_top -> fragment.presenter.topArticle(article.id, false)
R.id.admin_article_popup_menu_cancel_top -> fragment.presenter.topArticle(article.id, true)
R.id.admin_article_popup_menu_normal -> fragment.presenter.normalArticle(article.id)
R.id.admin_article_popup_menu_hidden -> fragment.presenter.hiddenArticle(article.id)
R.id.admin_article_popup_menu_recycle -> fragment.presenter.recycleArticle(article.id)
R.id.admin_article_popup_menu_delete -> fragment.presenter.deleteArticle(article.id)
}
return@setOnMenuItemClickListener true
}
holder.commentTotalView.setOnClickListener {
ShowCommentsActivity.launch(fragment.activity, 0, article.id)
}
}
} | gpl-3.0 | 960ca1d9040e0950c797af70cf8f07e1 | 38.007519 | 117 | 0.715057 | 4.418228 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/implementation/SocialRepositoryImpl.kt | 1 | 13935 | package com.habitrpg.android.habitica.data.implementation
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.local.SocialLocalRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.Achievement
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.responses.PostChatMessageResult
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.FindUsernameResult
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.models.social.GroupMembership
import com.habitrpg.android.habitica.models.social.InboxConversation
import com.habitrpg.android.habitica.models.user.User
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import java.util.UUID
class SocialRepositoryImpl(
localRepository: SocialLocalRepository,
apiClient: ApiClient,
userID: String
) : BaseRepositoryImpl<SocialLocalRepository>(localRepository, apiClient, userID), SocialRepository {
override suspend fun transferGroupOwnership(groupID: String, userID: String): Group? {
val group = localRepository.getGroup(groupID).first()?.let { localRepository.getUnmanagedCopy(it) }
group?.leaderID = userID
return group?.let { apiClient.updateGroup(groupID, it) }
}
override suspend fun removeMemberFromGroup(groupID: String, userID: String): List<Member>? {
apiClient.removeMemberFromGroup(groupID, userID)
return retrievePartyMembers(groupID, true)
}
override fun blockMember(userID: String): Flowable<List<String>> {
return apiClient.blockMember(userID)
}
override fun getGroupMembership(id: String) = localRepository.getGroupMembership(userID, id)
override fun getGroupMemberships(): Flowable<out List<GroupMembership>> {
return localRepository.getGroupMemberships(userID)
}
override suspend fun retrieveGroupChat(groupId: String): List<ChatMessage>? {
val messages = apiClient.listGroupChat(groupId)
messages?.forEach { it.groupId = groupId }
return messages
}
override fun getGroupChat(groupId: String): Flowable<out List<ChatMessage>> {
return localRepository.getGroupChat(groupId)
}
override fun markMessagesSeen(seenGroupId: String) {
apiClient.seenMessages(seenGroupId).subscribe({ }, ExceptionHandler.rx())
}
override fun flagMessage(chatMessageID: String, additionalInfo: String, groupID: String?): Flowable<Void> {
return when {
chatMessageID.isBlank() -> Flowable.empty()
userID == BuildConfig.ANDROID_TESTING_UUID -> Flowable.empty()
else -> {
val data = mutableMapOf<String, String>()
data["comment"] = additionalInfo
if (groupID?.isNotBlank() != true) {
apiClient.flagInboxMessage(chatMessageID, data)
} else {
apiClient.flagMessage(groupID, chatMessageID, data)
}
}
}
}
override fun likeMessage(chatMessage: ChatMessage): Flowable<ChatMessage> {
if (chatMessage.id.isBlank()) {
return Flowable.empty()
}
val liked = chatMessage.userLikesMessage(userID)
if (chatMessage.isManaged) {
localRepository.likeMessage(chatMessage, userID, !liked)
}
return apiClient.likeMessage(chatMessage.groupId ?: "", chatMessage.id)
.map {
it.groupId = chatMessage.groupId
it
}
}
override fun deleteMessage(chatMessage: ChatMessage): Flowable<Void> {
return if (chatMessage.isInboxMessage) {
apiClient.deleteInboxMessage(chatMessage.id)
} else {
apiClient.deleteMessage(chatMessage.groupId ?: "", chatMessage.id)
}.doOnNext { localRepository.deleteMessage(chatMessage.id) }
}
override fun postGroupChat(groupId: String, messageObject: HashMap<String, String>): Flowable<PostChatMessageResult> {
return apiClient.postGroupChat(groupId, messageObject)
.map { postChatMessageResult ->
postChatMessageResult.message.groupId = groupId
postChatMessageResult
}
}
override fun postGroupChat(groupId: String, message: String): Flowable<PostChatMessageResult> {
val messageObject = HashMap<String, String>()
messageObject["message"] = message
return postGroupChat(groupId, messageObject)
}
override suspend fun retrieveGroup(id: String): Group? {
val group = apiClient.getGroup(id)
group?.let { localRepository.saveGroup(it) }
retrieveGroupChat(id)
return group
}
override fun getGroup(id: String?): Flow<Group?> {
if (id?.isNotBlank() != true) {
return emptyFlow()
}
return localRepository.getGroup(id)
}
override suspend fun leaveGroup(id: String?, keepChallenges: Boolean): Group? {
if (id?.isNotBlank() != true) {
return null
}
apiClient.leaveGroup(id, if (keepChallenges) "remain-in-challenges" else "leave-challenges")
localRepository.updateMembership(userID, id, false)
return localRepository.getGroup(id).firstOrNull()
}
override suspend fun joinGroup(id: String?): Group? {
if (id?.isNotBlank() != true) {
return null
}
val group = apiClient.joinGroup(id)
group?.let {
localRepository.updateMembership(userID, id, true)
localRepository.save(group)
}
return group
}
override suspend fun createGroup(
name: String?,
description: String?,
leader: String?,
type: String?,
privacy: String?,
leaderCreateChallenge: Boolean?
): Group? {
val group = Group()
group.name = name
group.description = description
group.type = type
group.leaderID = leader
group.privacy = privacy
val savedGroup = apiClient.createGroup(group)
savedGroup?.let { localRepository.save(it) }
return savedGroup
}
override suspend fun updateGroup(
group: Group?,
name: String?,
description: String?,
leader: String?,
leaderCreateChallenge: Boolean?
): Group? {
if (group == null) {
return null
}
val copiedGroup = localRepository.getUnmanagedCopy(group)
copiedGroup.name = name
copiedGroup.description = description
copiedGroup.leaderID = leader
copiedGroup.leaderOnlyChallenges = leaderCreateChallenge ?: false
localRepository.save(copiedGroup)
return apiClient.updateGroup(copiedGroup.id, copiedGroup)
}
override fun retrieveGroups(type: String): Flowable<List<Group>> {
return apiClient.listGroups(type)
.doOnNext { groups ->
if ("guilds" == type) {
val memberships = groups.map {
GroupMembership(userID, it.id)
}
localRepository.saveGroupMemberships(userID, memberships)
}
localRepository.save(groups)
}
}
override fun getGroups(type: String) = localRepository.getGroups(type)
override fun getPublicGuilds() = localRepository.getPublicGuilds()
override fun getInboxConversations() = localRepository.getInboxConversation(userID)
override fun getInboxMessages(replyToUserID: String?) = localRepository.getInboxMessages(userID, replyToUserID)
override suspend fun retrieveInboxMessages(uuid: String, page: Int): List<ChatMessage>? {
val messages = apiClient.retrieveInboxMessages(uuid, page) ?: return null
messages.forEach {
it.isInboxMessage = true
}
localRepository.saveInboxMessages(userID, uuid, messages, page)
return messages
}
override fun retrieveInboxConversations(): Flowable<List<InboxConversation>> {
return apiClient.retrieveInboxConversations().doOnNext { conversations ->
localRepository.saveInboxConversations(userID, conversations)
}
}
override suspend fun postPrivateMessage(recipientId: String, messageObject: HashMap<String, String>): List<ChatMessage>? {
val message = apiClient.postPrivateMessage(messageObject)
return retrieveInboxMessages(recipientId, 0)
}
override suspend fun postPrivateMessage(recipientId: String, message: String): List<ChatMessage>? {
val messageObject = HashMap<String, String>()
messageObject["message"] = message
messageObject["toUserId"] = recipientId
return postPrivateMessage(recipientId, messageObject)
}
override suspend fun getPartyMembers(id: String) = localRepository.getPartyMembers(id)
override suspend fun getGroupMembers(id: String) = localRepository.getGroupMembers(id)
override suspend fun retrievePartyMembers(id: String, includeAllPublicFields: Boolean): List<Member>? {
val members = apiClient.getGroupMembers(id, includeAllPublicFields)
members?.let { localRepository.savePartyMembers(id, it) }
return members
}
override fun inviteToGroup(id: String, inviteData: Map<String, Any>): Flowable<List<Void>> = apiClient.inviteToGroup(id, inviteData)
override suspend fun retrieveMember(userId: String?): Member? {
return if (userId == null) {
null
} else {
try {
apiClient.getMember(UUID.fromString(userId).toString())
} catch (_: IllegalArgumentException) {
apiClient.getMemberWithUsername(userId)
}
}
}
override suspend fun retrieveMemberWithUsername(username: String?): Member? {
return retrieveMember(username)
}
override fun findUsernames(username: String, context: String?, id: String?): Flowable<List<FindUsernameResult>> {
return apiClient.findUsernames(username, context, id)
}
override fun markPrivateMessagesRead(user: User?): Flowable<Void> {
if (user?.isManaged == true) {
localRepository.modify(user) {
it.inbox?.hasUserSeenInbox = true
}
}
return apiClient.markPrivateMessagesRead()
}
override fun markSomePrivateMessagesAsRead(user: User?, messages: List<ChatMessage>) {
if (user?.isManaged == true) {
val numOfUnseenMessages = messages.count { !it.isSeen }
localRepository.modify(user) {
val numOfNewMessagesFromInbox = it.inbox?.newMessages ?: 0
if (numOfNewMessagesFromInbox > numOfUnseenMessages) {
it.inbox?.newMessages = numOfNewMessagesFromInbox - numOfUnseenMessages
} else {
it.inbox?.newMessages = 0
}
}
}
for (message in messages.filter { it.isManaged && !it.isSeen }) {
localRepository.modify(message) {
it.isSeen = true
}
}
}
override fun getUserGroups(type: String?) = localRepository.getUserGroups(userID, type)
override fun acceptQuest(user: User?, partyId: String): Flowable<Void> {
return apiClient.acceptQuest(partyId)
.doOnNext {
user?.let {
localRepository.updateRSVPNeeded(it, false)
}
}
}
override fun rejectQuest(user: User?, partyId: String): Flowable<Void> {
return apiClient.rejectQuest(partyId)
.doOnNext { _ ->
user?.let {
localRepository.updateRSVPNeeded(it, false)
}
}
}
override fun leaveQuest(partyId: String): Flowable<Void> {
return apiClient.leaveQuest(partyId)
}
override fun cancelQuest(partyId: String): Flowable<Void> {
return apiClient.cancelQuest(partyId)
.doOnNext { localRepository.removeQuest(partyId) }
}
override fun abortQuest(partyId: String): Flowable<Quest> {
return apiClient.abortQuest(partyId)
.doOnNext { localRepository.removeQuest(partyId) }
}
override fun rejectGroupInvite(groupId: String): Flowable<Void> {
return apiClient.rejectGroupInvite(groupId)
.doOnNext {
localRepository.rejectGroupInvitation(userID, groupId)
}
}
override fun forceStartQuest(party: Group): Flowable<Quest> {
return apiClient.forceStartQuest(party.id, localRepository.getUnmanagedCopy(party))
.doOnNext { localRepository.setQuestActivity(party, true) }
}
override fun getMemberAchievements(userId: String?): Flowable<List<Achievement>> {
return if (userId == null) {
Flowable.empty()
} else apiClient.getMemberAchievements(userId)
}
override fun transferGems(giftedID: String, amount: Int): Flowable<Void> {
return apiClient.transferGems(giftedID, amount)
}
}
| gpl-3.0 | c16e0daba5e7552ba2f17967cf797285 | 37.364407 | 136 | 0.640115 | 5.119398 | false | false | false | false |
ilya-g/kotlinx.collections.experimental | kotlinx-collections-experimental/src/main/kotlin/kotlinx.collections.experimental/grouping/groupFold.kt | 1 | 3285 | package kotlinx.collections.experimental.grouping
public inline fun <T, K, R> Iterable<T>.groupAggregateBy(keySelector: (T) -> K, operation: (key: K, value: R?, element: T, first: Boolean) -> R): Map<K, R> {
val result = mutableMapOf<K, R>()
for (e in this) {
val key = keySelector(e)
val value = result[key]
result[key] = operation(key, value, e, value == null && !result.containsKey(key))
}
return result
}
public inline fun <T, K, R> Iterable<T>.groupFoldBy1(keySelector: (T) -> K, initialValueSelector: (K, T) -> R, operation: (K, R, T) -> R): Map<K, R> =
groupAggregateBy(keySelector) { key, value, e, first -> operation(key, if (first) initialValueSelector(key, e) else value as R, e) }
public inline fun <T, K, R> Iterable<T>.groupFoldBy(crossinline keySelector: (T) -> K): ((key: K, value: R?, element: T, first: Boolean) -> R) -> Map<K, R> = {
operation -> groupAggregateBy(keySelector, operation)
}
public inline fun <T, K, R> Iterable<T>.groupFoldBy(keySelector: (T) -> K, initialValue: R, operation: (R, T) -> R): Map<K, R> =
groupAggregateBy<T, K, R>(keySelector, { k, v, e, first -> operation(if (first) initialValue else v as R, e) })
public inline fun <T, K, R> Iterable<T>.groupReduceBy(keySelector: (T) -> K, reducer: Reducer<R, T>): Map<K, R> =
groupAggregateBy(keySelector, { k, v, e, first -> if (first) reducer.initial(e) else reducer(v as R, e) })
public inline fun <T, K> Iterable<T>.groupCountBy(keySelector: (T) -> K): Map<K, Int> =
groupFoldBy(keySelector, 0, { acc, e -> acc + 1 })
public inline fun <K> IntArray.groupCountBy(keySelector: (Int) -> K): Map<K, Int> {
val result = mutableMapOf<K, Int>()
for (e in this) {
val key = keySelector(e)
val value = result[key]
result[key] = (value ?: 0) + 1
}
return result
}
public inline fun <S, T : S, K> Iterable<T>.groupReduceBy(keySelector: (T) -> K, operation: (K, S, T) -> S): Map<K, S> {
return groupAggregateBy(keySelector) { key, value, e, first ->
if (first) e else operation(key, value as S, e)
}
}
public inline fun <K> Iterable<Int>.groupBySum(keySelector: (Int) -> K): Map<K, Int> =
groupReduceBy(keySelector, { k, sum, e -> sum + e })
public inline fun <T, K> Iterable<T>.groupBySumBy(keySelector: (T) -> K, valueSelector: (T) -> Int): Map<K, Int> =
groupFoldBy(keySelector, 0, { acc, e -> acc + valueSelector(e)})
fun <T, K> Iterable<T>.countBy(keySelector: (T) -> K) =
groupBy(keySelector).mapValues { it.value.fold(0) { acc, e -> acc + 1 } }
fun main(args: Array<String>) {
val values = listOf("apple", "fooz", "bisquit", "abc", "far", "bar", "foo")
val keySelector = { s: String -> s[0] }
val countByChar = values.groupFoldBy(keySelector, 0, { acc, e -> acc + 1 })
val sumLengthByChar: Map<Char, Int> = values.groupAggregateBy({ it[0] }) { k, v, e, first -> v ?: 0 + e.length }
val sumLengthByChar2 = values.groupBySumBy( keySelector, { it.length } )
println(sumLengthByChar2)
val countByChar2 = values.groupCountBy { it.first() }
println(countByChar2)
println(values.groupReduceBy(keySelector, Count))
println(values.groupReduceBy(keySelector, Sum.by { it.length }))
}
| apache-2.0 | d3496d5fbab5bef6e1389c31e893573c | 39.555556 | 159 | 0.622831 | 3.204878 | false | false | false | false |
da1z/intellij-community | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 1 | 21158 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.ex.ProjectNameProvider
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.*
import com.intellij.util.containers.computeIfAny
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import gnu.trove.THashSet
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
if (isDirectoryBased) {
normalizeDefaultProjectElement(defaultProject, element, Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)))
}
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory()
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny {
LOG.runAndLogException { it.customizeStorageSpecs(component, project, result!!, operation) }
}?.let {
// yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case
return it
}
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (!isDirectoryBased) {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
LOG.runAndLogException {
nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
}
return ProjectNameProvider.EP_NAME.extensions.computeIfAny {
LOG.runAndLogException { it.getDefaultName(project) }
} ?: PathUtilRt.getFileName(baseDir).replace(":", "")
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
}
private fun moveComponentConfiguration(defaultProject: Project, element: Element, projectConfigDir: Path) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val workspaceComponentNames = THashSet(listOf("GradleLocalSettings"))
val compilerComponentNames = THashSet<String>()
fun processComponents(aClass: Class<*>) {
val stateAnnotation = StoreUtil.getStateSpec(aClass)
if (stateAnnotation == null || stateAnnotation.name.isEmpty()) {
return
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return
when {
storage.path == StoragePathMacros.WORKSPACE_FILE -> workspaceComponentNames.add(stateAnnotation.name)
storage.path == "compiler.xml" -> compilerComponentNames.add(stateAnnotation.name)
}
}
@Suppress("DEPRECATION")
val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
processComponents(it.javaClass)
}
ServiceManagerImpl.processAllImplementationClasses(defaultProject as ProjectImpl) { aClass, _ ->
processComponents(aClass)
true
}
@Suppress("RemoveExplicitTypeArguments")
val elements = mapOf(compilerComponentNames to SmartList<Element>(), workspaceComponentNames to SmartList<Element>())
val iterator = componentElements.iterator()
for (componentElement in iterator) {
val name = componentElement.getAttributeValue("name") ?: continue
for ((names, list) in elements) {
if (names.contains(name)) {
iterator.remove()
list.add(componentElement)
}
}
}
for ((names, list) in elements) {
writeConfigFile(list, projectConfigDir.resolve(if (names === workspaceComponentNames) "workspace.xml" else "compiler.xml"))
}
}
private fun writeConfigFile(elements: List<Element>, file: Path) {
if (elements.isEmpty()) {
return
}
var wrapper = Element("project").attribute("version", "4")
if (file.exists()) {
try {
wrapper = loadElement(file)
}
catch (e: Exception) {
LOG.warn(e)
}
}
elements.forEach { wrapper.addContent(it) }
// .idea component configuration files uses XML prolog due to historical reasons
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, SaveSession { }, null, wrapper, LineSeparator.LF, prependXmlProlog = true)
}
else {
file.outputStream().use {
it.write(XML_PROLOG)
it.write(LineSeparator.LF.separatorBytes)
wrapper.write(it)
}
}
}
// public only to test
fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path) {
LOG.runAndLogException {
moveComponentConfiguration(defaultProject, element, projectConfigDir)
}
LOG.runAndLogException {
val iterator = element.getChildren("component").iterator()
for (component in iterator) {
val componentName = component.getAttributeValue("name")
fun writeProfileSettings(schemeDir: Path) {
component.removeAttribute("name")
if (!component.isEmpty()) {
val wrapper = Element("component").attribute("name", componentName)
component.name = "settings"
wrapper.addContent(component)
val file = schemeDir.resolve("profiles_settings.xml")
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, SaveSession { }, null, wrapper, LineSeparator.LF, prependXmlProlog = false)
}
else {
file.outputStream().use {
wrapper.write(it)
}
}
}
}
when (componentName) {
"InspectionProjectProfileManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("inspectionProfiles")
convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir)
component.removeChild("version")
writeProfileSettings(schemeDir)
}
"CopyrightManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("copyright")
convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir)
writeProfileSettings(schemeDir)
}
ModuleManagerImpl.COMPONENT_NAME -> {
iterator.remove()
}
}
}
}
}
private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) {
for (profile in profileIterator) {
val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue
profileIterator.remove()
val wrapper = Element("component").attribute("name", componentName)
wrapper.addContent(profile)
val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.write(wrapper, path.outputStream(), "\n")
}
} | apache-2.0 | 6a9405818b3c9688595efc16893d7af5 | 35.991259 | 191 | 0.726108 | 5.125484 | false | false | false | false |
mattvchandler/ProgressBars | app/src/main/java/db/Progress_bars_table.kt | 1 | 21491 | /*
Copyright (C) 2020 Matthew Chandler
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.mattvchandler.progressbars.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import androidx.preference.PreferenceManager
import org.mattvchandler.progressbars.R
// DB Table schema
open class Progress_bars_table: BaseColumns
{
// associated enums
enum class Days_of_week (val index: Int, val mask: Int)
{
SUNDAY(0, 0x01),
MONDAY(1, 0x02),
TUESDAY(2, 0x04),
WEDNESDAY(3, 0x08),
THURSDAY(4, 0x10),
FRIDAY(5, 0x20),
SATURDAY(6, 0x40);
companion object
{
fun all_days_mask(): Int
{
return SUNDAY.mask or MONDAY.mask or TUESDAY.mask or WEDNESDAY.mask or THURSDAY.mask or FRIDAY.mask or SATURDAY.mask
}
}
}
enum class Unit(val index: Int)
{
SECOND(0),
MINUTE(1),
HOUR(2),
DAY(3),
WEEK(4),
MONTH(5),
YEAR(6)
}
companion object
{
const val TABLE_NAME = "progress_bar"
const val ID_COL = "id"
const val ORDER_COL = "order_ind"
const val WIDGET_ID_COL = "widget_id"
const val SEPARATE_TIME_COL = "separate_time"
const val START_TIME_COL = "start_time"
const val START_TZ_COL = "start_tz"
const val END_TIME_COL = "end_time"
const val END_TZ_COL = "end_tz"
const val REPEATS_COL = "repeats"
const val REPEAT_COUNT_COL = "repeat_count"
const val REPEAT_UNIT_COL = "repeat_unit"
const val REPEAT_DAYS_OF_WEEK_COL = "repeat_days_of_week"
const val TITLE_COL = "title"
const val PRE_TEXT_COL = "pre_text"
const val START_TEXT_COL = "start_text"
const val COUNTDOWN_TEXT_COL = "countdown_text"
const val COMPLETE_TEXT_COL = "complete_text"
const val POST_TEXT_COL = "post_text"
const val SINGLE_PRE_TEXT_COL = "single_pre_text"
const val SINGLE_COMPLETE_TEXT_COL = "single_complete_text"
const val SINGLE_POST_TEXT_COL = "single_post_text"
const val PRECISION_COL = "precision"
const val SHOW_START_COL = "show_start"
const val SHOW_END_COL = "show_end"
const val SHOW_PROGRESS_COL = "show_progress"
const val SHOW_YEARS_COL = "show_years"
const val SHOW_MONTHS_COL = "show_months"
const val SHOW_WEEKS_COL = "show_weeks"
const val SHOW_DAYS_COL = "show_days"
const val SHOW_HOURS_COL = "show_hours"
const val SHOW_MINUTES_COL = "show_minutes"
const val SHOW_SECONDS_COL = "show_seconds"
const val TERMINATE_COL = "terminate"
const val NOTIFY_START_COL = "notify_start"
const val NOTIFY_END_COL = "notify_end"
const val HAS_NOTIFICATION_CHANNEL_COL = "has_notification_channel"
const val NOTIFICATION_PRIORITY_COL = "notification_priority"
const val SELECT_ALL_ROWS = "SELECT * FROM $TABLE_NAME ORDER BY $ORDER_COL, $WIDGET_ID_COL"
const val SELECT_ALL_ROWS_NO_WIDGET = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL IS NULL ORDER BY $ORDER_COL"
const val SELECT_ALL_WIDGETS = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL IS NOT NULL ORDER BY $WIDGET_ID_COL"
const val SELECT_WIDGET = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL = ?"
// table schema
const val CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ID_COL + " INTEGER UNIQUE NOT NULL, " +
ORDER_COL + " INTEGER UNIQUE, " +
WIDGET_ID_COL + " INTEGER UNIQUE, " +
SEPARATE_TIME_COL + " INTEGER NOT NULL, " +
START_TIME_COL + " INTEGER NOT NULL, " +
START_TZ_COL + " TEXT NOT NULL, " +
END_TIME_COL + " INTEGER NOT NULL, " +
END_TZ_COL + " TEXT NOT NULL, " +
REPEATS_COL + " INTEGER NOT NULL, " +
REPEAT_COUNT_COL + " INTEGER NOT NULL, " +
REPEAT_UNIT_COL + " INTEGER NOT NULL, " +
REPEAT_DAYS_OF_WEEK_COL + " INTEGER NOT NULL, " +
TITLE_COL + " TEXT NOT NULL, " +
PRE_TEXT_COL + " TEXT NOT NULL, " +
START_TEXT_COL + " TEXT NOT NULL, " +
COUNTDOWN_TEXT_COL + " TEXT NOT NULL, " +
COMPLETE_TEXT_COL + " TEXT NOT NULL, " +
POST_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_PRE_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_COMPLETE_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_POST_TEXT_COL + " TEXT NOT NULL, " +
PRECISION_COL + " INTEGER NOT NULL, " +
SHOW_START_COL + " INTEGER NOT NULL, " +
SHOW_END_COL + " INTEGER NOT NULL, " +
SHOW_PROGRESS_COL + " INTEGER NOT NULL, " +
SHOW_YEARS_COL + " INTEGER NOT NULL, " +
SHOW_MONTHS_COL + " INTEGER NOT NULL, " +
SHOW_WEEKS_COL + " INTEGER NOT NULL, " +
SHOW_DAYS_COL + " INTEGER NOT NULL, " +
SHOW_HOURS_COL + " INTEGER NOT NULL, " +
SHOW_MINUTES_COL + " INTEGER NOT NULL, " +
SHOW_SECONDS_COL + " INTEGER NOT NULL, " +
TERMINATE_COL + " INTEGER NOT NULL, " +
NOTIFY_START_COL + " INTEGER NOT NULL, " +
NOTIFY_END_COL + " INTEGER NOT NULL, " +
HAS_NOTIFICATION_CHANNEL_COL + " INTEGER NOT NULL, " +
NOTIFICATION_PRIORITY_COL + " TEXT NOT NULL)"
fun upgrade(context: Context, db: SQLiteDatabase, old_version: Int)
{
val table_exists = db.query("sqlite_master", arrayOf("name"), "type = 'table' AND name = ?", arrayOf(TABLE_NAME), null, null, null)
if(table_exists.count == 0)
{
db.execSQL(CREATE_TABLE)
return
}
fun set_new_id()
{
val cursor = db.rawQuery("SELECT MAX($ID_COL) from $TABLE_NAME", null)
cursor.moveToFirst()
val count = cursor.getInt(0)
cursor.close()
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(context.resources.getString(R.string.pref_next_id_key), count + 1).apply()
}
when(old_version)
{
1 ->
{
// Added some new columns - copy old data and insert defaults for new columns
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ORDER_COL + ", " + // using order for id
ORDER_COL + ", " +
"NULL, " +
"1, " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
"0, " +
"1, " +
Unit.DAY.index.toString() + ", " +
Days_of_week.all_days_mask().toString() + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
"'" + context.getString(R.string.default_single_pre_text) + "', " +
"'" + context.getString(R.string.default_single_complete_text) + "', " +
"'" + context.getString(R.string.default_single_post_text) + "', " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
"0, " +
"'HIGH' " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
2, 3 ->
{
// 2 -> 3 fixed NOT NULL for some columns - copy all data over
// 3 -> 4 add SEPARATE_TIME_COL, countdown text for single time, ID col, notification channel
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ORDER_COL + ", " + // using order for id
ORDER_COL + ", " +
"NULL, " +
"1, " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
"'" + context.getString(R.string.default_single_pre_text) + "', " +
"'" + context.getString(R.string.default_single_complete_text) + "', " +
"'" + context.getString(R.string.default_single_post_text) + "', " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
"0, " +
"'HIGH' " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
4 ->
{
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ID_COL + ", " +
ORDER_COL + ", " +
"NULL, " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL + " " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
else ->
{
db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
db.execSQL(CREATE_TABLE)
}
}
table_exists.close()
}
}
}
| mit | 19d3fa3e51e02fa6284922e6c7e3b17b | 45.517316 | 159 | 0.377972 | 4.762021 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/clipboard/ClipboardEventEmitter.kt | 2 | 1581 | package abi43_0_0.expo.modules.clipboard
import android.content.Context
import android.content.ClipboardManager
import android.os.Bundle
import android.util.Log
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.interfaces.LifecycleEventListener
import abi43_0_0.expo.modules.core.interfaces.services.EventEmitter
import abi43_0_0.expo.modules.core.interfaces.services.UIManager
class ClipboardEventEmitter(context: Context, moduleRegistry: ModuleRegistry) : LifecycleEventListener {
private val onClipboardEventName = "onClipboardChanged"
private var isListening = true
private var eventEmitter = moduleRegistry.getModule(EventEmitter::class.java)
init {
moduleRegistry.getModule(UIManager::class.java).registerLifecycleEventListener(this)
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
if (clipboard == null) {
Log.e("Clipboard", "CLIPBOARD_SERVICE unavailable. Events wont be received")
} else {
clipboard.addPrimaryClipChangedListener {
if (isListening) {
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount >= 1) {
eventEmitter.emit(
onClipboardEventName,
Bundle().apply {
putString("content", clip.getItemAt(0).text.toString())
}
)
}
}
}
}
}
override fun onHostResume() {
isListening = true
}
override fun onHostPause() {
isListening = false
}
override fun onHostDestroy() = Unit
}
| bsd-3-clause | d0e17428a1801036fcd6c418886d9f66 | 31.265306 | 104 | 0.70272 | 4.530086 | false | false | false | false |
abigpotostew/easypolitics | db/src/main/kotlin/bz/stewart/bracken/db/bill/database/mongodb/MongoTransaction.kt | 1 | 3257 | package bz.stewart.bracken.db.bill.database.mongodb
import bz.stewart.bracken.db.bill.RuntimeMode
import bz.stewart.bracken.db.bill.data.Bill
import bz.stewart.bracken.db.bill.index.BillIndexDefinition
import bz.stewart.bracken.db.database.DatabaseClient
import bz.stewart.bracken.db.database.Transaction
import bz.stewart.bracken.db.database.index.InlineSyncIndex
import bz.stewart.bracken.db.database.mongo.AbstractMongoDb
import bz.stewart.bracken.db.database.mongo.CollectionWriter
import bz.stewart.bracken.db.debug.DebugUtils
import com.mongodb.MongoClient
import com.mongodb.MongoCommandException
import com.mongodb.MongoTimeoutException
import com.mongodb.MongoWriteException
import mu.KLogging
import java.io.File
/**
* Created by stew on 3/12/17.
*/
class MongoTransaction(val dbClient: DatabaseClient<MongoClient>,
val data: File,
val test: Boolean,
val mode: RuntimeMode,
val congressParseLimit: Set<Int>) : Transaction<Bill, AbstractMongoDb<Bill>> {
companion object : KLogging()
private var writer: CollectionWriter<Bill, AbstractMongoDb<Bill>>? = null
private var db: BillJsonDataDatabase? = null
private var startedTransaction: Boolean = false
override fun setWriter(writer: CollectionWriter<Bill, AbstractMongoDb<Bill>>) {
this.writer = writer
}
override fun beginTransaction() {
val writer = when (test) {
true -> emptyBillWriter()
false -> SingleBillWriter()
}
val collName = "bills"
db = BillJsonDataDatabase(this.data, this.dbClient, collName, mode, test, writer)
logger.info { "Loading bill into database@${this.dbClient.databaseName} in collection@$collName with mode@$mode and test@$test" }
db!!.openDatabase()
startedTransaction = true
}
override fun execute() {
if (!startedTransaction) {
throw IllegalStateException("trying to run MongoTransaction before calling beginTransaction() or before starting successfully.")
}
val db = this.db ?: return
try {
db.loadData(if (congressParseLimit.isEmpty()) null else congressParseLimit.map(Int::toString))//todo move this write logic to a writer
InlineSyncIndex(db, { BillIndexDefinition(it) }).doSync(this.test)
} catch (e: MongoCommandException) {
abort("Mongo exception: ${DebugUtils.stackTraceToString(e)}")
} catch (e: MongoWriteException) {
abort("Mongo write error: $e @ $e")
} catch (e: MongoTimeoutException) {
logger.error { "Timeout while connecting to the database. Is mongod running? @ $e" }
abort("Aborting due to mongod timeout @ $e")
} catch (e: RuntimeException) {
abort("Unknown error, this should be fixed:\n\n ${DebugUtils.stackTraceToString(e)}")
}
}
override fun endTransaction() {
if (startedTransaction) {
db!!.closeDatabase()
}
startedTransaction = false
}
override fun abort(msg: String) {
logger.error { "Aborting transaction: $msg" }
endTransaction()
error("Aborting transaction.")
}
} | apache-2.0 | 70da85a56ce85d496096f18c5c65617c | 38.253012 | 146 | 0.669635 | 4.486226 | false | true | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/service/RuntimeShareService.kt | 1 | 3633 | package com.bajdcc.LALR1.grammar.runtime.service
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeArray
import org.apache.log4j.Logger
/**
* 【运行时】运行时共享服务
*
* @author bajdcc
*/
class RuntimeShareService(private val service: RuntimeService) : IRuntimeShareService {
private val mapShares = mutableMapOf<String, ShareStruct>()
internal data class ShareStruct(var name: String, var obj: RuntimeObject, var page: String,
var reference: Int = 1, var locked: Boolean = false) {
val objType: String
get() = obj.type.desc
}
override fun startSharing(name: String, obj: RuntimeObject, page: String): Int {
if (mapShares.size >= MAX_SHARING)
return -1
if (mapShares.containsKey(name))
return 0
mapShares[name] = ShareStruct(name, obj, page)
logger.debug("Sharing '$name' created")
return 1
}
override fun createSharing(name: String, obj: RuntimeObject, page: String): Int {
if (mapShares.size >= MAX_SHARING)
return -1
mapShares[name] = ShareStruct(name, obj, page)
logger.debug("Sharing '$name' created")
return 1
}
override fun getSharing(name: String, reference: Boolean): RuntimeObject {
val ss = mapShares[name]
if (ss != null) {
if (reference)
ss.reference++
return ss.obj
}
return RuntimeObject(null)
}
override fun stopSharing(name: String): Int {
if (!mapShares.containsKey(name))
return -1
val ss = mapShares[name]!!
ss.reference--
if (ss.reference == 0) {
mapShares.remove(name)
return 1
}
return if (ss.reference < 0) {
2
} else 0
}
override fun isLocked(name: String): Boolean {
return mapShares.containsKey(name) && mapShares[name]!!.locked
}
override fun setLocked(name: String, lock: Boolean) {
if (mapShares.containsKey(name))
mapShares[name]!!.locked = lock
}
override fun size(): Long {
return mapShares.size.toLong()
}
override fun stat(api: Boolean): RuntimeArray {
val array = RuntimeArray()
if (api) {
mapShares.values.sortedBy { it.objType }.sortedBy { it.name }
.forEach { value ->
val item = RuntimeArray()
item.add(RuntimeObject(value.name))
item.add(RuntimeObject(value.obj.type.desc))
item.add(RuntimeObject(value.page))
item.add(RuntimeObject(value.reference.toString()))
item.add(RuntimeObject(if (value.locked) "是" else "否"))
array.add(RuntimeObject(item))
}
} else {
array.add(RuntimeObject(String.format(" %-20s %-15s %-5s %-5s",
"Name", "Type", "Ref", "Locked")))
mapShares.values.sortedBy { it.objType }.sortedBy { it.name }
.forEach { value ->
array.add(RuntimeObject(String.format(" %-20s %-15s %-5s %-5s",
value.name, value.obj.type.desc, value.reference.toString(), value.locked.toString())))
}
}
return array
}
companion object {
private val logger = Logger.getLogger("share")
private const val MAX_SHARING = 1000
}
}
| mit | 5d88061990ec2660da3d97ba66bf863d | 33.009434 | 119 | 0.554508 | 4.417892 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/host/ParticleContextTest.kt | 1 | 24300 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.data.Plan
import arcs.core.entity.Handle
import arcs.core.host.ParticleState.Companion.Desynced
import arcs.core.host.ParticleState.Companion.Failed
import arcs.core.host.ParticleState.Companion.Failed_NeverStarted
import arcs.core.host.ParticleState.Companion.FirstStart
import arcs.core.host.ParticleState.Companion.Instantiated
import arcs.core.host.ParticleState.Companion.MaxFailed
import arcs.core.host.ParticleState.Companion.Running
import arcs.core.host.ParticleState.Companion.Stopped
import arcs.core.host.ParticleState.Companion.Waiting
import arcs.core.host.api.HandleHolder
import arcs.core.host.api.Particle
import arcs.core.storage.StorageProxy.StorageEvent
import arcs.core.testutil.runTest
import arcs.core.util.Scheduler
import arcs.core.util.testutil.LogRule
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.only
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.test.assertFailsWith
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mock
import org.mockito.MockitoAnnotations
@RunWith(JUnit4::class)
class ParticleContextTest {
@get:Rule
val log = LogRule()
@Mock
lateinit var particle: Particle
@Mock
lateinit var handles: HandleHolder
@Mock
lateinit var mark: (String) -> Unit
lateinit var context: ParticleContext
val scheduler = Scheduler(EmptyCoroutineContext)
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
whenever(particle.handles).thenReturn(handles)
context = ParticleContext(
particle,
Plan.Particle("name", "location", mapOf())
)
}
@Ignore("b/159257058: write-only handles still need to sync")
@Test
fun fullLifecycle_writeOnlyParticle() = runTest {
val handle = mockHandle(HandleMode.Write)
mark("initParticle")
context.initParticle(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("registerHandle")
context.registerHandle(handle)
assertThat(context.particleState).isEqualTo(Waiting)
mark("runParticleAsync")
context.runParticleAsync(scheduler).await()
assertThat(context.particleState).isEqualTo(Running)
mark("stopParticle")
context.stopParticle(scheduler)
assertThat(context.particleState).isEqualTo(Stopped)
val mocks = arrayOf(particle, mark, handles, handle)
with(inOrder(*mocks)) {
verify(mark).invoke("initParticle")
verify(particle).onFirstStart()
verify(particle).onStart()
verify(mark).invoke("registerHandle")
verify(handle).mode
verify(mark).invoke("runParticleAsync")
verify(particle).onReady()
verify(mark).invoke("stopParticle")
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun fullLifecycle_readingParticle() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
mark("initParticle")
context.initParticle(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("registerHandle")
context.registerHandle(handle)
assertThat(context.particleState).isEqualTo(Waiting)
mark("runParticleAsync")
val particleReady = context.runParticleAsync(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("notify(READY)")
context.notify(StorageEvent.READY, handle)
particleReady.await()
assertThat(context.particleState).isEqualTo(Running)
mark("stopParticle")
context.stopParticle(scheduler)
assertThat(context.particleState).isEqualTo(Stopped)
val mocks = arrayOf(particle, mark, handles, handle)
with(inOrder(*mocks)) {
verify(mark).invoke("initParticle")
verify(particle).onFirstStart()
verify(particle).onStart()
verify(mark).invoke("registerHandle")
verify(handle).mode
verify(handle).registerForStorageEvents(any())
verify(mark).invoke("runParticleAsync")
verify(handle).maybeInitiateSync()
verify(mark).invoke("notify(READY)")
verify(particle).onReady()
verify(mark).invoke("stopParticle")
verify(particle).handles
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun initParticle_secondInstantiation() = runTest {
context.particleState = Stopped
context.initParticle(scheduler)
verify(particle, only()).onStart()
assertThat(context.particleState).isEqualTo(Waiting)
}
@Test
fun storageEvents() = runTest {
context.initParticle(scheduler)
val handle1 = mockHandle(HandleMode.Write).also { context.registerHandle(it) }
val handle2 = mockHandle(HandleMode.ReadWrite).also { context.registerHandle(it) }
val handle3 = mockHandle(HandleMode.Read).also { context.registerHandle(it) }
val handle4 = mockHandle(HandleMode.ReadWrite).also { context.registerHandle(it) }
val particleReady = context.runParticleAsync(scheduler)
verify(particle).onFirstStart()
verify(particle).onStart()
// TODO(b/159257058): write-only handles still need to sync
arrayOf(handle1, handle2, handle3, handle4).forEach {
verify(it).mode
verify(it).registerForStorageEvents(any())
verify(it).maybeInitiateSync()
}
// All handle.onReady calls are required for particle.onReady
context.notify(StorageEvent.READY, handle1) // TODO(b/159257058)
context.notify(StorageEvent.READY, handle2)
assertThat(context.particleState).isEqualTo(Waiting)
context.notify(StorageEvent.READY, handle3)
assertThat(context.particleState).isEqualTo(Waiting)
mark("ready")
context.notify(StorageEvent.READY, handle4)
particleReady.await()
assertThat(context.particleState).isEqualTo(Running)
// Every handle.onUpdate triggers particle.onUpdate
mark("update")
context.notify(StorageEvent.UPDATE, handle2)
context.notify(StorageEvent.UPDATE, handle3)
context.notify(StorageEvent.UPDATE, handle4)
// Only the first handle.onDesync triggers particle.onDesync
// All handle.onResyncs are required for particle.onResync
mark("desync1")
context.notify(StorageEvent.DESYNC, handle2) // h2 desynced
assertThat(context.particleState).isEqualTo(Desynced)
context.notify(StorageEvent.DESYNC, handle3) // h2, h3 desynced
context.notify(StorageEvent.RESYNC, handle2) // h3 desynced
context.notify(StorageEvent.DESYNC, handle4) // h3, h4 desynced
context.notify(StorageEvent.RESYNC, handle4) // h3 desynced
assertThat(context.particleState).isEqualTo(Desynced)
mark("desync2")
context.notify(StorageEvent.RESYNC, handle3) // all resynced
assertThat(context.particleState).isEqualTo(Running)
val mocks = arrayOf(particle, mark, handle1, handle2, handle3, handle4)
with(inOrder(*mocks)) {
verify(mark).invoke("ready")
verify(particle).onReady()
verify(mark).invoke("update")
verify(particle, times(3)).onUpdate()
verify(mark).invoke("desync1")
verify(particle).onDesync()
verify(mark).invoke("desync2")
verify(particle).onResync()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun errors_onFirstStart_firstInstantiation() = runTest {
whenever(particle.onFirstStart()).thenThrow(RuntimeException("boom"))
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
verify(particle, only()).onFirstStart()
assertThat(context.particleState).isEqualTo(Failed_NeverStarted)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_onStart_secondInstantiation() = runTest {
whenever(particle.onStart()).thenThrow(RuntimeException("boom"))
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
with(inOrder(particle)) {
verify(particle).onFirstStart()
verify(particle).onStart()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_onReady_runParticle() = runTest {
whenever(particle.onReady()).thenThrow(RuntimeException("boom"))
context.initParticle(scheduler)
val deferred = context.runParticleAsync(scheduler)
assertFailsWith<RuntimeException> {
deferred.await()
}
with(inOrder(particle)) {
verify(particle).onFirstStart()
verify(particle).onStart()
verify(particle).onReady()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_storageEventTriggered() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val error = RuntimeException("boom")
context.particleState = Running
whenever(particle.onUpdate()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.UPDATE, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
context.particleState = Running
whenever(particle.onDesync()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.DESYNC, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
context.particleState = Desynced
whenever(particle.onResync()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.RESYNC, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
}
@Test
fun errors_onShutdown() = runTest {
whenever(particle.onShutdown()).thenThrow(RuntimeException("boom"))
context.initParticle(scheduler)
context.runParticleAsync(scheduler).await()
// stopParticle doesn't throw but still marks the particle as failed
context.stopParticle(scheduler)
with(inOrder(particle, handles)) {
verify(particle).onFirstStart()
verify(particle).onStart()
verify(particle).onReady()
verify(particle).handles
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_crashLoopingParticle() = runTest {
whenever(particle.onStart()).thenThrow(RuntimeException("boom"))
for (i in 1..MAX_CONSECUTIVE_FAILURES) {
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
assertThat(context.consecutiveFailureCount).isEqualTo(i)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
assertThat(context.particleState).isEqualTo(MaxFailed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun copyWith() {
val originalParticle = mock<Particle>()
val planParticle = Plan.Particle("PlanParticle", "location", emptyMap())
val newParticle = mock<Particle>()
val originalContext = ParticleContext(
particle = originalParticle,
planParticle = planParticle,
particleState = Running,
consecutiveFailureCount = 0
)
val copiedContext = originalContext.copyWith(newParticle)
assertThat(copiedContext.particle).isSameInstanceAs(newParticle)
assertThat(copiedContext.planParticle).isSameInstanceAs(planParticle)
assertThat(copiedContext.particleState).isEqualTo(Running)
assertThat(copiedContext.consecutiveFailureCount).isEqualTo(0)
}
@Test
fun toString_rendersImportantPieces() {
assertThat(context.toString()).contains("particle=")
assertThat(context.toString()).contains("particleState=")
assertThat(context.toString()).contains("consecutiveFailureCount=")
assertThat(context.toString()).contains("awaitingReady=")
}
@Test
fun registerHandle_readWrite_notifiesOnFirstReady() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.READY)
capturedRegistration(StorageEvent.READY)
// Only one of the READY events should make it to the particle.
verify(particle).onReady()
}
@Test
fun registerHandle_readWrite_notifiesOnFirstDesync() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.DESYNC)
capturedRegistration(StorageEvent.DESYNC)
// Only one of the DESYNC events should make it to the particle.
verify(particle).onDesync()
}
@Test
fun registerHandle_readWrite_notifiesOnAnyResync() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.RESYNC)
capturedRegistration(StorageEvent.RESYNC)
// Any resync event should make it through.
verify(particle, times(2)).onResync()
}
@Test
fun registerHandle_writeOnly_onlyNotifiesOnReady() = runTest {
val handle = mockHandle(HandleMode.Write)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.READY)
capturedRegistration(StorageEvent.DESYNC)
capturedRegistration(StorageEvent.RESYNC)
capturedRegistration(StorageEvent.UPDATE)
// Only the onReady event should make it through.
verify(particle).onReady()
verify(particle, never()).onDesync()
verify(particle, never()).onResync()
verify(particle, never()).onUpdate()
}
@Test
fun initParticle_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $FirstStart")
}
@Test
fun initParticle_whenWaiting_throws() = runTest {
val context = createParticleContext(particleState = Waiting)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Waiting")
}
@Test
fun initParticle_whenRunning_throws() = runTest {
val context = createParticleContext(particleState = Running)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Running")
}
@Test
fun initParticle_whenDesynced_throws() = runTest {
val context = createParticleContext(particleState = Desynced)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Desynced")
}
@Test
fun initParticle_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $MaxFailed")
}
@Test
fun notify_whenInstantiated_throws() = runTest {
val context = createParticleContext(particleState = Instantiated)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Instantiated")
}
@Test
fun notify_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $FirstStart")
}
@Test
fun notify_whenStopped_throws() = runTest {
val context = createParticleContext(particleState = Stopped)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Stopped")
}
@Test
fun notify_whenFailed_throws() = runTest {
val context = createParticleContext(particleState = Failed)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Failed")
}
@Test
fun notify_whenFailedNeverStarted_throws() = runTest {
val context = createParticleContext(particleState = Failed_NeverStarted)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Failed_NeverStarted")
}
@Test
fun notify_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $MaxFailed")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenRunningAndAwaitingReadyFromAHandle_throws() = runTest {
val context = createParticleContext(particleState = Running)
context.registerHandle(mockHandle(HandleMode.ReadWrite))
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains(
"runParticleAsync called on an already running particle; awaitingReady should be empty " +
"but still has 1 handles"
)
}
@Test
fun runParticleAsync_whenRunningAndHandlesReady_returnsCompletedDeferred() = runTest {
val context = createParticleContext(particleState = Running)
val actualDeferred = context.runParticleAsync(scheduler)
assertThat(actualDeferred.isCompleted).isTrue()
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_calledMoreThanOnceWhenWaiting_throws() = runTest {
val context = createParticleContext(particleState = Waiting)
context.registerHandle(mockHandle(HandleMode.ReadWrite))
// First call should be okay.
context.runParticleAsync(scheduler)
// Second call should fail.
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync called more than once on a waiting particle")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenInstantiated_throws() = runTest {
val context = createParticleContext(particleState = Instantiated)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Instantiated")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $FirstStart")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenDesynced_throws() = runTest {
val context = createParticleContext(particleState = Desynced)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Desynced")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenStopped_throws() = runTest {
val context = createParticleContext(particleState = Stopped)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Stopped")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFailed_throws() = runTest {
val context = createParticleContext(particleState = Failed)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Failed")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFailedNeverStarted_throws() = runTest {
val context = createParticleContext(particleState = Failed_NeverStarted)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Failed_NeverStarted")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $MaxFailed")
}
private fun mockHandle(handleMode: HandleMode) =
mock<Handle> { on { mode }.thenReturn(handleMode) }
private fun createParticleContext(
particle: Particle = this.particle,
planParticle: Plan.Particle = Plan.Particle("name", "location", mapOf()),
particleState: ParticleState = Instantiated
): ParticleContext = ParticleContext(particle, planParticle, particleState)
}
| bsd-3-clause | ea12a149a21073b54247d83ee394a754 | 34.371179 | 100 | 0.740864 | 4.803321 | false | true | false | false |
SourceUtils/hl2-toolkit | src/main/kotlin/com/timepath/hl2/swing/VBFCanvas.kt | 1 | 5562 | package com.timepath.hl2.swing
import com.timepath.Logger
import com.timepath.hl2.io.font.VBF
import com.timepath.hl2.io.image.VTF
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.awt.event.MouseMotionListener
import java.io.IOException
import java.util.LinkedList
import java.util.logging.Level
import javax.swing.JPanel
import javax.swing.SwingUtilities
public class VBFCanvas
/**
* Creates new form VBFTest
*/
: JPanel(), MouseListener, MouseMotionListener {
private var img: Image? = null
private var last: Point? = null
var selected: MutableList<VBF.BitmapGlyph> = LinkedList()
private var vbf: VBF? = null
private var vtf: VTF? = null
init {
addMouseListener(this)
addMouseMotionListener(this)
}
public fun setVBF(vbf: VBF) {
this.vbf = vbf
revalidate()
}
public fun setVTF(t: VTF) {
vtf = t
vbf!!.width = vtf!!.width.toShort()
vbf!!.height = vtf!!.height.toShort()
repaint()
}
override fun mouseClicked(e: MouseEvent) {
}
override fun mousePressed(e: MouseEvent) {
last = e.getPoint()
if (!SwingUtilities.isLeftMouseButton(e)) {
return
}
val old = LinkedList(selected)
val clicked = get(e.getPoint())
for (g in clicked) {
if (g in selected) {
return
}
}
if (e.isControlDown()) {
selected.addAll(clicked)
} else {
selected = clicked
}
for (g in old) {
repaint(g.bounds)
}
for (g in selected) {
repaint(g.bounds)
}
}
fun get(p: Point): MutableList<VBF.BitmapGlyph> {
val intersected = LinkedList<VBF.BitmapGlyph>()
vbf?.let {
for (g in it.glyphs) {
if (p in g.bounds) {
intersected.add(g)
}
}
}
return intersected
}
override fun mouseReleased(e: MouseEvent) {
}
override fun mouseEntered(e: MouseEvent) {
}
override fun mouseExited(e: MouseEvent) {
}
override fun mouseDragged(e: MouseEvent) {
val p = e.getPoint()
last?.let {
e.translatePoint(-it.x, -it.y)
}
for (sel in selected) {
if (SwingUtilities.isRightMouseButton(e)) {
sel.bounds.width += e.getPoint().x
sel.bounds.height += e.getPoint().y
} else {
sel.bounds.x += e.getPoint().x
sel.bounds.y += e.getPoint().y
}
}
last = p
repaint()
}
override fun mouseMoved(e: MouseEvent) {
}
public fun select(g: VBF.BitmapGlyph?) {
selected.clear()
g?.let { g ->
selected.add(g)
repaint(g.bounds)
}
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setComposite(acNormal)
g2.setColor(Color.BLACK)
g2.fillRect(0, 0, getWidth(), getHeight())
if ((img == null) && (vtf != null)) {
try {
img = vtf!!.getImage(0)
} catch (ex: IOException) {
LOG.log(Level.SEVERE, { null }, ex)
}
}
vbf?.let {
g2.setColor(Color.GRAY)
g2.fillRect(0, 0, it.width.toInt(), it.height.toInt())
}
img?.let {
g2.drawImage(it, 0, 0, this)
}
vbf?.let {
for (glyph in it.glyphs) {
if (glyph == null) {
continue
}
val bounds = glyph.bounds
if ((bounds == null) || bounds.isEmpty()) {
continue
}
g2.setComposite(acNormal)
g2.setColor(Color.GREEN)
g2.drawRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1)
if (glyph in selected) {
g2.setComposite(acSelected)
g2.fillRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1)
}
// TODO: Negative font folor
// Map<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
// map.put(TextAttribute.SWAP_COLORS, TextAttribute.SWAP_COLORS_ON);
// map.put(TextAttribute.FOREGROUND, Color.BLACK);
// map.put(TextAttribute.BACKGROUND, Color.TRANSLUCENT);
// Font f = this.getFont().deriveFont(map);
// g.setFont(f);
// g.setXORMode(Color.WHITE);
g2.setComposite(acText)
g2.setColor(Color.GREEN)
g2.drawString(Integer.toString(glyph.index.toInt()), bounds.x + 1, (bounds.y + bounds.height) - 1)
}
}
}
override fun getPreferredSize() = vbf?.let {
Dimension(it.width.toInt(), it.height.toInt())
} ?: Dimension(128, 128)
companion object {
private val LOG = Logger()
private val serialVersionUID = 1
private val acNormal = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)
private val acSelected = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)
private val acText = AlphaComposite.getInstance(AlphaComposite.SRC_OVER)
}
}
| artistic-2.0 | 3479521ae93e501905bbd7827c30c6a2 | 29.064865 | 114 | 0.519777 | 4.268611 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/onboarding/BloggingPromptsOnboardingViewModel.kt | 1 | 5308 | package org.wordpress.android.ui.bloggingprompts.onboarding
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.firstOrNull
import org.wordpress.android.R
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DismissDialog
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DoNothing
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenEditor
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenRemindersIntro
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenSitePicker
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.INFORMATION
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.ONBOARDING
import org.wordpress.android.ui.bloggingprompts.onboarding.usecase.GetIsFirstBloggingPromptsOnboardingUseCase
import org.wordpress.android.ui.bloggingprompts.onboarding.usecase.SaveFirstBloggingPromptsOnboardingUseCase
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import java.util.Date
import javax.inject.Inject
import javax.inject.Named
class BloggingPromptsOnboardingViewModel @Inject constructor(
private val siteStore: SiteStore,
private val uiStateMapper: BloggingPromptsOnboardingUiStateMapper,
private val selectedSiteRepository: SelectedSiteRepository,
private val bloggingPromptsStore: BloggingPromptsStore,
private val analyticsTracker: BloggingPromptsOnboardingAnalyticsTracker,
@Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher,
private val getIsFirstBloggingPromptsOnboardingUseCase: GetIsFirstBloggingPromptsOnboardingUseCase,
private val saveFirstBloggingPromptsOnboardingUseCase: SaveFirstBloggingPromptsOnboardingUseCase
) : ScopedViewModel(bgDispatcher) {
private val _uiState = MutableLiveData<BloggingPromptsOnboardingUiState>()
val uiState: LiveData<BloggingPromptsOnboardingUiState> = _uiState
private val _action = MutableLiveData<BloggingPromptsOnboardingAction>()
val action: LiveData<BloggingPromptsOnboardingAction> = _action
private val _snackBarMessage = MutableLiveData<Event<SnackbarMessageHolder>>()
val snackBarMessage = _snackBarMessage as LiveData<Event<SnackbarMessageHolder>>
private lateinit var dialogType: DialogType
private var hasTrackedScreenShown = false
private var isFirstBloggingPromptsOnboarding = false
fun start(type: DialogType) {
if (!hasTrackedScreenShown) {
hasTrackedScreenShown = true
analyticsTracker.trackScreenShown()
}
if (type == ONBOARDING) {
isFirstBloggingPromptsOnboarding = getIsFirstBloggingPromptsOnboardingUseCase.execute()
saveFirstBloggingPromptsOnboardingUseCase.execute(isFirstTime = false)
}
dialogType = type
_uiState.value = uiStateMapper.mapReady(dialogType, ::onPrimaryButtonClick, ::onSecondaryButtonClick)
}
fun onSiteSelected(selectedSiteLocalId: Int) {
_action.value = OpenRemindersIntro(selectedSiteLocalId)
}
private fun onPrimaryButtonClick() = launch {
val action = when (dialogType) {
ONBOARDING -> {
analyticsTracker.trackTryItNowClicked()
val site = selectedSiteRepository.getSelectedSite()
val bloggingPrompt = bloggingPromptsStore.getPromptForDate(site!!, Date()).firstOrNull()?.model
if (bloggingPrompt == null) {
_snackBarMessage.postValue(
Event(
SnackbarMessageHolder(
UiStringRes(R.string.blogging_prompts_onboarding_prompts_loading)
)
)
)
DoNothing
} else {
OpenEditor(bloggingPrompt.id)
}
}
INFORMATION -> {
analyticsTracker.trackGotItClicked()
DismissDialog
}
}
_action.postValue(action)
}
private fun onSecondaryButtonClick() {
analyticsTracker.trackRemindMeClicked()
if (siteStore.sitesCount > 1 && isFirstBloggingPromptsOnboarding) {
_action.value = OpenSitePicker(selectedSiteRepository.getSelectedSite())
} else {
siteStore.sites.firstOrNull()?.let {
_action.value = OpenRemindersIntro(it.id)
}
}
}
}
| gpl-2.0 | e087a66c91edf796c5b4558d8612f2cb | 48.148148 | 121 | 0.740957 | 5.878184 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/ltm/LTMBackwardHelper.kt | 1 | 5154 | /* 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.ltm
import com.kotlinnlp.simplednn.core.arrays.getInputErrors
import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The helper which executes the backward on a [layer].
*
* @property layer the [LTMLayer] in which the backward is executed
*/
internal class LTMBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>(
override val layer: LTMLayer<InputNDArrayType>
) : BackwardHelper<InputNDArrayType>(layer) {
/**
* Executes the backward calculating the errors of the parameters and eventually of the input through the SGD
* algorithm, starting from the preset errors of the output array.
*
* @param propagateToInput whether to propagate the errors to the input array
*/
override fun execBackward(propagateToInput: Boolean) {
val prevStateLayer = this.layer.layersWindow.getPrevState() as? LTMLayer
val nextStateLayer = this.layer.layersWindow.getNextState() as? LTMLayer
if (nextStateLayer != null) this.addOutputRecurrentGradients(nextStateLayer)
this.assignCellGradients(nextStateLayer)
this.assignGatesGradients()
this.assignParamsGradients()
// Note: the previous layer will use the input gradients of this layer because they are equal to the recurrent
// error of the output.
if (propagateToInput || prevStateLayer != null) {
this.assignInputGradients()
}
}
/**
* @param nextStateLayer the layer in the next state
*/
private fun assignCellGradients(nextStateLayer: LTMLayer<*>?) {
val l3: DenseNDArray = this.layer.inputGate3.values
val gy: DenseNDArray = this.layer.outputArray.errors
val cellDeriv: DenseNDArray = this.layer.cell.calculateActivationDeriv()
this.layer.cell.assignErrorsByProd(gy, l3)
if (nextStateLayer != null)
this.layer.cell.errors.assignSum(nextStateLayer.c.errors)
this.layer.cell.errors.assignProd(cellDeriv)
val wCell: DenseNDArray = this.layer.params.cell.weights.values
this.layer.c.assignErrors(this.layer.cell.getInputErrors(wCell))
}
/**
* Assign the gradients of the gates.
*/
private fun assignGatesGradients() {
val gy: DenseNDArray = this.layer.outputArray.errors
val gC: DenseNDArray = this.layer.c.errors
val l1: DenseNDArray = this.layer.inputGate1.values
val l2: DenseNDArray = this.layer.inputGate2.values
val cell: DenseNDArray = this.layer.cell.values
val l1Deriv: DenseNDArray = this.layer.inputGate1.calculateActivationDeriv()
val l2Deriv: DenseNDArray = this.layer.inputGate2.calculateActivationDeriv()
val l3Deriv: DenseNDArray = this.layer.inputGate3.calculateActivationDeriv()
this.layer.inputGate1.assignErrorsByProd(gC, l1Deriv.assignProd(l2))
this.layer.inputGate2.assignErrorsByProd(gC, l2Deriv.assignProd(l1))
this.layer.inputGate3.assignErrorsByProd(gy, l3Deriv.assignProd(cell))
}
/**
* Assign the gradients of the parameters.
*/
private fun assignParamsGradients() {
this.layer.inputGate1.assignParamsGradients(
gw = this.layer.params.inputGate1.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.inputGate2.assignParamsGradients(
gw = this.layer.params.inputGate2.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.inputGate3.assignParamsGradients(
gw = this.layer.params.inputGate3.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.cell.assignParamsGradients(
gw = this.layer.params.cell.weights.errors.values,
gb = null,
x = this.layer.c.values)
}
/**
* Add output gradients coming from the next state.
*
* @param nextStateLayer the layer structure in the next state
*/
private fun addOutputRecurrentGradients(nextStateLayer: LTMLayer<*>) {
val gy: DenseNDArray = this.layer.outputArray.errors
// Note: the output recurrent errors are equal to the input errors of the next state
val gyRec: DenseNDArray = nextStateLayer.inputArray.errors
gy.assignSum(gyRec)
}
/**
* Assign the gradients of the input.
*/
private fun assignInputGradients() {
val w1: DenseNDArray = this.layer.params.inputGate1.weights.values
val w2: DenseNDArray = this.layer.params.inputGate2.weights.values
val w3: DenseNDArray = this.layer.params.inputGate3.weights.values
val gL1: DenseNDArray = this.layer.inputGate1.getInputErrors(w1)
val gL2: DenseNDArray = this.layer.inputGate2.getInputErrors(w2)
val gL3: DenseNDArray = this.layer.inputGate3.getInputErrors(w3)
this.layer.inputArray.assignErrors(gL1.assignSum(gL2).assignSum(gL3))
}
}
| mpl-2.0 | 7a0dc5f7408129a509ca81c7d7510e19 | 34.544828 | 114 | 0.727202 | 4.18684 | false | false | false | false |
eugeis/ee-elastic | ee-elastic/src/main/kotlin/ee/es/Exporter.kt | 1 | 2652 | package ee.es
import org.elasticsearch.client.Client
import org.elasticsearch.cluster.ClusterModule
import org.elasticsearch.common.unit.TimeValue
import org.elasticsearch.common.xcontent.NamedXContentRegistry
import org.elasticsearch.common.xcontent.XContentFactory
import org.elasticsearch.common.xcontent.XContentType
import org.elasticsearch.search.builder.SearchSourceBuilder
import java.nio.file.Path
open class Exporter(val client: Client) {
fun export(index: Array<String>, searchSource: String, targetPath: Path, fields: Array<String>,
separator: String = " ") {
val scroll = TimeValue(60000)
var scrollResp =
client.prepareSearch(*index).setSource(searchSourceBuilder(searchSource)).setScroll(scroll).execute()
.actionGet()
targetPath.toFile().bufferedWriter().use { out ->
println("Export started to $targetPath, please wait...")
while (scrollResp.hits.hits.isNotEmpty()) {
scrollResp.hits.forEach { hit ->
val s = hit.sourceAsMap
fields.forEach { field ->
if (s.containsKey(field)) {
out.write(s[field].toString().removeSuffix("\n").removeSuffix("\r"))
} else {
out.write(" ")
}
out.write(separator)
}
out.write("\n")
}
scrollResp = client.prepareSearchScroll(scrollResp.scrollId).setScroll(scroll).execute().actionGet()
}
println("Export done to $targetPath.")
}
client.close()
}
protected fun searchSourceBuilder(searchSource: String): SearchSourceBuilder {
/*
// from Map to XContent
XContentBuilder builder = ... // see above
// from XContent to JSON
String json = new String(builder.getBytes(), "UTF-8");
// use JSON to populate SearchSourceBuilder
JsonXContent parser = createParser(JsonXContent.jsonXContent, json));
sourceBuilder.parseXContent(new QueryParseContext(parser));
*/
//val parser = XContentFactory.xContent(XContentType.JSON).createParser(namedXContentRegistry(), searchSource)
val searchSourceBuilder = SearchSourceBuilder.fromXContent(null) //QueryParseContext(parser)
return searchSourceBuilder
}
private fun namedXContentRegistry(): NamedXContentRegistry {
//return NamedXContentRegistry(NetworkModule.getNamedXContents())
return NamedXContentRegistry(ClusterModule.getNamedXWriteables())
}
} | apache-2.0 | 3366677aed80523c11c5863889aa8705 | 40.453125 | 118 | 0.638763 | 5.041825 | false | false | false | false |
LittleLightCz/SheepsGoHome | core/src/com/sheepsgohome/screens/GameplayClassicModeScreen.kt | 1 | 9784 | package com.sheepsgohome.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Gdx.gl
import com.badlogic.gdx.Gdx.graphics
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.FPSLogger
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad
import com.badlogic.gdx.utils.viewport.StretchViewport
import com.sheepsgohome.dataholders.WolvesData
import com.sheepsgohome.enums.GameResult
import com.sheepsgohome.enums.GameState.*
import com.sheepsgohome.gameobjects.*
import com.sheepsgohome.gdx.screens.switchScreen
import com.sheepsgohome.positioning.BodyPositioner
import com.sheepsgohome.enums.GameResult.*
import com.sheepsgohome.shared.GameData.CAMERA_HEIGHT
import com.sheepsgohome.shared.GameData.CAMERA_WIDTH
import com.sheepsgohome.shared.GameData.LEVEL
import com.sheepsgohome.shared.GameData.SOUND_ENABLED
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_LEFT
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_NONE
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_RIGHT
import com.sheepsgohome.shared.GameData.loc
import com.sheepsgohome.shared.GameMusic.ambient
import com.sheepsgohome.shared.GameSkins.skin
import java.util.*
class GameplayClassicModeScreen : Screen, ContactListener {
private val fpsLogger by lazy { FPSLogger() }
//Box2D Physics
private val debugRenderer = Box2DDebugRenderer()
private val world = World(Vector2(0f, 0f), true)
private val multiplier = 1f
private val camera: OrthographicCamera = OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT)
private val batch = SpriteBatch()
private var gameState = RUNNING
private val touchpadEnabled = VIRTUAL_JOYSTICK != VIRTUAL_JOYSTICK_NONE
private val touchpad by lazy { Touchpad(0f, skin).apply {
val touchPadSize = 30f
when (VIRTUAL_JOYSTICK) {
VIRTUAL_JOYSTICK_RIGHT -> setBounds(CAMERA_WIDTH - touchPadSize, 0f, touchPadSize, touchPadSize)
VIRTUAL_JOYSTICK_LEFT -> setBounds(0f, 0f, touchPadSize, touchPadSize)
}
addAction(Actions.alpha(0.5f))
}}
private val stage = Stage(StretchViewport(CAMERA_WIDTH * multiplier, CAMERA_HEIGHT * multiplier))
private val levelLabel = Label(loc.format("level", LEVEL), skin, "levelTitle").apply {
setFontScale((CAMERA_WIDTH * multiplier - 40) / prefWidth)
addAction(Actions.sequence(
Actions.alpha(1f),
Actions.fadeOut(3f)
))
}
private val grass = Grass()
private val home = Home(world)
private val sheep = Sheep(world)
private val walls = listOf(
TopWall(world),
BottomWall(world),
LeftWall(world),
RightWall(world)
)
private val wolves: List<Wolf>
init {
Box2D.init()
world.setContactListener(this)
val data = getWolvesData(LEVEL)
wolves = mutableListOf(
List(data.wildWolvesCount) { WildWolf(world) },
List(data.hungryWolvesCount) { HungryWolf(world, sheep) },
List(data.alphaWolvesCount) { AlphaWolf(world, sheep) }
).flatten()
Collections.shuffle(wolves)
}
override fun show() {
//catch menu and back buttons
Gdx.input.isCatchBackKey = true
Gdx.input.setCatchMenuKey(true)
//Ambient
if (SOUND_ENABLED && !ambient.isPlaying) {
ambient.play()
}
val table = Table().apply {
add(levelLabel)
setFillParent(true)
}
stage.addActor(table)
if (touchpadEnabled) {
stage.addActor(touchpad)
}
Gdx.input.inputProcessor = stage
kickOffWildWolves()
}
override fun render(delta: Float) {
gl.glClearColor(0.9f, 0.9f, 0.9f, 1f)
gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
when (gameState) {
RUNNING -> renderGameScene()
GAME_OVER_BY_WILD_WOLF -> gameOver(SHEEP_EATEN_BY_WILD_WOLF)
GAME_OVER_BY_HUNGRY_WOLF -> gameOver(SHEEP_EATEN_BY_HUNGRY_WOLF)
GAME_OVER_BY_ALPHA_WOLF -> gameOver(SHEEP_EATEN_BY_ALPHA_WOLF)
NEXT_LEVEL -> nextLevel()
}
// fpsLogger.log();
}
private fun renderGameScene() {
//positioning
sheep.updateSprite()
//input
if (touchpadEnabled) {
if (touchpad.isTouched) {
handleTouch()
} else {
sheep.nullifyVelocity()
}
} else {
if (Gdx.input.isTouched) {
handleTouch(Gdx.input.x, Gdx.input.y)
} else {
sheep.nullifyVelocity()
}
}
//drawing
batch.projectionMatrix = camera.combined
batch.begin()
grass.draw(batch)
sheep.draw(batch)
//draw home (top center)
home.draw(batch)
//draw wolves
for (wolf in wolves) {
when (wolf) {
is AlphaWolf -> {
wolf.updateVelocity()
wolf.updateSprite()
}
is HungryWolf -> {
wolf.calculateSteeringBehaviour()
wolf.updateSprite()
}
else -> wolf.updateSprite()
}
wolf.draw(batch)
}
batch.end()
// fpsLogger.log()
// debugRenderer.render(world, camera.combined);
world.step(graphics.deltaTime, 6, 2)
stage.act()
stage.draw()
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
//world boundaries
walls.forEach { it.setDefaultPosition() }
//sheep
sheep.positionBottomCenter()
//home
home.positionTopCenter()
//wolves positioning
val wolfBodies = wolves.map { it.body }
BodyPositioner().alignInCenteredGrid(
wolfBodies,
maxBodiesInRow = 13,
columnSize = WildWolf.WILD_WOLF_SIZE + 0.5f,
verticalOffset = (CAMERA_HEIGHT / 2) - Home.HOME_SIZE - 5
)
}
override fun pause() {}
override fun resume() {}
override fun hide() {
//stop ambient
if (ambient.isPlaying) {
ambient.pause()
}
//release menu and back buttons
Gdx.input.isCatchBackKey = false
Gdx.input.setCatchMenuKey(false)
dispose()
}
override fun dispose() {
grass.dispose()
home.dispose()
sheep.dispose()
wolves.forEach { it.dispose() }
batch.dispose()
world.dispose()
stage.dispose()
}
private fun getWolvesData(level: Int): WolvesData {
val data = WolvesData()
data.wildWolvesCount = ((level - 1) % 5 + 1) * 5
if (level < 6) {
data.hungryWolvesCount = 0
} else {
data.hungryWolvesCount = (level - 1 - 5) / 5 % 4 + 1
}
if (level < 26) {
data.alphaWolvesCount = 0
} else {
data.alphaWolvesCount = (level - 1 - 5) / 20
}
return data
}
//Touchpad touch
private fun handleTouch() {
val vec = Vector2(touchpad.knobPercentX, touchpad.knobPercentY).nor()
sheep.updateVelocity(vec)
}
//Finger touch
private fun handleTouch(x: Int, y: Int) {
var targetx = x.toFloat()
var targety = (Gdx.graphics.height - y).toFloat()
targetx = targetx / Gdx.graphics.width.toFloat() * CAMERA_WIDTH - CAMERA_WIDTH / 2f
targety = targety / Gdx.graphics.height.toFloat() * CAMERA_HEIGHT - CAMERA_HEIGHT / 2f
val pos = sheep.steerableBody.position
targetx -= pos.x
targety -= pos.y
val divider = Math.max(Math.abs(targetx), Math.abs(targety))
targetx /= divider
targety /= divider
sheep.updateVelocity(targetx, targety)
}
private fun kickOffWildWolves() {
wolves.filterIsInstance<WildWolf>().forEach { it.setRandomMovement() }
}
private fun handleContact(bodyA: Body, bodyB: Body) {
val objA = bodyA.userData
val objB = bodyB.userData
when (objA) {
is WildWolf -> objA.setRandomMovement()
is Sheep -> when (objB) {
is WildWolf -> gameState = GAME_OVER_BY_WILD_WOLF
is HungryWolf -> gameState = GAME_OVER_BY_HUNGRY_WOLF
is AlphaWolf -> gameState = GAME_OVER_BY_ALPHA_WOLF
is Home -> gameState = NEXT_LEVEL
}
}
}
private fun gameOver(result: GameResult) = switchScreen(ClassicModeResultScreen(result))
private fun nextLevel() = gameOver(SHEEP_SUCCEEDED)
/**
* Contact handling
*/
override fun beginContact(contact: Contact) {
val bodyA = contact.fixtureA.body
val bodyB = contact.fixtureB.body
// Both combinations - reducing quadratic complexity to linear
handleContact(bodyA, bodyB)
handleContact(bodyB, bodyA)
}
override fun endContact(contact: Contact) {}
override fun preSolve(contact: Contact, oldManifold: Manifold) {}
override fun postSolve(contact: Contact, impulse: ContactImpulse) {}
}
| gpl-3.0 | dbbecf7e2e0966796ab1f88c1a962436 | 27.195965 | 108 | 0.613655 | 4.181197 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt | 2 | 31458 | // 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.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import org.jdom.Element
import java.util.*
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 {
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 = HashMap<String, MutableList<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
}
}
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()
for (entry in actionIdToShortcuts.entries) {
otherKeymap.actionIdToShortcuts[entry.key] = ContainerUtil.copyList(entry.value)
}
// 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 list = actionIdToShortcuts.getOrPut(actionId) {
val result = SmartList<Shortcut>()
val boundShortcuts = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
if (boundShortcuts != null) {
result.addAll(boundShortcuts)
}
else {
parent?.getMutableShortcutList(actionId)?.mapTo(result) { convertShortcut(it) }
}
result
}
if (!list.contains(shortcut)) {
list.add(shortcut)
}
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
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 list = actionIdToShortcuts[actionId]
if (list == null) {
val inherited = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited != null) {
var newShortcuts: MutableList<Shortcut>? = null
for (itemIndex in 0..inherited.lastIndex) {
val item = inherited[itemIndex]
if (toDelete == item) {
if (newShortcuts == null) {
newShortcuts = SmartList()
for (notAddedItemIndex in 0 until itemIndex) {
newShortcuts.add(inherited[notAddedItemIndex])
}
}
}
else newShortcuts?.add(item)
}
newShortcuts?.let {
actionIdToShortcuts.put(actionId, it)
}
}
}
else {
val index = list.indexOf(toDelete)
if (index >= 0) {
if (parent == null) {
if (list.size == 1) {
actionIdToShortcuts.remove(actionId)
}
else {
list.removeAt(index)
}
}
else {
list.removeAt(index)
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun MutableList<Shortcut>.areShortcutsEqualToParent(actionId: String) =
parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getMutableShortcutList(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)
}
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) || actionIdToShortcuts.containsKey(keymapManager.getActionBinding(id))) {
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> =
getMutableShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getMutableShortcutList(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?.getMutableShortcutList(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>()
// creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts)
actionIdToShortcuts[id] = shortcuts
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")
}
}
}
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 getMutableShortcutList(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 | 904209501111dc5bf155b27fd057185b | 39.643411 | 158 | 0.684119 | 5.248248 | false | false | false | false |
ChristopherGittner/OSMBugs | app/src/main/java/org/gittner/osmbugs/mapdust/MapdustAddErrorDialog.kt | 1 | 2425 | package org.gittner.osmbugs.mapdust
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.addTextChangedListener
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.gittner.osmbugs.R
import org.gittner.osmbugs.databinding.DialogAddMapdustErrorBinding
import org.gittner.osmbugs.ui.ErrorViewModel
import org.osmdroid.api.IGeoPoint
class MapdustAddErrorDialog(context: Context, viewModel: ErrorViewModel, mapCenter: IGeoPoint, successCb: SuccessCb) : AlertDialog(context) {
private val mViewModel = viewModel
private val mMapCenter = mapCenter
private val mSuccessCb = successCb
override fun onCreate(savedInstanceState: Bundle?) {
setTitle(R.string.dialog_add_mapdust_error_title)
val v = layoutInflater.inflate(R.layout.dialog_add_mapdust_error, null)
setView(v)
val binding = DialogAddMapdustErrorBinding.bind(v)
binding.apply {
spinner.adapter = MapdustTypeAdapter(context)
edtxtComment.addTextChangedListener {
imgSave.visibility = if (it!!.isEmpty()) View.GONE else View.VISIBLE
}
imgSave.setOnClickListener {
MainScope().launch {
progressbarSave.visibility = View.VISIBLE
imgSave.visibility = View.GONE
edtxtComment.isEnabled = false
try {
mViewModel.addMapdustError(
mMapCenter,
spinner.selectedItem as MapdustError.ERROR_TYPE,
edtxtComment.text.toString()
)
dismiss()
mSuccessCb.onSuccess()
} catch (err: Exception) {
Toast.makeText(context, context.getString(R.string.failed_to_add_error).format(err.message), Toast.LENGTH_LONG).show()
} finally {
progressbarSave.visibility = View.GONE
imgSave.visibility = View.VISIBLE
edtxtComment.isEnabled = true
}
}
}
}
super.onCreate(savedInstanceState)
}
interface SuccessCb {
fun onSuccess()
}
} | mit | 2b35548ab49858607dff6ec598446da5 | 35.208955 | 142 | 0.60866 | 5.052083 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/util/HashUtils.kt | 1 | 3647 | package au.id.micolous.metrodroid.util
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.key.ClassicSectorKey
import au.id.micolous.metrodroid.multi.Log
object HashUtils {
private fun calculateCRCReversed(data: ImmutableByteArray, init: Int, table: IntArray) =
data.fold(init) { cur1, b -> (cur1 shr 8) xor table[(cur1 xor b.toInt()) and 0xff] }
private fun getCRCTableReversed(poly: Int) =
(0..255).map { v ->
(0..7).fold(v) { cur, _ ->
if ((cur and 1) != 0)
(cur shr 1) xor poly
else
(cur shr 1)
}
}.toIntArray()
private val CRC16_IBM_TABLE = getCRCTableReversed(0xa001)
fun calculateCRC16IBM(data: ImmutableByteArray, crc: Int = 0) =
calculateCRCReversed(data, crc, CRC16_IBM_TABLE)
/**
* Checks if a salted hash of a value is found in a group of expected hash values.
*
* This is only really useful for MIFARE Classic cards, where the only way to identify a
* particular transit card is to check the key against a known list. We don't want to ship
* any agency-specific keys with Metrodroid (no matter how well-known they are), so this
* obfuscates the keys.
*
* It is fairly straight forward to crack any MIFARE Classic card anyway, and this is only
* intended to be "on par" with the level of security on the cards themselves.
*
* This isn't useful for **all** cards, and should only be used as a last resort. Many transit
* cards implement key diversification on all sectors (ie: every sector of every card has a key
* that is unique to a single card), which renders this technique unusable.
*
* The hash is defined as:
*
* hash = lowercase(base16(md5(salt + key + salt)))
*
* @param key The key to test.
* @param salt The salt string to add to the key.
* @param expectedHashes Expected hash values that might be returned.
* @return The index of the hash that matched, or a number less than 0 if the value was not
* found, or there was some other error with the input.
*/
fun checkKeyHash(key: ImmutableByteArray, salt: String, vararg expectedHashes: String): Int {
// Validate input arguments.
if (expectedHashes.isEmpty()) {
return -1
}
val md5 = MD5Ctx()
md5.update(ImmutableByteArray.fromASCII(salt))
md5.update(key)
md5.update(ImmutableByteArray.fromASCII(salt))
val digest = md5.digest().toHexString()
Log.d(TAG, "Key digest: $digest")
return expectedHashes.indexOf(digest)
}
/**
* Checks a keyhash with a {@link ClassicSectorKey}.
*
* See {@link #checkKeyHash(ImmutableByteArray, String, String...)} for further information.
*
* @param key The key to check. If this is null, then this will always return a value less than
* 0 (ie: error).
*/
fun checkKeyHash(key: ClassicSectorKey?, salt: String, vararg expectedHashes: String): Int {
if (key == null)
return -1
return checkKeyHash(key.key, salt, *expectedHashes)
}
fun checkKeyHash(key: ClassicSector?, salt: String, vararg expectedHashes: String): Int {
if (key == null)
return -1
val a = checkKeyHash(key.keyA, salt, *expectedHashes)
if (a != -1)
return a
return checkKeyHash(key.keyB, salt, *expectedHashes)
}
private const val TAG = "HashUtils"
}
| gpl-3.0 | 4d0fbfa28fb7ac1f553385c444bf1cba | 38.215054 | 99 | 0.623252 | 4.153759 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/MediaSelectionNavigator.kt | 2 | 2102 | package org.thoughtcrime.securesms.mediasend.v2
import android.Manifest
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.util.navigation.safeNavigate
class MediaSelectionNavigator(
private val toCamera: Int = -1,
private val toGallery: Int = -1
) {
fun goToReview(navController: NavController) {
navController.popBackStack(R.id.mediaReviewFragment, false)
}
fun goToCamera(navController: NavController) {
if (toCamera == -1) return
navController.safeNavigate(toCamera)
}
fun goToGallery(navController: NavController) {
if (toGallery == -1) return
navController.safeNavigate(toGallery)
}
companion object {
fun Fragment.requestPermissionsForCamera(
onGranted: () -> Unit
) {
Permissions.with(this)
.request(Manifest.permission.CAMERA)
.ifNecessary()
.withRationaleDialog(getString(R.string.ConversationActivity_to_capture_photos_and_video_allow_signal_access_to_the_camera), R.drawable.ic_camera_24)
.withPermanentDenialDialog(getString(R.string.ConversationActivity_signal_needs_the_camera_permission_to_take_photos_or_video))
.onAllGranted(onGranted)
.onAnyDenied { Toast.makeText(requireContext(), R.string.ConversationActivity_signal_needs_camera_permissions_to_take_photos_or_video, Toast.LENGTH_LONG).show() }
.execute()
}
fun Fragment.requestPermissionsForGallery(
onGranted: () -> Unit
) {
Permissions.with(this)
.request(Manifest.permission.READ_EXTERNAL_STORAGE)
.ifNecessary()
.withPermanentDenialDialog(getString(R.string.AttachmentKeyboard_Signal_needs_permission_to_show_your_photos_and_videos))
.onAllGranted(onGranted)
.onAnyDenied { Toast.makeText(this.requireContext(), R.string.AttachmentKeyboard_Signal_needs_permission_to_show_your_photos_and_videos, Toast.LENGTH_LONG).show() }
.execute()
}
}
}
| gpl-3.0 | adc69db4cedddc4ccbba410a52888738 | 35.877193 | 172 | 0.73882 | 4.121569 | false | false | false | false |
MichaelRocks/grip | library/src/test/java/io/michaelrocks/grip/FileRegistryImplTest.kt | 1 | 5402 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.io.FileSource
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getObjectType
import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName
import io.michaelrocks.mockito.RETURNS_DEEP_STUBS
import io.michaelrocks.mockito.any
import io.michaelrocks.mockito.given
import io.michaelrocks.mockito.mock
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class FileRegistryImplTest {
@Test
fun containsFile() {
val source = mock<FileSource>()
val file = File("source1")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertTrue(registry.contains(file))
assertFalse(registry.contains(File("source2")))
}
@Test
fun containsType() {
val source = mock<FileSource>()
given(source.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
val file = File("source")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertTrue(registry.contains(getObjectTypeByInternalName("Type1")))
assertFalse(registry.contains(getObjectTypeByInternalName("Type2")))
}
@Test
fun classpath() {
val classpath = (1..1000).map { File("source$it") }
val factory = mock<FileSource.Factory>(RETURNS_DEEP_STUBS)
val registry = FileRegistryImpl(classpath, factory)
assertEquals(classpath.map { it.canonicalFile }, registry.classpath().toList())
}
@Test
fun readClass() {
val data = ByteArray(0)
val source = mock<FileSource>()
given(source.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
given(source.readFile("Type1.class")).thenReturn(data)
val file = File("source")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertSame(data, registry.readClass(getObjectTypeByInternalName("Type1")))
assertThrows<IllegalArgumentException> { registry.readClass(getObjectTypeByInternalName("Type2")) }
}
@Test
fun findTypesForFile() {
val source1 = mock<FileSource>()
given(source1.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
val source2 = mock<FileSource>()
val file1 = File("file1")
val file2 = File("file2")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file1.canonicalFile)).thenReturn(source1)
given(factory.createFileSource(file2.canonicalFile)).thenReturn(source2)
val registry = FileRegistryImpl(listOf(file1, file2), factory)
assertEquals(listOf(getObjectTypeByInternalName("Type1")), registry.findTypesForFile(file1).toList())
assertEquals(listOf<Type.Object>(), registry.findTypesForFile(file2).toList())
assertThrows<IllegalArgumentException> { registry.findTypesForFile(File("file3")) }
}
@Test
fun close() {
val factory = mock<FileSource.Factory>(RETURNS_DEEP_STUBS)
val registry = FileRegistryImpl(listOf(File("source")), factory)
registry.close()
assertThrows<IllegalStateException> { registry.contains(File("source")) }
assertThrows<IllegalStateException> { registry.contains(getObjectType<Any>()) }
assertThrows<IllegalStateException> { registry.classpath() }
assertThrows<IllegalStateException> { registry.readClass(getObjectType<Any>()) }
assertThrows<IllegalStateException> { registry.findTypesForFile(File("source")) }
registry.close()
}
private inline fun <reified T : Throwable> assertThrows(noinline body: () -> Any) {
assertThrows(T::class.java, body)
}
private fun <T : Throwable> assertThrows(exceptionClass: Class<T>, body: () -> Any) {
try {
body()
throw AssertionError("$exceptionClass expected but no exception was thrown")
} catch (exception: Throwable) {
if (exception.javaClass != exceptionClass) {
throw AssertionError("$exceptionClass expected but ${exception.javaClass} was thrown")
}
}
}
}
| apache-2.0 | 744df9e25577e86ca4e1b37bcab910b1 | 38.720588 | 105 | 0.727508 | 4.381184 | false | true | false | false |
mdanielwork/intellij-community | plugins/devkit/devkit-core/src/inspections/StatefulEpInspection2.kt | 4 | 3505 | // 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.idea.devkit.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.lang.jvm.DefaultJvmElementVisitor
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmField
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.types.JvmReferenceType
import com.intellij.lang.jvm.util.JvmInheritanceUtil.isInheritor
import com.intellij.lang.jvm.util.JvmUtil
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import org.jetbrains.idea.devkit.util.ExtensionCandidate
import org.jetbrains.idea.devkit.util.ExtensionLocator
class StatefulEpInspection2 : DevKitJvmInspection() {
override fun buildVisitor(project: Project, sink: HighlightSink, isOnTheFly: Boolean): DefaultJvmElementVisitor<Boolean?> = object : DefaultJvmElementVisitor<Boolean?> {
override fun visitField(field: JvmField): Boolean? {
val clazz = field.containingClass ?: return null
val fieldTypeClass = JvmUtil.resolveClass(field.type as? JvmReferenceType) ?: return null
val isQuickFix by lazy(LazyThreadSafetyMode.NONE) { isInheritor(clazz, localQuickFixFqn) }
val targets = findEpCandidates(project, clazz)
if (targets.isEmpty() && !isQuickFix) return null
if (isInheritor(fieldTypeClass, PsiElement::class.java.canonicalName)) {
sink.highlight(
"Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead${if (isQuickFix) "; also see LocalQuickFixOnPsiElement" else ""}"
)
return false
}
if (isInheritor(fieldTypeClass, PsiReference::class.java.canonicalName)) {
sink.highlight(message(PsiReference::class.java.simpleName, isQuickFix))
return false
}
if (!isProjectFieldAllowed(field, clazz, targets) && isInheritor(fieldTypeClass, Project::class.java.canonicalName)) {
sink.highlight(message(Project::class.java.simpleName, isQuickFix))
return false
}
return false
}
}
companion object {
private val localQuickFixFqn = LocalQuickFix::class.java.canonicalName
private val projectComponentFqn = ProjectComponent::class.java.canonicalName
private fun findEpCandidates(project: Project, clazz: JvmClass): Collection<ExtensionCandidate> {
val name = clazz.name ?: return emptyList()
return ExtensionLocator.byClass(project, clazz).findCandidates().filter { candidate ->
val forClass = candidate.pointer.element?.getAttributeValue("forClass")
forClass == null || !forClass.contains(name)
}
}
private fun isProjectFieldAllowed(field: JvmField, clazz: JvmClass, targets: Collection<ExtensionCandidate>): Boolean {
val finalField = field.hasModifier(JvmModifier.FINAL)
if (finalField) return true
val isProjectEP = targets.any { candidate ->
val name = candidate.pointer.element?.name
"projectService" == name || "projectConfigurable" == name
}
if (isProjectEP) return true
return isInheritor(clazz, projectComponentFqn)
}
private fun message(what: String, quickFix: Boolean): String {
val where = if (quickFix) "quick fix" else "extension"
return "Don't use $what as a field in $where"
}
}
}
| apache-2.0 | e0404d819de6ff4533baf6adff825d99 | 41.228916 | 171 | 0.738088 | 4.642384 | false | false | false | false |
pkleimann/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/StepTemplate.kt | 1 | 4750 | package org.livingdoc.engine.execution.examples.scenarios.matching
/**
* Represents a template specified by a fixture developer for scenario steps. Used for matching scenario
* steps to methods in a fixture. A valid `StepTemplate` consists of a sequence of fragments (text and variables).
* The sequence of fragments is never empty and does not contain two consecutive fragments of the same type.
*
* Variables can be quoted with optional `quotationCharacters` (e.g. single quotation marks). A matching step
* *must* contain exactly the same quotation characters. By default, no quotation characters are used.
*/
internal class StepTemplate(
val fragments: List<Fragment>,
val quotationCharacters: Set<Char>
) {
init {
assert(!fragments.isEmpty())
assertAlternatingSequenceOfFragments()
}
private fun assertAlternatingSequenceOfFragments() {
var wasTextFragment = fragments.first() !is Text
fragments.forEach {
assert(wasTextFragment xor (it is Text))
wasTextFragment = it is Text
}
}
/**
* Returns an `Alignment` of the template and the specified scenario step.
*/
fun alignWith(step: String, maxCostOfAlignment: Int = 20) = Alignment(this, step, maxCostOfAlignment)
override fun toString(): String = fragments.joinToString(separator = "") {
when (it) {
is Text -> it.content
is Variable -> "{${it.name}}"
}
}
companion object {
/**
* Reads a template for a scenario step description from a string. Optionally takes a set of quotation
* characters for variable separation.
*
* @return a valid `StepTemplate`
* @throws IllegalFormatException if the specified template string is malformed
*/
fun parse(templateAsString: String, quotationCharacters: Set<Char> = emptySet()) =
StepTemplate(parseString(templateAsString), quotationCharacters)
private fun parseString(templateAsString: String): List<Fragment> {
if (templateAsString.isEmpty()) {
throw IllegalFormatException("StepTemplates cannot be empty!")
}
return split(templateAsString).map { createFragment(it) }.toList()
}
private fun split(templateAsString: String): List<String> {
val tokens = mutableListOf<String>()
var lastIndex = 0
var isVariable = false
var isPreceededByVariable = false
for ((i, c) in templateAsString.withIndex()) {
if (c == '{' && !isEscaped(templateAsString, i)) {
if (isVariable) {
throw IllegalFormatException("Illegal opening curly brace at position $i!\nOffending string was: $templateAsString")
}
if (isPreceededByVariable) {
throw IllegalFormatException("Consecutive variables at position $i! StepTemplate must contain an intervening text fragment to keep them apart.\nOffending string was: $templateAsString")
}
isVariable = true
if (lastIndex < i) {
tokens.add(templateAsString.substring(lastIndex, i))
}
lastIndex = i
} else if (c == '}' && !isEscaped(templateAsString, i)) {
if (!isVariable) {
throw IllegalFormatException("Illegal closing curly brace at position $i!\nOffending string was: $templateAsString")
}
isPreceededByVariable = true
isVariable = false
tokens.add(templateAsString.substring(lastIndex, i + 1))
lastIndex = i + 1
} else {
isPreceededByVariable = false
}
}
if (lastIndex < templateAsString.length) {
tokens.add(templateAsString.substring(lastIndex))
}
return tokens
}
private fun isEscaped(s: String, i: Int) = (i > 0 && s[i - 1] == '\\')
private fun createFragment(fragmentAsString: String): Fragment {
return if (fragmentAsString.startsWith('{') && fragmentAsString.endsWith('}'))
Variable(fragmentAsString.substring(1, fragmentAsString.length - 1))
else
Text(fragmentAsString)
}
}
}
internal class IllegalFormatException(msg: String) : IllegalArgumentException(msg)
internal sealed class Fragment
internal data class Text(val content: String) : Fragment()
internal data class Variable(val name: String) : Fragment()
| apache-2.0 | 5c229a8e9076c3bd29a822e89c5087d8 | 39.254237 | 209 | 0.605263 | 5.319149 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/IndicatorEvaluatorIntegrationShould.kt | 1 | 4107 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine.IndicatorEngine
import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStoreImpl
import org.hisp.dhis.android.core.constant.internal.ConstantStore
import org.hisp.dhis.android.core.dataelement.internal.DataElementStore
import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitGroupStore
import org.hisp.dhis.android.core.parser.internal.service.ExpressionService
import org.hisp.dhis.android.core.program.internal.ProgramStageStore
import org.hisp.dhis.android.core.program.internal.ProgramStore
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLExecutor
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeStore
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.runner.RunWith
@RunWith(D2JunitRunner::class)
internal class IndicatorEvaluatorIntegrationShould : IndicatorEvaluatorIntegrationBaseShould() {
private val dataElementEvaluator = DataElementSQLEvaluator(databaseAdapter)
private val programIndicatorExecutor = ProgramIndicatorSQLExecutor(
ConstantStore.create(databaseAdapter),
DataElementStore.create(databaseAdapter),
TrackedEntityAttributeStore.create(databaseAdapter),
databaseAdapter
)
private val programIndicatorEvaluator = ProgramIndicatorSQLEvaluator(
programIndicatorExecutor
)
private val eventDataItemEvaluator = EventDataItemSQLEvaluator(databaseAdapter)
private val expressionService = ExpressionService(
DataElementStore.create(databaseAdapter),
CategoryOptionComboStoreImpl.create(databaseAdapter),
OrganisationUnitGroupStore.create(databaseAdapter),
ProgramStageStore.create(databaseAdapter)
)
private val indicatorEngine = IndicatorEngine(
indicatorTypeStore,
DataElementStore.create(databaseAdapter),
TrackedEntityAttributeStore.create(databaseAdapter),
CategoryOptionComboStoreImpl.create(databaseAdapter),
ProgramStore.create(databaseAdapter),
d2.programModule().programIndicators(),
dataElementEvaluator,
programIndicatorEvaluator,
eventDataItemEvaluator,
ConstantStore.create(databaseAdapter),
expressionService
)
override val indicatorEvaluator = IndicatorEvaluator(indicatorEngine)
}
| bsd-3-clause | 3f1c27687a381584a11292838d745349 | 50.3375 | 105 | 0.792793 | 4.978182 | false | false | false | false |
mre/the-coding-interview | problems/cash-units/cash-units.kt | 1 | 844 | import kotlin.test.assertEquals
private val availableCashUnits = listOf(500_00, 200_00, 100_00, 50_00, 20_00, 10_00, 5_00, 2_00, 1_00, 50, 20, 10, 5, 2, 1)
fun Int.cashUnits(): Map<Int, Int> =
LinkedHashMap<Int, Int>(availableCashUnits.size).also { result ->
var rest = this
for (cashUnit in availableCashUnits) {
val n = rest / cashUnit
result[cashUnit] = n
rest %= cashUnit
}
}
fun main(args: Array<String>) {
val expected = mapOf(
500_00 to 3,
200_00 to 2,
100_00 to 0,
50_00 to 1,
20_00 to 1,
10_00 to 0,
5_00 to 0,
2_00 to 1,
1_00 to 0,
50 to 1,
20 to 1,
10 to 0,
5 to 1,
2 to 1,
1 to 1
)
assertEquals(expected, 1972_78.cashUnits())
}
| mit | 3c7f8b6bd16601c209c9209209db35a0 | 23.114286 | 123 | 0.509479 | 3.184906 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/codeaction/quickfix/ImplementAbstractMembersQuickFix.kt | 1 | 6434 | package org.javacs.kt.codeaction.quickfix
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.javacs.kt.CompiledFile
import org.javacs.kt.index.SymbolIndex
import org.javacs.kt.position.offset
import org.javacs.kt.position.position
import org.javacs.kt.util.toPath
import org.javacs.kt.overridemembers.createFunctionStub
import org.javacs.kt.overridemembers.createVariableStub
import org.javacs.kt.overridemembers.getClassDescriptor
import org.javacs.kt.overridemembers.getDeclarationPadding
import org.javacs.kt.overridemembers.getNewMembersStartPosition
import org.javacs.kt.overridemembers.getSuperClassTypeProjections
import org.javacs.kt.overridemembers.hasNoBody
import org.javacs.kt.overridemembers.overridesDeclaration
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.isInterface
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.isAbstract
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
class ImplementAbstractMembersQuickFix : QuickFix {
override fun compute(file: CompiledFile, index: SymbolIndex, range: Range, diagnostics: List<Diagnostic>): List<Either<Command, CodeAction>> {
val diagnostic = findDiagnosticMatch(diagnostics, range)
val startCursor = offset(file.content, range.start)
val endCursor = offset(file.content, range.end)
val kotlinDiagnostics = file.compile.diagnostics
// If the client side and the server side diagnostics contain a valid diagnostic for this range.
if (diagnostic != null && anyDiagnosticMatch(kotlinDiagnostics, startCursor, endCursor)) {
// Get the class with the missing members
val kotlinClass = file.parseAtPoint(startCursor)
if (kotlinClass is KtClass) {
// Get the functions that need to be implemented
val membersToImplement = getAbstractMembersStubs(file, kotlinClass)
val uri = file.parse.toPath().toUri().toString()
// Get the padding to be introduced before the member declarations
val padding = getDeclarationPadding(file, kotlinClass)
// Get the location where the new code will be placed
val newMembersStartPosition = getNewMembersStartPosition(file, kotlinClass)
val bodyAppendBeginning = listOf(TextEdit(Range(newMembersStartPosition, newMembersStartPosition), "{")).takeIf { kotlinClass.hasNoBody() } ?: emptyList()
val bodyAppendEnd = listOf(TextEdit(Range(newMembersStartPosition, newMembersStartPosition), System.lineSeparator() + "}")).takeIf { kotlinClass.hasNoBody() } ?: emptyList()
val textEdits = bodyAppendBeginning + membersToImplement.map {
// We leave two new lines before the member is inserted
val newText = System.lineSeparator() + System.lineSeparator() + padding + it
TextEdit(Range(newMembersStartPosition, newMembersStartPosition), newText)
} + bodyAppendEnd
val codeAction = CodeAction()
codeAction.edit = WorkspaceEdit(mapOf(uri to textEdits))
codeAction.kind = CodeActionKind.QuickFix
codeAction.title = "Implement abstract members"
codeAction.diagnostics = listOf(diagnostic)
return listOf(Either.forRight(codeAction))
}
}
return listOf()
}
}
fun findDiagnosticMatch(diagnostics: List<Diagnostic>, range: Range) =
diagnostics.find { diagnosticMatch(it, range, hashSetOf("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED")) }
private fun anyDiagnosticMatch(diagnostics: Diagnostics, startCursor: Int, endCursor: Int) =
diagnostics.any { diagnosticMatch(it, startCursor, endCursor, hashSetOf("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED")) }
private fun getAbstractMembersStubs(file: CompiledFile, kotlinClass: KtClass) =
// For each of the super types used by this class
kotlinClass.superTypeListEntries.mapNotNull {
// Find the definition of this super type
val referenceAtPoint = file.referenceExpressionAtPoint(it.startOffset)
val descriptor = referenceAtPoint?.second
val classDescriptor = getClassDescriptor(descriptor)
// If the super class is abstract or an interface
if (null != classDescriptor && (classDescriptor.kind.isInterface || classDescriptor.modality == Modality.ABSTRACT)) {
val superClassTypeArguments = getSuperClassTypeProjections(file, it)
classDescriptor.getMemberScope(superClassTypeArguments).getContributedDescriptors().filter { classMember ->
(classMember is FunctionDescriptor && classMember.modality == Modality.ABSTRACT && !overridesDeclaration(kotlinClass, classMember)) || (classMember is PropertyDescriptor && classMember.modality == Modality.ABSTRACT && !overridesDeclaration(kotlinClass, classMember))
}.mapNotNull { member ->
when (member) {
is FunctionDescriptor -> createFunctionStub(member)
is PropertyDescriptor -> createVariableStub(member)
else -> null
}
}
} else {
null
}
}.flatten()
| mit | 2db2e0779545ad181f88089588098083 | 54.465517 | 281 | 0.734224 | 5.070134 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/KotlinLibraryData.kt | 2 | 1350 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.platforms
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import java.io.File
@ApiStatus.Internal
enum class KotlinLibraryData(val libraryName: String, val kind: PersistentLibraryKind<*>?, val classesRoot: File, val sourcesRoot: File) {
KOTLIN_STDLIB(
libraryName = "kotlin-stdlib",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlib,
sourcesRoot = KotlinArtifacts.kotlinStdlibSources
),
KOTLIN_STDLIB_JDK7(
libraryName = "kotlin-stdlib-jdk7",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlibJdk7,
sourcesRoot = KotlinArtifacts.kotlinStdlibJdk7Sources
),
KOTLIN_STDLIB_JDK8(
libraryName = "kotlin-stdlib-jdk8",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlibJdk8,
sourcesRoot = KotlinArtifacts.kotlinStdlibJdk8Sources
),
KOTLIN_STDLIB_JS(
libraryName = "kotlin-stdlib-js",
kind = KotlinJavaScriptLibraryKind,
classesRoot = KotlinArtifacts.kotlinStdlibJs,
sourcesRoot = KotlinArtifacts.kotlinStdlibSources
)
} | apache-2.0 | c20230e602652b3dd721c55edf5357db | 37.6 | 138 | 0.742222 | 4.770318 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitStageConflictActions.kt | 2 | 3142 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.Project
import com.intellij.util.containers.asJBIterable
import git4idea.conflicts.GitConflictsUtil.acceptConflictSide
import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow
import git4idea.conflicts.GitConflictsUtil.getConflictOperationLock
import git4idea.conflicts.GitConflictsUtil.showMergeWindow
import git4idea.conflicts.GitMergeHandler
import git4idea.i18n.GitBundle
import git4idea.index.ui.*
import git4idea.repo.GitConflict
import org.jetbrains.annotations.Nls
import java.util.function.Supplier
class GitStageAcceptTheirsAction : GitStageAcceptConflictSideAction(GitBundle.messagePointer("conflicts.accept.theirs.action.text"), true)
class GitStageAcceptYoursAction : GitStageAcceptConflictSideAction(GitBundle.messagePointer("conflicts.accept.yours.action.text"), false)
abstract class GitStageConflictAction(text: Supplier<@Nls String>) :
GitFileStatusNodeAction(text, Presentation.NULL_STRING, null) {
override fun update(e: AnActionEvent) {
val project = e.project
val nodes = e.getData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable()
if (project == null || nodes.filter(this::matches).isEmpty) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = isEnabled(project, nodes.filterMap(GitFileStatusNode::createConflict).asSequence() as Sequence<GitConflict>)
}
override fun matches(statusNode: GitFileStatusNode): Boolean = statusNode.kind == NodeKind.CONFLICTED
override fun perform(project: Project, nodes: List<GitFileStatusNode>) {
perform(project, createMergeHandler(project), nodes.mapNotNull { it.createConflict() })
}
protected open fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean {
return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked }
}
protected abstract fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>)
}
abstract class GitStageAcceptConflictSideAction(text: Supplier<@Nls String>, private val takeTheirs: Boolean)
: GitStageConflictAction(text) {
override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) {
acceptConflictSide(project, handler, conflicts, takeTheirs)
}
}
class GitStageMergeConflictAction : GitStageConflictAction(GitBundle.messagePointer("action.Git.Merge.text")) {
override fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean {
val handler = createMergeHandler(project)
return conflicts.any { conflict -> canShowMergeWindow(project, handler, conflict) }
}
override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) {
showMergeWindow(project, handler, conflicts)
}
}
| apache-2.0 | a6bd19d0c7fce311c9a0f9feb776fe13 | 45.895522 | 139 | 0.802355 | 4.710645 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/source/online/YamlOnlineSource.kt | 1 | 8038 | package eu.kanade.tachiyomi.data.source.online
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.network.GET
import eu.kanade.tachiyomi.data.network.POST
import eu.kanade.tachiyomi.data.source.getLanguages
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.util.attrOrText
import okhttp3.Request
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
class YamlOnlineSource(mappings: Map<*, *>) : OnlineSource() {
val map = YamlSourceNode(mappings)
override val name: String
get() = map.name
override val baseUrl = map.host.let {
if (it.endsWith("/")) it.dropLast(1) else it
}
override val lang = map.lang.toUpperCase().let { code ->
getLanguages().find { code == it.code }!!
}
override val supportsLatest = map.latestupdates != null
override val client = when(map.client) {
"cloudflare" -> network.cloudflareClient
else -> network.client
}
override val id = map.id.let {
if (it is Int) it else (lang.code.hashCode() + 31 * it.hashCode()) and 0x7fffffff
}
override fun popularMangaRequest(page: MangasPage): Request {
if (page.page == 1) {
page.url = popularMangaInitialUrl()
}
return when (map.popular.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.popular.createForm())
else -> GET(page.url, headers)
}
}
override fun popularMangaInitialUrl() = map.popular.url
override fun popularMangaParse(response: Response, page: MangasPage) {
val document = response.asJsoup()
for (element in document.select(map.popular.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.popular.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun searchMangaRequest(page: MangasPage, query: String, filters: List<Filter>): Request {
if (page.page == 1) {
page.url = searchMangaInitialUrl(query, filters)
}
return when (map.search.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.search.createForm())
else -> GET(page.url, headers)
}
}
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = map.search.url.replace("\$query", query)
override fun searchMangaParse(response: Response, page: MangasPage, query: String, filters: List<Filter>) {
val document = response.asJsoup()
for (element in document.select(map.search.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.search.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun latestUpdatesRequest(page: MangasPage): Request {
if (page.page == 1) {
page.url = latestUpdatesInitialUrl()
}
return when (map.latestupdates!!.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.latestupdates.createForm())
else -> GET(page.url, headers)
}
}
override fun latestUpdatesInitialUrl() = map.latestupdates!!.url
override fun latestUpdatesParse(response: Response, page: MangasPage) {
val document = response.asJsoup()
for (element in document.select(map.latestupdates!!.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.latestupdates.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun mangaDetailsParse(response: Response, manga: Manga) {
val document = response.asJsoup()
with(map.manga) {
val pool = parts.get(document)
manga.author = author?.process(document, pool)
manga.artist = artist?.process(document, pool)
manga.description = summary?.process(document, pool)
manga.thumbnail_url = cover?.process(document, pool)
manga.genre = genres?.process(document, pool)
manga.status = status?.getStatus(document, pool) ?: Manga.UNKNOWN
}
}
override fun chapterListParse(response: Response, chapters: MutableList<Chapter>) {
val document = response.asJsoup()
with(map.chapters) {
val pool = emptyMap<String, Element>()
val dateFormat = SimpleDateFormat(date?.format, Locale.ENGLISH)
for (element in document.select(chapter_css)) {
val chapter = Chapter.create()
element.select(title).first().let {
chapter.name = it.text()
chapter.setUrlWithoutDomain(it.attr("href"))
}
val dateElement = element.select(date?.select).first()
chapter.date_upload = date?.getDate(dateElement, pool, dateFormat)?.time ?: 0
chapters.add(chapter)
}
}
}
override fun pageListParse(response: Response, pages: MutableList<Page>) {
val body = response.body().string()
val url = response.request().url().toString()
// TODO lazy initialization in Kotlin 1.1
val document = Jsoup.parse(body, url)
with(map.pages) {
// Capture a list of values where page urls will be resolved.
val capturedPages = if (pages_regex != null)
pages_regex!!.toRegex().findAll(body).map { it.value }.toList()
else if (pages_css != null)
document.select(pages_css).map { it.attrOrText(pages_attr!!) }
else
null
// For each captured value, obtain the url and create a new page.
capturedPages?.forEach { value ->
// If the captured value isn't an url, we have to use replaces with the chapter url.
val pageUrl = if (replace != null && replacement != null)
url.replace(replace!!.toRegex(), replacement!!.replace("\$value", value))
else
value
pages.add(Page(pages.size, pageUrl))
}
// Capture a list of images.
val capturedImages = if (image_regex != null)
image_regex!!.toRegex().findAll(body).map { it.groups[1]?.value }.toList()
else if (image_css != null)
document.select(image_css).map { it.absUrl(image_attr) }
else
null
// Assign the image url to each page
capturedImages?.forEachIndexed { i, url ->
val page = pages.getOrElse(i) { Page(i, "").apply { pages.add(this) } }
page.imageUrl = url
}
}
}
override fun imageUrlParse(response: Response): String {
val body = response.body().string()
val url = response.request().url().toString()
with(map.pages) {
return if (image_regex != null)
image_regex!!.toRegex().find(body)!!.groups[1]!!.value
else if (image_css != null)
Jsoup.parse(body, url).select(image_css).first().absUrl(image_attr)
else
throw Exception("image_regex and image_css are null")
}
}
}
| apache-2.0 | 580068cea6317a9f232f04b981176f1d | 36.386047 | 119 | 0.58945 | 4.485491 | false | true | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/main/MainActivity.kt | 1 | 12089 | package org.secfirst.umbrella.feature.main
import android.app.SearchManager
import android.content.Context
import android.content.Intent.ACTION_VIEW
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.attachRouter
import com.github.tbouron.shakedetector.library.ShakeDetector
import com.google.android.material.bottomnavigation.BottomNavigationView
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.main_view.*
import org.secfirst.advancedsearch.interfaces.AdvancedSearchPresenter
import org.secfirst.advancedsearch.interfaces.DataProvider
import org.secfirst.advancedsearch.models.SearchCriteria
import org.secfirst.advancedsearch.util.mvp.ThreadSpec
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.disk.isRepository
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_LOGGED_IN
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_MASK_APP
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_SHOW_MOCK_VIEW
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.PREF_NAME
import org.secfirst.umbrella.feature.account.view.AccountController
import org.secfirst.umbrella.feature.checklist.view.controller.HostChecklistController
import org.secfirst.umbrella.feature.form.view.controller.HostFormController
import org.secfirst.umbrella.feature.lesson.view.LessonController
import org.secfirst.umbrella.feature.login.view.LoginController
import org.secfirst.umbrella.feature.maskapp.view.CalculatorController
import org.secfirst.umbrella.feature.reader.view.HostReaderController
import org.secfirst.umbrella.feature.search.view.SearchController
import org.secfirst.umbrella.feature.tour.view.TourController
import org.secfirst.umbrella.misc.*
import org.secfirst.umbrella.misc.AppExecutors.Companion.uiContext
import java.util.*
class MainActivity : AppCompatActivity(), AdvancedSearchPresenter {
lateinit var router: Router
private fun performDI() = AndroidInjection.inject(this)
private lateinit var menuItem: Menu
private var disableSearch = false
private var deepLink = false
private var searchProvider: AdvancedSearchPresenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLanguage()
setContentView(R.layout.main_view)
router = attachRouter(baseContainer, savedInstanceState)
performDI()
isDeepLink()
initNavigation()
showNavigation()
}
override fun getCriteria(): List<SearchCriteria> {
return searchProvider?.getCriteria()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun getDataProvider(): DataProvider {
return searchProvider?.getDataProvider()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun getThreadSpec(): ThreadSpec {
return searchProvider?.getThreadSpec()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun onResume() {
super.onResume()
ShakeDetector.start()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
return true
}
fun registerSearchProvider(provider: AdvancedSearchPresenter) {
this.searchProvider = provider
}
fun releaseSearchProvider() {
this.searchProvider = null
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the options menu from XML
val inflater = menuInflater
menuItem = menu
inflater.inflate(R.menu.option_menu, menu)
val menuItem = menu.findItem(R.id.menu_search)
// Get the SearchView and set the searchable configuration
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
(menuItem.actionView as SearchView).apply {
menuItem.isVisible = !disableSearch
val searchEditText = this.findViewById<View>(androidx.appcompat.R.id.search_src_text) as EditText
searchEditText.setTextColor(resources.getColor(R.color.white))
searchEditText.setHintTextColor(resources.getColor(R.color.white))
// Assumes current activity is the searchable activity
if (componentName!=null && searchManager.getSearchableInfo(componentName) != null)
setSearchableInfo(searchManager.getSearchableInfo(componentName))
setIconifiedByDefault(false) // Do not iconify the widget; expand it by default
isSubmitButtonEnabled = true
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
query?.let {
router.pushController(RouterTransaction.with(SearchController(it)))
return true
}
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
return false
}
})
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
hideKeyboard()
return true
}
return super.onOptionsItemSelected(item)
}
private fun setLanguage() {
val preference = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val pref = preference.getString(AppPreferenceHelper.EXTRA_LANGUAGE, "")
val isoCountry: String
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (pref!!.isNotBlank())
this.setLocale(pref)
} else {
isoCountry = if (pref!!.isNotBlank()) pref
else Locale.getDefault().language
this.setLocale(isoCountry)
}
}
private fun initNavigation() {
navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener)
if (isMaskMode() && isShowMockView()) {
router.setRoot(RouterTransaction.with(CalculatorController()))
} else {
when(UmbrellaApplication.instance.checkPassword()) {
false -> {
router.pushController(RouterTransaction.with(LoginController()))
}
true -> {
setShowMockView()
when {
isLoggedUser() -> {
if (!deepLink) {
router.setRoot(RouterTransaction.with(LoginController()))
navigation.menu.getItem(2).isChecked = true
disableSearch = true
}
}
isRepository() -> {
if (!deepLink) {
router.setRoot(RouterTransaction.with(HostChecklistController()))
navigation.menu.getItem(2).isChecked = true
disableSearch = false
}
}
else -> router.setRoot(RouterTransaction.with(TourController()))
}
}
}
}
}
fun resetAppbar() {
disableSearch = false
menuItem.clear()
}
private val navigationItemSelectedListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_feeds -> {
router.pushController(RouterTransaction.with(HostReaderController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_forms -> {
router.pushController(RouterTransaction.with(HostFormController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_checklists -> {
router.pushController(RouterTransaction.with(HostChecklistController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_lessons -> {
router.pushController(RouterTransaction.with(LessonController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_account -> {
router.pushController(RouterTransaction.with(AccountController()))
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onStop() {
super.onStop()
ShakeDetector.stop()
}
override fun onDestroy() {
super.onDestroy()
ShakeDetector.destroy()
}
override fun onBackPressed() {
if (!router.handleBack())
super.onBackPressed()
}
fun hideNavigation() = navigation?.let { it.visibility = INVISIBLE }
fun showNavigation() = navigation?.let { it.visibility = VISIBLE }
fun navigationPositionToCenter() {
navigation.menu.getItem(2).isChecked = true
}
private fun isLoggedUser(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
return shared.getBoolean(EXTRA_LOGGED_IN, false)
}
private fun setShowMockView() {
if (isMaskMode()) {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
shared.edit().putBoolean(EXTRA_SHOW_MOCK_VIEW, true).apply()
}
}
private fun isMaskMode(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val isMask = shared.getBoolean(EXTRA_MASK_APP, false)
if (!isMask)
setMaskMode(this, false)
return isMask
}
private fun isShowMockView(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
return shared.getBoolean(EXTRA_SHOW_MOCK_VIEW, false)
}
private fun isDeepLink() {
if (ACTION_VIEW == intent.action) {
deepLink = true
val uri = intent.data
val uriString = uri?.toString() ?: ""
val path = uriString.substringAfterLast(SCHEMA)
val uriSplitted = path.split("/")
when (uri?.host) {
FEED_HOST -> openFeedByUrl(router, navigation)
FORM_HOST -> openFormByUrl(router, navigation, uriString)
// CHECKLIST_HOST -> openChecklistByUrl(router, navigation, uriString)
SEARCH_HOST -> {
intent?.data?.lastPathSegment?.let {
router.pushController(RouterTransaction.with(SearchController(it)))
}
}
else -> {
launchSilent(uiContext) {
if (isLessonDeepLink(uriSplitted))
openSpecificLessonByUrl(router, navigation, uriString)
else
openDifficultyByUrl(router, navigation, path)
}
}
}
}
}
}
| gpl-3.0 | fc01a9d11272e34ee5075614e8cd7c3b | 38.89769 | 117 | 0.629332 | 5.525137 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/rekognition/src/main/kotlin/com/kotlin/rekognition/CelebrityInfo.kt | 1 | 1905 | // snippet-sourcedescription:[CelebrityInfo.kt demonstrates how to get information about a detected celebrity.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Rekognition]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.rekognition
// snippet-start:[rekognition.kotlin.celebrityInfo.import]
import aws.sdk.kotlin.services.rekognition.RekognitionClient
import aws.sdk.kotlin.services.rekognition.model.GetCelebrityInfoRequest
import kotlin.system.exitProcess
// snippet-end:[rekognition.kotlin.celebrityInfo.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:
<id>
Where:
id - The id value of the celebrity. You can use the RecognizeCelebrities example to get the ID value.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val id = args[0]
getCelebrityInfo(id)
}
// snippet-start:[rekognition.kotlin.celebrityInfo.main]
suspend fun getCelebrityInfo(idVal: String?) {
val request = GetCelebrityInfoRequest {
id = idVal
}
RekognitionClient { region = "us-east-1" }.use { rekClient ->
val response = rekClient.getCelebrityInfo(request)
// Display celebrity information.
println("The celebrity name is ${response.name}")
println("Further information (if available):")
response.urls?.forEach { url ->
println(url)
}
}
}
// snippet-end:[rekognition.kotlin.celebrityInfo.main]
| apache-2.0 | dc8fab7716fa382e7cfbce7284384c8d | 29.229508 | 114 | 0.672966 | 4.070513 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/inspection/StaticListenerInspectionSuppressor.kt | 1 | 1112 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.inspection
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.util.findContainingMethod
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiElement
class StaticListenerInspectionSuppressor : InspectionSuppressor {
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId != "MethodMayBeStatic") {
return false
}
val method = element.findContainingMethod() ?: return false
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false
val facet = MinecraftFacet.getInstance(module) ?: return false
return facet.suppressStaticListener(method)
}
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> =
SuppressQuickFix.EMPTY_ARRAY
}
| mit | 364ccc7ef81375e6c89ba7195804224c | 29.054054 | 100 | 0.749101 | 4.898678 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/Tool.kt | 2 | 1485 | package io.github.chrislo27.rhre3.editor
import com.badlogic.gdx.graphics.Texture
import io.github.chrislo27.rhre3.track.tracker.Tracker
import io.github.chrislo27.rhre3.track.tracker.musicvolume.MusicVolumeChange
import io.github.chrislo27.rhre3.track.tracker.tempo.TempoChange
import io.github.chrislo27.toolboks.registry.AssetRegistry
import kotlin.reflect.KClass
enum class Tool(val texId: String, val nameId: String,
val trackerClass: KClass<out Tracker<*>>? = null, val keybinds: List<String> = listOf(),
val showSubbeatLines: Boolean = trackerClass != null) {
SELECTION("tool_selection", "tool.normal.name"),
MULTIPART_SPLIT("tool_multipart_split", "tool.multipartSplit.name"),
TEMPO_CHANGE("tool_tempo_change", "tool.tempoChange.name", trackerClass = TempoChange::class),
MUSIC_VOLUME("tool_music_volume", "tool.musicVolume.name", trackerClass = MusicVolumeChange::class),
TIME_SIGNATURE("tool_time_signature", "tool.timeSignature.name", showSubbeatLines = true),
SWING("tool_swing", "tool.swing.name"),
RULER("tool_ruler", "tool.ruler.name", keybinds = listOf("R"), showSubbeatLines = true),
PICKAXE("tool_pickaxe", "tool.pickaxe.name");
companion object {
val VALUES: List<Tool> by lazy { Tool.values().toList() }
}
val isTrackerRelated: Boolean = trackerClass != null
val index: Int by lazy { VALUES.indexOf(this) }
val texture: Texture
get() = AssetRegistry[texId]
} | gpl-3.0 | a062984f7c806917874705bd30934f2c | 44.030303 | 104 | 0.718519 | 3.69403 | false | false | false | false |
datafrost1997/GitterChat | app/src/main/java/com/devslopes/datafrost1997/gitterchat/Services/MessageService.kt | 1 | 4082 | package com.devslopes.datafrost1997.gitterchat.Services
import android.content.Context
import android.util.Log
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.devslopes.datafrost1997.gitterchat.Controller.App
import com.devslopes.datafrost1997.gitterchat.Model.Channel
import com.devslopes.datafrost1997.gitterchat.Model.Message
import com.devslopes.datafrost1997.gitterchat.Utilities.URL_GET_CHANNELS
import com.devslopes.datafrost1997.gitterchat.Utilities.URL_GET_MESSAGES
import org.json.JSONException
/**
* Created by datafrost1997 on 16/10/17.
*/
object MessageService {
val channels = ArrayList<Channel> ()
val messages = ArrayList<Message> ()
fun getChannels(complete: (Boolean) -> Unit) {
val channelsRequest = object : JsonArrayRequest(Method.GET, URL_GET_CHANNELS, null , Response.Listener { response ->
try {
for (x in 0 until response.length()) {
val channel = response.getJSONObject(x)
val name = channel.getString("name")
val chanDesc = channel.getString("description")
val channelId = channel.getString("_id")
val newChannel = Channel(name, chanDesc, channelId)
this.channels.add(newChannel)
}
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC: " + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener { error ->
Log.d("ERROR", "Couldn't Retrieve Channels")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(channelsRequest)
}
fun getMessages(channelId: String, complete: (Boolean) -> Unit) {
val url = "$URL_GET_MESSAGES$channelId"
val messagesRequest = object : JsonArrayRequest(Method.GET, url, null, Response.Listener { response ->
clearMessages()
try {
for (x in 0 until response.length()) {
val message = response.getJSONObject(x)
val messageBody = message.getString("messageBody")
val channelId = message.getString("channelId")
val id = message.getString("_id")
val userName = message.getString("userName")
val userAvatar = message.getString("userAvatar")
val userAvatarColor = message.getString("userAvatarColor")
val timeStamp = message.getString("timeStamp")
val newMessage = Message(messageBody, userName, channelId, userAvatar, userAvatarColor, id, timeStamp)
this.messages.add(newMessage)
}
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC: " + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener {
Log.d("ERROR", "Couldn't Retrieve Channels")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(messagesRequest)
}
fun clearMessages() {
messages.clear()
}
fun clearChannels(){
channels.clear()
}
} | gpl-3.0 | 7e18da70d5b0a29c7c0e146494a2a222 | 37.885714 | 124 | 0.583782 | 5.008589 | false | false | false | false |
allotria/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageUastVisitor.kt | 1 | 18356 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.apiUsage
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.uast.UastVisitorAdapter
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
/**
* Non-recursive UAST visitor that detects usages of APIs in source code of UAST-supporting languages
* and reports them via [ApiUsageProcessor] interface.
*/
@ApiStatus.Experimental
class ApiUsageUastVisitor(private val apiUsageProcessor: ApiUsageProcessor) : AbstractUastNonRecursiveVisitor() {
companion object {
@JvmStatic
fun createPsiElementVisitor(apiUsageProcessor: ApiUsageProcessor): PsiElementVisitor =
UastVisitorAdapter(ApiUsageUastVisitor(apiUsageProcessor), true)
}
override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean {
if (maybeProcessReferenceInsideImportStatement(node)) {
return true
}
if (maybeProcessJavaModuleReference(node)) {
return true
}
if (isMethodReferenceOfCallExpression(node)
|| isNewArrayClassReference(node)
|| isMethodReferenceOfCallableReferenceExpression(node)
|| isSelectorOfQualifiedReference(node)
) {
return true
}
if (isSuperOrThisCall(node)) {
return true
}
val resolved = node.resolve()
if (resolved is PsiMethod) {
if (isClassReferenceInConstructorInvocation(node) || isClassReferenceInKotlinSuperClassConstructor(node)) {
/*
Suppose a code:
```
object : SomeClass(42) { }
or
new SomeClass(42)
```
with USimpleNameReferenceExpression pointing to `SomeClass`.
We want ApiUsageProcessor to notice two events: 1) reference to `SomeClass` and 2) reference to `SomeClass(int)` constructor.
But Kotlin UAST resolves this simple reference to the PSI constructor of the class SomeClass.
So we resolve it manually to the class because the constructor will be handled separately
in "visitObjectLiteralExpression" or "visitCallExpression".
*/
val resolvedClass = resolved.containingClass
if (resolvedClass != null) {
apiUsageProcessor.processReference(node, resolvedClass, null)
}
return true
}
}
if (resolved is PsiModifierListOwner) {
apiUsageProcessor.processReference(node, resolved, null)
return true
}
if (resolved == null) {
/*
* KT-30522 UAST for Kotlin: reference to annotation parameter resolves to null.
*/
val psiReferences = node.sourcePsi?.references.orEmpty()
for (psiReference in psiReferences) {
val target = psiReference.resolve()?.toUElement()?.javaPsi as? PsiAnnotationMethod
if (target != null) {
apiUsageProcessor.processReference(node, target, null)
return true
}
}
}
return true
}
override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean {
if (maybeProcessReferenceInsideImportStatement(node)) {
return true
}
if (node.sourcePsi is PsiMethodCallExpression || node.selector is UCallExpression) {
//UAST for Java produces UQualifiedReferenceExpression for both PsiMethodCallExpression and PsiReferenceExpression inside it
//UAST for Kotlin produces UQualifiedReferenceExpression with UCallExpression as selector
return true
}
var resolved = node.resolve()
if (resolved == null) {
resolved = node.selector.tryResolve()
}
if (resolved is PsiModifierListOwner) {
apiUsageProcessor.processReference(node.selector, resolved, node.receiver)
}
return true
}
private fun isKotlin(node: UElement): Boolean {
val sourcePsi = node.sourcePsi ?: return false
return sourcePsi.language.id.contains("kotlin", true)
}
override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean {
/*
* KT-31181: Kotlin UAST: UCallableReferenceExpression.referenceNameElement is always null.
*/
fun workaroundKotlinGetReferenceNameElement(node: UCallableReferenceExpression): UElement? {
if (isKotlin(node)) {
val sourcePsi = node.sourcePsi
if (sourcePsi != null) {
val children = sourcePsi.children
if (children.size == 2) {
return children[1].toUElement()
}
}
}
return null
}
val resolve = node.resolve()
if (resolve is PsiModifierListOwner) {
val sourceNode = node.referenceNameElement ?: workaroundKotlinGetReferenceNameElement(node) ?: node
apiUsageProcessor.processReference(sourceNode, resolve, node.qualifierExpression)
//todo support this for other JVM languages
val javaMethodReference = node.sourcePsi as? PsiMethodReferenceExpression
if (javaMethodReference != null) {
//a reference to the functional interface will be added by compiler
val resolved = PsiUtil.resolveGenericsClassInType(javaMethodReference.functionalInterfaceType).element
if (resolved != null) {
apiUsageProcessor.processReference(node, resolved, null)
}
}
}
return true
}
override fun visitCallExpression(node: UCallExpression): Boolean {
if (node.sourcePsi is PsiExpressionStatement) {
//UAST for Java generates UCallExpression for PsiExpressionStatement and PsiMethodCallExpression inside it.
return true
}
val psiMethod = node.resolve()
val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node
if (psiMethod != null) {
val containingClass = psiMethod.containingClass
if (psiMethod.isConstructor) {
if (containingClass != null) {
apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, null)
}
}
else {
apiUsageProcessor.processReference(sourceNode, psiMethod, node.receiver)
}
return true
}
if (node.kind == UastCallKind.CONSTRUCTOR_CALL) {
//Java does not resolve constructor for subclass constructor's "super()" statement
// if the superclass has the default constructor, which is not declared in source code and lacks PsiMethod.
val superClass = node.getContainingUClass()?.javaPsi?.superClass ?: return true
apiUsageProcessor.processConstructorInvocation(sourceNode, superClass, null, null)
return true
}
val classReference = node.classReference
if (classReference != null) {
val resolvedClass = classReference.resolve() as? PsiClass
if (resolvedClass != null) {
if (node.kind == UastCallKind.CONSTRUCTOR_CALL) {
val emptyConstructor = resolvedClass.constructors.find { it.parameterList.isEmpty }
apiUsageProcessor.processConstructorInvocation(sourceNode, resolvedClass, emptyConstructor, null)
}
else {
apiUsageProcessor.processReference(sourceNode, resolvedClass, node.receiver)
}
}
return true
}
return true
}
override fun visitObjectLiteralExpression(node: UObjectLiteralExpression): Boolean {
val psiMethod = node.resolve()
val sourceNode = node.methodIdentifier
?: node.classReference?.referenceNameElement
?: node.classReference
?: node.declaration.uastSuperTypes.firstOrNull()
?: node
if (psiMethod != null) {
val containingClass = psiMethod.containingClass
if (psiMethod.isConstructor) {
if (containingClass != null) {
apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, node.declaration)
}
}
}
else {
maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode, node.declaration)
}
return true
}
override fun visitElement(node: UElement): Boolean {
if (node is UNamedExpression) {
//IDEA-209279: UAstVisitor lacks a hook for UNamedExpression
//KT-30522: Kotlin does not generate UNamedExpression for annotation's parameters.
processNamedExpression(node)
return true
}
return super.visitElement(node)
}
override fun visitClass(node: UClass): Boolean {
val uastAnchor = node.uastAnchor
if (uastAnchor == null || node is UAnonymousClass || node.javaPsi is PsiTypeParameter) {
return true
}
maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(uastAnchor, node)
return true
}
override fun visitMethod(node: UMethod): Boolean {
if (node.isConstructor) {
checkImplicitCallOfSuperEmptyConstructor(node)
}
else {
checkMethodOverriding(node)
}
return true
}
override fun visitLambdaExpression(node: ULambdaExpression): Boolean {
val explicitClassReference = (node.uastParent as? UCallExpression)?.classReference
if (explicitClassReference == null) {
//a reference to the functional interface will be added by compiler
val resolved = PsiUtil.resolveGenericsClassInType(node.functionalInterfaceType).element
if (resolved != null) {
apiUsageProcessor.processReference(node, resolved, null)
}
}
return true
}
private fun maybeProcessJavaModuleReference(node: UElement): Boolean {
val sourcePsi = node.sourcePsi
if (sourcePsi is PsiJavaModuleReferenceElement) {
val reference = sourcePsi.reference
val target = reference?.resolve()
if (target != null) {
apiUsageProcessor.processJavaModuleReference(reference, target)
}
return true
}
return false
}
private fun maybeProcessReferenceInsideImportStatement(node: UReferenceExpression): Boolean {
if (isInsideImportStatement(node)) {
if (isKotlin(node)) {
/*
UAST for Kotlin 1.3.30 import statements have bugs.
KT-30546: some references resolve to nulls.
KT-30957: simple references for members resolve incorrectly to class declaration, not to the member declaration
Therefore, we have to fallback to base PSI for Kotlin references.
*/
val resolved = node.sourcePsi?.reference?.resolve()
val target = (resolved?.toUElement()?.javaPsi ?: resolved) as? PsiModifierListOwner
if (target != null) {
apiUsageProcessor.processImportReference(node, target)
}
}
else {
val resolved = node.resolve() as? PsiModifierListOwner
if (resolved != null) {
apiUsageProcessor.processImportReference(node.referenceNameElement ?: node, resolved)
}
}
return true
}
return false
}
private fun isInsideImportStatement(node: UElement): Boolean {
val sourcePsi = node.sourcePsi
if (sourcePsi != null && sourcePsi.language == JavaLanguage.INSTANCE) {
return PsiTreeUtil.getParentOfType(sourcePsi, PsiImportStatementBase::class.java) != null
}
return sourcePsi.findContaining(UImportStatement::class.java) != null
}
private fun maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode: UElement, subclassDeclaration: UClass) {
val instantiatedClass = subclassDeclaration.javaPsi.superClass ?: return
val subclassHasExplicitConstructor = subclassDeclaration.methods.any { it.isConstructor }
val emptyConstructor = instantiatedClass.constructors.find { it.parameterList.isEmpty }
if (subclassDeclaration is UAnonymousClass || !subclassHasExplicitConstructor) {
apiUsageProcessor.processConstructorInvocation(sourceNode, instantiatedClass, emptyConstructor, subclassDeclaration)
}
}
private fun processNamedExpression(node: UNamedExpression) {
val sourcePsi = node.sourcePsi
val annotationMethod = sourcePsi?.reference?.resolve() as? PsiAnnotationMethod
if (annotationMethod != null) {
val sourceNode = (sourcePsi as? PsiNameValuePair)?.nameIdentifier?.toUElement() ?: node
apiUsageProcessor.processReference(sourceNode, annotationMethod, null)
}
}
private fun checkImplicitCallOfSuperEmptyConstructor(constructor: UMethod) {
val containingUClass = constructor.getContainingUClass() ?: return
val superClass = containingUClass.javaPsi.superClass ?: return
val uastBody = constructor.uastBody
val uastAnchor = constructor.uastAnchor
if (uastAnchor != null && isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(uastBody)) {
val emptyConstructor = superClass.constructors.find { it.parameterList.isEmpty }
apiUsageProcessor.processConstructorInvocation(uastAnchor, superClass, emptyConstructor, null)
}
}
private fun isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(constructorBody: UExpression?): Boolean {
if (constructorBody == null || constructorBody is UBlockExpression && constructorBody.expressions.isEmpty()) {
//Empty constructor body => implicit super() call.
return true
}
val firstExpression = (constructorBody as? UBlockExpression)?.expressions?.firstOrNull() ?: constructorBody
if (firstExpression !is UCallExpression) {
//First expression is not super() => the super() is implicit.
return true
}
if (firstExpression.valueArgumentCount > 0) {
//Invocation of non-empty super(args) constructor.
return false
}
val methodName = firstExpression.methodIdentifier?.name ?: firstExpression.methodName
return methodName != "super" && methodName != "this"
}
private fun checkMethodOverriding(node: UMethod) {
val method = node.javaPsi
val superMethods = method.findSuperMethods(true)
for (superMethod in superMethods) {
apiUsageProcessor.processMethodOverriding(node, superMethod)
}
}
/**
* UAST for Kotlin generates UAST tree with "UnknownKotlinExpression (CONSTRUCTOR_CALLEE)" for the following expressions:
* 1) an object literal expression: `object : BaseClass() { ... }`
* 2) a super class constructor invocation `class Derived : BaseClass(42) { ... }`
*
*
* ```
* UObjectLiteralExpression
* UnknownKotlinExpression (CONSTRUCTOR_CALLEE)
* UTypeReferenceExpression (BaseClass)
* USimpleNameReferenceExpression (BaseClass)
* ```
*
* and
*
* ```
* UCallExpression (kind = CONSTRUCTOR_CALL)
* UnknownKotlinExpression (CONSTRUCTOR_CALLEE)
* UTypeReferenceExpression (BaseClass)
* USimpleNameReferenceExpression (BaseClass)
* ```
*
* This method checks if the given simple reference points to the `BaseClass` part,
* which is treated by Kotlin UAST as a reference to `BaseClass'` constructor, not to the `BaseClass` itself.
*/
private fun isClassReferenceInKotlinSuperClassConstructor(expression: USimpleNameReferenceExpression): Boolean {
val parent1 = expression.uastParent
val parent2 = parent1?.uastParent
val parent3 = parent2?.uastParent
return parent1 is UTypeReferenceExpression
&& parent2 != null && parent2.asLogString().contains("CONSTRUCTOR_CALLEE")
&& (parent3 is UObjectLiteralExpression || parent3 is UCallExpression && parent3.kind == UastCallKind.CONSTRUCTOR_CALL)
}
private fun isSelectorOfQualifiedReference(expression: USimpleNameReferenceExpression): Boolean {
val qualifiedReference = expression.uastParent as? UQualifiedReferenceExpression ?: return false
return haveSameSourceElement(expression, qualifiedReference.selector)
}
private fun isNewArrayClassReference(simpleReference: USimpleNameReferenceExpression): Boolean {
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
return callExpression.kind == UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
}
private fun isSuperOrThisCall(simpleReference: USimpleNameReferenceExpression): Boolean {
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
return callExpression.kind == UastCallKind.CONSTRUCTOR_CALL &&
(callExpression.methodIdentifier?.name == "super" || callExpression.methodIdentifier?.name == "this")
}
private fun isClassReferenceInConstructorInvocation(simpleReference: USimpleNameReferenceExpression): Boolean {
if (isSuperOrThisCall(simpleReference)) {
return false
}
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
if (callExpression.kind != UastCallKind.CONSTRUCTOR_CALL) {
return false
}
val classReferenceNameElement = callExpression.classReference?.referenceNameElement
if (classReferenceNameElement != null) {
return haveSameSourceElement(classReferenceNameElement, simpleReference.referenceNameElement)
}
return callExpression.resolve()?.name == simpleReference.resolvedName
}
private fun isMethodReferenceOfCallExpression(expression: USimpleNameReferenceExpression): Boolean {
val callExpression = expression.uastParent as? UCallExpression ?: return false
if (callExpression.kind != UastCallKind.METHOD_CALL) {
return false
}
val expressionNameElement = expression.referenceNameElement
val methodIdentifier = callExpression.methodIdentifier
return methodIdentifier != null && haveSameSourceElement(expressionNameElement, methodIdentifier)
}
private fun isMethodReferenceOfCallableReferenceExpression(expression: USimpleNameReferenceExpression): Boolean {
val callableReferenceExpression = expression.uastParent as? UCallableReferenceExpression ?: return false
if (haveSameSourceElement(callableReferenceExpression.referenceNameElement, expression)) {
return true
}
return expression.identifier == callableReferenceExpression.callableName
}
private fun haveSameSourceElement(element1: UElement?, element2: UElement?): Boolean {
if (element1 == null || element2 == null) return false
val sourcePsi1 = element1.sourcePsi
return sourcePsi1 != null && sourcePsi1 == element2.sourcePsi
}
}
| apache-2.0 | 9df7fbca204abd13d92bed17dd3b5e83 | 39.88196 | 140 | 0.718566 | 5.661937 | false | false | false | false |
ursjoss/sipamato | public/public-web/src/main/kotlin/ch/difty/scipamato/publ/misc/ParentUrlLocaleExtractor.kt | 2 | 1252 | package ch.difty.scipamato.publ.misc
import ch.difty.scipamato.publ.config.ScipamatoPublicProperties
import org.springframework.stereotype.Service
import java.util.Locale
import java.util.regex.Pattern
/**
* [LocaleExtractor] implementation that is capable of extracting
* the locale string from a parentUrl passed in as input.
*
* Examples of `parentUrl` and the resulting locales are:
*
* * https://www.foo.ch/de/whatever/follows/next/ : Locale.German
* * https://www.foo.ch/en/projects/something/else/ : Locale.English
* * https://www.foo.ch/fr/bar/baz/ : LOCALE.FRENCH
*/
@Service
class ParentUrlLocaleExtractor(properties: ScipamatoPublicProperties) : LocaleExtractor {
private val defaultLocale: String = properties.defaultLocalization
override fun extractLocaleFrom(input: String?): Locale = Locale.forLanguageTag(extractLanguageCode(input))
private fun extractLanguageCode(input: String?): String {
if (input != null) {
val matcher = PATTERN.matcher(input)
if (matcher.find()) return matcher.group(1)
}
return defaultLocale
}
companion object {
private val PATTERN = Pattern.compile("""https?://?[^/]+/(\w\w)/.+""", Pattern.CASE_INSENSITIVE)
}
}
| gpl-3.0 | 46074e334dff53c81096b06480bf7172 | 33.777778 | 110 | 0.710863 | 4.03871 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt | 1 | 1316 | /*
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import java.util.concurrent.atomic.*
/**
* Atomic array with lock-free reads and synchronized modifications. It logically has an unbounded size,
* is implicitly filled with nulls, and is resized on updates as needed to grow.
*/
internal class ResizableAtomicArray<T>(initialLength: Int) {
@Volatile
private var array = AtomicReferenceArray<T>(initialLength)
// for debug output
public fun currentLength(): Int = array.length()
public operator fun get(index: Int): T? {
val array = this.array // volatile read
return if (index < array.length()) array[index] else null
}
// Must not be called concurrently, e.g. always use synchronized(this) to call this function
fun setSynchronized(index: Int, value: T?) {
val curArray = this.array
val curLen = curArray.length()
if (index < curLen) {
curArray[index] = value
} else {
val newArray = AtomicReferenceArray<T>((index + 1).coerceAtLeast(2 * curLen))
for (i in 0 until curLen) newArray[i] = curArray[i]
newArray[index] = value
array = newArray // copy done
}
}
}
| apache-2.0 | add96d6c37dd61f2cee2ce2830ea5781 | 33.631579 | 104 | 0.652736 | 4.217949 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/text/regex/sets/WordBoundarySet.kt | 2 | 3063 | /*
* 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.
*/
/*
* 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 kotlin.text.regex
/**
* Represents word boundary, checks current character and previous one. If they have different types returns true;
*/
internal class WordBoundarySet(var positive: Boolean) : SimpleSet() {
override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val curChar = if (startIndex >= testString.length) ' ' else testString[startIndex]
val prevChar = if (startIndex == 0) ' ' else testString[startIndex - 1]
val right = curChar == ' ' || isSpace(curChar, startIndex, testString)
val left = prevChar == ' ' || isSpace(prevChar, startIndex - 1, testString)
return if (left xor right xor positive)
-1
else
next.matches(startIndex, testString, matchResult)
}
/** Returns false, because word boundary does not consumes any characters and do not move string index. */
override fun hasConsumed(matchResult: MatchResultImpl): Boolean = false
override val name: String
get() = "WordBoundarySet"
private fun isSpace(char: Char, startIndex: Int, testString: CharSequence): Boolean {
if (char.isLetterOrDigit() || char == '_') {
return false
}
if (char.category == CharCategory.NON_SPACING_MARK) {
var index = startIndex
while (--index >= 0) {
val ch = testString[index]
when {
ch.isLetterOrDigit() -> return false
char.category != CharCategory.NON_SPACING_MARK -> return true
}
}
}
return true
}
}
| apache-2.0 | afb5a1e8bb87174322000988ecef745a | 38.269231 | 114 | 0.671237 | 4.54451 | false | true | false | false |
AndroidX/androidx | compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/FlingCalculator.kt | 3 | 4422 | /*
* 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.animation
import androidx.compose.ui.unit.Density
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.sign
/**
* Earth's gravity in SI units (m/s^2); used to compute deceleration based on friction.
*/
private const val GravityEarth = 9.80665f
private const val InchesPerMeter = 39.37f
/**
* The default rate of deceleration for a fling if not specified in the
* [FlingCalculator] constructor.
*/
private val DecelerationRate = (ln(0.78) / ln(0.9)).toFloat()
/**
* Compute the rate of deceleration based on pixel density, physical gravity
* and a [coefficient of friction][friction].
*/
private fun computeDeceleration(friction: Float, density: Float): Float =
GravityEarth * InchesPerMeter * density * 160f * friction
/**
* Configuration for Android-feel flinging motion at the given density.
*
* @param friction scroll friction.
* @param density density of the screen. Use LocalDensity to get current density in composition.
*/
internal class FlingCalculator(
private val friction: Float,
val density: Density
) {
/**
* A density-specific coefficient adjusted to physical values.
*/
private val magicPhysicalCoefficient: Float = computeDeceleration(density)
/**
* Computes the rate of deceleration in pixels based on
* the given [density].
*/
private fun computeDeceleration(density: Density) =
computeDeceleration(0.84f, density.density)
private fun getSplineDeceleration(velocity: Float): Double = AndroidFlingSpline.deceleration(
velocity,
friction * magicPhysicalCoefficient
)
/**
* Compute the duration in milliseconds of a fling with an initial velocity of [velocity]
*/
fun flingDuration(velocity: Float): Long {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return (1000.0 * exp(l / decelMinusOne)).toLong()
}
/**
* Compute the distance of a fling in units given an initial [velocity] of units/second
*/
fun flingDistance(velocity: Float): Float {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return (
friction * magicPhysicalCoefficient
* exp(DecelerationRate / decelMinusOne * l)
).toFloat()
}
/**
* Compute all interesting information about a fling of initial velocity [velocity].
*/
fun flingInfo(velocity: Float): FlingInfo {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return FlingInfo(
initialVelocity = velocity,
distance = (
friction * magicPhysicalCoefficient
* exp(DecelerationRate / decelMinusOne * l)
).toFloat(),
duration = (1000.0 * exp(l / decelMinusOne)).toLong()
)
}
/**
* Info about a fling started with [initialVelocity]. The units of [initialVelocity]
* determine the distance units of [distance] and the time units of [duration].
*/
data class FlingInfo(
val initialVelocity: Float,
val distance: Float,
val duration: Long
) {
fun position(time: Long): Float {
val splinePos = if (duration > 0) time / duration.toFloat() else 1f
return distance * sign(initialVelocity) *
AndroidFlingSpline.flingPosition(splinePos).distanceCoefficient
}
fun velocity(time: Long): Float {
val splinePos = if (duration > 0) time / duration.toFloat() else 1f
return AndroidFlingSpline.flingPosition(splinePos).velocityCoefficient *
sign(initialVelocity) * distance / duration * 1000.0f
}
}
} | apache-2.0 | b9b0ace315cbd1d82b826dc1d2c0f44f | 33.286822 | 97 | 0.668024 | 4.563467 | false | false | false | false |
smmribeiro/intellij-community | platform/util-ex/src/com/intellij/util/RecursionPreventingSafePublicationLazy.kt | 12 | 2270 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util
import com.intellij.openapi.util.RecursionManager
import java.util.concurrent.atomic.AtomicReference
/**
* Same as [SafePublicationLazyImpl], but returns `null` in case of computation recursion occurred.
*/
internal class RecursionPreventingSafePublicationLazy<T>(recursionKey: Any?, initializer: () -> T) : Lazy<T?> {
@Volatile
private var initializer: (() -> T)? = { ourNotNullizer.notNullize(initializer()) }
private val valueRef: AtomicReference<T?> = AtomicReference()
private val recursionKey: Any = recursionKey ?: this
override val value: T?
get() {
val computedValue = valueRef.get()
if (computedValue !== null) {
return ourNotNullizer.nullize(computedValue)
}
val initializerValue = initializer
if (initializerValue === null) {
// Some thread managed to clear the initializer => it managed to set the value.
return ourNotNullizer.nullize(requireNotNull(valueRef.get()))
}
val stamp = RecursionManager.markStack()
val newValue = ourRecursionGuard.doPreventingRecursion(recursionKey, false, initializerValue)
// In case of recursion don't update [valueRef] and don't clear [initializer].
if (newValue === null) {
// Recursion occurred for this lazy.
return null
}
if (!stamp.mayCacheNow()) {
// Recursion occurred somewhere deep.
return ourNotNullizer.nullize(newValue)
}
if (!valueRef.compareAndSet(null, newValue)) {
// Some thread managed to set the value.
return ourNotNullizer.nullize(requireNotNull(valueRef.get()))
}
initializer = null
return ourNotNullizer.nullize(newValue)
}
override fun isInitialized(): Boolean = valueRef.get() !== null
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
companion object {
private val ourRecursionGuard = RecursionManager.createGuard<Any>("RecursionPreventingSafePublicationLazy")
private val ourNotNullizer = NotNullizer("RecursionPreventingSafePublicationLazy")
}
}
| apache-2.0 | 0619baaa629095a2af75d582f408d226 | 37.474576 | 140 | 0.702203 | 5.011038 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/tests/git4idea/test/GitTestUtil.kt | 12 | 7399 | // 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.
@file:JvmName("GitTestUtil")
package git4idea.test
import com.intellij.dvcs.push.PushSpec
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.HeavyPlatformTestCase
import com.intellij.util.io.write
import com.intellij.vcs.log.VcsLogObjectsFactory
import com.intellij.vcs.log.VcsLogProvider
import com.intellij.vcs.log.VcsRef
import com.intellij.vcs.log.VcsUser
import git4idea.GitRemoteBranch
import git4idea.GitStandardRemoteBranch
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.config.GitVersionSpecialty
import git4idea.log.GitLogProvider
import git4idea.push.GitPushSource
import git4idea.push.GitPushTarget
import git4idea.repo.GitRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assume.assumeTrue
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
const val USER_NAME = "John Doe"
const val USER_EMAIL = "[email protected]"
/**
*
* Creates file structure for given paths. Path element should be a relative (from project root)
* path to a file or a directory. All intermediate paths will be created if needed.
* To create a dir without creating a file pass "dir/" as a parameter.
*
* Usage example:
* `createFileStructure("a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt", "anotherdir/");`
*
* This will create files a.txt and b.txt in the project dir, create directories dir, dir/subdir and anotherdir,
* and create file c.txt in dir and d.txt in dir/subdir.
*
* Note: use forward slash to denote directories, even if it is backslash that separates dirs in your system.
*
* All files are populated with "initial content" string.
*/
fun createFileStructure(rootDir: VirtualFile, vararg paths: String) {
val parent = rootDir.toNioPath()
for (path in paths) {
val file = parent.resolve(path)
if (path.endsWith('/')) {
Files.createDirectories(file)
}
else {
file.write("initial_content_in_{$path}")
}
}
rootDir.refresh(false, true)
}
internal fun initRepo(project: Project, repoRoot: Path, makeInitialCommit: Boolean) {
Files.createDirectories(repoRoot)
cd(repoRoot.toString())
git(project, "init")
setupDefaultUsername(project)
setupLocalIgnore(repoRoot)
if (makeInitialCommit) {
touch("initial.txt")
git(project, "add initial.txt")
git(project, "commit -m initial")
}
}
private fun setupLocalIgnore(repoRoot: Path) {
repoRoot.resolve(".git/info/exclude").write(".shelf")
}
fun GitPlatformTest.cloneRepo(source: String, destination: String, bare: Boolean) {
cd(source)
if (bare) {
git("clone --bare -- . $destination")
}
else {
git("clone -- . $destination")
}
cd(destination)
setupDefaultUsername()
}
internal fun setupDefaultUsername(project: Project) {
setupUsername(project, USER_NAME, USER_EMAIL)
}
internal fun GitPlatformTest.setupDefaultUsername() {
setupDefaultUsername(project)
}
internal fun setupUsername(project: Project, name: String, email: String) {
assertFalse("Can not set empty user name ", name.isEmpty())
assertFalse("Can not set empty user email ", email.isEmpty())
git(project, "config user.name '$name'")
git(project, "config user.email '$email'")
}
private fun disableGitGc(project: Project) {
git(project, "config gc.auto 0")
}
/**
* Creates a Git repository in the given root directory;
* registers it in the Settings;
* return the [GitRepository] object for this newly created repository.
*/
fun createRepository(project: Project, root: String) = createRepository(project, Paths.get(root), true)
internal fun createRepository(project: Project, root: Path, makeInitialCommit: Boolean): GitRepository {
initRepo(project, root, makeInitialCommit)
LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root.resolve(GitUtil.DOT_GIT))!!
return registerRepo(project, root)
}
internal fun GitRepository.createSubRepository(name: String): GitRepository {
val childRoot = File(this.root.path, name)
HeavyPlatformTestCase.assertTrue(childRoot.mkdir())
val repo = createRepository(this.project, childRoot.path)
this.tac(".gitignore", name)
return repo
}
internal fun registerRepo(project: Project, root: Path): GitRepository {
val vcsManager = ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl
vcsManager.setDirectoryMapping(root.toString(), GitVcs.NAME)
Files.createDirectories(root)
val file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root)
assertFalse("There are no VCS roots. Active VCSs: ${vcsManager.allActiveVcss}", vcsManager.allVcsRoots.isEmpty())
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(file)
assertThat(repository).describedAs("Couldn't find repository for root $root").isNotNull()
cd(root)
disableGitGc(project)
return repository!!
}
fun assumeSupportedGitVersion(vcs: GitVcs) {
val version = vcs.version
assumeTrue("Unsupported Git version: $version", version.isSupported)
}
fun GitPlatformTest.readAllRefs(root: VirtualFile, objectsFactory: VcsLogObjectsFactory): Set<VcsRef> {
val refs = git("log --branches --tags --no-walk --format=%H%d --decorate=full").lines()
val result = mutableSetOf<VcsRef>()
for (ref in refs) {
result.addAll(RefParser(objectsFactory).parseCommitRefs(ref, root))
}
return result
}
fun GitPlatformTest.makeCommit(file: String): String {
append(file, "some content")
addCommit("some message")
return last()
}
fun GitPlatformTest.makeCommit(author: VcsUser, file: String): String {
setupUsername(project, author.name, author.email)
val commit = modify(file)
setupDefaultUsername(project)
return commit
}
fun findGitLogProvider(project: Project): GitLogProvider {
val providers = VcsLogProvider.LOG_PROVIDER_EP.getExtensions(project)
.filter { provider -> provider.supportedVcs == GitVcs.getKey() }
assertEquals("Incorrect number of GitLogProviders", 1, providers.size)
return providers[0] as GitLogProvider
}
internal fun makePushSpec(repository: GitRepository, from: String, to: String): PushSpec<GitPushSource, GitPushTarget> {
val source = repository.branches.findLocalBranch(from)!!
var target: GitRemoteBranch? = repository.branches.findBranchByName(to) as GitRemoteBranch?
val newBranch: Boolean
if (target == null) {
val firstSlash = to.indexOf('/')
val remote = GitUtil.findRemoteByName(repository, to.substring(0, firstSlash))!!
target = GitStandardRemoteBranch(remote, to.substring(firstSlash + 1))
newBranch = true
}
else {
newBranch = false
}
return PushSpec(GitPushSource.create(source), GitPushTarget(target, newBranch))
}
internal fun GitRepository.resolveConflicts() {
cd(this)
this.git("add -u .")
}
internal fun getPrettyFormatTagForFullCommitMessage(project: Project): String {
return if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) "%B" else "%s%n%n%-b"
}
| apache-2.0 | 66e3d2ca4715a60b908de955cf900926 | 34.401914 | 140 | 0.759832 | 4.023382 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/JpsLike.kt | 2 | 6681 | // 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.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
interface ModuleTestEntity : WorkspaceEntityWithPersistentId {
val name: String
val contentRoots: List<@Child ContentRootTestEntity>
val facets: List<@Child FacetTestEntity>
override val persistentId: PersistentEntityId<WorkspaceEntityWithPersistentId>
get() = ModuleTestEntityPersistentId(name)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ModuleTestEntity, ModifiableWorkspaceEntity<ModuleTestEntity>, ObjBuilder<ModuleTestEntity> {
override var entitySource: EntitySource
override var name: String
override var contentRoots: List<ContentRootTestEntity>
override var facets: List<FacetTestEntity>
}
companion object : Type<ModuleTestEntity, Builder>() {
operator fun invoke(name: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleTestEntity {
val builder = builder()
builder.name = name
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ModuleTestEntity, modification: ModuleTestEntity.Builder.() -> Unit) = modifyEntity(
ModuleTestEntity.Builder::class.java, entity, modification)
//endregion
interface ContentRootTestEntity : WorkspaceEntity {
val module: ModuleTestEntity
val sourceRootOrder: @Child SourceRootTestOrderEntity?
val sourceRoots: List<@Child SourceRootTestEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ContentRootTestEntity, ModifiableWorkspaceEntity<ContentRootTestEntity>, ObjBuilder<ContentRootTestEntity> {
override var entitySource: EntitySource
override var module: ModuleTestEntity
override var sourceRootOrder: SourceRootTestOrderEntity?
override var sourceRoots: List<SourceRootTestEntity>
}
companion object : Type<ContentRootTestEntity, Builder>() {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ContentRootTestEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ContentRootTestEntity, modification: ContentRootTestEntity.Builder.() -> Unit) = modifyEntity(
ContentRootTestEntity.Builder::class.java, entity, modification)
//endregion
interface SourceRootTestOrderEntity : WorkspaceEntity {
val data: String
val contentRoot: ContentRootTestEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SourceRootTestOrderEntity, ModifiableWorkspaceEntity<SourceRootTestOrderEntity>, ObjBuilder<SourceRootTestOrderEntity> {
override var entitySource: EntitySource
override var data: String
override var contentRoot: ContentRootTestEntity
}
companion object : Type<SourceRootTestOrderEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootTestOrderEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SourceRootTestOrderEntity,
modification: SourceRootTestOrderEntity.Builder.() -> Unit) = modifyEntity(
SourceRootTestOrderEntity.Builder::class.java, entity, modification)
//endregion
interface SourceRootTestEntity : WorkspaceEntity {
val data: String
val contentRoot: ContentRootTestEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SourceRootTestEntity, ModifiableWorkspaceEntity<SourceRootTestEntity>, ObjBuilder<SourceRootTestEntity> {
override var entitySource: EntitySource
override var data: String
override var contentRoot: ContentRootTestEntity
}
companion object : Type<SourceRootTestEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootTestEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SourceRootTestEntity, modification: SourceRootTestEntity.Builder.() -> Unit) = modifyEntity(
SourceRootTestEntity.Builder::class.java, entity, modification)
//endregion
data class ModuleTestEntityPersistentId(val name: String) : PersistentEntityId<ModuleTestEntity> {
override val presentableName: String
get() = name
}
data class FacetTestEntityPersistentId(val name: String) : PersistentEntityId<FacetTestEntity> {
override val presentableName: String
get() = name
}
interface FacetTestEntity : WorkspaceEntityWithPersistentId {
val data: String
val moreData: String
val module: ModuleTestEntity
override val persistentId: PersistentEntityId<WorkspaceEntityWithPersistentId>
get() = FacetTestEntityPersistentId(data)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetTestEntity, ModifiableWorkspaceEntity<FacetTestEntity>, ObjBuilder<FacetTestEntity> {
override var entitySource: EntitySource
override var data: String
override var moreData: String
override var module: ModuleTestEntity
}
companion object : Type<FacetTestEntity, Builder>() {
operator fun invoke(data: String, moreData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetTestEntity {
val builder = builder()
builder.data = data
builder.moreData = moreData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetTestEntity, modification: FacetTestEntity.Builder.() -> Unit) = modifyEntity(
FacetTestEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | 0218b70c868aeb52be9bddf622ba6e2f | 36.116667 | 142 | 0.768148 | 5.581454 | false | true | false | false |
ozbek/quran_android | app/src/main/java/com/quran/labs/androidquran/view/JuzView.kt | 2 | 3157 | package com.quran.labs.androidquran.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.text.TextPaint
import androidx.core.content.ContextCompat
import com.quran.labs.androidquran.R
class JuzView(
context: Context,
type: Int,
private val overlayText: String?
) : Drawable() {
private var radius = 0
private var circleY = 0
private val percentage: Int
private var textOffset = 0f
private lateinit var circleRect: RectF
private val circlePaint = Paint()
private var overlayTextPaint: TextPaint? = null
private val circleBackgroundPaint = Paint()
init {
val resources = context.resources
val circleColor = ContextCompat.getColor(context, R.color.accent_color)
val circleBackground = ContextCompat.getColor(context, R.color.accent_color_dark)
circlePaint.apply {
style = Paint.Style.FILL
color = circleColor
isAntiAlias = true
}
circleBackgroundPaint.apply {
style = Paint.Style.FILL
color = circleBackground
isAntiAlias = true
}
if (!overlayText.isNullOrEmpty()) {
val textPaintColor = ContextCompat.getColor(context, R.color.header_background)
val textPaintSize = resources.getDimensionPixelSize(R.dimen.juz_overlay_text_size)
overlayTextPaint = TextPaint()
overlayTextPaint?.apply {
isAntiAlias = true
color = textPaintColor
textSize = textPaintSize.toFloat()
textAlign = Paint.Align.CENTER
}
overlayTextPaint?.let { textPaint ->
val textHeight = textPaint.descent() - textPaint.ascent()
textOffset = textHeight / 2 - textPaint.descent()
}
}
this.percentage = when (type) {
TYPE_JUZ -> 100
TYPE_THREE_QUARTERS -> 75
TYPE_HALF -> 50
TYPE_QUARTER -> 25
else -> 0
}
}
override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) {
super.setBounds(left, top, right, bottom)
radius = (right - left) / 2
val yOffset = (bottom - top - 2 * radius) / 2
circleY = radius + yOffset
circleRect = RectF(
left.toFloat(), (top + yOffset).toFloat(),
right.toFloat(), (top + yOffset + 2 * radius).toFloat()
)
}
override fun draw(canvas: Canvas) {
canvas.drawCircle(radius.toFloat(), circleY.toFloat(), radius.toFloat(), circleBackgroundPaint)
canvas.drawArc(
circleRect, -90f,
(3.6 * percentage).toFloat(), true, circlePaint
)
overlayTextPaint?.let { textPaint ->
if (overlayText != null) {
canvas.drawText(
overlayText, circleRect.centerX(),
circleRect.centerY() + textOffset, textPaint
)
}
}
}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(cf: ColorFilter?) {}
companion object {
const val TYPE_JUZ = 1
const val TYPE_QUARTER = 2
const val TYPE_HALF = 3
const val TYPE_THREE_QUARTERS = 4
}
}
| gpl-3.0 | ae6775bf6ebd8fc387c5fe21a3bdf383 | 27.1875 | 99 | 0.673107 | 4.354483 | false | false | false | false |
sewerk/Bill-Calculator | app/src/main/java/pl/srw/billcalculator/form/fragment/FormPresenter.kt | 1 | 4432 | package pl.srw.billcalculator.form.fragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import pl.srw.billcalculator.bill.save.BillSaver
import pl.srw.billcalculator.bill.save.model.NewBillInput
import pl.srw.billcalculator.form.FormVM
import pl.srw.billcalculator.form.FormValueValidator
import pl.srw.billcalculator.form.FormValueValidator.isDatesOrderCorrect
import pl.srw.billcalculator.form.FormValueValidator.isValueFilled
import pl.srw.billcalculator.form.FormValueValidator.isValueOrderCorrect
import pl.srw.billcalculator.type.Provider
import pl.srw.billcalculator.type.Provider.PGNIG
import pl.srw.billcalculator.util.analytics.Analytics
import pl.srw.billcalculator.util.analytics.EventType
import timber.log.Timber
class FormPresenter(
private val view: FormView,
private val provider: Provider,
private val billSaver: BillSaver,
private val historyUpdater: HistoryChangeListener
) {
fun closeButtonClicked() {
Timber.i("Form: Close clicked")
view.hideForm()
}
fun calculateButtonClicked(vm: FormVM) {
Timber.i("Form: Calculate clicked")
view.cleanErrorsOnFields()
val singleReadings = provider == PGNIG || vm.isSingleReadingsProcessing()
val validInput = if (singleReadings) {
isSingleReadingsFormValid(
vm.readingFrom, vm.readingTo,
vm.dateFrom, vm.dateTo
)
} else {
isDoubleReadingsFormValid(
vm.readingDayFrom, vm.readingDayTo,
vm.readingNightFrom, vm.readingNightTo,
vm.dateFrom, vm.dateTo
)
}
if (!validInput) return
billSaver.storeBill(NewBillInput.from(vm, singleReadings))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
historyUpdater.onHistoryChanged()
with(view) {
startBillActivity(provider)
hideForm()
}
}
Analytics.event(EventType.CALCULATE, "provider", provider)
}
private fun isSingleReadingsFormValid(
readingFrom: String, readingTo: String,
dateFrom: String, dateTo: String
): Boolean {
return (isValueFilled(readingFrom, onErrorCallback(FormView.Field.READING_FROM))
&& isValueFilled(readingTo, onErrorCallback(FormView.Field.READING_TO))
&& isValueOrderCorrect(readingFrom, readingTo, onErrorCallback(FormView.Field.READING_TO))
&& isDatesOrderCorrect(dateFrom, dateTo, onDateErrorCallback()))
}
private fun isDoubleReadingsFormValid(
readingDayFrom: String, readingDayTo: String,
readingNightFrom: String, readingNightTo: String,
dateFrom: String, dateTo: String
): Boolean {
return (isValueFilled(readingDayFrom, onErrorCallback(FormView.Field.READING_DAY_FROM))
&& isValueFilled(readingDayTo, onErrorCallback(FormView.Field.READING_DAY_TO))
&& isValueFilled(readingNightFrom, onErrorCallback(FormView.Field.READING_NIGHT_FROM))
&& isValueFilled(readingNightTo, onErrorCallback(FormView.Field.READING_NIGHT_TO))
&& isValueOrderCorrect(readingDayFrom, readingDayTo, onErrorCallback(FormView.Field.READING_DAY_TO))
&& isValueOrderCorrect(readingNightFrom, readingNightTo, onErrorCallback(FormView.Field.READING_NIGHT_TO))
&& isDatesOrderCorrect(dateFrom, dateTo, onDateErrorCallback()))
}
private fun onErrorCallback(field: FormView.Field) = FormValueValidator.OnErrorCallback { view.showReadingFieldError(field, it) }
private fun onDateErrorCallback() = FormValueValidator.OnErrorCallback(view::showDateFieldError)
interface FormView {
fun showProviderSettings(provider: Provider)
fun hideForm()
fun showReadingFieldError(field: Field, errorMsgRes: Int)
fun showDateFieldError(errorMsgRes: Int)
fun cleanErrorsOnFields()
fun startBillActivity(provider: Provider)
enum class Field {
READING_FROM, READING_TO,
READING_DAY_FROM, READING_DAY_TO,
READING_NIGHT_FROM, READING_NIGHT_TO
}
}
interface HistoryChangeListener {
fun onHistoryChanged()
}
}
| mit | a1851ddd44efe2fee7f2345e7054108e | 37.206897 | 133 | 0.685244 | 4.801733 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedDataClassCopyResultInspection.kt | 2 | 1620 | // 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.ProblemsHolder
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
class UnusedDataClassCopyResultInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val callee = call.calleeExpression ?: return
if (callee.text != "copy") return
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val descriptor = call.getResolvedCall(context)?.resultingDescriptor ?: return
val receiver = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter ?: return
if ((receiver.value as? ImplicitClassReceiver)?.classDescriptor?.isData != true) return
if (call.getQualifiedExpressionForSelectorOrThis().isUsedAsExpression(context)) return
holder.registerProblem(callee, KotlinBundle.message("inspection.unused.result.of.data.class.copy"))
})
}
| apache-2.0 | e80f9d506c5c8ec0131ec50edfd901f6 | 61.307692 | 158 | 0.801852 | 5.031056 | false | false | false | false |
zsmb13/MaterialDrawerKt | library/src/main/java/co/zsmb/materialdrawerkt/draweritems/BadgeKt.kt | 1 | 13389 | @file:Suppress("RedundantVisibilityModifier")
package co.zsmb.materialdrawerkt.draweritems
import android.graphics.drawable.Drawable
import co.zsmb.materialdrawerkt.DrawerMarker
import co.zsmb.materialdrawerkt.draweritems.badgeable.BadgeableKt
import co.zsmb.materialdrawerkt.nonReadable
import com.mikepenz.materialdrawer.holder.BadgeStyle
import com.mikepenz.materialdrawer.holder.DimenHolder
import com.mikepenz.materialdrawer.holder.StringHolder
/**
* Adds a badge with the given [text].
*/
@Suppress("DEPRECATION")
public fun BadgeableKt.badge(text: String = "", setup: BadgeKt.() -> Unit = {}) {
val badge = BadgeKt(text)
badge.setup()
this.badgeHolder = badge.holder
this.badgeStyle = badge.style
}
@DrawerMarker
public class BadgeKt(text: String) {
//region Builder basics
internal val style = BadgeStyle()
internal var holder = StringHolder(text)
//endregion
//region BadgeStyle methods
/**
* The background of the badge as a Drawable.
*
* Non-readable property. Wraps the [BadgeStyle.withBadgeBackground] method.
*/
public var backgroundDrawable: Drawable
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withBadgeBackground(value)
}
/**
* The color of the badge, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withColor] method.
*/
public var color: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColor(value.toInt())
}
/**
* The color of the badge when it's tapped, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withColorPressed] method.
*/
public var colorPressed: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorPressed(value.toInt())
}
/**
* The color of the badge when it's tapped, as a a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withColorPressedRes] method.
*/
public var colorPressedRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorPressedRes(value)
}
/**
* The color of the badge, as a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withColor] method.
*/
public var colorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorRes(value)
}
/**
* The corner radius of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withCornersDp] method.
*/
public var cornersDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCornersDp(value)
}
/**
* The corner radius of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withCorners] method.
*/
public var cornersPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCorners(value)
}
/**
* The corner radius of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withCorners] method.
*/
public var cornersRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCorners(DimenHolder.fromResource(value))
}
/**
* The background of the badge as a GradientDrawable resource.
*
* Non-readable property. Wraps the [BadgeStyle.withGradientDrawable] method.
*/
public var gradientDrawableRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withGradientDrawable(value)
}
/**
* The minimum width of the badge (more precisely, the badge's text), in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(DimenHolder.fromDp(value))
}
/**
* The minimum width of the badge (more precisely, the badge's text), in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(value)
}
/**
* The minimum width of the badge (more precisely, the badge's text), as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(DimenHolder.fromResource(value))
}
/**
* The padding of all sides of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
paddingHorizontalDp = value
paddingVerticalDp = value
}
/**
* The horizontal padding of the badge, in dps.
*
* Replacement for paddingLeftRightDp.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightDp] method.
*/
public var paddingHorizontalDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightDp(value)
}
/**
* The horizontal padding of the badge, in pixels.
*
* Replacement for paddingLeftRightPx.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightPx] method.
*/
public var paddingHorizontalPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightPx(value)
}
/**
* The horizontal padding of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightRes] method.
*/
public var paddingHorizontalRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightRes(value)
}
/**
* The padding of the left and right sides of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightDp] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingHorizontalDp"),
message = "Use paddingHorizontalDp instead")
public var paddingLeftRightDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightDp(value)
}
/**
* The padding of the left and right sides of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightPx] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingHorizontalPx"),
message = "Use paddingHorizontalPx instead")
public var paddingLeftRightPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightPx(value)
}
/**
* The padding of all sides of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPadding(value)
}
/**
* The padding of all sides of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
paddingHorizontalRes = value
paddingVerticalRes = value
}
/**
* The padding of the top and bottom of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomDp] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingVerticalDp"),
message = "Use paddingVerticalDp instead")
public var paddingTopBottomDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomDp(value)
}
/**
* The padding of the top and bottom of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomPx] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingVerticalPx"),
message = "Use paddingVerticalPx instead")
public var paddingTopBottomPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomPx(value)
}
/**
* The vertical padding of the badge, in dps.
*
* Replacement for paddingTopBottomDp.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomDp] method.
*/
public var paddingVerticalDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomDp(value)
}
/**
* The vertical padding of the badge, in pixels.
*
* Replacement for paddingTopBottomPx.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomPx] method.
*/
public var paddingVerticalPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomPx(value)
}
/**
* The vertical padding of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomRes] method.
*/
public var paddingVerticalRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomRes(value)
}
/**
* The text of the badge as a String.
*
* Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method.
*/
public var text: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
holder = StringHolder(value)
}
/**
* The color of the badge's text, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withTextColor] method.
*/
public var textColor: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withTextColor(value.toInt())
}
/**
* The color of the badge's text, as a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withTextColorRes] method.
*/
public var textColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withTextColorRes(value)
}
/**
* The text of the badge as a String resource.
*
* Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method.
*/
public var textRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
holder.textRes = value
}
//endregion
}
| apache-2.0 | fa17695afb7c0a0cd92602421c493db2 | 31.816176 | 114 | 0.625887 | 4.701194 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/ktx/TextView.kt | 3 | 1496 | @file:JvmName("TextViewUtils")
package org.schabi.newpipe.ktx
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.util.Log
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.animation.addListener
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import org.schabi.newpipe.MainActivity
private const val TAG = "TextViewUtils"
/**
* Animate the text color of any view that extends [TextView] (Buttons, EditText...).
*
* @param duration the duration of the animation
* @param colorStart the text color to start with
* @param colorEnd the text color to end with
*/
fun TextView.animateTextColor(duration: Long, @ColorInt colorStart: Int, @ColorInt colorEnd: Int) {
if (MainActivity.DEBUG) {
Log.d(
TAG,
"animateTextColor() called with: " +
"view = [" + this + "], duration = [" + duration + "], " +
"colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"
)
}
val viewPropertyAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorStart, colorEnd)
viewPropertyAnimator.interpolator = FastOutSlowInInterpolator()
viewPropertyAnimator.duration = duration
viewPropertyAnimator.addUpdateListener { setTextColor(it.animatedValue as Int) }
viewPropertyAnimator.addListener(onCancel = { setTextColor(colorEnd) }, onEnd = { setTextColor(colorEnd) })
viewPropertyAnimator.start()
}
| gpl-3.0 | 6a620be444ce5399f0340e24a97e8bfb | 38.368421 | 111 | 0.718583 | 4.734177 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ApiMetadataPlugin.kt | 1 | 6236 | /*
* Copyright 2018 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.gradlebuild.packaging
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.WriteProperties
import org.gradle.internal.classloader.ClassLoaderFactory
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.build.ReproduciblePropertiesWriter
import com.thoughtworks.qdox.JavaProjectBuilder
import com.thoughtworks.qdox.library.SortedClassLibraryBuilder
import com.thoughtworks.qdox.model.JavaMethod
import accessors.java
import org.gradle.kotlin.dsl.*
import org.gradle.kotlin.dsl.support.serviceOf
import java.net.URLClassLoader
open class ApiMetadataExtension(project: Project) {
val sources = project.files()
val includes = project.objects.listProperty<String>()
val excludes = project.objects.listProperty<String>()
val classpath = project.files()
init {
includes.set(listOf())
excludes.set(listOf())
}
}
/**
* Generates Gradle API metadata resources.
*
* Include and exclude patterns for the Gradle API.
* Parameter names for the Gradle API.
*/
open class ApiMetadataPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val extension =
extensions.create("apiMetadata", ApiMetadataExtension::class, project)
val apiDeclarationTask =
tasks.register("apiDeclarationResource", WriteProperties::class) {
property("includes", extension.includes.get().joinToString(":"))
property("excludes", extension.excludes.get().joinToString(":"))
outputFile = generatedPropertiesFileFor(apiDeclarationFilename).get().asFile
}
val apiParameterNamesTask =
tasks.register("apiParameterNamesResource", ParameterNamesResourceTask::class) {
sources.from(extension.sources.asFileTree.matching {
include(extension.includes.get())
exclude(extension.excludes.get())
})
classpath.from(extension.classpath)
destinationFile.set(generatedPropertiesFileFor(apiParametersFilename))
}
mapOf(
apiDeclarationTask to generatedDirFor(apiDeclarationFilename),
apiParameterNamesTask to generatedDirFor(apiParametersFilename)
).forEach { task, dir ->
java.sourceSets["main"].output.dir(mapOf("builtBy" to task), dir)
}
}
private
fun Project.generatedDirFor(name: String) =
layout.buildDirectory.dir("generated-resources/$name")
private
fun Project.generatedPropertiesFileFor(name: String) =
layout.buildDirectory.file("generated-resources/$name/$name.properties")
}
private
const val apiDeclarationFilename = "gradle-api-declaration"
private
const val apiParametersFilename = "gradle-api-parameter-names"
@CacheableTask
open class ParameterNamesResourceTask : DefaultTask() {
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
val sources = project.files()
@InputFiles
@Classpath
val classpath = project.files()
@OutputFile
@PathSensitive(PathSensitivity.NONE)
val destinationFile = project.objects.fileProperty()
@TaskAction
fun generate() {
isolatedClassLoaderFor(classpath).use { loader ->
val qdoxBuilder = JavaProjectBuilder(sortedClassLibraryBuilderWithClassLoaderFor(loader))
val qdoxSources = sources.asSequence().mapNotNull { qdoxBuilder.addSource(it) }
val properties = qdoxSources
.flatMap { it.classes.asSequence().filter { it.isPublic } }
.flatMap { it.methods.asSequence().filter { it.isPublic && it.parameterTypes.isNotEmpty() } }
.map { method ->
fullyQualifiedSignatureOf(method) to commaSeparatedParameterNamesOf(method)
}.toMap(linkedMapOf())
write(properties)
}
}
private
fun write(properties: LinkedHashMap<String, String>) {
destinationFile.get().asFile.let { file ->
file.parentFile.mkdirs()
ReproduciblePropertiesWriter.store(properties, file)
}
}
private
fun fullyQualifiedSignatureOf(method: JavaMethod): String =
"${method.declaringClass.binaryName}.${method.name}(${signatureOf(method)})"
private
fun signatureOf(method: JavaMethod): String =
method.parameters.joinToString(separator = ",") { p ->
if (p.isVarArgs || p.javaClass.isArray) "${p.type.binaryName}[]"
else p.type.binaryName
}
private
fun commaSeparatedParameterNamesOf(method: JavaMethod) =
method.parameters.joinToString(separator = ",") { it.name }
private
fun sortedClassLibraryBuilderWithClassLoaderFor(loader: ClassLoader): SortedClassLibraryBuilder =
SortedClassLibraryBuilder().apply {
appendClassLoader(loader)
}
private
fun isolatedClassLoaderFor(classpath: FileCollection) =
classLoaderFactory.createIsolatedClassLoader("parameter names", DefaultClassPath.of(classpath.files)) as URLClassLoader
private
val classLoaderFactory
get() = project.serviceOf<ClassLoaderFactory>()
}
| apache-2.0 | 164641c1a41ec5be6afa26e12a22f277 | 31.821053 | 127 | 0.699326 | 4.731411 | false | false | false | false |
sewerk/Bill-Calculator | app/src/main/java/pl/srw/billcalculator/bill/calculation/PgeG11CalculatedBill.kt | 1 | 1315 | package pl.srw.billcalculator.bill.calculation
import org.threeten.bp.LocalDate
import pl.srw.billcalculator.pojo.IPgePrices
class PgeG11CalculatedBill(
readingFrom: Int,
readingTo: Int,
dateFrom: LocalDate,
dateTo: LocalDate,
prices: IPgePrices
) : CalculatedEnergyBill(
dateFrom,
dateTo,
prices.oplataAbonamentowa,
prices.oplataPrzejsciowa,
prices.oplataStalaZaPrzesyl,
prices
) {
override val totalConsumption = readingTo - readingFrom
val consumptionFromJuly16 = countConsumptionPartFromJuly16(dateFrom, dateTo, totalConsumption)
val zaEnergieCzynnaNetCharge = countNetAndAddToSum(prices.zaEnergieCzynna, totalConsumption)
val skladnikJakosciowyNetCharge = countNetAndAddToSum(prices.skladnikJakosciowy, totalConsumption)
val oplataSieciowaNetCharge = countNetAndAddToSum(prices.oplataSieciowa, totalConsumption)
val oplataOzeNetCharge = countNetAndAddToSum(prices.oplataOze, (consumptionFromJuly16 * 0.001).toString())
val zaEnergieCzynnaVatCharge = countVatAndAddToSum(zaEnergieCzynnaNetCharge)
val skladnikJakosciowyVatCharge = countVatAndAddToSum(skladnikJakosciowyNetCharge)
val oplataSieciowaVatCharge = countVatAndAddToSum(oplataSieciowaNetCharge)
val oplataOzeVatCharge = countVatAndAddToSum(oplataOzeNetCharge)
}
| mit | 91137cb94e31188da7df044dd16fd16d | 38.848485 | 110 | 0.809125 | 4.283388 | false | false | false | false |
JetBrains/xodus | entity-store/src/main/kotlin/jetbrains/exodus/entitystore/iterate/binop/SortedIterator.kt | 1 | 1660 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.entitystore.iterate.binop
import jetbrains.exodus.entitystore.EntityId
import jetbrains.exodus.entitystore.EntityIterator
import java.util.*
internal fun toEntityIdIterator(it: EntityIterator): Iterator<EntityId?> {
return object : Iterator<EntityId?> {
override fun hasNext() = it.hasNext()
override fun next() = it.nextId()
}
}
internal fun toSortedEntityIdIterator(it: EntityIterator): Iterator<EntityId?> {
var array = arrayOfNulls<EntityId>(8)
var size = 0
while (it.hasNext()) {
if (size == array.size) {
array = array.copyOf(size * 2)
}
array[size++] = it.nextId()
}
if (size > 1) {
Arrays.sort(array, 0, size) { o1, o2 ->
when {
o1 == null -> 1
o2 == null -> -1
else -> o1.compareTo(o2)
}
}
}
return object : Iterator<EntityId?> {
var i = 0
override fun hasNext() = i < size
override fun next() = array[i++]
}
} | apache-2.0 | 941c6a238e6d7b83badea8fea028dc80 | 28.660714 | 80 | 0.628916 | 4.078624 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt | 1 | 41524 | // 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.jps.build
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.LightVirtualFile
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.io.Decompressor
import com.intellij.util.io.ZipUtil
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.api.CanceledStatus
import org.jetbrains.jps.builders.BuildResult
import org.jetbrains.jps.builders.CompileScopeTestBuilder
import org.jetbrains.jps.builders.TestProjectBuilderLogger
import org.jetbrains.jps.builders.impl.BuildDataPathsImpl
import org.jetbrains.jps.builders.logging.BuildLoggingManager
import org.jetbrains.jps.cmdline.ProjectDescriptor
import org.jetbrains.jps.devkit.model.JpsPluginModuleType
import org.jetbrains.jps.incremental.BuilderRegistry
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.IncProjectBuilder
import org.jetbrains.jps.incremental.ModuleLevelBuilder
import org.jetbrains.jps.incremental.messages.BuildMessage
import org.jetbrains.jps.incremental.messages.CompilerMessage
import org.jetbrains.jps.model.JpsModuleRootModificationUtil
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaDependencyScope
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import org.jetbrains.kotlin.cli.common.Usage
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.JvmCodegenUtil
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.KotlinCompilerVersion.TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.jps.build.KotlinJpsBuildTestBase.LibraryDependency.*
import org.jetbrains.kotlin.jps.incremental.CacheAttributesDiff
import org.jetbrains.kotlin.jps.model.kotlinCommonCompilerArguments
import org.jetbrains.kotlin.jps.model.kotlinCompilerArguments
import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.junit.Assert
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.net.URLClassLoader
import java.util.*
import java.util.zip.ZipOutputStream
open class KotlinJpsBuildTest : KotlinJpsBuildTestBase() {
companion object {
private const val ADDITIONAL_MODULE_NAME = "module2"
private val EXCLUDE_FILES = arrayOf("Excluded.class", "YetAnotherExcluded.class")
private val NOTHING = arrayOf<String>()
private const val KOTLIN_JS_LIBRARY = "jslib-example"
private const val KOTLIN_JS_LIBRARY_JAR = "$KOTLIN_JS_LIBRARY.jar"
private val PATH_TO_KOTLIN_JS_LIBRARY =
TEST_DATA_PATH + "general/KotlinJavaScriptProjectWithDirectoryAsLibrary/" + KOTLIN_JS_LIBRARY
private fun getMethodsOfClass(classFile: File): Set<String> {
val result = TreeSet<String>()
ClassReader(FileUtil.loadFileBytes(classFile)).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<String>?
): MethodVisitor? {
result.add(name)
return null
}
}, 0)
return result
}
@JvmStatic
protected fun klass(moduleName: String, classFqName: String): String {
val outputDirPrefix = "out/production/$moduleName/"
return outputDirPrefix + classFqName.replace('.', '/') + ".class"
}
@JvmStatic
protected fun module(moduleName: String): String {
return "out/production/$moduleName/${JvmCodegenUtil.getMappingFileName(moduleName)}"
}
}
protected fun doTest() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
}
protected fun doTestWithRuntime() {
initProject(JVM_FULL_RUNTIME)
buildAllModules().assertSuccessful()
}
protected fun doTestWithKotlinJavaScriptLibrary() {
initProject(JS_STDLIB)
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
buildAllModules().assertSuccessful()
}
fun testKotlinProject() {
doTest()
checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "Test1Kt"))
}
fun testSourcePackagePrefix() {
doTest()
}
fun testSourcePackageLongPrefix() {
initProject(JVM_MOCK_RUNTIME)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about invalid package prefix in module 2 is expected: $warnings", 1, warnings.size)
assertEquals("Invalid package prefix name is ignored: invalid-prefix.test", warnings.first().messageText)
}
fun testSourcePackagePrefixWithInnerClasses() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProject() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, pathsToDelete = k2jsOutput(PROJECT_NAME))
}
private fun k2jsOutput(vararg moduleNames: String): Array<String> {
val moduleNamesSet = moduleNames.toSet()
val list = mutableListOf<String>()
myProject.modules.forEach { module ->
if (module.name in moduleNamesSet) {
val outputDir = module.productionBuildTarget.outputDir!!
list.add(toSystemIndependentName(File("$outputDir/${module.name}.js").relativeTo(workDir).path))
list.add(toSystemIndependentName(File("$outputDir/${module.name}.meta.js").relativeTo(workDir).path))
val kjsmFiles = outputDir.walk().filter { it.isFile && it.extension.equals("kjsm", ignoreCase = true) }
list.addAll(kjsmFiles.map { toSystemIndependentName(it.relativeTo(workDir).path) })
}
}
return list.toTypedArray()
}
fun testKotlinJavaScriptProjectNewSourceRootTypes() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
}
fun testKotlinJavaScriptProjectWithCustomOutputPaths() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList(File(workDir, "target"))
}
fun testKotlinJavaScriptProjectWithSourceMap() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText()
val expectedPath = "prefix-dir/src/pkg/test1.kt"
assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\""))
val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map")
assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists())
}
fun testKotlinJavaScriptProjectWithSourceMapRelativePaths() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText()
val expectedPath = "../../../src/pkg/test1.kt"
assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\""))
val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map")
assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists())
}
fun testKotlinJavaScriptProjectWithTwoModules() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
checkWhen(touch("module2/src/module2.kt"), null, k2jsOutput(ADDITIONAL_MODULE_NAME))
checkWhen(arrayOf(touch("src/test1.kt"), touch("module2/src/module2.kt")), null, k2jsOutput(PROJECT_NAME, ADDITIONAL_MODULE_NAME))
}
@WorkingDir("KotlinJavaScriptProjectWithTwoModules")
fun testKotlinJavaScriptProjectWithTwoModulesAndWithLibrary() {
initProject()
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
addKotlinJavaScriptStdlibDependency()
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithDirectoryAsStdlib() {
initProject()
val jslibJar = KotlinArtifacts.instance.kotlinStdlibJs
val jslibDir = File(workDir, "KotlinJavaScript")
try {
Decompressor.Zip(jslibJar).extract(jslibDir.toPath())
} catch (ex: IOException) {
throw IllegalStateException(ex.message)
}
addDependency("KotlinJavaScript", jslibDir)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithDirectoryAsLibrary() {
initProject(JS_STDLIB)
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY))
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibrary() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryCustomOutputDir() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryNoCopy() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryAndErrors() {
initProject(JS_STDLIB)
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
buildAllModules().assertFailed()
checkOutputFilesList()
}
fun testKotlinJavaScriptProjectWithEmptyDependencies() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptInternalFromSpecialRelatedModule() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTests() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTestsAndSeparateTestAndSrcModuleDependencies() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTestsAndTestAndSrcModuleDependency() {
initProject(JS_STDLIB)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size)
}
fun testKotlinJavaScriptProjectWithTwoSrcModuleDependency() {
initProject(JS_STDLIB)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size)
}
fun testExcludeFolderInSourceRoot() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
checkWhen(
touch("src/foo.kt"), null,
arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject"))
)
}
fun testExcludeModuleFolderInSourceRootOfAnotherModule() {
doTest()
for (module in myProject.modules) {
assertFilesExistInOutput(module, "Foo.class")
}
checkWhen(
touch("src/foo.kt"), null,
arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject"))
)
checkWhen(
touch("src/module2/src/foo.kt"), null,
arrayOf(klass("module2", "Foo"), module("module2"))
)
}
fun testExcludeFileUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
}
checkWhen(touch("src/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/dir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testExcludeFolderNonRecursivelyUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
checkWhen(touch("src/dir/subdir/bar.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Bar")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
checkWhen(touch("src/dir/subdir/bar.kt"), null, allClasses)
}
checkWhen(touch("src/dir/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/dir/subdir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testExcludeFolderRecursivelyUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
}
checkWhen(touch("src/exclude/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/YetAnotherExcluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/subdir/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/subdir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testKotlinProjectTwoFilesInOnePackage() {
doTest()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "_DefaultPackage"))
checkWhen(touch("src/test2.kt"), null, packageClasses("kotlinProject", "src/test2.kt", "_DefaultPackage"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/test1.kt"), null, allClasses)
checkWhen(touch("src/test2.kt"), null, allClasses)
}
checkWhen(
arrayOf(del("src/test1.kt"), del("src/test2.kt")), NOTHING,
arrayOf(
packagePartClass("kotlinProject", "src/test1.kt", "_DefaultPackage"),
packagePartClass("kotlinProject", "src/test2.kt", "_DefaultPackage"),
module("kotlinProject")
)
)
assertFilesNotExistInOutput(myProject.modules[0], "_DefaultPackage.class")
}
fun testDefaultLanguageVersionCustomApiVersion() {
initProject(JVM_FULL_RUNTIME)
buildAllModules().assertFailed()
assertEquals(1, myProject.modules.size)
val module = myProject.modules.first()
val args = module.kotlinCompilerArguments
args.apiVersion = "1.4"
myProject.kotlinCommonCompilerArguments = args
buildAllModules().assertSuccessful()
}
fun testKotlinJavaProject() {
doTestWithRuntime()
}
fun testJKJProject() {
doTestWithRuntime()
}
fun testKJKProject() {
doTestWithRuntime()
}
fun testKJCircularProject() {
doTestWithRuntime()
}
fun testJKJInheritanceProject() {
doTestWithRuntime()
}
fun testKJKInheritanceProject() {
doTestWithRuntime()
}
fun testCircularDependenciesNoKotlinFiles() {
doTest()
}
fun testCircularDependenciesDifferentPackages() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
// Check that outputs are located properly
assertFilesExistInOutput(findModule("module2"), "kt1/Kt1Kt.class")
assertFilesExistInOutput(findModule("kotlinProject"), "kt2/Kt2Kt.class")
result.assertSuccessful()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/kt2.kt"), null, packageClasses("kotlinProject", "src/kt2.kt", "kt2.Kt2Kt"))
checkWhen(touch("module2/src/kt1.kt"), null, packageClasses("module2", "module2/src/kt1.kt", "kt1.Kt1Kt"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/kt2.kt"), null, allClasses)
checkWhen(touch("module2/src/kt1.kt"), null, allClasses)
}
}
fun testCircularDependenciesSamePackage() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
// Check that outputs are located properly
val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class")
val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "<clinit>", "a", "getA")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "<clinit>", "b", "getB", "setB")
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage"))
checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("module1/src/a.kt"), null, allClasses)
checkWhen(touch("module2/src/b.kt"), null, allClasses)
}
}
fun testCircularDependenciesSamePackageWithTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
// Check that outputs are located properly
val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class")
val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "<clinit>", "a", "funA", "getA")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "<clinit>", "b", "funB", "getB", "setB")
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage"))
checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage"))
} else {
val allProductionClasses = myProject.outputPaths(tests = false)
checkWhen(touch("module1/src/a.kt"), null, allProductionClasses)
checkWhen(touch("module2/src/b.kt"), null, allProductionClasses)
}
}
fun testInternalFromAnotherModule() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testInternalFromSpecialRelatedModule() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val classpath = listOf("out/production/module1", "out/test/module2").map { File(workDir, it).toURI().toURL() }.toTypedArray()
val clazz = URLClassLoader(classpath).loadClass("test2.BarKt")
clazz.getMethod("box").invoke(null)
}
fun testCircularDependenciesInternalFromAnotherModule() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testCircularDependenciesWrongInternalFromTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testCircularDependencyWithReferenceToOldVersionLib() {
initProject(JVM_MOCK_RUNTIME)
val sources = listOf(File(workDir, "oldModuleLib/src"))
val libraryJar = KotlinCompilerStandalone(sources).compile()
addDependency(
JpsJavaDependencyScope.COMPILE,
listOf(findModule("module1"), findModule("module2")),
false,
"module-lib",
libraryJar,
)
val result = buildAllModules()
result.assertSuccessful()
}
fun testDependencyToOldKotlinLib() {
initProject()
val sources = listOf(File(workDir, "oldModuleLib/src"))
val libraryJar = KotlinCompilerStandalone(sources).compile()
addDependency(JpsJavaDependencyScope.COMPILE, listOf(findModule("module")), false, "module-lib", libraryJar)
addKotlinStdlibDependency()
val result = buildAllModules()
result.assertSuccessful()
}
fun testDevKitProject() {
initProject(JVM_MOCK_RUNTIME)
val module = myProject.modules.single()
assertEquals(module.moduleType, JpsPluginModuleType.INSTANCE)
buildAllModules().assertSuccessful()
assertFilesExistInOutput(module, "TestKt.class")
}
fun testAccessToInternalInProductionFromTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
}
private fun createKotlinJavaScriptLibraryArchive() {
val jarFile = File(workDir, KOTLIN_JS_LIBRARY_JAR)
try {
val zip = ZipOutputStream(FileOutputStream(jarFile))
ZipUtil.addDirToZipRecursively(zip, jarFile, File(PATH_TO_KOTLIN_JS_LIBRARY), "", null, null)
zip.close()
} catch (ex: FileNotFoundException) {
throw IllegalStateException(ex.message)
} catch (ex: IOException) {
throw IllegalStateException(ex.message)
}
}
protected fun checkOutputFilesList(outputDir: File = productionOutputDir) {
if (!expectedOutputFile.exists()) {
expectedOutputFile.writeText("")
throw IllegalStateException("$expectedOutputFile did not exist. Created empty file.")
}
val sb = StringBuilder()
val p = Printer(sb, " ")
outputDir.printFilesRecursively(p)
UsefulTestCase.assertSameLinesWithFile(expectedOutputFile.canonicalPath, sb.toString(), true)
}
private fun File.printFilesRecursively(p: Printer) {
val files = listFiles() ?: return
for (file in files.sortedBy { it.name }) {
when {
file.isFile -> {
p.println(file.name)
}
file.isDirectory -> {
p.println(file.name + "/")
p.pushIndent()
file.printFilesRecursively(p)
p.popIndent()
}
}
}
}
private val productionOutputDir
get() = File(workDir, "out/production")
private fun getOutputDir(moduleName: String): File = File(productionOutputDir, moduleName)
fun testReexportedDependency() {
initProject()
addKotlinStdlibDependency(myProject.modules.filter { module -> module.name == "module2" }, true)
buildAllModules().assertSuccessful()
}
fun testCheckIsCancelledIsCalledOftenEnough() {
val classCount = 30
val methodCount = 30
fun generateFiles() {
val srcDir = File(workDir, "src")
srcDir.mkdirs()
for (i in 0..classCount) {
val code = buildString {
appendLine("package foo")
appendLine("class Foo$i {")
for (j in 0..methodCount) {
appendLine(" fun get${j * j}(): Int = square($j)")
}
appendLine("}")
}
File(srcDir, "Foo$i.kt").writeText(code)
}
}
generateFiles()
initProject(JVM_MOCK_RUNTIME)
var checkCancelledCalledCount = 0
val countingCancelledStatus = CanceledStatus {
checkCancelledCalledCount++
false
}
val logger = TestProjectBuilderLogger()
val buildResult = BuildResult()
buildCustom(countingCancelledStatus, logger, buildResult)
buildResult.assertSuccessful()
assert(checkCancelledCalledCount > classCount) {
"isCancelled should be called at least once per class. Expected $classCount, but got $checkCancelledCalledCount"
}
}
fun testCancelKotlinCompilation() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "foo/Bar.class")
val buildResult = BuildResult()
val canceledStatus = object : CanceledStatus {
var checkFromIndex = 0
override fun isCanceled(): Boolean {
val messages = buildResult.getMessages(BuildMessage.Kind.INFO)
for (i in checkFromIndex until messages.size) {
if (messages[i].messageText.matches("kotlinc-jvm .+ \\(JRE .+\\)".toRegex())) {
return true
}
}
checkFromIndex = messages.size
return false
}
}
touch("src/Bar.kt").apply()
buildCustom(canceledStatus, TestProjectBuilderLogger(), buildResult)
assertCanceled(buildResult)
}
fun testFileDoesNotExistWarning() {
fun absoluteFiles(vararg paths: String): Array<File> =
paths.map { File(it).absoluteFile }.toTypedArray()
initProject(JVM_MOCK_RUNTIME)
val filesToBeReported = absoluteFiles("badroot.jar", "some/test.class")
val otherFiles = absoluteFiles("test/other/file.xml", "some/other/baddir")
addDependency(
JpsJavaDependencyScope.COMPILE,
listOf(findModule("module")),
false,
"LibraryWithBadRoots",
*(filesToBeReported + otherFiles),
)
val result = buildAllModules()
result.assertSuccessful()
val actualWarnings = result.getMessages(BuildMessage.Kind.WARNING).map { it.messageText }
val expectedWarnings = filesToBeReported.map { "Classpath entry points to a non-existent location: $it" }
val expectedText = expectedWarnings.sorted().joinToString("\n")
val actualText = actualWarnings.sorted().joinToString("\n")
Assert.assertEquals(expectedText, actualText)
}
fun testHelp() {
initProject()
val result = buildAllModules()
result.assertSuccessful()
val warning = result.getMessages(BuildMessage.Kind.WARNING).single()
val expectedText = StringUtil.convertLineSeparators(Usage.render(K2JVMCompiler(), K2JVMCompilerArguments()))
Assert.assertEquals(expectedText, warning.messageText)
}
fun testWrongArgument() {
initProject()
val result = buildAllModules()
result.assertFailed()
val errors = result.getMessages(BuildMessage.Kind.ERROR).joinToString("\n\n") { it.messageText }
Assert.assertEquals("Invalid argument: -abcdefghij-invalid-argument", errors)
}
fun testCodeInKotlinPackage() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
val errors = result.getMessages(BuildMessage.Kind.ERROR)
Assert.assertEquals("Only the Kotlin standard library is allowed to use the 'kotlin' package", errors.single().messageText)
}
fun testDoNotCreateUselessKotlinIncrementalCaches() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot
assertFalse(File(storageRoot, "targets/java-test/kotlinProject/kotlin").exists())
assertFalse(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists())
}
fun testDoNotCreateUselessKotlinIncrementalCachesForDependentTargets() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/utils.kt"), null, packageClasses("kotlinProject", "src/utils.kt", "_DefaultPackage"))
} else {
val allClasses = findModule("kotlinProject").outputFilesPaths()
checkWhen(touch("src/utils.kt"), null, allClasses.toTypedArray())
}
val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot
assertFalse(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists())
assertFalse(File(storageRoot, "targets/java-production/module2/kotlin").exists())
}
fun testKotlinProjectWithEmptyProductionOutputDir() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testKotlinProjectWithEmptyTestOutputDir() {
doTest()
}
fun testKotlinProjectWithEmptyProductionOutputDirWithoutSrcDir() {
doTest()
}
fun testKotlinProjectWithEmptyOutputDirInSomeModules() {
doTest()
}
fun testEAPToReleaseIC() {
fun setPreRelease(value: Boolean) {
System.setProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY, value.toString())
}
try {
withIC {
initProject(JVM_MOCK_RUNTIME)
setPreRelease(true)
buildAllModules().assertSuccessful()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt")
touch("src/Foo.kt").apply()
buildAllModules()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Foo.kt")
setPreRelease(false)
touch("src/Foo.kt").apply()
buildAllModules().assertSuccessful()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt")
}
} finally {
System.clearProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY)
}
}
fun testGetDependentTargets() {
fun addModuleWithSourceAndTestRoot(name: String): JpsModule {
return addModule(name, "src/").apply {
contentRootsList.addUrl(JpsPathUtil.pathToUrl("test/"))
addSourceRoot(JpsPathUtil.pathToUrl("test/"), JavaSourceRootType.TEST_SOURCE)
}
}
// c -> b -exported-> a
// c2 -> b2 ------------^
val a = addModuleWithSourceAndTestRoot("a")
val b = addModuleWithSourceAndTestRoot("b")
val c = addModuleWithSourceAndTestRoot("c")
val b2 = addModuleWithSourceAndTestRoot("b2")
val c2 = addModuleWithSourceAndTestRoot("c2")
JpsModuleRootModificationUtil.addDependency(b, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ true)
JpsModuleRootModificationUtil.addDependency(c, b, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
JpsModuleRootModificationUtil.addDependency(b2, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
JpsModuleRootModificationUtil.addDependency(c2, b2, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
val actual = StringBuilder()
buildCustom(CanceledStatus.NULL, TestProjectBuilderLogger(), BuildResult()) {
project.setTestingContext(TestingContext(LookupTracker.DO_NOTHING, object : TestingBuildLogger {
override fun chunkBuildStarted(context: CompileContext, chunk: ModuleChunk) {
actual.append("Targets dependent on ${chunk.targets.joinToString()}:\n")
val dependentRecursively = mutableSetOf<KotlinChunk>()
context.kotlin.getChunk(chunk)!!.collectDependentChunksRecursivelyExportedOnly(dependentRecursively)
dependentRecursively.asSequence().map { it.targets.joinToString() }.sorted().joinTo(actual, "\n")
actual.append("\n---------\n")
}
override fun afterChunkBuildStarted(context: CompileContext, chunk: ModuleChunk) {}
override fun invalidOrUnusedCache(
chunk: KotlinChunk?,
target: KotlinModuleBuildTarget<*>?,
attributesDiff: CacheAttributesDiff<*>
) {
}
override fun addCustomMessage(message: String) {}
override fun buildFinished(exitCode: ModuleLevelBuilder.ExitCode) {}
override fun markedAsDirtyBeforeRound(files: Iterable<File>) {}
override fun markedAsDirtyAfterRound(files: Iterable<File>) {}
}))
}
val expectedFile = File(getCurrentTestDataRoot(), "expected.txt")
KotlinTestUtils.assertEqualsToFile(expectedFile, actual.toString())
}
fun testCustomDestination() {
loadProject(workDir.absolutePath + File.separator + PROJECT_NAME + ".ipr")
addKotlinStdlibDependency()
buildAllModules().apply {
assertSuccessful()
val aClass = File(workDir, "customOut/A.class")
assert(aClass.exists()) { "$aClass does not exist!" }
val warnings = getMessages(BuildMessage.Kind.WARNING)
assert(warnings.isEmpty()) { "Unexpected warnings: \n${warnings.joinToString("\n")}" }
}
}
private fun BuildResult.checkErrors() {
val actualErrors = getMessages(BuildMessage.Kind.ERROR)
.map { it as CompilerMessage }
.map { "${it.messageText} at line ${it.line}, column ${it.column}" }.sorted().joinToString("\n")
val expectedFile = File(getCurrentTestDataRoot(), "errors.txt")
KotlinTestUtils.assertEqualsToFile(expectedFile, actualErrors)
}
private fun getCurrentTestDataRoot() = File(TEST_DATA_PATH + "general/" + getTestName(false))
private fun buildCustom(
canceledStatus: CanceledStatus,
logger: TestProjectBuilderLogger,
buildResult: BuildResult,
setupProject: ProjectDescriptor.() -> Unit = {}
) {
val scopeBuilder = CompileScopeTestBuilder.make().allModules()
val descriptor = this.createProjectDescriptor(BuildLoggingManager(logger))
descriptor.setupProject()
try {
val builder = IncProjectBuilder(descriptor, BuilderRegistry.getInstance(), this.myBuildParams, canceledStatus, true)
builder.addMessageHandler(buildResult)
builder.build(scopeBuilder.build(), false)
} finally {
descriptor.dataManager.flush(false)
descriptor.release()
}
}
private fun assertCanceled(buildResult: BuildResult) {
val list = buildResult.getMessages(BuildMessage.Kind.INFO)
assertTrue("The build has been canceled" == list.last().messageText)
}
private fun findModule(name: String): JpsModule {
for (module in myProject.modules) {
if (module.name == name) {
return module
}
}
throw IllegalStateException("Couldn't find module $name")
}
protected fun checkWhen(action: Action, pathsToCompile: Array<String>?, pathsToDelete: Array<String>?) {
checkWhen(arrayOf(action), pathsToCompile, pathsToDelete)
}
protected fun checkWhen(actions: Array<Action>, pathsToCompile: Array<String>?, pathsToDelete: Array<String>?) {
for (action in actions) {
action.apply()
}
buildAllModules().assertSuccessful()
if (pathsToCompile != null) {
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, *pathsToCompile)
}
if (pathsToDelete != null) {
assertDeleted(*pathsToDelete)
}
}
protected fun packageClasses(moduleName: String, fileName: String, packageClassFqName: String): Array<String> {
return arrayOf(module(moduleName), packagePartClass(moduleName, fileName, packageClassFqName))
}
protected fun packagePartClass(moduleName: String, fileName: String, packageClassFqName: String): String {
val path = FileUtilRt.toSystemIndependentName(File(workDir, fileName).absolutePath)
val fakeVirtualFile = object : LightVirtualFile(path.substringAfterLast('/')) {
override fun getPath(): String {
// strip extra "/" from the beginning
return path.substring(1)
}
}
val packagePartFqName = PackagePartClassUtils.getDefaultPartFqName(FqName(packageClassFqName), fakeVirtualFile)
return klass(moduleName, AsmUtil.internalNameByFqNameWithoutInnerClasses(packagePartFqName))
}
private fun JpsProject.outputPaths(production: Boolean = true, tests: Boolean = true) =
modules.flatMap { it.outputFilesPaths(production = production, tests = tests) }.toTypedArray()
private fun JpsModule.outputFilesPaths(production: Boolean = true, tests: Boolean = true): List<String> {
val outputFiles = arrayListOf<File>()
if (production) {
prodOut.walk().filterTo(outputFiles) { it.isFile }
}
if (tests) {
testsOut.walk().filterTo(outputFiles) { it.isFile }
}
return outputFiles.map { FileUtilRt.toSystemIndependentName(it.relativeTo(workDir).path) }
}
private val JpsModule.prodOut: File
get() = outDir(forTests = false)
private val JpsModule.testsOut: File
get() = outDir(forTests = true)
private fun JpsModule.outDir(forTests: Boolean) =
JpsJavaExtensionService.getInstance().getOutputDirectory(this, forTests)!!
protected enum class Operation {
CHANGE,
DELETE
}
protected fun touch(path: String): Action = Action(Operation.CHANGE, path)
protected fun del(path: String): Action = Action(Operation.DELETE, path)
// TODO inline after KT-3974 will be fixed
protected fun touch(file: File): Unit = change(file.absolutePath)
protected inner class Action constructor(private val operation: Operation, private val path: String) {
fun apply() {
val file = File(workDir, path)
when (operation) {
Operation.CHANGE ->
touch(file)
Operation.DELETE ->
assertTrue("Can not delete file \"" + file.absolutePath + "\"", file.delete())
}
}
}
}
private inline fun <R> withIC(enabled: Boolean = true, fn: () -> R): R {
val isEnabledBackup = IncrementalCompilation.isEnabledForJvm()
IncrementalCompilation.setIsEnabledForJvm(enabled)
try {
return fn()
} finally {
IncrementalCompilation.setIsEnabledForJvm(isEnabledBackup)
}
} | apache-2.0 | 3a6525e892bdd32e2a81a8a57012ed4e | 37.378004 | 158 | 0.659811 | 5.01074 | false | true | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/AbstractBlockCopyFactory.kt | 2 | 1604 | package com.github.kerubistan.kerub.planner.steps.storage.block.copy
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.collection.VirtualStorageDataCollection
import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation
import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import com.github.kerubistan.kerub.planner.steps.storage.gvinum.create.CreateGvinumVolumeFactory
import com.github.kerubistan.kerub.planner.steps.storage.lvm.create.CreateLvFactory
import io.github.kerubistan.kroki.collections.update
import kotlin.reflect.KClass
abstract class AbstractBlockCopyFactory<T : AbstractBlockCopy> : AbstractOperationalStepFactory<T>() {
protected val allocationFactories = listOf(CreateLvFactory, CreateGvinumVolumeFactory)
protected fun createUnallocatedState(state: OperationalState, targetStorage: VirtualStorageDataCollection) =
state.copy(
vStorage = state.vStorage.update(targetStorage.id) { targetStorageColl ->
targetStorageColl.copy(
stat = targetStorageColl.stat.copy(
expectations = listOf(StorageAvailabilityExpectation())
)
)
}
)
final override val expectationHints: Set<KClass<out Expectation>>
get() = setOf(CloneOfStorageExpectation::class)
final override val problemHints: Set<KClass<out Problem>>
get() = setOf()
} | apache-2.0 | 78559b35716d8c037813a8d73a10da86 | 44.857143 | 109 | 0.818579 | 4.467967 | false | false | false | false |
GunoH/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/CodeWithMeClientDownloader.kt | 1 | 36332 | package com.intellij.remoteDev.downloader
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileSystemUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.remoteDev.RemoteDevSystemSettings
import com.intellij.remoteDev.RemoteDevUtilBundle
import com.intellij.remoteDev.connection.CodeWithMeSessionInfoProvider
import com.intellij.remoteDev.connection.StunTurnServerInfo
import com.intellij.remoteDev.util.*
import com.intellij.util.PlatformUtils
import com.intellij.util.application
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.EdtScheduledExecutorService
import com.intellij.util.io.*
import com.intellij.util.io.HttpRequests.HttpStatusException
import com.intellij.util.system.CpuArch
import com.intellij.util.text.VersionComparatorUtil
import com.intellij.util.withFragment
import com.intellij.util.withQuery
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifier
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifierLogger
import com.jetbrains.infra.pgpVerifier.Sha256ChecksumSignatureVerifier
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.fire
import com.sun.jna.platform.win32.Kernel32
import com.sun.jna.platform.win32.WinBase
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.ptr.IntByReference
import org.jetbrains.annotations.ApiStatus
import java.io.ByteArrayInputStream
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.*
import java.nio.file.attribute.FileTime
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.io.path.*
import kotlin.math.min
@ApiStatus.Experimental
object CodeWithMeClientDownloader {
private val LOG = logger<CodeWithMeClientDownloader>()
private const val extractDirSuffix = ".ide.d"
private val config get () = service<JetBrainsClientDownloaderConfigurationProvider>()
private fun isJbrSymlink(file: Path): Boolean = file.name == "jbr" && isSymlink(file)
private fun isSymlink(file: Path): Boolean = FileSystemUtil.getAttributes(file.toFile())?.isSymLink == true
val cwmJbrManifestFilter: (Path) -> Boolean = { !it.isDirectory() || isSymlink(it) }
fun getJetBrainsClientManifestFilter(clientBuildNumber: String): (Path) -> Boolean {
if (isClientWithBundledJre(clientBuildNumber)) {
return { !it.isDirectory() || isSymlink(it) }
} else {
return { !isJbrSymlink(it) && (!it.isDirectory() || isSymlink(it)) }
}
}
private const val minimumClientBuildWithBundledJre = "223.4374"
fun isClientWithBundledJre(clientBuildNumber: String) = VersionComparatorUtil.compare(clientBuildNumber, minimumClientBuildWithBundledJre) >= 0
@ApiStatus.Internal
class DownloadableFileData(
val fileCaption: String,
val url: URI,
val archivePath: Path,
val targetPath: Path,
val includeInManifest: (Path) -> Boolean,
val downloadFuture: CompletableFuture<Boolean> = CompletableFuture(),
val status: AtomicReference<DownloadableFileState> = AtomicReference(DownloadableFileState.Downloading),
) {
companion object {
private val prohibitedFileNameChars = Regex("[^._\\-a-zA-Z0-9]")
private fun sanitizeFileName(fileName: String) = prohibitedFileNameChars.replace(fileName, "_")
fun build(url: URI, tempDir: Path, cachesDir: Path, includeInManifest: (Path) -> Boolean): DownloadableFileData {
val urlWithoutFragment = url.withFragment(null)
val bareUrl = urlWithoutFragment.withQuery(null)
val fileNameFromUrl = sanitizeFileName(bareUrl.path.toString().substringAfterLast('/'))
val fileName = fileNameFromUrl.take(100) +
"-" +
DigestUtil.sha256Hex(urlWithoutFragment.toString().toByteArray()).substring(0, 10)
return DownloadableFileData(
fileCaption = fileNameFromUrl,
url = url,
archivePath = tempDir.resolve(fileName),
targetPath = cachesDir / (fileName + extractDirSuffix),
includeInManifest = includeInManifest,
)
}
}
override fun toString(): String {
return "DownloadableFileData(fileCaption='$fileCaption', url=$url, archivePath=$archivePath, targetPath=$targetPath)"
}
enum class DownloadableFileState {
Downloading,
Extracting,
Done,
}
}
private const val buildNumberPattern = """[0-9]{3}\.(([0-9]+(\.[0-9]+)?)|SNAPSHOT)"""
val buildNumberRegex = Regex(buildNumberPattern)
private fun getClientDistributionName(clientBuildVersion: String) = when {
VersionComparatorUtil.compare(clientBuildVersion, "211.6167") < 0 -> "IntelliJClient"
VersionComparatorUtil.compare(clientBuildVersion, "213.5318") < 0 -> "CodeWithMeGuest"
else -> "JetBrainsClient"
}
fun createSessionInfo(clientBuildVersion: String, jreBuild: String?, unattendedMode: Boolean): CodeWithMeSessionInfoProvider {
val isSnapshot = "SNAPSHOT" in clientBuildVersion
if (isSnapshot) {
LOG.warn("Thin client download from sources may result in failure due to different sources on host and client, " +
"don't forget to update your locally built archive")
}
val bundledJre = isClientWithBundledJre(clientBuildVersion)
val jreBuildToDownload = if (bundledJre) {
null
}
else {
jreBuild ?: error("JRE build number must be passed for client build number < $clientBuildVersion")
}
val hostBuildNumber = buildNumberRegex.find(clientBuildVersion)!!.value
val platformSuffix = if (jreBuildToDownload != null) when {
SystemInfo.isLinux && CpuArch.isIntel64() -> "-no-jbr.tar.gz"
SystemInfo.isLinux && CpuArch.isArm64() -> "-no-jbr-aarch64.tar.gz"
SystemInfo.isWindows && CpuArch.isIntel64() -> ".win.zip"
SystemInfo.isWindows && CpuArch.isArm64() -> "-aarch64.win.zip"
SystemInfo.isMac && CpuArch.isIntel64() -> "-no-jdk.sit"
SystemInfo.isMac && CpuArch.isArm64() -> "-no-jdk-aarch64.sit"
else -> null
} else when {
SystemInfo.isLinux && CpuArch.isIntel64() -> ".tar.gz"
SystemInfo.isLinux && CpuArch.isArm64() -> "-aarch64.tar.gz"
SystemInfo.isWindows && CpuArch.isIntel64() -> ".jbr.win.zip"
SystemInfo.isWindows && CpuArch.isArm64() -> "-aarch64.jbr.win.zip"
SystemInfo.isMac && CpuArch.isIntel64() -> ".sit"
SystemInfo.isMac && CpuArch.isArm64() -> "-aarch64.sit"
else -> null
} ?: error("Current platform is not supported: OS ${SystemInfo.OS_NAME} ARCH ${SystemInfo.OS_ARCH}")
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientBuildNumber = if (isSnapshot && config.downloadLatestBuildFromCDNForSnapshotHost) getLatestBuild(hostBuildNumber) else hostBuildNumber
val clientDownloadUrl = "${config.clientDownloadUrl.toString().trimEnd('/')}/$clientDistributionName-$clientBuildNumber$platformSuffix"
val jreDownloadUrl = if (jreBuildToDownload != null) {
val platformString = when {
SystemInfo.isLinux && CpuArch.isIntel64() -> "linux-x64"
SystemInfo.isLinux && CpuArch.isArm64() -> "linux-aarch64"
SystemInfo.isWindows && CpuArch.isIntel64() -> "windows-x64"
SystemInfo.isWindows && CpuArch.isArm64() -> "windows-aarch64"
SystemInfo.isMac && CpuArch.isIntel64() -> "osx-x64"
SystemInfo.isMac && CpuArch.isArm64() -> "osx-aarch64"
else -> error("Current platform is not supported")
}
val jreBuildParts = jreBuildToDownload.split("b")
require(jreBuildParts.size == 2) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
require(jreBuildParts[0].matches(Regex("^[0-9_.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
require(jreBuildParts[1].matches(Regex("^[0-9.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
/**
* After upgrade to JRE 17 Jetbrains Runtime Team made a couple of incompatible changes:
* 1. Java version began to contain dots in its version
* 2. Root directory was renamed from 'jbr' to 'jbr_jcef_12.3.4b1235'
*
* We decided to maintain backward compatibility with old IDEs and
* rename archives and root directories back to old format.
*/
val jdkVersion = jreBuildParts[0].replace(".", "_")
val jdkBuild = jreBuildParts[1]
val jreDownloadUrl = "${config.jreDownloadUrl.toString().trimEnd('/')}/jbr_jcef-$jdkVersion-$platformString-b${jdkBuild}.tar.gz"
jreDownloadUrl
} else null
val pgpPublicKeyUrl = if (unattendedMode) {
RemoteDevSystemSettings.getPgpPublicKeyUrl().value
} else null
val sessionInfo = object : CodeWithMeSessionInfoProvider {
override val hostBuildNumber = hostBuildNumber
override val compatibleClientUrl = clientDownloadUrl
override val isUnattendedMode = unattendedMode
override val compatibleJreUrl = jreDownloadUrl
override val hostFeaturesToEnable: Set<String>? = null
override val stunTurnServers: List<StunTurnServerInfo>? = null
override val downloadPgpPublicKeyUrl: String? = pgpPublicKeyUrl
}
LOG.info("Generated session info: $sessionInfo")
return sessionInfo
}
private fun getLatestBuild(hostBuildNumber: String): String {
val majorVersion = hostBuildNumber.substringBefore('.')
val latestBuildTxtFileName = "$majorVersion-LAST-BUILD.txt"
val latestBuildTxtUri = "${config.clientDownloadUrl.toASCIIString().trimEnd('/')}/$latestBuildTxtFileName"
val tempFile = Files.createTempFile(latestBuildTxtFileName, "")
return try {
downloadWithRetries(URI(latestBuildTxtUri), tempFile, EmptyProgressIndicator()).let {
tempFile.readText().trim()
}
}
finally {
Files.delete(tempFile)
}
}
private val currentlyDownloading = ConcurrentHashMap<Path, CompletableFuture<Boolean>>()
@ApiStatus.Experimental
fun downloadClientAndJdk(clientBuildVersion: String,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val jdkBuild = if (isClientWithBundledJre(clientBuildVersion)) null else {
// Obsolete since 2022.3. Now the client has JRE bundled in
LOG.info("Downloading Thin Client jdk-build.txt")
val jdkBuildProgressIndicator = progressIndicator.createSubProgress(0.1)
jdkBuildProgressIndicator.text = RemoteDevUtilBundle.message("thinClientDownloader.checking")
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientJdkDownloadUrl = "${config.clientDownloadUrl}$clientDistributionName-$clientBuildVersion-jdk-build.txt"
LOG.info("Downloading from $clientJdkDownloadUrl")
val tempFile = Files.createTempFile("jdk-build", "txt")
try {
downloadWithRetries(URI(clientJdkDownloadUrl), tempFile, EmptyProgressIndicator()).let {
tempFile.readText()
}
}
finally {
Files.delete(tempFile)
}
}
val sessionInfo = createSessionInfo(clientBuildVersion, jdkBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator.createSubProgress(0.9))
}
/**
* @param clientBuildVersion format: 213.1337[.23]
* @param jreBuild format: 11_0_11b1536.1
* where 11_0_11 is jdk version, b1536.1 is the build version
* @returns Pair(path/to/thin/client, path/to/jre)
*
* Update this method (any jdk-related stuff) together with:
* `org/jetbrains/intellij/build/impl/BundledJreManager.groovy`
*/
fun downloadClientAndJdk(clientBuildVersion: String,
jreBuild: String?,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val sessionInfo = createSessionInfo(clientBuildVersion, jreBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator)
}
/**
* @returns Pair(path/to/thin/client, path/to/jre)
*/
fun downloadClientAndJdk(sessionInfoResponse: CodeWithMeSessionInfoProvider,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val tempDir = FileUtil.createTempDirectory("jb-cwm-dl", null).toPath()
LOG.info("Downloading Thin Client in $tempDir...")
val clientUrl = URI(sessionInfoResponse.compatibleClientUrl)
val guestData = DownloadableFileData.build(
url = clientUrl,
tempDir = tempDir,
cachesDir = config.clientCachesDir,
includeInManifest = getJetBrainsClientManifestFilter(sessionInfoResponse.hostBuildNumber),
)
val jdkUrl = sessionInfoResponse.compatibleJreUrl?.let { URI(it) }
val jdkData = if (jdkUrl != null) {
DownloadableFileData.build(
url = jdkUrl,
tempDir = tempDir,
cachesDir = config.clientCachesDir,
includeInManifest = cwmJbrManifestFilter,
)
}
else null
val dataList = listOfNotNull(jdkData, guestData)
val activity: StructuredIdeActivity? =
if (dataList.isNotEmpty()) RemoteDevStatisticsCollector.onGuestDownloadStarted()
else null
fun updateStateText() {
val downloadList = dataList.filter { it.status.get() == DownloadableFileData.DownloadableFileState.Downloading }.joinToString(", ") { it.fileCaption }
val extractList = dataList.filter { it.status.get() == DownloadableFileData.DownloadableFileState.Extracting }.joinToString(", ") { it.fileCaption }
progressIndicator.text =
if (downloadList.isNotBlank() && extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading.and.extracting", downloadList, extractList)
else if (downloadList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading", downloadList)
else if (extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.extracting", extractList)
else RemoteDevUtilBundle.message("thinClientDownloader.ready")
}
updateStateText()
val dataProgressIndicators = MultipleSubProgressIndicator.create(progressIndicator, dataList.size)
for ((index, data) in dataList.withIndex()) {
// download
val future = data.downloadFuture
// Update only fraction via progress indicator API, text will be updated by updateStateText function
val dataProgressIndicator = dataProgressIndicators[index]
AppExecutorUtil.getAppScheduledExecutorService().execute {
try {
val existingDownloadFuture = synchronized(currentlyDownloading) {
val existingDownloadInnerFuture = currentlyDownloading[data.targetPath]
if (existingDownloadInnerFuture != null) {
existingDownloadInnerFuture
}
else {
currentlyDownloading[data.targetPath] = data.downloadFuture
null
}
}
// TODO: how to merge progress indicators in this case?
if (existingDownloadFuture != null) {
LOG.warn("Already downloading and extracting to ${data.targetPath}, will wait until download finished")
existingDownloadFuture.whenComplete { res, ex ->
if (ex != null) {
future.completeExceptionally(ex)
}
else {
future.complete(res)
}
}
return@execute
}
if (isAlreadyDownloaded(data)) {
LOG.info("Already downloaded and extracted ${data.fileCaption} to ${data.targetPath}")
data.status.set(DownloadableFileData.DownloadableFileState.Done)
dataProgressIndicator.fraction = 1.0
updateStateText()
future.complete(true)
return@execute
}
val downloadingDataProgressIndicator = dataProgressIndicator.createSubProgress(0.5)
try {
fun download(url: URI, path: Path) {
downloadWithRetries(url, path, downloadingDataProgressIndicator)
}
download(data.url, data.archivePath)
LOG.info("Signature verification is ${if (config.verifySignature) "ON" else "OFF"}")
if (config.verifySignature) {
val pgpKeyRingFile = Files.createTempFile(tempDir, "KEYS", "")
download(URI(sessionInfoResponse.downloadPgpPublicKeyUrl ?: JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_SUB_KEYS_URL), pgpKeyRingFile)
val checksumPath = data.archivePath.addSuffix(SHA256_SUFFIX)
val signaturePath = data.archivePath.addSuffix(SHA256_ASC_SUFFIX)
download(data.url.addPathSuffix(SHA256_SUFFIX), checksumPath)
download(data.url.addPathSuffix(SHA256_ASC_SUFFIX), signaturePath)
val pgpVerifier = PgpSignaturesVerifier(object : PgpSignaturesVerifierLogger {
override fun info(message: String) {
LOG.info("Verifying ${data.url} PGP signature: $message")
}
})
LOG.info("Running checksum signature verifier for ${data.archivePath}")
Sha256ChecksumSignatureVerifier(pgpVerifier).verifyChecksumAndSignature(
file = data.archivePath,
detachedSignatureFile = signaturePath,
checksumFile = checksumPath,
expectedFileName = data.url.path.substringAfterLast('/'),
untrustedPublicKeyRing = ByteArrayInputStream(Files.readAllBytes(pgpKeyRingFile)),
trustedMasterKey = ByteArrayInputStream(JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY.toByteArray()),
)
LOG.info("Signature verified for ${data.archivePath}")
}
}
catch (ex: IOException) {
future.completeExceptionally(ex)
LOG.warn(ex)
return@execute
}
// extract
dataProgressIndicator.fraction = 0.75
data.status.set(DownloadableFileData.DownloadableFileState.Extracting)
updateStateText()
// downloading a .zip file will get a VirtualFile with a path of `jar://C:/Users/ivan.pashchenko/AppData/Local/Temp/CodeWithMeGuest-212.2033-windows-x64.zip!/`
// see FileDownloaderImpl.findVirtualFiles making a call to VfsUtil.getUrlForLibraryRoot(ioFile)
val archivePath = data.archivePath
LOG.info("Extracting $archivePath to ${data.targetPath}...")
FileUtil.delete(data.targetPath)
require(data.targetPath.notExists()) { "Target path \"${data.targetPath}\" for $archivePath already exists" }
FileManifestUtil.decompressWithManifest(archivePath, data.targetPath, data.includeInManifest)
require(FileManifestUtil.isUpToDate(data.targetPath, data.includeInManifest)) {
"Manifest verification failed for archive: $archivePath -> ${data.targetPath}"
}
dataProgressIndicator.fraction = 1.0
data.status.set(DownloadableFileData.DownloadableFileState.Done)
updateStateText()
Files.delete(archivePath)
future.complete(true)
}
catch (e: Throwable) {
future.completeExceptionally(e)
LOG.warn(e)
}
finally {
synchronized(currentlyDownloading) {
currentlyDownloading.remove(data.targetPath)
}
}
}
}
try {
val guestSucceeded = guestData.downloadFuture.get()
val jdkSucceeded = jdkData?.downloadFuture?.get() ?: true
if (!guestSucceeded || !jdkSucceeded) error("Guest or jdk was not downloaded")
LOG.info("Download of guest and jdk succeeded")
return ExtractedJetBrainsClientData(clientDir = guestData.targetPath, jreDir = jdkData?.targetPath, version = sessionInfoResponse.hostBuildNumber)
}
catch(e: ProcessCanceledException) {
LOG.info("Download was canceled")
return null
}
catch (e: Throwable) {
RemoteDevStatisticsCollector.onGuestDownloadFinished(activity, isSucceeded = false)
LOG.warn(e)
if (e is ExecutionException) {
e.cause?.let { throw it }
}
throw e
}
}
private fun isAlreadyDownloaded(fileData: DownloadableFileData): Boolean {
val extractDirectory = FileManifestUtil.getExtractDirectory(fileData.targetPath, fileData.includeInManifest)
return extractDirectory.isUpToDate && !fileData.targetPath.fileName.toString().contains("SNAPSHOT")
}
private fun downloadWithRetries(url: URI, path: Path, progressIndicator: ProgressIndicator) {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
@Suppress("LocalVariableName")
val MAX_ATTEMPTS = 5
@Suppress("LocalVariableName")
val BACKOFF_INITIAL_DELAY_MS = 500L
var delayMs = BACKOFF_INITIAL_DELAY_MS
for (i in 1..MAX_ATTEMPTS) {
try {
LOG.info("Downloading from $url to ${path.absolutePathString()}, attempt $i of $MAX_ATTEMPTS")
when (url.scheme) {
"http", "https" -> {
HttpRequests.request(url.toString()).saveToFile(path, progressIndicator)
}
"file" -> {
Files.copy(url.toPath(), path, StandardCopyOption.REPLACE_EXISTING)
}
else -> {
error("scheme ${url.scheme} is not supported")
}
}
LOG.info("Download from $url to ${path.absolutePathString()} succeeded on attempt $i of $MAX_ATTEMPTS")
return
}
catch (e: Throwable) {
if (e is ControlFlowException) throw e
if (e is HttpStatusException) {
if (e.statusCode in 400..499) {
LOG.warn("Received ${e.statusCode} with message ${e.message}, will not retry")
throw e
}
}
if (i < MAX_ATTEMPTS) {
LOG.warn("Attempt $i of $MAX_ATTEMPTS to download from $url to ${path.absolutePathString()} failed, retrying in $delayMs ms", e)
Thread.sleep(delayMs)
delayMs = (delayMs * 1.5).toLong()
} else {
LOG.warn("Failed to download from $url to ${path.absolutePathString()} in $MAX_ATTEMPTS attempts", e)
throw e
}
}
}
}
private fun findCwmGuestHome(guestRoot: Path): Path {
// maxDepth 2 for macOS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
if (dir.resolve("bin").exists() && dir.resolve("lib").exists()) {
return dir
}
}
}
error("JetBrains Client home is not found under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherNames: List<String>): Pair<Path, List<String>> {
val launcher = launcherNames.firstNotNullOfOrNull {
val launcherRelative = Path.of("bin", it)
val launcher = findLauncher(guestRoot, launcherRelative)
launcher?.let {
launcher to listOf(launcher.toString())
}
}
return launcher ?: error("Could not find launchers (${launcherNames.joinToString { "'$it'" }}) under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherName: Path): Path? {
// maxDepth 2 for macOS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
val candidate = dir.resolve(launcherName)
if (candidate.exists()) {
return candidate
}
}
}
return null
}
private fun findLauncherUnderCwmGuestRoot(guestRoot: Path): Pair<Path, List<String>> {
when {
SystemInfo.isWindows -> {
val batchLaunchers = listOf("intellij_client.bat", "jetbrains_client.bat")
val exeLaunchers = listOf("jetbrains_client64.exe", "cwm_guest64.exe", "intellij_client64.exe")
val eligibleLaunchers = if (Registry.`is`("com.jetbrains.gateway.client.use.batch.launcher", false))
batchLaunchers
else
exeLaunchers + batchLaunchers
return findLauncher(guestRoot, eligibleLaunchers)
}
SystemInfo.isUnix -> {
if (SystemInfo.isMac) {
val app = guestRoot.toFile().listFiles { file -> file.name.endsWith(".app") && file.isDirectory }!!.singleOrNull()
if (app != null) {
return app.toPath() to listOf("open", "-n", "-W", "-a", app.toString(), "--args")
}
}
val shLauncherNames = listOf("jetbrains_client.sh", "cwm_guest.sh", "intellij_client.sh")
return findLauncher(guestRoot, shLauncherNames)
}
else -> error("Unsupported OS: ${SystemInfo.OS_NAME}")
}
}
private val remoteDevYouTrackFlag = "-Dapplication.info.youtrack.url=https://youtrack.jetbrains.com/newissue?project=GTW&clearDraft=true&description=\$DESCR"
/**
* Launches client and returns process's lifetime (which will be terminated on process exit)
*/
fun runCwmGuestProcessFromDownload(
lifetime: Lifetime,
url: String,
extractedJetBrainsClientData: ExtractedJetBrainsClientData
): Lifetime {
val (executable, fullLauncherCmd) = findLauncherUnderCwmGuestRoot(extractedJetBrainsClientData.clientDir)
if (extractedJetBrainsClientData.jreDir != null) {
createSymlinkToJdkFromGuest(extractedJetBrainsClientData.clientDir, extractedJetBrainsClientData.jreDir)
}
// Update mtime on JRE & CWM Guest roots. The cleanup process will use it later.
listOfNotNull(extractedJetBrainsClientData.clientDir, extractedJetBrainsClientData.jreDir).forEach { path ->
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()))
}
val parameters = if (CodeWithMeGuestLauncher.isUnattendedModeUri(URI(url))) listOf("thinClient", url, remoteDevYouTrackFlag) else listOf("thinClient", url)
val processLifetimeDef = lifetime.createNested()
val vmOptionsFile = if (SystemInfoRt.isMac) {
// macOS stores vmoptions file inside .app file – we can't edit it
Paths.get(
PathManager.getDefaultConfigPathFor(PlatformUtils.JETBRAINS_CLIENT_PREFIX + extractedJetBrainsClientData.version),
"jetbrains_client.vmoptions"
)
} else executable.resolveSibling("jetbrains_client64.vmoptions")
service<JetBrainsClientDownloaderConfigurationProvider>().patchVmOptions(vmOptionsFile)
if (SystemInfo.isWindows) {
val hProcess = WindowsFileUtil.windowsShellExecute(
executable = executable,
workingDirectory = extractedJetBrainsClientData.clientDir,
parameters = parameters
)
@Suppress("LocalVariableName")
val STILL_ACTIVE = 259
application.executeOnPooledThread {
val exitCode = IntByReference(STILL_ACTIVE)
while (exitCode.value == STILL_ACTIVE) {
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
Thread.sleep(1000)
}
processLifetimeDef.terminate()
}
lifetime.onTerminationOrNow {
val exitCode = IntByReference(WinBase.INFINITE)
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
if (exitCode.value == STILL_ACTIVE)
LOG.info("Terminating cwm guest process")
else return@onTerminationOrNow
if (!Kernel32.INSTANCE.TerminateProcess(hProcess, 1)) {
val error = Kernel32.INSTANCE.GetLastError()
val hResult = WinNT.HRESULT(error)
LOG.error("Failed to terminate cwm guest process, HRESULT=${"0x%x".format(hResult)}")
}
}
}
else {
// Mac gets multiple start attempts because starting it fails occasionally (CWM-2244, CWM-1733)
var attemptCount = if (SystemInfo.isMac) 5 else 1
var lastProcessStartTime: Long
fun doRunProcess() {
val commandLine = GeneralCommandLine(fullLauncherCmd + parameters)
config.modifyClientCommandLine(commandLine)
LOG.info("Starting JetBrains Client process (attempts left: $attemptCount): ${commandLine}")
attemptCount--
lastProcessStartTime = System.currentTimeMillis()
val processHandler = object : OSProcessHandler(commandLine) {
override fun readerOptions(): BaseOutputReader.Options = BaseOutputReader.Options.forMostlySilentProcess()
}
val listener = object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
super.onTextAvailable(event, outputType)
LOG.info("GUEST OUTPUT: ${event.text}")
}
override fun processTerminated(event: ProcessEvent) {
super.processTerminated(event)
LOG.info("Guest process terminated, exit code " + event.exitCode)
if (event.exitCode == 0) {
application.invokeLater {
processLifetimeDef.terminate()
}
} else {
// if process exited abnormally but took longer than 10 seconds, it's likely to be an issue with connection instead of Mac-specific bug
if ((System.currentTimeMillis() - lastProcessStartTime) < 10_000 ) {
if (attemptCount > 0) {
LOG.info("Previous attempt to start guest process failed, will try again in one second")
EdtScheduledExecutorService.getInstance().schedule({ doRunProcess() }, ModalityState.any(), 1, TimeUnit.SECONDS)
}
else {
LOG.warn("Running client process failed after specified number of attempts")
application.invokeLater {
processLifetimeDef.terminate()
}
}
}
}
}
}
processHandler.addProcessListener(listener)
processHandler.startNotify()
config.clientLaunched.fire()
lifetime.onTerminationOrNow {
processHandler.process.children().forEach {
it.destroyForcibly()
}
processHandler.process.destroyForcibly()
}
}
doRunProcess()
}
return processLifetimeDef.lifetime
}
fun createSymlinkToJdkFromGuest(guestRoot: Path, jdkRoot: Path): Path {
val linkTarget = getJbrDirectory(jdkRoot)
val guestHome = findCwmGuestHome(guestRoot)
val link = guestHome / "jbr"
createSymlink(link, linkTarget)
return link
}
private fun createSymlink(link: Path, target: Path) {
val targetRealPath = target.toRealPath()
val linkExists = true
val linkRealPath = if (link.exists(LinkOption.NOFOLLOW_LINKS)) link.toRealPath() else null
val isSymlink = FileSystemUtil.getAttributes(link.toFile())?.isSymLink == true
LOG.info("$link: exists=$linkExists, realPath=$linkRealPath, isSymlink=$isSymlink")
if (linkExists && isSymlink && linkRealPath == targetRealPath) {
LOG.info("Symlink/junction '$link' is UP-TO-DATE and points to '$target'")
}
else {
FileUtil.deleteWithRenamingIfExists(link)
LOG.info("Creating symlink/junction '$link' -> '$target'")
try {
if (SystemInfo.isWindows) {
WindowsFileUtil.createJunction(junctionFile = link, targetFile = target.absolute())
}
else {
Files.createSymbolicLink(link, target.absolute())
}
}
catch (e: IOException) {
if (link.exists() && link.toRealPath() == targetRealPath) {
LOG.warn("Creating symlink/junction to already existing target. '$link' -> '$target'")
}
else {
throw e
}
}
try {
val linkRealPath2 = link.toRealPath()
if (linkRealPath2 != targetRealPath) {
LOG.error("Symlink/junction '$link' should point to '$targetRealPath', but points to '$linkRealPath2' instead")
}
}
catch (e: Throwable) {
LOG.error(e)
throw e
}
}
}
private fun getJbrDirectory(root: Path): Path =
tryGetMacOsJbrDirectory(root) ?: tryGetJdkRoot(root) ?: error("Unable to detect jdk content directory in path: '$root'")
private fun tryGetJdkRoot(jdkDownload: Path): Path? {
jdkDownload.toFile().walk(FileWalkDirection.TOP_DOWN).forEach { file ->
if (File(file, "bin").isDirectory && File(file, "lib").isDirectory) {
return file.toPath()
}
}
return null
}
private fun tryGetMacOsJbrDirectory(root: Path): Path? {
if (!SystemInfo.isMac) {
return null
}
val jbrDirectory = root.listDirectoryEntries().find { it.nameWithoutExtension.startsWith("jbr") }
LOG.debug { "JBR directory: $jbrDirectory" }
return jbrDirectory
}
fun versionsMatch(hostBuildNumberString: String, localBuildNumberString: String): Boolean {
try {
val hostBuildNumber = BuildNumber.fromString(hostBuildNumberString)!!
val localBuildNumber = BuildNumber.fromString(localBuildNumberString)!!
// Any guest in that branch compatible with SNAPSHOT version (it's used by IDEA developers mostly)
if ((localBuildNumber.isSnapshot || hostBuildNumber.isSnapshot) && hostBuildNumber.baselineVersion == localBuildNumber.baselineVersion) {
return true
}
return hostBuildNumber.asStringWithoutProductCode() == localBuildNumber.asStringWithoutProductCode()
}
catch (t: Throwable) {
LOG.error("Error comparing versions $hostBuildNumberString and $localBuildNumberString: ${t.message}", t)
return false
}
}
private fun Path.addSuffix(suffix: String) = resolveSibling(fileName.toString() + suffix)
private const val SHA256_SUFFIX = ".sha256"
private const val SHA256_ASC_SUFFIX = ".sha256.asc"
private val urlAllowedChars = Regex("^[._\\-a-zA-Z0-9:/]+$")
fun isValidDownloadUrl(url: String): Boolean {
return urlAllowedChars.matches(url) && !url.contains("..")
}
private class MultipleSubProgressIndicator(parent: ProgressIndicator,
private val onFractionChange: () -> Unit) : SubProgressIndicatorBase(parent) {
companion object {
fun create(parent: ProgressIndicator, count: Int): List<MultipleSubProgressIndicator> {
val result = mutableListOf<MultipleSubProgressIndicator>()
val parentBaseFraction = parent.fraction
for (i in 0..count) {
val element = MultipleSubProgressIndicator(parent) {
val subFraction = result.sumOf { it.subFraction }
parent.fraction = min(parentBaseFraction + subFraction * (1.0 / count), 1.0)
}
result.add(element)
}
return result
}
}
private var subFraction = 0.0
override fun getFraction() = subFraction
override fun setFraction(fraction: Double) {
subFraction = fraction
onFractionChange()
}
}
} | apache-2.0 | 5340694b4d783f9ebe74e2e5c65b514a | 40.005643 | 172 | 0.683732 | 4.790348 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/english/Kissmanga.kt | 1 | 7263 | /*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* TachiyomiEX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package eu.kanade.tachiyomi.data.source.online.english
import android.content.Context
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.network.GET
import eu.kanade.tachiyomi.data.network.POST
import eu.kanade.tachiyomi.data.source.EN
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.regex.Pattern
class Kissmanga(override val source: Sources) : ParsedOnlineSource() {
override val baseUrl = "http://kissmanga.com"
override val lang: Language get() = EN
override fun supportsLatest() = true
override val client: OkHttpClient = network.cloudflareClient
override fun popularMangaInitialUrl() = "$baseUrl/MangaList/MostPopular"
override fun latestUpdatesInitialUrl() = "http://kissmanga.com/MangaList/LatestUpdate"
override fun popularMangaSelector() = "table.listing tr:gt(1)"
override fun popularMangaFromElement(element: Element, manga: Manga) {
element.select("td a:eq(0)").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
}
override fun popularMangaNextPageSelector() = "li > a:contains(› Next)"
override fun searchMangaRequest(page: MangasPage, query: String, filters: List<Filter>): Request {
if (page.page == 1) {
page.url = searchMangaInitialUrl(query, filters)
}
val form = FormBody.Builder().apply {
add("authorArtist", "")
add("mangaName", query)
add("status", "")
[email protected] { filter ->
add("genres", if (filter in filters) "1" else "0")
}
}
return POST(page.url, headers, form.build())
}
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/AdvanceSearch"
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element, manga: Manga) {
popularMangaFromElement(element, manga)
}
override fun searchMangaNextPageSelector() = null
override fun mangaDetailsParse(document: Document, manga: Manga) {
val infoElement = document.select("div.barContent").first()
manga.author = infoElement.select("p:has(span:contains(Author:)) > a").first()?.text()
manga.genre = infoElement.select("p:has(span:contains(Genres:)) > *:gt(0)").text()
manga.description = infoElement.select("p:has(span:contains(Summary:)) ~ p").text()
manga.status = infoElement.select("p:has(span:contains(Status:))").first()?.text().orEmpty().let { parseStatus(it) }
manga.thumbnail_url = document.select(".rightBox:eq(0) img").first()?.attr("src")
}
fun parseStatus(status: String) = when {
status.contains("Ongoing") -> Manga.ONGOING
status.contains("Completed") -> Manga.COMPLETED
else -> Manga.UNKNOWN
}
override fun chapterListSelector() = "table.listing tr:gt(1)"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("a").first()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let {
SimpleDateFormat("MM/dd/yyyy").parse(it).time
} ?: 0
}
override fun pageListRequest(chapter: Chapter) = POST(baseUrl + chapter.url, headers)
override fun pageListParse(response: Response, pages: MutableList<Page>) {
//language=RegExp
val p = Pattern.compile("""lstImages.push\("(.+?)"""")
val m = p.matcher(response.body().string())
var i = 0
while (m.find()) {
pages.add(Page(i++, "", m.group(1)))
}
}
// Not used
override fun pageListParse(document: Document, pages: MutableList<Page>) {
}
override fun imageUrlRequest(page: Page) = GET(page.url)
override fun imageUrlParse(document: Document) = ""
// $("select[name=\"genres\"]").map((i,el) => `Filter("${i}", "${$(el).next().text().trim()}")`).get().join(',\n')
// on http://kissmanga.com/AdvanceSearch
override fun getFilterList(): List<Filter> = listOf(
Filter("0", "Action"),
Filter("1", "Adult"),
Filter("2", "Adventure"),
Filter("3", "Comedy"),
Filter("4", "Comic"),
Filter("5", "Cooking"),
Filter("6", "Doujinshi"),
Filter("7", "Drama"),
Filter("8", "Ecchi"),
Filter("9", "Fantasy"),
Filter("10", "Gender Bender"),
Filter("11", "Harem"),
Filter("12", "Historical"),
Filter("13", "Horror"),
Filter("14", "Josei"),
Filter("15", "Lolicon"),
Filter("16", "Manga"),
Filter("17", "Manhua"),
Filter("18", "Manhwa"),
Filter("19", "Martial Arts"),
Filter("20", "Mature"),
Filter("21", "Mecha"),
Filter("22", "Medical"),
Filter("23", "Music"),
Filter("24", "Mystery"),
Filter("25", "One shot"),
Filter("26", "Psychological"),
Filter("27", "Romance"),
Filter("28", "School Life"),
Filter("29", "Sci-fi"),
Filter("30", "Seinen"),
Filter("31", "Shotacon"),
Filter("32", "Shoujo"),
Filter("33", "Shoujo Ai"),
Filter("34", "Shounen"),
Filter("35", "Shounen Ai"),
Filter("36", "Slice of Life"),
Filter("37", "Smut"),
Filter("38", "Sports"),
Filter("39", "Supernatural"),
Filter("40", "Tragedy"),
Filter("41", "Webtoon"),
Filter("42", "Yaoi"),
Filter("43", "Yuri")
)
} | gpl-3.0 | 773eb6363584d2b41c01762cbe3fa325 | 37.020942 | 124 | 0.61851 | 4.236289 | false | false | false | false |
siosio/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/features/history/FilePredictionNGramFeatures.kt | 10 | 1099 | // 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.filePrediction.features.history
import kotlin.math.max
import kotlin.math.min
class FilePredictionNGramFeatures(private val byFile: Map<String, Double>) {
private val minProbability: Double
private val maxProbability: Double
init {
var minProb = 1.0
var maxProb = 0.0
for (nGram in byFile.values) {
minProb = min(minProb, nGram)
maxProb = max(maxProb, nGram)
}
minProbability = max(minProb, 0.0001)
maxProbability = max(maxProb, 0.0001)
}
fun calculateFileFeatures(fileUrl: String): NextFileProbability? {
val probability = byFile[fileUrl]
if (probability == null) {
return null
}
val mleToMin = if (minProbability != 0.0) probability / minProbability else 0.0
val mleToMax = if (maxProbability != 0.0) probability / maxProbability else 0.0
return NextFileProbability(probability, minProbability, maxProbability, mleToMin, mleToMax)
}
} | apache-2.0 | a1f07497acb7d296dec575cf1482b005 | 33.375 | 158 | 0.721565 | 3.763699 | false | false | false | false |
ohmae/VoiceMessageBoard | app/src/main/java/net/mm2d/android/vmb/settings/Settings.kt | 1 | 3866 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.vmb.settings
import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.ColorInt
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import net.mm2d.android.vmb.BuildConfig
import net.mm2d.log.Logger
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class Settings private constructor(private val storage: SettingsStorage) {
var backgroundColor: Int
@ColorInt
get() = storage.readInt(Key.KEY_BACKGROUND)
set(@ColorInt color) = storage.writeInt(Key.KEY_BACKGROUND, color)
var foregroundColor: Int
@ColorInt
get() = storage.readInt(Key.KEY_FOREGROUND)
set(@ColorInt color) = storage.writeInt(Key.KEY_FOREGROUND, color)
val screenOrientation: Int
get() {
val value = storage.readString(Key.SCREEN_ORIENTATION)
if (value.isNotEmpty()) {
try {
return Integer.parseInt(value)
} catch (e: NumberFormatException) {
e.printStackTrace()
}
}
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
var useFont: Boolean
get() = storage.readBoolean(Key.USE_FONT)
set(value) = storage.writeBoolean(Key.USE_FONT, value)
var fontPath: String
get() = storage.readString(Key.FONT_PATH)
set(value) = storage.writeString(Key.FONT_PATH, value)
val fontPathToUse: String
get() = if (useFont) fontPath else ""
fun shouldUseSpeechRecognizer(): Boolean =
storage.readBoolean(Key.SPEECH_RECOGNIZER)
fun shouldShowCandidateList(): Boolean =
storage.readBoolean(Key.CANDIDATE_LIST)
fun shouldShowEditorWhenLongTap(): Boolean =
storage.readBoolean(Key.LONG_TAP_EDIT)
fun shouldShowEditorAfterSelect(): Boolean =
storage.readBoolean(Key.LIST_EDIT)
var history: Set<String>
get() = storage.readStringSet(Key.HISTORY)
set(history) = storage.writeStringSet(Key.HISTORY, history)
companion object {
private var settings: Settings? = null
private val lock: Lock = ReentrantLock()
private val condition: Condition = lock.newCondition()
/**
* Settingsのインスタンスを返す。
*
* 初期化が完了していなければブロックされる。
*/
fun get(): Settings = lock.withLock {
while (settings == null) {
if (BuildConfig.DEBUG) {
Logger.e("!!!!!!!!!! BLOCK !!!!!!!!!!")
}
if (!condition.await(1, TimeUnit.SECONDS)) {
throw IllegalStateException("Settings initialization timeout")
}
}
settings as Settings
}
/**
* アプリ起動時に一度だけコールされ、初期化を行う。
*
* @param context コンテキスト
*/
fun initialize(context: Context) {
Completable.fromAction { initializeInner(context) }
.subscribeOn(Schedulers.io())
.subscribe()
}
private fun initializeInner(context: Context) {
val storage = SettingsStorage(context)
Maintainer.maintain(storage)
lock.withLock {
settings = Settings(storage)
condition.signalAll()
}
}
}
}
| mit | 91677b4f0d20d59c7dca4458da47c085 | 30.310924 | 82 | 0.612185 | 4.521845 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt | 2 | 19445 | // 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.vcs.log.history
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogProgress
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.history.FileHistoryPaths.withFileHistory
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import com.intellij.vcs.log.util.StopWatch
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference
class FileHistoryFilterer(private val logData: VcsLogData, private val logId: String) : VcsLogFilterer, Disposable {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache, logData.commitDetailsGetter, index)
private var fileHistoryTask: FileHistoryTask? = null
private val vcsLogObjectsFactory: VcsLogObjectsFactory get() = project.service()
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters)
val root = filePath?.let { VcsLogUtil.getActualRoot(project, filePath) }
val hash = getHash(filters)
if (root != null && !filePath.isDirectory) {
val result = MyWorker(root, filePath, hash).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
if (result != null) return result
}
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private fun cancelLastTask(wait: Boolean) {
fileHistoryTask?.cancel(wait)
fileHistoryTask = null
}
private fun createFileHistoryTask(vcs: AbstractVcs,
root: VirtualFile,
filePath: FilePath,
hash: Hash?,
isInitial: Boolean): FileHistoryTask {
val oldHistoryTask = fileHistoryTask
if (oldHistoryTask != null && !oldHistoryTask.isCancelled && !isInitial &&
oldHistoryTask.filePath == filePath && oldHistoryTask.hash == hash) return oldHistoryTask
cancelLastTask(false)
val factory = vcsLogObjectsFactory
val newHistoryTask = object : FileHistoryTask(vcs, filePath, hash, createProgressIndicator()) {
override fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath {
return factory.createCommitMetadataWithPath(revision as VcsFileRevisionEx, root)
}
}
fileHistoryTask = newHistoryTask
return newHistoryTask
}
private fun VcsLogObjectsFactory.createCommitMetadataWithPath(revision: VcsFileRevisionEx,
root: VirtualFile): CommitMetadataWithPath {
val commitHash = createHash(revision.revisionNumber.asString())
val metadata = createCommitMetadata(commitHash, emptyList(), revision.revisionDate.time, root,
CommitPresentationUtil.getSubject(revision.commitMessage!!),
revision.author!!, revision.authorEmail!!,
revision.commitMessage!!,
revision.committerName!!, revision.committerEmail!!, revision.authorDate!!.time)
return CommitMetadataWithPath(storage.getCommitIndex(commitHash, root), metadata,
MaybeDeletedFilePath(revision.path, revision.isDeleted))
}
private fun createProgressIndicator(): ProgressIndicator {
return logData.progress.createProgressIndicator(VcsLogProgress.ProgressKey("file history task for $logId"))
}
override fun dispose() {
cancelLastTask(true)
}
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? {
val start = System.currentTimeMillis()
TraceManager.getTracer("vcs").spanBuilder("computing history").useWithScope { scope ->
val isInitial = commitCount == CommitCountStage.INITIAL
val indexDataGetter = index.dataGetter
scope.setAttribute("filePath", filePath.toString())
if (indexDataGetter != null && index.isIndexed(root) && dataPack.isFull) {
cancelLastTask(false)
val visiblePack = filterWithIndex(indexDataGetter, dataPack, oldVisiblePack, sortType, filters, isInitial)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index")
scope.setAttribute("type", "index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters, commitCount)
scope.setAttribute("type", "history provider")
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for computing history for $filePath with history provider")
checkNotEmpty(dataPack, visiblePack, false)
return@filter Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return null
}
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): VisiblePack {
val historyHandler = logProviders[root]?.fileHistoryHandler
val isFastStart = commitCount == CommitCountStage.INITIAL && historyHandler != null
val (revisions, isDone) = if (isFastStart) {
cancelLastTask(false)
historyHandler!!.getHistoryFast(root, filePath, hash, commitCount.count).map {
vcsLogObjectsFactory.createCommitMetadataWithPath(it, root)
} to false
}
else {
createFileHistoryTask(vcs, root, filePath, hash,
(commitCount == CommitCountStage.FIRST_STEP && historyHandler != null) ||
commitCount == CommitCountStage.INITIAL).waitForRevisions()
}
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull && !isFastStart) {
val pathsMap = revisions.associate { Pair(it.commit, it.path) }
val visibleGraph = createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(pathsMap))
.apply {
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
val commits = revisions.map { GraphCommitImpl.createCommit(it.commit, emptyList(), it.metadata.timestamp) }
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(revisions.associate { Pair(it.commit, it.path) }))
.apply {
putUserData(VisiblePack.NO_GRAPH_INFORMATION, true)
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(indexDataGetter, dataPack, filters, sortType,
oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(indexDataGetter, dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
val fileHistory = FileHistory(data.buildPathsMap())
return VisiblePack(dataPack, visibleGraph, false, filters).withFileHistory(fileHistory)
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory,
removeTrivialMerges = FileHistoryBuilder.isRemoveTrivialMerges,
refine = FileHistoryBuilder.isRefine)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters).withFileHistory(fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
TraceManager.getTracer("vcs").spanBuilder("collecting renames").useWithScope {
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull { ad ->
val parentHash = storage.getCommitId(ad.parent)!!.hash
val childHash = storage.getCommitId(ad.child)!!.hash
if (ad.isAddition) handler.getRename(root, ad.filePath, parentHash, childHash)
else handler.getRename(root, ad.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
it.setAttribute("renamesSize", renames.size.toLong())
it.setAttribute("numberOfAdditionDeletions", fileHistory.unmatchedAdditionsDeletions.size.toLong())
val result = MultiMap<UnorderedPair<Int>, Rename>()
renames.forEach { rename -> result.putValue(rename.commits, rename) }
return result
}
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = logger<FileHistoryFilterer>()
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
private fun createVisibleGraph(dataPack: DataPack,
sortType: PermanentGraph.SortType,
matchingHeads: Set<Int>?,
matchingCommits: Set<Int>?): VisibleGraph<Int> {
if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) {
return EmptyVisibleGraph.getInstance()
}
return dataPack.permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) {
return map
}
if (map.isEmpty) {
return this
}
val result = MultiMap<K, V>()
result.putAllValues(this)
result.putAllValues(map)
return result
}
private data class CommitMetadataWithPath(val commit: Int, val metadata: VcsCommitMetadata, val path: MaybeDeletedFilePath)
private abstract class FileHistoryTask(val vcs: AbstractVcs, val filePath: FilePath, val hash: Hash?, val indicator: ProgressIndicator) {
private val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
private val future: Future<*>
private val _revisions = ConcurrentLinkedQueue<CommitMetadataWithPath>()
private val exception = AtomicReference<VcsException>()
@Volatile
private var lastSize = 0
val isCancelled get() = indicator.isCanceled
init {
future = AppExecutorUtil.getAppExecutorService().submit {
ProgressManager.getInstance().runProcess(Runnable {
try {
VcsCachingHistory.collect(vcs, filePath, revisionNumber) { revision ->
_revisions.add(createCommitMetadataWithPath(revision))
}
}
catch (e: VcsException) {
exception.set(e)
}
}, indicator)
}
}
protected abstract fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath
@Throws(VcsException::class)
fun waitForRevisions(): Pair<List<CommitMetadataWithPath>, Boolean> {
throwOnError()
while (_revisions.size == lastSize) {
try {
future.get(100, TimeUnit.MILLISECONDS)
ProgressManager.checkCanceled()
throwOnError()
return Pair(getRevisionsSnapshot(), true)
}
catch (_: TimeoutException) {
}
}
return Pair(getRevisionsSnapshot(), false)
}
private fun getRevisionsSnapshot(): List<CommitMetadataWithPath> {
val list = _revisions.toList()
lastSize = list.size
return list
}
@Throws(VcsException::class)
private fun throwOnError() {
if (exception.get() != null) throw VcsException(exception.get())
}
fun cancel(wait: Boolean) {
indicator.cancel()
if (wait) {
try {
future.get(20, TimeUnit.MILLISECONDS)
}
catch (_: Throwable) {
}
}
}
}
| apache-2.0 | 8c22c73c69ad574609e716e0676df860 | 43.701149 | 158 | 0.677295 | 5.492938 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/find/actions/ShowUsagesHeader.kt | 3 | 3414 | // 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.find.actions
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.RightGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.usageView.UsageViewBundle
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.JBUI
import com.intellij.xml.util.XmlStringUtil
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import javax.swing.JLabel
internal class ShowUsagesHeader(pinButton: JComponent, @NlsContexts.PopupTitle title: String) {
@JvmField
val panel: DialogPanel
private lateinit var titleLabel: JLabel
private lateinit var processIcon: AsyncProcessIcon
private lateinit var statusLabel: JLabel
init {
panel = panel {
customizeSpacingConfiguration(spacingConfiguration = object : IntelliJSpacingConfiguration() {
// Remove default vertical gap around cells, so the header can be smaller
override val verticalComponentGap: Int
get() = 0
}) {
row {
// Don't use Row.label method: it processes mnemonics and breaks symbol &
val titleCell = cell(JLabel(XmlStringUtil.wrapInHtml("<body><nobr>$title</nobr></body>")))
.resizableColumn()
.gap(RightGap.SMALL)
titleLabel = titleCell.component
processIcon = cell(AsyncProcessIcon("xxx"))
.gap(RightGap.SMALL)
.component
val statusCell = label("")
statusLabel = statusCell.component
val pinCell = cell(pinButton)
if (ExperimentalUI.isNewUI()) {
val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets()
titleCell.customize(Gaps(top = headerInsets.top, bottom = headerInsets.bottom, right = JBUI.scale(12)))
statusCell.component.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND
statusCell.customize(JBGaps(right = 8))
// Fix vertical alignment for the pin icon
pinCell.customize(JBGaps(top = 2))
}
else {
statusCell.gap(RightGap.SMALL)
}
}
}
}
}
fun setStatusText(hasMore: Boolean, visibleCount: Int, totalCount: Int) {
statusLabel.text = getStatusString(!processIcon.isDisposed, hasMore, visibleCount, totalCount)
}
fun disposeProcessIcon() {
Disposer.dispose(processIcon)
processIcon.parent?.apply {
remove(processIcon)
repaint()
}
}
@NlsContexts.PopupTitle
fun getTitle(): String {
return titleLabel.text
}
private fun getStatusString(findUsagesInProgress: Boolean, hasMore: Boolean, visibleCount: Int, totalCount: Int): @Nls String {
return if (findUsagesInProgress || hasMore) {
UsageViewBundle.message("showing.0.usages", visibleCount - if (hasMore) 1 else 0)
}
else if (visibleCount != totalCount) {
UsageViewBundle.message("showing.0.of.1.usages", visibleCount, totalCount)
}
else {
UsageViewBundle.message("found.0.usages", totalCount)
}
}
} | apache-2.0 | 1df6f4598be14b2705af6de9cbc4cd89 | 34.947368 | 129 | 0.700644 | 4.552 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stackFrame/InlineStackTraceCalculator.kt | 1 | 8370 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stackFrame
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.xdebugger.frame.XStackFrame
import com.sun.jdi.Location
import com.sun.jdi.Method
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.getBorders
import org.jetbrains.kotlin.load.java.JvmAbi
object InlineStackTraceCalculator {
fun calculateInlineStackTrace(frameProxy: StackFrameProxyImpl): List<XStackFrame> {
val location = frameProxy.safeLocation() ?: return emptyList()
val method = location.safeMethod() ?: return emptyList()
val inlineStackFramesInfo = method.getInlineStackFramesInfo(location)
if (inlineStackFramesInfo.isEmpty()) {
return emptyList()
}
val allLocations = method.safeAllLineLocations()
if (allLocations.isEmpty()) {
return emptyList()
}
inlineStackFramesInfo.fetchDepths()
val newFrameProxyLocation = inlineStackFramesInfo.fetchLocationsAndGetNewFrameProxyLocation(allLocations, location)
return createInlineStackFrames(inlineStackFramesInfo, frameProxy, newFrameProxyLocation)
}
private fun createInlineStackFrames(
inlineStackFramesInfo: List<InlineStackFrameInfo>,
frameProxy: StackFrameProxyImpl,
frameProxyLocation: Location
): MutableList<KotlinStackFrame> {
val stackFrames = mutableListOf<KotlinStackFrame>()
var variableHolder: InlineStackFrameVariableHolder? =
InlineStackFrameVariableHolder.fromStackFrame(frameProxy)
for (info in inlineStackFramesInfo.asReversed()) {
stackFrames.add(
info.toInlineStackFrame(
frameProxy,
variableHolder.getVisibleVariables()
)
)
variableHolder = variableHolder?.parentFrame
}
val originalFrame = KotlinStackFrameWithProvidedVariables(
safeInlineStackFrameProxy(frameProxyLocation, 0, frameProxy),
variableHolder.getVisibleVariables()
)
stackFrames.add(originalFrame)
return stackFrames
}
private fun Method.getInlineStackFramesInfo(location: Location) =
getInlineFunctionInfos()
.filter { it.contains(location) }
.sortedBy { it.borders.start }
.map { InlineStackFrameInfo(it, location, 0) }
private fun Method.getInlineFunctionInfos(): List<AbstractInlineFunctionInfo> {
val localVariables = safeVariables() ?: return emptyList()
val inlineFunctionInfos = mutableListOf<AbstractInlineFunctionInfo>()
for (variable in localVariables) {
val borders = variable.getBorders() ?: continue
val variableName = variable.name()
if (variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
inlineFunctionInfos.add(InlineFunctionInfo(variableName, borders))
} else if (variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT)) {
inlineFunctionInfos.add(InlineLambdaInfo(variableName, borders))
}
}
return inlineFunctionInfos
}
// Consider the following example:
// inline fun baz() = 1 // Breakpoint
// inline fun bar(f: () -> Unit) = f()
// inline fun foo(f: () -> Unit) = bar { f() }
// fun main() = foo { baz() }
// The depth of an inline lambda is equal to the depth of a method where it was declared.
// Inline function infos should be listed according to the function call order,
// so that depths of inline lambdas could be calculated correctly.
// The method will produce the following depths:
// foo -> 1
// bar -> 2
// $i$a$-bar-MainKt$foo$1$iv -> 1
// $i$a$-foo-MainKt$main$1 -> 0
// baz -> 1
private fun List<InlineStackFrameInfo>.fetchDepths() {
var currentDepth = 0
val depths = mutableMapOf<String, Int>()
for (inlineStackFrameInfo in this) {
val inlineFunctionInfo = inlineStackFrameInfo.inlineFunctionInfo
val calculatedDepth =
if (inlineFunctionInfo is InlineLambdaInfo) {
inlineFunctionInfo.getDeclarationFunctionName()
?.let { depths[it] }
?: 0 // The lambda was declared in the top frame
} else {
currentDepth + 1
}
depths[inlineFunctionInfo.name] = calculatedDepth
inlineStackFrameInfo.depth = calculatedDepth
currentDepth = calculatedDepth
}
}
private fun List<InlineStackFrameInfo>.fetchLocationsAndGetNewFrameProxyLocation(
allLocations: List<Location>,
originalLocation: Location
): Location {
val iterator = allLocations.iterator()
val newFrameProxyLocation =
iterator.getInlineFunctionCallLocation(first().inlineFunctionInfo)
?: originalLocation
var inlineStackFrameIndex = 1
var prevLocation = originalLocation
for (location in iterator) {
if (inlineStackFrameIndex > lastIndex) {
break
}
if (this[inlineStackFrameIndex].inlineFunctionInfo.contains(location)) {
this[inlineStackFrameIndex - 1].location = prevLocation
inlineStackFrameIndex++
}
prevLocation = location
}
last().location = originalLocation
return newFrameProxyLocation
}
private fun Iterator<Location>.getInlineFunctionCallLocation(inlineFunctionInfo: AbstractInlineFunctionInfo): Location? {
var prevLocation: Location? = null
for (location in this) {
if (inlineFunctionInfo.contains(location)) {
return prevLocation
}
prevLocation = location
}
return null
}
private fun InlineStackFrameVariableHolder?.getVisibleVariables() =
this?.visibleVariables.orEmpty()
}
private data class InlineStackFrameInfo(val inlineFunctionInfo: AbstractInlineFunctionInfo, var location: Location, var depth: Int) {
fun toInlineStackFrame(
frameProxy: StackFrameProxyImpl,
visibleVariables: List<LocalVariableProxyImpl>
) =
InlineStackFrame(
location,
inlineFunctionInfo.getDisplayName(),
frameProxy,
depth,
visibleVariables
)
}
private abstract class AbstractInlineFunctionInfo(val name: String, val borders: ClosedRange<Location>) {
abstract fun getDisplayName(): String
fun contains(location: Location) =
location in borders
}
private class InlineFunctionInfo(
name: String,
borders: ClosedRange<Location>
) : AbstractInlineFunctionInfo(
name.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION),
borders
) {
override fun getDisplayName() = name
}
private class InlineLambdaNameWrapper(name: String) {
companion object {
private val inlineLambdaRegex =
"${JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT.replace("$", "\\$")}-(.+)-[^\$]+\\$([^\$]+)\\$.*"
.toRegex()
}
private val groupValues = inlineLambdaRegex.matchEntire(name)?.groupValues
val lambdaName = groupValues?.getOrNull(1)
val declarationFunctionName = groupValues?.getOrNull(2)
fun isValid() =
groupValues != null
}
private class InlineLambdaInfo(name: String, borders: ClosedRange<Location>) : AbstractInlineFunctionInfo(name, borders) {
private val nameWrapper = InlineLambdaNameWrapper(name)
override fun getDisplayName(): String {
if (!nameWrapper.isValid()) {
return name
}
return "lambda '${nameWrapper.lambdaName}' in '${nameWrapper.declarationFunctionName}'"
}
fun getDeclarationFunctionName(): String? =
nameWrapper.declarationFunctionName
}
| apache-2.0 | 8e7b9a548dd9ca1154e99f50a2b6ee76 | 38.481132 | 158 | 0.65221 | 5.474166 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/extractVariablesFromCall.kt | 13 | 477 | package extractVariablesFromCall
fun main(args: Array<String>) {
val a = 1
val s = "str"
val klass = MyClass()
//Breakpoint!
val c = 0
}
fun f1(i: Int, s: String) = i + s.length
infix fun Int.f2(s: String) = this + s.length
class MyClass {
fun f1(i: Int, s: String) = i + s.length
}
// EXPRESSION: f1(a, s)
// RESULT: 4: I
// EXPRESSION: a.f2(s)
// RESULT: 4: I
// EXPRESSION: a f2 s
// RESULT: 4: I
// EXPRESSION: klass.f1(a, s)
// RESULT: 4: I
| apache-2.0 | 6425598cf255e6c9eec34a7bb3f825e1 | 16.035714 | 45 | 0.584906 | 2.564516 | false | false | false | false |
smmribeiro/intellij-community | platform/script-debugger/protocol/protocol-reader/src/Util.kt | 16 | 1485 | // 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.protocolReader
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
const val TYPE_FACTORY_NAME_PREFIX: Char = 'F'
const val READER_NAME: String = "reader"
const val PENDING_INPUT_READER_NAME: String = "inputReader"
const val JSON_READER_CLASS_NAME: String = "JsonReaderEx"
val JSON_READER_PARAMETER_DEF: String = "$READER_NAME: $JSON_READER_CLASS_NAME"
/**
* Generate Java type name of the passed type. Type may be parameterized.
*/
internal fun writeJavaTypeName(arg: Type, out: TextOutput) {
if (arg is Class<*>) {
val name = arg.canonicalName
out.append(
if (name == "java.util.List") "List"
else if (name == "java.lang.String") "String?"
else name
)
}
else if (arg is ParameterizedType) {
writeJavaTypeName(arg.rawType, out)
out.append('<')
val params = arg.actualTypeArguments
for (i in params.indices) {
if (i != 0) {
out.comma()
}
writeJavaTypeName(params[i], out)
}
out.append('>')
}
else if (arg is WildcardType) {
val upperBounds = arg.upperBounds!!
if (upperBounds.size != 1) {
throw RuntimeException()
}
out.append("? extends ")
writeJavaTypeName(upperBounds.first(), out)
}
else {
out.append(arg.toString())
}
} | apache-2.0 | ae793d02f125e91791e73ca8e1fcdc3b | 28.137255 | 140 | 0.668687 | 3.788265 | false | false | false | false |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/dsl/LessonUtil.kt | 1 | 23253 | // 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.dsl
import com.intellij.codeInsight.documentation.DocumentationComponent
import com.intellij.codeInsight.documentation.DocumentationEditorPane
import com.intellij.codeInsight.documentation.QuickDocUtil.isDocumentationV2Enabled
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.WindowStateService
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.TextWithMnemonic
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.ui.ScreenUtil
import com.intellij.ui.content.Content
import com.intellij.ui.tabs.impl.JBTabsImpl
import com.intellij.usageView.UsageViewContentManager
import com.intellij.util.messages.Topic
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebuggerManager
import org.assertj.swing.timing.Timeout
import org.jetbrains.annotations.Nls
import training.dsl.LessonUtil.checkExpectedStateOfEditor
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.ui.*
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.getActionById
import training.util.learningToolWindow
import java.awt.*
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import javax.swing.JList
import javax.swing.KeyStroke
object LessonUtil {
val productName: String get() {
return ApplicationNamesInfo.getInstance().fullProductName
}
fun getHelpLink(topic: String): String = getHelpLink(null, topic)
fun getHelpLink(ide: String?, topic: String): String {
val helpIdeName: String = ide ?: when (val name = ApplicationNamesInfo.getInstance().productName) {
"GoLand" -> "go"
"RubyMine" -> "ruby"
"AppCode" -> "objc"
else -> name.lowercase(Locale.ENGLISH)
}
return "https://www.jetbrains.com/help/$helpIdeName/$topic"
}
fun hideStandardToolwindows(project: Project) {
val windowManager = ToolWindowManager.getInstance(project)
for (id in windowManager.toolWindowIds) {
if (id != LearnToolWindowFactory.LEARN_TOOL_WINDOW) {
windowManager.getToolWindow(id)?.hide()
}
}
}
fun insertIntoSample(sample: LessonSample, inserted: String): String {
return sample.text.substring(0, sample.startOffset) + inserted + sample.text.substring(sample.startOffset)
}
/**
* Checks that user edited sample text, moved caret to any place of editor or changed selection
*/
fun TaskContext.restoreIfModifiedOrMoved(sample: LessonSample? = null) {
proposeRestore {
checkPositionOfEditor(sample ?: previous.sample)
}
}
/**
* Checks that user edited sample text, moved caret to any place of editor or changed selection
*/
fun TaskContext.restoreIfModified(sample: LessonSample? = null) {
proposeRestore {
checkExpectedStateOfEditor(sample ?: previous.sample, false)
}
}
/**
* Checks that user edited sample text or moved caret outside of [possibleCaretArea] text
*/
fun TaskContext.restoreIfModifiedOrMovedIncorrectly(possibleCaretArea: String, sample: LessonSample? = null) {
proposeRestore {
checkPositionOfEditor(sample ?: previous.sample) {
checkCaretOnText(possibleCaretArea)
}
}
}
fun TaskRuntimeContext.checkPositionOfEditor(sample: LessonSample,
checkCaret: TaskRuntimeContext.(LessonSample) -> Boolean = { checkCaretValid(it) }
): TaskContext.RestoreNotification? {
return checkExpectedStateOfEditor(sample, false)
?: if (!checkCaret(sample)) sampleRestoreNotification(TaskContext.CaretRestoreProposal, sample) else null
}
private fun TaskRuntimeContext.checkCaretValid(sample: LessonSample): Boolean {
val selection = sample.selection
val currentCaret = editor.caretModel.currentCaret
return if (selection != null && selection.first != selection.second) {
currentCaret.selectionStart == selection.first && currentCaret.selectionEnd == selection.second
}
else currentCaret.offset == sample.startOffset
}
private fun TaskRuntimeContext.checkCaretOnText(text: String): Boolean {
val caretOffset = editor.caretModel.offset
val textStartOffset = editor.document.charsSequence.indexOf(text)
if (textStartOffset == -1) return false
val textEndOffset = textStartOffset + text.length
return caretOffset in textStartOffset..textEndOffset
}
fun TaskRuntimeContext.checkExpectedStateOfEditor(sample: LessonSample,
checkPosition: Boolean = true,
checkModification: (String) -> Boolean = { it.isEmpty() }): TaskContext.RestoreNotification? {
val prefix = sample.text.substring(0, sample.startOffset)
val postfix = sample.text.substring(sample.startOffset)
val docText = editor.document.charsSequence
val message = if (docText.startsWith(prefix) && docText.endsWith(postfix)) {
val middle = docText.subSequence(prefix.length, docText.length - postfix.length).toString()
if (checkModification(middle)) {
val offset = editor.caretModel.offset
if (!checkPosition || (prefix.length <= offset && offset <= prefix.length + middle.length)) {
null
}
else {
TaskContext.CaretRestoreProposal
}
}
else {
TaskContext.ModificationRestoreProposal
}
}
else {
TaskContext.ModificationRestoreProposal
}
return if (message != null) sampleRestoreNotification(message, sample) else null
}
fun TaskRuntimeContext.sampleRestoreNotification(@Nls message: String, sample: LessonSample) =
TaskContext.RestoreNotification(message) { setSample(sample) }
fun findItem(ui: JList<*>, checkList: (item: Any) -> Boolean): Int? {
for (i in 0 until ui.model.size) {
val elementAt = ui.model.getElementAt(i)
if (elementAt != null && checkList(elementAt)) {
return i
}
}
return null
}
fun setEditorReadOnly(editor: Editor) {
if (editor !is EditorEx) return
editor.isViewer = true
EditorModificationUtil.setReadOnlyHint(editor, LearnBundle.message("learn.task.read.only.hint"))
}
fun actionName(actionId: String): @NlsActions.ActionText String {
val name = getActionById(actionId).templatePresentation.text?.replace("...", "")
return "<strong>${name}</strong>"
}
/**
* Use constants from [java.awt.event.KeyEvent] as keyCode.
* For example: rawKeyStroke(KeyEvent.VK_SHIFT)
*/
fun rawKeyStroke(keyCode: Int): String = rawKeyStroke(KeyStroke.getKeyStroke(keyCode, 0))
fun rawKeyStroke(keyStroke: KeyStroke): String {
return " <raw_shortcut>$keyStroke</raw_shortcut> "
}
fun rawEnter(): String = rawKeyStroke(KeyEvent.VK_ENTER)
fun rawCtrlEnter(): String {
return if (SystemInfo.isMac) {
rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.META_DOWN_MASK))
}
else {
rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK))
}
}
fun checkToolbarIsShowing(ui: ActionButton): Boolean {
// Some buttons are duplicated to several tab-panels. It is a way to find an active one.
val parentOfType = UIUtil.getParentOfType(JBTabsImpl.Toolbar::class.java, ui)
val location = parentOfType?.location
val x = location?.x
return x != 0
}
val breakpointXRange: (width: Int) -> IntRange = { IntRange(20, it - 27) }
fun LessonContext.highlightBreakpointGutter(xRange: (width: Int) -> IntRange = breakpointXRange,
logicalPosition: () -> LogicalPosition
) {
task {
triggerByPartOfComponent<EditorGutterComponentEx> l@{ ui ->
if (CommonDataKeys.EDITOR.getData(ui as DataProvider) != editor) return@l null
val y = editor.visualLineToY(editor.logicalToVisualPosition(logicalPosition()).line)
val range = xRange(ui.width)
return@l Rectangle(range.first, y, range.last - range.first + 1, editor.lineHeight)
}
}
}
/**
* Should be called after task with detection of UI element inside desired window to adjust
* @return location of window before adjustment
*/
fun TaskRuntimeContext.adjustPopupPosition(windowKey: String): Point? {
val window = UIUtil.getWindow(previous.ui) ?: return null
val previousWindowLocation = WindowStateService.getInstance(project).getLocation(windowKey)
return if (adjustPopupPosition(project, window)) previousWindowLocation else null
}
fun restorePopupPosition(project: Project, windowKey: String, savedLocation: Point?) {
if (savedLocation != null) invokeLater {
WindowStateService.getInstance(project).putLocation(windowKey, savedLocation)
}
}
fun adjustPopupPosition(project: Project, popupWindow: Window): Boolean {
val learningToolWindow = learningToolWindow(project) ?: return false
val learningComponent = learningToolWindow.component
val learningRectangle = Rectangle(learningComponent.locationOnScreen, learningToolWindow.component.size)
val popupBounds = popupWindow.bounds
val screenRectangle = ScreenUtil.getScreenRectangle(learningComponent)
if (!learningRectangle.intersects(popupBounds)) return false // ok, no intersection
if (!screenRectangle.contains(learningRectangle)) return false // we can make some strange moves in this case
if (learningRectangle.width + popupBounds.width > screenRectangle.width) return false // some huge sizes
when (learningToolWindow.anchor) {
ToolWindowAnchor.LEFT -> {
val rightScreenBorder = screenRectangle.x + screenRectangle.width
val expectedRightPopupBorder = learningRectangle.x + learningRectangle.width + popupBounds.width
if (expectedRightPopupBorder > rightScreenBorder) {
val mainWindow = UIUtil.getParentOfType(IdeFrameImpl::class.java, learningComponent) ?: return false
mainWindow.location = Point(mainWindow.location.x - (expectedRightPopupBorder - rightScreenBorder), mainWindow.location.y)
popupWindow.location = Point(rightScreenBorder - popupBounds.width, popupBounds.y)
}
else {
popupWindow.location = Point(learningRectangle.x + learningRectangle.width, popupBounds.y)
}
}
ToolWindowAnchor.RIGHT -> {
val learningScreenOffset = learningRectangle.x - screenRectangle.x
if (popupBounds.width > learningScreenOffset) {
val mainWindow = UIUtil.getParentOfType(IdeFrameImpl::class.java, learningComponent) ?: return false
mainWindow.location = Point(mainWindow.location.x + (popupBounds.width - learningScreenOffset), mainWindow.location.y)
popupWindow.location = Point(screenRectangle.x, popupBounds.y)
}
else {
popupWindow.location = Point(learningRectangle.x - popupBounds.width, popupBounds.y)
}
}
else -> return false
}
return true
}
inline fun<reified T: Component> findUiParent(start: Component, predicate: (Component) -> Boolean): T? {
if (start is T && predicate(start)) return start
var ui: Container? = start.parent
while (ui != null) {
if (ui is T && predicate(ui)) {
return ui
}
ui = ui.parent
}
return null
}
fun returnToWelcomeScreenRemark(): String {
val isSingleProject = ProjectManager.getInstance().openProjects.size == 1
return if (isSingleProject) LessonsBundle.message("onboarding.return.to.welcome.remark") else ""
}
fun showFeedbackNotification(lesson: Lesson, project: Project) {
invokeLater {
if (project.isDisposed) {
return@invokeLater
}
lesson.module.primaryLanguage?.let { langSupport ->
// exit link will show notification directly and reset this field to null
langSupport.onboardingFeedbackData?.let {
showOnboardingFeedbackNotification(project, it)
}
langSupport.onboardingFeedbackData = null
}
}
}
}
fun LessonContext.firstLessonCompletedMessage() {
text(LessonsBundle.message("goto.action.propose.to.go.next.new.ui", LessonUtil.rawEnter()))
}
fun LessonContext.highlightDebugActionsToolbar() {
task {
before {
LearningUiHighlightingManager.clearHighlights()
}
highlightToolbarWithAction(ActionPlaces.DEBUGGER_TOOLBAR, "Resume", clearPreviousHighlights = false)
if (!Registry.`is`("debugger.new.tool.window.layout")) {
highlightToolbarWithAction(ActionPlaces.DEBUGGER_TOOLBAR, "ShowExecutionPoint", clearPreviousHighlights = false)
}
}
}
private fun TaskContext.highlightToolbarWithAction(place: String, actionId: String, clearPreviousHighlights: Boolean = true) {
val needAction = getActionById(actionId)
triggerByUiComponentAndHighlight(usePulsation = true, clearPreviousHighlights = clearPreviousHighlights) { ui: ActionToolbarImpl ->
if (ui.size.let { it.width > 0 && it.height > 0 } && ui.place == place) {
ui.components.filterIsInstance<ActionButton>().any { it.action == needAction }
}
else false
}
}
fun TaskContext.proceedLink(additionalAbove: Int = 0) {
val gotIt = CompletableFuture<Boolean>()
runtimeText {
removeAfterDone = true
textProperties = TaskTextProperties(UISettings.instance.taskInternalParagraphAbove + additionalAbove, 12)
LessonsBundle.message("proceed.to.the.next.step", LearningUiManager.addCallback { gotIt.complete(true) })
}
addStep(gotIt)
test {
clickLessonMessagePaneLink("Click to proceed")
}
}
/**
* Will click on the first occurrence of [linkText] in the [LessonMessagePane]
*/
fun TaskTestContext.clickLessonMessagePaneLink(linkText: String) {
ideFrame {
val lessonMessagePane = findComponentWithTimeout(defaultTimeout) { _: LessonMessagePane -> true }
val offset = lessonMessagePane.text.indexOf(linkText)
if (offset == -1) error("Not found '$linkText' in the LessonMessagePane")
val rect = lessonMessagePane.modelToView2D(offset + linkText.length / 2)
robot.click(lessonMessagePane, Point(rect.centerX.toInt(), rect.centerY.toInt()))
}
}
fun TaskContext.proposeRestoreForInvalidText(needToType: String) {
proposeRestore {
checkExpectedStateOfEditor(previous.sample) {
needToType.contains(it.replace(" ", ""))
}
}
}
fun TaskContext.checkToolWindowState(toolWindowId: String, isShowing: Boolean) {
addFutureStep {
subscribeForMessageBus(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
val toolWindow = toolWindowManager.getToolWindow(toolWindowId)
if (toolWindow == null && !isShowing || toolWindow?.isVisible == isShowing) {
completeStep()
}
}
})
}
}
fun <L : Any> TaskRuntimeContext.subscribeForMessageBus(topic: Topic<L>, handler: L) {
project.messageBus.connect(taskDisposable).subscribe(topic, handler)
}
fun TaskRuntimeContext.lineWithBreakpoints(): Set<Int> {
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
return breakpointManager.allBreakpoints.filter {
val file = FileDocumentManager.getInstance().getFile(editor.document)
it.sourcePosition?.file == file
}.mapNotNull {
it.sourcePosition?.line
}.toSet()
}
val defaultRestoreDelay: Int
get() = Registry.intValue("ift.default.restore.delay")
/**
* @param [restoreId] where to restore, `null` means the previous task
* @param [restoreRequired] returns true iff restore is needed
*/
fun TaskContext.restoreAfterStateBecomeFalse(restoreId: TaskContext.TaskId? = null,
restoreRequired: TaskRuntimeContext.() -> Boolean) {
var restoreIsPossible = false
restoreState(restoreId) {
val required = restoreRequired()
(restoreIsPossible && required).also { restoreIsPossible = restoreIsPossible || !required }
}
}
fun TaskRuntimeContext.closeAllFindTabs() {
val usageViewManager = UsageViewContentManager.getInstance(project)
var selectedContent: Content?
while (usageViewManager.selectedContent.also { selectedContent = it } != null) {
usageViewManager.closeContent(selectedContent!!)
}
}
fun @Nls String.dropMnemonic(): @Nls String {
return TextWithMnemonic.parse(this).dropMnemonic(true).text
}
fun TaskContext.waitSmartModeStep() {
val future = CompletableFuture<Boolean>()
addStep(future)
DumbService.getInstance(project).runWhenSmart {
future.complete(true)
}
}
private val seconds01 = Timeout.timeout(1, TimeUnit.SECONDS)
fun LessonContext.showWarningIfInplaceRefactoringsDisabled() {
task {
val step = stateCheck {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled
}
val callbackId = LearningUiManager.addCallback {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled = true
step.complete(true)
}
showWarning(LessonsBundle.message("refactorings.change.settings.warning.message", action("ShowSettings"),
strong(OptionsBundle.message("configurable.group.editor.settings.display.name")),
strong(ApplicationBundle.message("title.code.editing")),
strong(ApplicationBundle.message("radiobutton.rename.local.variables.inplace")),
strong(ApplicationBundle.message("radiogroup.rename.local.variables").dropLast(1)),
callbackId)
) {
!EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled
}
}
}
fun LessonContext.restoreRefactoringOptionsInformer() {
if (EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled) return
restoreChangedSettingsInformer {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled = false
}
}
fun LessonContext.restoreChangedSettingsInformer(restoreSettings: () -> Unit) {
task {
runtimeText {
val newMessageIndex = LessonManager.instance.messagesNumber()
val callbackId = LearningUiManager.addCallback {
restoreSettings()
LessonManager.instance.removeMessageAndRepaint(newMessageIndex)
}
LessonsBundle.message("restore.settings.informer", callbackId)
}
}
}
fun LessonContext.highlightButtonById(actionId: String, clearHighlights: Boolean = true): CompletableFuture<Boolean> {
val feature: CompletableFuture<Boolean> = CompletableFuture()
val needToFindButton = getActionById(actionId)
prepareRuntimeTask {
if (clearHighlights) {
LearningUiHighlightingManager.clearHighlights()
}
invokeInBackground {
val result = try {
LearningUiUtil.findAllShowingComponentWithTimeout(project, ActionButton::class.java, seconds01) { ui ->
ui.action == needToFindButton && LessonUtil.checkToolbarIsShowing(ui)
}
}
catch (e: Throwable) {
// Just go to the next step if we cannot find needed button (when this method is used as pass trigger)
feature.complete(false)
throw IllegalStateException("Cannot find button for $actionId", e)
}
taskInvokeLater {
feature.complete(result.isNotEmpty())
for (button in result) {
val options = LearningUiHighlightingManager.HighlightingOptions(usePulsation = true, clearPreviousHighlights = false)
LearningUiHighlightingManager.highlightComponent(button, options)
}
}
}
}
return feature
}
inline fun <reified ComponentType : Component> LessonContext.highlightAllFoundUi(
clearPreviousHighlights: Boolean = true,
highlightInside: Boolean = true,
usePulsation: Boolean = false,
crossinline finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean
) {
val componentClass = ComponentType::class.java
@Suppress("DEPRECATION")
highlightAllFoundUiWithClass(componentClass, clearPreviousHighlights, highlightInside, usePulsation) {
finderFunction(it)
}
}
@Deprecated("Use inline form instead")
fun <ComponentType : Component> LessonContext.highlightAllFoundUiWithClass(componentClass: Class<ComponentType>,
clearPreviousHighlights: Boolean,
highlightInside: Boolean,
usePulsation: Boolean,
finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) {
prepareRuntimeTask {
if (clearPreviousHighlights) LearningUiHighlightingManager.clearHighlights()
invokeInBackground {
val result =
LearningUiUtil.findAllShowingComponentWithTimeout(project, componentClass, seconds01) { ui ->
finderFunction(ui)
}
taskInvokeLater {
for (ui in result) {
val options = LearningUiHighlightingManager.HighlightingOptions(clearPreviousHighlights = false,
highlightInside = highlightInside,
usePulsation = usePulsation)
LearningUiHighlightingManager.highlightComponent(ui, options)
}
}
}
}
}
fun TaskContext.triggerOnQuickDocumentationPopup() {
if (isDocumentationV2Enabled()) {
triggerByUiComponentAndHighlight(false, false) { _: DocumentationEditorPane -> true }
}
else {
triggerByUiComponentAndHighlight(false, false) { _: DocumentationComponent -> true }
}
}
| apache-2.0 | 63e956adfbce8c4272e26ff9ee35e01a | 39.160622 | 146 | 0.715779 | 4.956939 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-core/src/main/kotlin/org/craftsmenlabs/gareth/validator/mongo/ExperimentTemplateConverter.kt | 1 | 1875 | package org.craftsmenlabs.gareth.validator.mongo
import org.craftsmenlabs.gareth.validator.model.ExperimentTemplateCreateDTO
import org.craftsmenlabs.gareth.validator.model.ExperimentTemplateDTO
import org.craftsmenlabs.gareth.validator.model.Gluelines
import org.craftsmenlabs.gareth.validator.time.TimeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ExperimentTemplateConverter @Autowired constructor(val timeService: TimeService) {
fun toEntity(dto: ExperimentTemplateCreateDTO): ExperimentTemplateEntity {
val entity = ExperimentTemplateEntity()
entity.name = dto.name
entity.projectId = dto.projectid
entity.dateCreated = timeService.now()
entity.baseline = dto.glueLines.baseline
entity.assume = dto.glueLines.assume
entity.success = dto.glueLines.success
entity.failure = dto.glueLines.failure
entity.timeline = dto.glueLines.time
entity.projectId = dto.projectid
entity.interval = dto.interval
return entity
}
fun toDTO(entity: ExperimentTemplateEntity): ExperimentTemplateDTO {
val glueLines = Gluelines(
assume = entity.assume,
baseline = entity.baseline,
success = entity.success,
failure = entity.failure,
time = entity.timeline)
return ExperimentTemplateDTO(id = entity.id ?: throw IllegalStateException("Cannot convert ExperimentTemplate with null ID to DTO"),
name = entity.name,
projectId = entity.projectId,
created = entity.dateCreated,
ready = entity.ready,
archived = entity.archived,
interval = entity.interval,
glueLines = glueLines
)
}
} | gpl-2.0 | bf70a9baa8981e9c35395493c79cf640 | 40.688889 | 140 | 0.682667 | 5.222841 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorDocumentMd.kt | 2 | 4629 | package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.Before
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.decisiontables.BeforeRow
import org.livingdoc.api.fixtures.decisiontables.Check
import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture
import org.livingdoc.api.fixtures.decisiontables.Input
import org.livingdoc.api.fixtures.scenarios.Binding
import org.livingdoc.api.fixtures.scenarios.ScenarioFixture
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.api.tagging.Tag
/**
* [ExecutableDocuments][ExecutableDocument] can also be specified in Markdown
*
* @see ExecutableDocument
*/
@Tag("markdown")
@ExecutableDocument("local://Calculator.md")
class CalculatorDocumentMd {
@DecisionTableFixture(parallel = true)
class CalculatorDecisionTableFixture {
private lateinit var sut: Calculator
@Input("a")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("b")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
@ScenarioFixture
class CalculatorScenarioFixture {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
@Step("adding {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} and {bb} and {cc} and {dd} and {ee} and {ff} and {gg} equals {hh}")
fun addMultiple(
@Binding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") a: Float,
@Binding("bb") b: Float,
@Binding("cc") c: Float,
@Binding("dd") d: Float,
@Binding("ee") e: Float,
@Binding("ff") f: Float,
@Binding("gg") g: Float,
@Binding("hh") h: Float
) {
assertThat(a + b + c + d + e + f + g).isEqualTo(h)
}
@Step("subtraction {b} form {a} equals {c}")
fun subtract(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.diff(a, b)
assertThat(result).isEqualTo(c)
}
@Step("multiplying {a} and {b} equals {c}")
fun multiply(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.multiply(a, b)
assertThat(result).isEqualTo(c)
}
@Step("dividing {a} by {b} equals {c}")
fun divide(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.divide(a, b)
assertThat(result).isEqualTo(c)
}
@Step("add {a} to itself and you get {b}")
fun selfadd(
@Binding("a") a: Float,
@Binding("b") b: Float
) {
val result = sut.sum(a, a)
assertThat(result).isEqualTo(b)
}
}
@ScenarioFixture
class CalculatorScenarioFixture2 {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
}
}
| apache-2.0 | ce9f073ff2decf744b4a6191447f66d0 | 27.574074 | 122 | 0.54353 | 4.192935 | false | false | false | false |
blademainer/intellij-community | plugins/settings-repository/testSrc/GitTest.kt | 2 | 11773 | /*
* 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.ApplicationStoreImpl
import com.intellij.configurationStore.write
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.vcs.merge.MergeSession
import com.intellij.testFramework.file
import com.intellij.testFramework.writeChild
import com.intellij.util.PathUtilRt
import org.assertj.core.api.Assertions.assertThat
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.copyLocalConfig
import org.jetbrains.settingsRepository.git.commit
import org.jetbrains.settingsRepository.git.computeIndexDiff
import org.junit.Test
import java.nio.charset.StandardCharsets
import java.util.*
// kotlin bug, cannot be val (.NoSuchMethodError: org.jetbrains.settingsRepository.SettingsRepositoryPackage.getMARKER_ACCEPT_MY()[B)
internal object AM {
val MARKER_ACCEPT_MY: ByteArray = "__accept my__".toByteArray()
val MARKER_ACCEPT_THEIRS: ByteArray = "__accept theirs__".toByteArray()
}
internal class GitTest : GitTestCase() {
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()
}
}
}
}
@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?) {
createLocalAndRemoteRepositories(remoteBranchName)
repositoryManager.pull()
compareFiles(repository.workTree, remoteRepository.workTree)
}
@Test fun pullToRepositoryWithCommits() {
doPullToRepositoryWithCommits(null)
}
@Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() {
doPullToRepositoryWithCommits("customRemoteBranchName")
}
private fun doPullToRepositoryWithCommits(remoteBranchName: String?) {
createLocalAndRemoteRepositories(remoteBranchName)
val file = addAndCommit("local.xml")
repositoryManager.commit()
repositoryManager.pull()
assertThat(repository.workTree.resolve(file.name)).hasBinaryContent(file.data)
compareFiles(repository.workTree, remoteRepository.workTree, PathUtilRt.getFileName(file.name))
}
// 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() {
createLocalAndRemoteRepositories(initialCommit = true)
sync(SyncType.OVERWRITE_LOCAL)
fs
.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.compare()
}
@Test fun `overwrite local: second merge is null`() {
createLocalAndRemoteRepositories(initialCommit = true)
sync(SyncType.MERGE)
restoreRemoteAfterPush()
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 `merge - resolve conflicts to my`() {
createLocalAndRemoteRepositories()
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`() {
createLocalAndRemoteRepositories()
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`() {
createLocalAndRemoteRepositories()
sync(SyncType.MERGE)
provider.delete(SAMPLE_FILE_NAME)
repositoryManager.commit()
remoteRepository.writePath(SAMPLE_FILE_NAME, AM.MARKER_ACCEPT_THEIRS)
remoteRepository.commit("")
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs.compare()
}
@Test fun `commit if unmerged`() {
createLocalAndRemoteRepositories()
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 `overwrite remote: uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE)
}
@Test fun `overwrite local - uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL)
}
@Test fun gitignore() {
createLocalAndRemoteRepositories()
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()
}
}
@Test fun `initial copy to repository: no local files`() {
createRemoteRepository(initialCommit = false)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(false)
}
@Test fun `initial copy to repository: some local files`() {
createRemoteRepository(initialCommit = false)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(true)
}
@Test fun `initial copy to repository: remote files removed`() {
createRemoteRepository(initialCommit = true)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(true, SyncType.OVERWRITE_REMOTE)
}
private fun testInitialCopy(addLocalFiles: Boolean, syncType: SyncType = SyncType.MERGE) {
repositoryManager.createRepositoryIfNeed()
repositoryManager.setUpstream(remoteRepository.getWorkTree().absolutePath)
val store = ApplicationStoreImpl(ApplicationManager.getApplication()!!)
val localConfigPath = tempDirManager.newPath("local_config")
val lafData = """<application>
<component name="UISettings">
<option name="HIDE_TOOL_STRIPES" value="false" />
</component>
</application>"""
if (addLocalFiles) {
localConfigPath.writeChild("options/ui.lnf.xml", lafData)
}
store.setPath(localConfigPath.toString())
store.storageManager.streamProvider = provider
icsManager.sync(syncType, GitTestCase.projectRule.project, { copyLocalConfig(store.storageManager) })
if (addLocalFiles) {
assertThat(localConfigPath).isDirectory()
fs
.file("ui.lnf.xml", lafData)
restoreRemoteAfterPush()
}
else {
assertThat(localConfigPath).doesNotExist()
}
fs.compare()
}
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)
if (syncType != SyncType.OVERWRITE_LOCAL) {
fs.file(path, data)
}
restoreRemoteAfterPush();
fs.compare()
}
} | apache-2.0 | a73e50435067344c3632c2d90288c761 | 30.821622 | 143 | 0.721821 | 4.531563 | false | true | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/MainActivity.kt | 1 | 16246 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 8/12/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.security.keystore.UserNotAuthenticatedException
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_UNLOCKED
import androidx.lifecycle.lifecycleScope
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import com.breadwallet.BuildConfig
import com.breadwallet.R
import com.breadwallet.app.BreadApp
import com.breadwallet.logger.logDebug
import com.breadwallet.tools.animation.BRDialog
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.auth.AuthenticationController
import com.breadwallet.ui.disabled.DisabledController
import com.breadwallet.ui.keystore.KeyStoreController
import com.breadwallet.ui.login.LoginController
import com.breadwallet.ui.migrate.MigrateController
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.ui.navigation.Navigator
import com.breadwallet.ui.navigation.OnCompleteAction
import com.breadwallet.ui.navigation.RouterNavigator
import com.breadwallet.ui.onboarding.IntroController
import com.breadwallet.ui.onboarding.OnBoardingController
import com.breadwallet.ui.pin.InputPinController
import com.breadwallet.ui.recovery.RecoveryKey
import com.breadwallet.ui.recovery.RecoveryKeyController
import com.breadwallet.ui.settings.SettingsController
import com.breadwallet.ui.settings.SettingsSection
import com.breadwallet.util.ControllerTrackingListener
import com.breadwallet.util.errorHandler
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.dropWhile
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.kodein.di.KodeinAware
import org.kodein.di.android.closestKodein
import org.kodein.di.android.retainedSubKodein
import org.kodein.di.erased.bind
import org.kodein.di.erased.instance
import org.kodein.di.erased.singleton
// String extra containing a recovery phrase to bootstrap the recovery process. (debug only)
private const val EXTRA_RECOVER_PHRASE = "RECOVER_PHRASE"
/**
* The main user entrypoint into the app.
*
* This activity serves as a Conductor router host and translates
* platform events into Mobius events.
*/
@Suppress("TooManyFunctions")
class MainActivity : AppCompatActivity(), KodeinAware {
companion object {
const val EXTRA_DATA = "com.breadwallet.ui.MainActivity.EXTRA_DATA"
const val EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID =
"com.breadwallet.ui.MainActivity.EXTRA_PUSH_CAMPAIGN_ID"
}
override val kodein by retainedSubKodein(closestKodein()) {
val router = router
bind<Navigator>() with singleton {
RouterNavigator { router }
}
}
private val userManager by instance<BrdUserManager>()
lateinit var router: Router
private var trackingListener: ControllerTrackingListener? = null
// NOTE: Used only to centralize deep link navigation handling.
private val navigator by instance<Navigator>()
private val resumedScope = CoroutineScope(
Default + SupervisorJob() + errorHandler("resumedScope")
)
private var closeDebugDrawer = { false }
private var launchedWithInvalidState = false
@Suppress("ComplexMethod", "LongMethod")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// The view of this activity is nothing more than a Controller host with animation support
val root = ChangeHandlerFrameLayout(this).also { view ->
router = Conductor.attachRouter(this, view, savedInstanceState)
}
setContentView(if (BuildConfig.DEBUG) createDebugLayout(root, savedInstanceState) else root)
trackingListener = ControllerTrackingListener(this).also(router::addChangeListener)
BreadApp.applicationScope.launch(Main) {
try {
userManager.checkAccountInvalidated()
} catch (e: UserNotAuthenticatedException) {
finish()
return@launch
}
val userState = userManager.getState()
if (userState is BrdUserState.KeyStoreInvalid) {
processUserState(userState)
return@launch
}
userManager.lock()
// Allow launching with a phrase to recover automatically
val hasWallet = userManager.isInitialized()
if (BuildConfig.DEBUG && intent.hasExtra(EXTRA_RECOVER_PHRASE) && !hasWallet) {
val phrase = intent.getStringExtra(EXTRA_RECOVER_PHRASE)!!
if (phrase.isNotBlank() && phrase.split(" ").size == RecoveryKey.M.RECOVERY_KEY_WORDS_COUNT) {
val controller = RecoveryKeyController(RecoveryKey.Mode.RECOVER, phrase)
router.setRoot(RouterTransaction.with(controller))
return@launch
}
}
// The app is launched, no screen to be restored
if (!router.hasRootController()) {
val rootController = when {
userManager.isMigrationRequired() -> MigrateController()
else -> when (userManager.getState()) {
is BrdUserState.Disabled -> DisabledController()
is BrdUserState.Uninitialized -> IntroController()
else -> if (userManager.hasPinCode()) {
val intentUrl = processIntentData(intent)
LoginController(intentUrl)
} else {
InputPinController(OnCompleteAction.GO_HOME)
}
}
}
router.setRoot(
RouterTransaction.with(rootController)
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
)
}
}
if (BuildConfig.DEBUG) {
Utils.printPhoneSpecs(this@MainActivity)
}
}
override fun onDestroy() {
super.onDestroy()
closeDebugDrawer = { false }
trackingListener?.run(router::removeChangeListener)
trackingListener = null
resumedScope.cancel()
}
override fun onResume() {
super.onResume()
BreadApp.setBreadContext(this)
userManager.stateChanges()
.dropWhile { router.backstackSize == 0 }
.map { processUserState(it) }
.flowOn(Main)
.launchIn(resumedScope)
}
override fun onPause() {
super.onPause()
BreadApp.setBreadContext(null)
resumedScope.coroutineContext.cancelChildren()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
router.onActivityResult(requestCode, resultCode, data)
userManager.onActivityResult(requestCode, resultCode)
}
override fun onBackPressed() {
// Defer to controller back-press control before exiting.
if (!closeDebugDrawer() && !router.handleBack()) {
super.onBackPressed()
}
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return checkOverlayAndDispatchTouchEvent(ev)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent ?: return
val data = processIntentData(intent) ?: ""
if (data.isNotBlank() && userManager.isInitialized()) {
val hasRoot = router.hasRootController()
val isTopLogin = router.backstack.lastOrNull()?.controller is LoginController
val isAuthenticated = !isTopLogin && hasRoot
navigator.navigateTo(NavigationTarget.DeepLink(data, isAuthenticated))
}
}
@SuppressLint("RtlHardcoded")
private fun createDebugLayout(root: View, bundle: Bundle?): View {
val drawerDirection = Gravity.RIGHT
val controller = SettingsController(SettingsSection.DEVELOPER_OPTION)
return DrawerLayout(this).apply {
lifecycleScope.launchWhenCreated {
userManager.stateChanges().collect { state ->
val mode = if (state is BrdUserState.Enabled) {
LOCK_MODE_UNLOCKED
} else {
LOCK_MODE_LOCKED_CLOSED
}
setDrawerLockMode(mode, drawerDirection)
}
}
closeDebugDrawer = {
isDrawerOpen(drawerDirection).also {
closeDrawer(drawerDirection)
}
}
addView(root, DrawerLayout.LayoutParams(
DrawerLayout.LayoutParams.MATCH_PARENT,
DrawerLayout.LayoutParams.MATCH_PARENT
))
addView(NavigationView(context).apply {
addView(ChangeHandlerFrameLayout(context).apply {
id = R.id.drawer_layout_id
Conductor.attachRouter(this@MainActivity, this, bundle)
.setRoot(RouterTransaction.with(controller))
}, FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.MATCH_PARENT
))
}, DrawerLayout.LayoutParams(
DrawerLayout.LayoutParams.WRAP_CONTENT,
DrawerLayout.LayoutParams.MATCH_PARENT
).apply {
gravity = drawerDirection
})
}
}
/** Process the new intent and return the url to browse if available */
private fun processIntentData(intent: Intent): String? {
if (intent.hasExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)) {
val campaignId = intent.getStringExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)!!
val attributes = mapOf(EventUtils.EVENT_ATTRIBUTE_CAMPAIGN_ID to campaignId)
EventUtils.pushEvent(EventUtils.EVENT_MIXPANEL_APP_OPEN, attributes)
EventUtils.pushEvent(EventUtils.EVENT_PUSH_NOTIFICATION_OPEN)
}
val data = intent.getStringExtra(EXTRA_DATA)
return if (data.isNullOrBlank()) {
intent.dataString
} else data
}
private fun processUserState(userState: BrdUserState) {
if (userState is BrdUserState.KeyStoreInvalid) {
launchedWithInvalidState = true
logDebug("Device state is invalid, $userState")
val needsKeyStoreController = router.backstack
.map(RouterTransaction::controller)
.filterIsInstance<KeyStoreController>()
.none()
if (needsKeyStoreController) {
router.setRoot(RouterTransaction.with(KeyStoreController()))
}
} else if (launchedWithInvalidState) {
logDebug("Device state is now valid, recreating activity.")
router.setBackstack(emptyList(), null)
recreate()
} else {
if (userManager.isInitialized() && router.hasRootController()) {
when (userState) {
BrdUserState.Locked -> lockApp()
is BrdUserState.Disabled -> disableApp()
}
}
}
}
private fun isBackstackDisabled() = router.backstack
.map(RouterTransaction::controller)
.filterIsInstance<DisabledController>()
.any()
private fun isBackstackLocked() =
router.backstack.lastOrNull()?.controller
?.let {
// Backstack is locked or requires a pin
it is LoginController || it is InputPinController ||
it is AuthenticationController ||
// Backstack is initialization flow
it is OnBoardingController || it is RecoveryKeyController ||
it is MigrateController
} ?: false
private fun disableApp() {
if (isBackstackDisabled()) return
logDebug("Disabling backstack.")
router.pushController(
RouterTransaction.with(DisabledController())
.pushChangeHandler(FadeChangeHandler())
.popChangeHandler(FadeChangeHandler())
)
}
private fun lockApp() {
if (isBackstackDisabled() || isBackstackLocked()) return
val controller = when {
userManager.hasPinCode() ->
LoginController(showHome = router.backstackSize == 0)
else -> InputPinController(
onComplete = OnCompleteAction.GO_HOME,
skipWriteDown = BRSharedPrefs.phraseWroteDown
)
}
logDebug("Locking with controller=$controller")
router.pushController(
RouterTransaction.with(controller)
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
)
}
/**
* Check if there is an overlay view over the screen, if an
* overlay view is found the event won't be dispatched and
* a dialog with a warning will be shown.
*
* @param event The touch screen event.
* @return boolean Return true if this event was consumed or if an overlay view was found.
*/
private fun checkOverlayAndDispatchTouchEvent(event: MotionEvent): Boolean {
// Filter obscured touches by consuming them.
if (event.flags and MotionEvent.FLAG_WINDOW_IS_OBSCURED != 0) {
if (event.action == MotionEvent.ACTION_UP) {
BRDialog.showSimpleDialog(
this, getString(R.string.Android_screenAlteringTitle),
getString(R.string.Android_screenAlteringMessage)
)
}
return true
}
return super.dispatchTouchEvent(event)
}
}
| mit | 665af85a7b622922392f075b7ff8fd6a | 39.212871 | 110 | 0.659424 | 5.300489 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.