content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package de.ph1b.audiobook.data.repo.internals
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.squareup.moshi.Moshi
import de.ph1b.audiobook.data.BookFactory
import de.ph1b.audiobook.data.di.DataComponent
import de.ph1b.audiobook.data.di.DataInjector
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class BookStorageTest {
init {
DataInjector.component = object : DataComponent {
override fun inject(converters: Converters) {
converters.moshi = Moshi.Builder().build()
}
}
}
private val db =
Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDb::class.java)
.allowMainThreadQueries()
.build()
private val storage = BookStorage(db.chapterDao(), db.bookMetadataDao(), db.bookSettingsDao(), db)
val bookA = BookFactory.create(name = "Name A", lastPlayedAtMillis = 5)
val bookB = BookFactory.create(name = "Name B", lastPlayedAtMillis = 10)
init {
runBlocking {
storage.addOrUpdate(bookA)
storage.addOrUpdate(bookB)
}
}
@Test
fun updateName() {
runBlocking {
storage.updateBookName(bookA.id, "Name A2")
val books = storage.books()
val updatedBook = bookA.updateMetaData { copy(name = "Name A2") }
assertThat(books).containsExactly(updatedBook, bookB)
}
}
@Test
fun updateLastPlayedAt() {
runBlocking {
storage.updateLastPlayedAt(bookA.id, 500)
val books = storage.books()
val updatedBook = bookA.update(updateSettings = { copy(lastPlayedAtMillis = 500) })
assertThat(books).containsExactly(updatedBook, bookB)
}
}
}
| data/src/test/java/de/ph1b/audiobook/data/repo/internals/BookStorageTest.kt | 1537601944 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.*
import com.intellij.configurationStore.schemeManager.SchemeManagerImpl
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.Project
import com.intellij.util.SmartList
import com.intellij.util.messages.MessageBus
import gnu.trove.THashSet
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.eclipse.jgit.errors.NoRemoteRepositoryException
import java.util.*
internal class SyncManager(private val icsManager: IcsManager, private val autoSyncManager: AutoSyncManager) {
@Volatile var writeAndDeleteProhibited = false
private set
private suspend fun runSyncTask(onAppExit: Boolean, project: Project?, task: suspend (indicator: ProgressIndicator) -> Unit) {
icsManager.runInAutoCommitDisabledMode {
if (!onAppExit) {
ApplicationManager.getApplication()!!.saveSettings()
}
try {
writeAndDeleteProhibited = true
runModalTask(icsMessage("task.sync.title"), project = project, task = {
runBlocking {
task(it)
}
})
}
finally {
writeAndDeleteProhibited = false
}
}
}
suspend fun sync(syncType: SyncType, project: Project? = null, localRepositoryInitializer: (() -> Unit)? = null, onAppExit: Boolean = false): Boolean {
var exception: Throwable? = null
var restartApplication = false
var updateResult: UpdateResult? = null
var isReadOnlySourcesChanged = false
runSyncTask(onAppExit, project) { indicator ->
indicator.isIndeterminate = true
if (!onAppExit) {
autoSyncManager.waitAutoSync(indicator)
}
val repositoryManager = icsManager.repositoryManager
suspend fun updateRepository() {
when (syncType) {
SyncType.MERGE -> {
updateResult = repositoryManager.pull(indicator)
var doPush = true
if (localRepositoryInitializer != null) {
// must be performed only after initial pull, so, local changes will be relative to remote files
localRepositoryInitializer()
if (!repositoryManager.commit(indicator, syncType) || repositoryManager.getAheadCommitsCount() == 0) {
// avoid error during findRemoteRefUpdatesFor on push - if localRepositoryInitializer specified and nothing to commit (failed or just no files to commit (empty local configuration - no files)),
// so, nothing to push
doPush = false
}
}
if (doPush) {
repositoryManager.push(indicator)
}
}
SyncType.OVERWRITE_LOCAL -> {
// we don't push - probably, repository will be modified/removed (user can do something, like undo) before any other next push activities (so, we don't want to disturb remote)
updateResult = repositoryManager.resetToTheirs(indicator)
}
SyncType.OVERWRITE_REMOTE -> {
updateResult = repositoryManager.resetToMy(indicator, localRepositoryInitializer)
if (repositoryManager.getAheadCommitsCount() > 0) {
repositoryManager.push(indicator)
}
}
}
}
if (localRepositoryInitializer == null) {
try {
// we commit before even if sync "OVERWRITE_LOCAL" - preserve history and ability to undo
repositoryManager.commit(indicator, syncType)
// well, we cannot commit? No problem, upcoming action must do something smart and solve the situation
}
catch (e: ProcessCanceledException) {
LOG.warn("Canceled")
return@runSyncTask
}
catch (e: Throwable) {
LOG.error(e)
// "RESET_TO_*" will do "reset hard", so, probably, error will be gone, so, we can continue operation
if (syncType == SyncType.MERGE) {
exception = e
return@runSyncTask
}
}
}
if (indicator.isCanceled) {
return@runSyncTask
}
try {
if (repositoryManager.hasUpstream()) {
updateRepository()
}
isReadOnlySourcesChanged = updateCloudSchemes(icsManager, indicator)
}
catch (e: ProcessCanceledException) {
LOG.debug("Canceled")
return@runSyncTask
}
catch (e: Throwable) {
if (e !is AuthenticationException && e !is NoRemoteRepositoryException && e !is CannotResolveConflictInTestMode) {
LOG.error(e)
}
exception = e
return@runSyncTask
}
if (updateResult != null) {
restartApplication = runBlocking {
val app = ApplicationManager.getApplication()
updateStoragesFromStreamProvider(icsManager, app.stateStore as ComponentStoreImpl, updateResult!!, app.messageBus,
reloadAllSchemes = syncType == SyncType.OVERWRITE_LOCAL)
}
}
}
if (!onAppExit && restartApplication) {
// disable auto sync on exit
autoSyncManager.enabled = false
// force to avoid saveAll & confirmation
(ApplicationManager.getApplication() as ApplicationImpl).exit(true, true, true)
}
else if (exception != null) {
throw exception!!
}
return updateResult != null || isReadOnlySourcesChanged
}
}
internal fun updateCloudSchemes(icsManager: IcsManager, indicator: ProgressIndicator? = null): Boolean {
val changedRootDirs = icsManager.readOnlySourcesManager.update(indicator) ?: return false
val schemeManagersToReload = SmartList<SchemeManagerImpl<*, *>>()
icsManager.schemeManagerFactory.value.process {
val fileSpec = toRepositoryPath(it.fileSpec, it.roamingType)
if (changedRootDirs.contains(fileSpec)) {
schemeManagersToReload.add(it)
}
}
if (schemeManagersToReload.isNotEmpty()) {
for (schemeManager in schemeManagersToReload) {
schemeManager.reload()
}
}
return schemeManagersToReload.isNotEmpty()
}
internal suspend fun updateStoragesFromStreamProvider(icsManager: IcsManager, store: ComponentStoreImpl, updateResult: UpdateResult, messageBus: MessageBus, reloadAllSchemes: Boolean = false): Boolean {
val (changed, deleted) = (store.storageManager as StateStorageManagerImpl).getCachedFileStorages(updateResult.changed, updateResult.deleted, ::toIdeaPath)
val schemeManagersToReload = SmartList<SchemeManagerImpl<*, *>>()
icsManager.schemeManagerFactory.value.process {
if (reloadAllSchemes) {
schemeManagersToReload.add(it)
}
else {
for (path in updateResult.changed) {
if (it.fileSpec == toIdeaPath(path)) {
schemeManagersToReload.add(it)
}
}
for (path in updateResult.deleted) {
if (it.fileSpec == toIdeaPath(path)) {
schemeManagersToReload.add(it)
}
}
}
}
if (changed.isEmpty() && deleted.isEmpty() && schemeManagersToReload.isEmpty()) {
return false
}
return withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
val changedComponentNames = LinkedHashSet<String>()
updateStateStorage(changedComponentNames, changed, false)
updateStateStorage(changedComponentNames, deleted, true)
for (schemeManager in schemeManagersToReload) {
schemeManager.reload()
}
if (changedComponentNames.isEmpty()) {
return@withContext false
}
val notReloadableComponents = store.getNotReloadableComponents(changedComponentNames)
val changedStorageSet = THashSet<StateStorage>(changed)
changedStorageSet.addAll(deleted)
runBatchUpdate(messageBus) {
store.reinitComponents(changedComponentNames, changedStorageSet, notReloadableComponents)
}
return@withContext !notReloadableComponents.isEmpty() && askToRestart(store, notReloadableComponents, null, true)
}
}
private fun updateStateStorage(changedComponentNames: MutableSet<String>, stateStorages: Collection<StateStorage>, deleted: Boolean) {
for (stateStorage in stateStorages) {
try {
(stateStorage as XmlElementStorage).updatedFromStreamProvider(changedComponentNames, deleted)
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
enum class SyncType(val messageKey: String) {
MERGE("Merge"),
OVERWRITE_LOCAL("ResetToTheirs"),
OVERWRITE_REMOTE("ResetToMy")
}
class NoRemoteRepositoryException(cause: Throwable) : RuntimeException(cause.message, cause)
class CannotResolveConflictInTestMode : RuntimeException() | plugins/settings-repository/src/sync.kt | 3091546933 |
package com.alexstyl.specialdates.people
import com.alexstyl.specialdates.CrashAndErrorTracker
import com.alexstyl.specialdates.date.TimePeriod
import com.alexstyl.specialdates.events.peopleevents.PeopleEventsProvider
import com.alexstyl.specialdates.permissions.MementoPermissions
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject
class PeoplePresenter(
private val permissions: MementoPermissions,
private val peopleEventsProvider: PeopleEventsProvider,
private val viewModelFactory: PeopleViewModelFactory,
private val errorTracker: CrashAndErrorTracker,
private val workScheduler: Scheduler,
private val resultScheduler: Scheduler) {
companion object {
private const val TRIGGER = 1
}
private var disposable: Disposable? = null
private val subject = PublishSubject.create<Int>()
fun startPresentingInto(view: PeopleView) {
disposable =
subject
.doOnSubscribe { _ ->
view.showLoading()
}
.observeOn(workScheduler)
.map { _ ->
peopleEventsProvider.fetchEventsBetween(TimePeriod.aYearFromNow())
}
.map { contacts ->
val viewModels = arrayListOf<PeopleRowViewModel>()
val contactIDs = HashSet<Long>()
viewModels.add(viewModelFactory.facebookViewModel())
if (contacts.isEmpty()) {
viewModels.add(viewModelFactory.noContactsViewModel())
} else {
val mutableList = contacts.toMutableList()
mutableList.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.contact.displayName.toString() }))
mutableList.forEach { contactEvent ->
val contact = contactEvent.contact
if (!contactIDs.contains(contact.contactID)) {
viewModels.add(viewModelFactory.personViewModel(contact))
contactIDs.add(contact.contactID)
}
}
}
viewModels
}
.observeOn(resultScheduler)
.onErrorReturn { error ->
errorTracker.track(error)
arrayListOf()
}
.subscribe { viewModels ->
view.displayPeople(viewModels)
}
if (permissions.canReadAndWriteContacts()) {
refreshData()
}
}
fun refreshData() {
subject.onNext(TRIGGER)
}
fun stopPresenting() {
disposable?.dispose()
}
}
| memento/src/main/java/com/alexstyl/specialdates/people/PeoplePresenter.kt | 1896847937 |
/*
* Copyright 2012-2022 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.boot.docs.data.nosql.elasticsearch.connectingusingspringdata
class User | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/data/nosql/elasticsearch/connectingusingspringdata/User.kt | 3109227525 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.impl
import com.intellij.CommonBundle
import com.intellij.configurationStore.runInAutoSaveDisabledMode
import com.intellij.configurationStore.saveSettings
import com.intellij.execution.wsl.WslPath.Companion.isWslUncPath
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.actions.OpenFileAction
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.application.*
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileChooser.impl.FileChooserUtil
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFrame
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.platform.CommandLineProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.attachToProject
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.createOptionsToOpenDotIdeaOrCreateNewIfNotExists
import com.intellij.project.stateStore
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.ui.AppIcon
import com.intellij.ui.ComponentUtil
import com.intellij.util.ModalityUiUtil
import com.intellij.util.PathUtil
import com.intellij.util.PlatformUtils
import com.intellij.util.SystemProperties
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.io.basicAttributesIfExists
import kotlinx.coroutines.*
import kotlinx.coroutines.future.asCompletableFuture
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.annotations.SystemDependent
import org.jetbrains.annotations.VisibleForTesting
import java.awt.Component
import java.awt.Frame
import java.awt.KeyboardFocusManager
import java.awt.Window
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import kotlin.Result
private val LOG = Logger.getInstance(ProjectUtil::class.java)
private var ourProjectsPath: String? = null
object ProjectUtil {
const val DEFAULT_PROJECT_NAME = "default"
private const val PROJECTS_DIR = "projects"
private const val PROPERTY_PROJECT_PATH = "%s.project.path"
@Deprecated("Use {@link #updateLastProjectLocation(Path)} ", ReplaceWith("updateLastProjectLocation(Path.of(projectFilePath))",
"com.intellij.ide.impl.ProjectUtil.updateLastProjectLocation",
"java.nio.file.Path"))
fun updateLastProjectLocation(projectFilePath: String) {
updateLastProjectLocation(Path.of(projectFilePath))
}
@JvmStatic
fun updateLastProjectLocation(lastProjectLocation: Path) {
var location: Path? = lastProjectLocation
if (Files.isRegularFile(location!!)) {
// for directory-based project storage
location = location.parent
}
if (location == null) {
// the immediate parent of the ipr file
return
}
// the candidate directory to be saved
location = location.parent
if (location == null) {
return
}
var path = location.toString()
path = try {
FileUtil.resolveShortWindowsName(path)
}
catch (e: IOException) {
LOG.info(e)
return
}
RecentProjectsManager.getInstance().lastProjectCreationLocation = PathUtil.toSystemIndependentName(path)
}
@Deprecated("Use {@link ProjectManager#closeAndDispose(Project)} ",
ReplaceWith("ProjectManager.getInstance().closeAndDispose(project)", "com.intellij.openapi.project.ProjectManager"))
@JvmStatic
fun closeAndDispose(project: Project): Boolean {
return ProjectManager.getInstance().closeAndDispose(project)
}
@JvmStatic
fun openOrImport(path: Path, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openOrImport(path, OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
/**
* @param path project file path
* @param projectToClose currently active project
* @param forceOpenInNewFrame forces opening in new frame
* @return project by path if the path was recognized as IDEA project file or one of the project formats supported by
* installed importers (regardless of opening/import result)
* null otherwise
*/
@JvmStatic
fun openOrImport(path: String, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openOrImport(Path.of(path), OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
@JvmStatic
@JvmOverloads
fun openOrImport(file: Path, options: OpenProjectTask = OpenProjectTask()): Project? {
return runUnderModalProgressIfIsEdt {
openOrImportAsync(file, options)
}
}
suspend fun openOrImportAsync(file: Path, options: OpenProjectTask = OpenProjectTask()): Project? {
if (!options.forceOpenInNewFrame) {
findAndFocusExistingProjectForPath(file)?.let {
return it
}
}
var virtualFileResult: Result<VirtualFile>? = null
for (provider in ProjectOpenProcessor.EXTENSION_POINT_NAME.iterable) {
if (!provider.isStrongProjectInfoHolder) {
continue
}
// `PlatformProjectOpenProcessor` is not a strong project info holder, so there is no need to optimize (VFS not required)
val virtualFile: VirtualFile = virtualFileResult?.getOrThrow() ?: blockingContext {
ProjectUtilCore.getFileAndRefresh(file)
}?.also {
virtualFileResult = Result.success(it)
} ?: return null
if (provider.canOpenProject(virtualFile)) {
return chooseProcessorAndOpenAsync(mutableListOf(provider), virtualFile, options)
}
}
if (ProjectUtilCore.isValidProjectPath(file)) {
// see OpenProjectTest.`open valid existing project dir with inability to attach using OpenFileAction` test about why `runConfigurators = true` is specified here
return ProjectManagerEx.getInstanceEx().openProjectAsync(file, options.copy(runConfigurators = true))
}
if (!options.preventIprLookup && Files.isDirectory(file)) {
try {
withContext(Dispatchers.IO) {
Files.newDirectoryStream(file)
}.use { directoryStream ->
for (child in directoryStream) {
val childPath = child.toString()
if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
return openProject(Path.of(childPath), options)
}
}
}
}
catch (ignore: IOException) {
}
}
var nullableVirtualFileResult: Result<VirtualFile?>? = virtualFileResult
val processors = blockingContext {
computeProcessors(file) {
val capturedNullableVirtualFileResult = nullableVirtualFileResult
if (capturedNullableVirtualFileResult != null) {
capturedNullableVirtualFileResult.getOrThrow()
}
else {
ProjectUtilCore.getFileAndRefresh(file).also {
nullableVirtualFileResult = Result.success(it)
}
}
}
}
if (processors.isEmpty()) {
return null
}
val project: Project?
if (processors.size == 1 && processors[0] is PlatformProjectOpenProcessor) {
project = ProjectManagerEx.getInstanceEx().openProjectAsync(
projectStoreBaseDir = file,
options = options.copy(
isNewProject = true,
useDefaultProjectAsTemplate = true,
runConfigurators = true,
beforeOpen = {
it.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, true)
true
},
)
)
}
else {
val virtualFile = nullableVirtualFileResult?.let {
it.getOrThrow() ?: return null
} ?: blockingContext {
ProjectUtilCore.getFileAndRefresh(file)
} ?: return null
project = chooseProcessorAndOpenAsync(processors, virtualFile, options)
}
return postProcess(project)
}
private fun computeProcessors(file: Path, lazyVirtualFile: () -> VirtualFile?): MutableList<ProjectOpenProcessor> {
val processors = ArrayList<ProjectOpenProcessor>()
ProjectOpenProcessor.EXTENSION_POINT_NAME.forEachExtensionSafe { processor: ProjectOpenProcessor ->
if (processor is PlatformProjectOpenProcessor) {
if (Files.isDirectory(file)) {
processors.add(processor)
}
}
else {
val virtualFile = lazyVirtualFile()
if (virtualFile != null && processor.canOpenProject(virtualFile)) {
processors.add(processor)
}
}
}
return processors
}
private fun postProcess(project: Project?): Project? {
if (project == null) {
return null
}
StartupManager.getInstance(project).runAfterOpened {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed) {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW)
toolWindow?.activate(null)
}
}
return project
}
fun openProject(path: String, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openProject(Path.of(path), OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
private suspend fun chooseProcessorAndOpenAsync(processors: MutableList<ProjectOpenProcessor>,
virtualFile: VirtualFile,
options: OpenProjectTask): Project? {
val processor = when (processors.size) {
1 -> {
processors.first()
}
else -> {
processors.removeIf { it is PlatformProjectOpenProcessor }
if (processors.size == 1) {
processors.first()
}
else {
val chooser = options.processorChooser
if (chooser == null) {
withContext(Dispatchers.EDT) {
SelectProjectOpenProcessorDialog.showAndGetChoice(processors, virtualFile)
} ?: return null
}
else {
LOG.info("options.openProcessorChooser will handle the open processor dilemma")
chooser(processors) as ProjectOpenProcessor
}
}
}
}
processor.openProjectAsync(virtualFile, options.projectToClose, options.forceOpenInNewFrame)?.let {
return it.orElse(null)
}
return withContext(Dispatchers.EDT) {
processor.doOpenProject(virtualFile, options.projectToClose, options.forceOpenInNewFrame)
}
}
@JvmStatic
fun openProject(file: Path, options: OpenProjectTask): Project? {
val fileAttributes = file.basicAttributesIfExists()
if (fileAttributes == null) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", file.toString()), CommonBundle.getErrorTitle())
return null
}
val existing = findAndFocusExistingProjectForPath(file)
if (existing != null) {
return existing
}
if (isRemotePath(file.toString()) && !RecentProjectsManager.getInstance().hasPath(FileUtil.toSystemIndependentName(file.toString()))) {
if (!confirmLoadingFromRemotePath(file.toString(), "warning.load.project.from.share", "title.load.project.from.share")) {
return null
}
}
if (fileAttributes.isDirectory) {
val dir = file.resolve(Project.DIRECTORY_STORE_FOLDER)
if (!Files.isDirectory(dir)) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", dir.toString()), CommonBundle.getErrorTitle())
return null
}
}
try {
return ProjectManagerEx.getInstanceEx().openProject(file, options)
}
catch (e: Exception) {
Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.message),
IdeBundle.message("title.cannot.load.project"), Messages.getErrorIcon())
}
return null
}
fun confirmLoadingFromRemotePath(path: String,
msgKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String,
titleKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String): Boolean {
return showYesNoDialog(IdeBundle.message(msgKey, path), titleKey)
}
fun showYesNoDialog(message: @Nls String, titleKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String): Boolean {
return yesNo(IdeBundle.message(titleKey), message)
.icon(Messages.getWarningIcon())
.ask(getActiveFrameOrWelcomeScreen())
}
@JvmStatic
fun getActiveFrameOrWelcomeScreen(): Window? {
val window = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusedWindow
if (window != null) {
return window
}
for (frame in Frame.getFrames()) {
if (frame is IdeFrame && frame.isVisible) {
return frame
}
}
return null
}
fun isRemotePath(path: String): Boolean {
return (path.contains("://") || path.contains("\\\\")) && !isWslUncPath(path)
}
fun findProject(file: Path): Project? = getOpenProjects().firstOrNull { isSameProject(file, it) }
@JvmStatic
fun findAndFocusExistingProjectForPath(file: Path): Project? {
val project = findProject(file)
if (project != null) {
focusProjectWindow(project = project)
}
return project
}
/**
* @return [GeneralSettings.OPEN_PROJECT_SAME_WINDOW] or
* [GeneralSettings.OPEN_PROJECT_NEW_WINDOW] or
* [GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH] or
* `-1` (when a user cancels the dialog)
*/
fun confirmOpenOrAttachProject(): Int {
var mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
val exitCode = Messages.showDialog(
IdeBundle.message("prompt.open.project.or.attach"),
IdeBundle.message("prompt.open.project.or.attach.title"), arrayOf(
IdeBundle.message("prompt.open.project.or.attach.button.this.window"),
IdeBundle.message("prompt.open.project.or.attach.button.new.window"),
IdeBundle.message("prompt.open.project.or.attach.button.attach"),
CommonBundle.getCancelButtonText()
),
0,
Messages.getQuestionIcon(),
ProjectNewWindowDoNotAskOption())
mode = if (exitCode == 0) GeneralSettings.OPEN_PROJECT_SAME_WINDOW else if (exitCode == 1) GeneralSettings.OPEN_PROJECT_NEW_WINDOW else if (exitCode == 2) GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH else -1
if (mode != -1) {
LifecycleUsageTriggerCollector.onProjectFrameSelected(mode)
}
}
return mode
}
@Deprecated("Use {@link #isSameProject(Path, Project)} ",
ReplaceWith("projectFilePath != null && isSameProject(Path.of(projectFilePath), project)",
"com.intellij.ide.impl.ProjectUtil.isSameProject", "java.nio.file.Path"))
fun isSameProject(projectFilePath: String?, project: Project): Boolean {
return projectFilePath != null && isSameProject(Path.of(projectFilePath), project)
}
@JvmStatic
fun isSameProject(projectFile: Path, project: Project): Boolean {
val projectStore = project.stateStore
val existingBaseDirPath = projectStore.projectBasePath
if (existingBaseDirPath.fileSystem !== projectFile.fileSystem) {
return false
}
if (Files.isDirectory(projectFile)) {
return try {
Files.isSameFile(projectFile, existingBaseDirPath)
}
catch (ignore: IOException) {
false
}
}
if (projectStore.storageScheme == StorageScheme.DEFAULT) {
return try {
Files.isSameFile(projectFile, projectStore.projectFilePath)
}
catch (ignore: IOException) {
false
}
}
var parent: Path? = projectFile.parent ?: return false
val parentFileName = parent!!.fileName
if (parentFileName != null && parentFileName.toString() == Project.DIRECTORY_STORE_FOLDER) {
parent = parent.parent
return parent != null && FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString())
}
return projectFile.fileName.toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) &&
FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString())
}
/**
* Focuses the specified project's window. If `stealFocusIfAppInactive` is `true` and corresponding logic is supported by OS
* (making it work on Windows requires enabling focus stealing system-wise, see [com.intellij.ui.WinFocusStealer]), the window will
* get the focus even if other application is currently active. Otherwise, there will be some indication that the target window requires
* user attention. Focus stealing behaviour (enabled by `stealFocusIfAppInactive`) is generally not considered a proper application
* behaviour, and should only be used in special cases, when we know that user definitely expects it.
*/
@JvmStatic
fun focusProjectWindow(project: Project?, stealFocusIfAppInactive: Boolean = false) {
val frame = WindowManager.getInstance().getFrame(project) ?: return
val appIsActive = KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow != null
// On macOS, `j.a.Window#toFront` restores the frame if needed.
// On X Window, restoring minimized frame can steal focus from an active application, so we do it only when the IDE is active.
if (SystemInfoRt.isWindows || (SystemInfoRt.isXWindow && appIsActive)) {
val state = frame.extendedState
if (state and Frame.ICONIFIED != 0) {
frame.extendedState = state and Frame.ICONIFIED.inv()
}
}
if (stealFocusIfAppInactive) {
AppIcon.getInstance().requestFocus(frame as IdeFrame)
}
else {
if (!SystemInfoRt.isXWindow || appIsActive) {
// some Linux window managers allow `j.a.Window#toFront` to steal focus, so we don't call it on Linux when the IDE is inactive
frame.toFront()
}
if (!SystemInfoRt.isWindows) {
// on Windows, `j.a.Window#toFront` will request attention if needed
AppIcon.getInstance().requestAttention(project, true)
}
}
}
@JvmStatic
fun getBaseDir(): String {
val defaultDirectory = GeneralSettings.getInstance().defaultProjectDirectory
if (!defaultDirectory.isNullOrEmpty()) {
return defaultDirectory.replace('/', File.separatorChar)
}
val lastProjectLocation = RecentProjectsManager.getInstance().lastProjectCreationLocation
return lastProjectLocation?.replace('/', File.separatorChar) ?: getUserHomeProjectDir()
}
@JvmStatic
fun getUserHomeProjectDir(): String {
val productName = if (PlatformUtils.isCLion() || PlatformUtils.isAppCode() || PlatformUtils.isDataGrip()) {
ApplicationNamesInfo.getInstance().productName
}
else {
ApplicationNamesInfo.getInstance().lowercaseProductName
}
return SystemProperties.getUserHome().replace('/', File.separatorChar) + File.separator + productName + "Projects"
}
suspend fun openOrImportFilesAsync(list: List<Path>, location: String, projectToClose: Project? = null): Project? {
for (file in list) {
openOrImportAsync(file = file, options = OpenProjectTask {
this.projectToClose = projectToClose
forceOpenInNewFrame = true
})?.let { return it }
}
var result: Project? = null
for (file in list) {
if (!Files.exists(file)) {
continue
}
LOG.debug("$location: open file ", file)
if (projectToClose == null) {
val processor = CommandLineProjectOpenProcessor.getInstanceIfExists()
if (processor != null) {
val opened = PlatformProjectOpenProcessor.openProjectAsync(file)
if (opened != null && result == null) {
result = opened
}
}
}
else {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtilRt.toSystemIndependentName(file.toString()))
if (virtualFile != null && virtualFile.isValid) {
OpenFileAction.openFile(virtualFile, projectToClose)
}
result = projectToClose
}
}
return result
}
//todo: merge somehow with getBaseDir
@JvmStatic
fun getProjectsPath(): @SystemDependent String {
val application = ApplicationManager.getApplication()
val fromSettings = if (application == null || application.isHeadlessEnvironment) null else GeneralSettings.getInstance().defaultProjectDirectory
if (!fromSettings.isNullOrEmpty()) {
return PathManager.getAbsolutePath(fromSettings)
}
if (ourProjectsPath == null) {
val produceName = ApplicationNamesInfo.getInstance().productName.lowercase()
val propertyName = String.format(PROPERTY_PROJECT_PATH, produceName)
val propertyValue = System.getProperty(propertyName)
ourProjectsPath = if (propertyValue != null) PathManager.getAbsolutePath(StringUtil.unquoteString(propertyValue, '\"'))
else projectsDirDefault
}
return ourProjectsPath!!
}
private val projectsDirDefault: String
get() = if (PlatformUtils.isDataGrip()) getUserHomeProjectDir() else PathManager.getConfigPath() + File.separator + PROJECTS_DIR
fun getProjectPath(name: String): Path {
return Path.of(getProjectsPath(), name)
}
fun getProjectFile(name: String): Path? {
val projectDir = getProjectPath(name)
return if (isProjectFile(projectDir)) projectDir else null
}
private fun isProjectFile(projectDir: Path): Boolean {
return Files.isDirectory(projectDir.resolve(Project.DIRECTORY_STORE_FOLDER))
}
@JvmStatic
fun openOrCreateProject(name: String, file: Path): Project? {
return runBlockingUnderModalProgress {
openOrCreateProjectInner(name, file)
}
}
private suspend fun openOrCreateProjectInner(name: String, file: Path): Project? {
val existingFile = if (isProjectFile(file)) file else null
val projectManager = ProjectManagerEx.getInstanceEx()
if (existingFile != null) {
val openProjects = ProjectManager.getInstance().openProjects
for (p in openProjects) {
if (!p.isDefault && isSameProject(existingFile, p)) {
focusProjectWindow(p, false)
return p
}
}
return projectManager.openProjectAsync(existingFile, OpenProjectTask { runConfigurators = true })
}
@Suppress("BlockingMethodInNonBlockingContext")
val created = try {
withContext(Dispatchers.IO) {
!Files.exists(file) && Files.createDirectories(file) != null || Files.isDirectory(file)
}
}
catch (e: IOException) {
false
}
var projectFile: Path? = null
if (created) {
val options = OpenProjectTask {
isNewProject = true
runConfigurators = true
projectName = name
}
val project = projectManager.newProjectAsync(file = file, options = options)
runInAutoSaveDisabledMode {
saveSettings(componentManager = project, forceSavingAllSettings = true)
}
writeAction {
Disposer.dispose(project)
}
projectFile = file
}
if (projectFile == null) {
return null
}
return projectManager.openProjectAsync(projectStoreBaseDir = projectFile, options = OpenProjectTask {
runConfigurators = true
isProjectCreatedWithWizard = true
isRefreshVfsNeeded = false
})
}
@JvmStatic
fun getRootFrameForWindow(window: Window?): IdeFrame? {
var w = window ?: return null
while (w.owner != null) {
w = w.owner
}
return w as? IdeFrame
}
fun getProjectForWindow(window: Window?): Project? {
return getRootFrameForWindow(window)?.project
}
@JvmStatic
fun getProjectForComponent(component: Component?): Project? = getProjectForWindow(ComponentUtil.getWindow(component))
@JvmStatic
fun getActiveProject(): Project? = getProjectForWindow(KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow)
interface ProjectCreatedCallback {
fun projectCreated(project: Project?)
}
@JvmStatic
fun getOpenProjects(): Array<Project> = ProjectUtilCore.getOpenProjects()
@Internal
@VisibleForTesting
suspend fun openExistingDir(file: Path, currentProject: Project?): Project? {
val canAttach = ProjectAttachProcessor.canAttachToProject()
val preferAttach = currentProject != null &&
canAttach &&
(PlatformUtils.isDataGrip() && !ProjectUtilCore.isValidProjectPath(file) || PlatformUtils.isDataSpell())
if (preferAttach && attachToProject(currentProject!!, file, null)) {
return null
}
val project = if (canAttach) {
val options = createOptionsToOpenDotIdeaOrCreateNewIfNotExists(file, currentProject)
ProjectManagerEx.getInstanceEx().openProjectAsync(file, options)
}
else {
openOrImportAsync(file, OpenProjectTask().withProjectToClose(currentProject))
}
if (!ApplicationManager.getApplication().isUnitTestMode) {
FileChooserUtil.setLastOpenedFile(project, file)
}
return project
}
@JvmStatic
fun isValidProjectPath(file: Path): Boolean {
return ProjectUtilCore.isValidProjectPath(file)
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@ScheduledForRemoval
@Deprecated(
"Use runBlockingModal on EDT with proper owner and title, " +
"or runBlockingCancellable(+withBackgroundProgressIndicator with proper title) on BGT"
)
// inline is not used - easier debug
fun <T> runUnderModalProgressIfIsEdt(task: suspend CoroutineScope.() -> T): T {
if (!ApplicationManager.getApplication().isDispatchThread) {
return runBlocking(CoreProgressManager.getCurrentThreadProgressModality().asContextElement()) { task() }
}
return runBlockingUnderModalProgress(task = task)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@RequiresEdt
@ScheduledForRemoval
@Deprecated("Use runBlockingModal with proper owner and title")
fun <T> runBlockingUnderModalProgress(@NlsContexts.ProgressTitle title: String = "", project: Project? = null, task: suspend CoroutineScope.() -> T): T {
return ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable {
val modalityState = CoreProgressManager.getCurrentThreadProgressModality()
runBlocking(modalityState.asContextElement()) {
task()
}
}, title, true, project)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun Project.executeOnPooledThread(task: Runnable) {
coroutineScope.launch { task.run() }
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun <T> Project.computeOnPooledThread(task: Callable<T>): CompletableFuture<T> {
return coroutineScope.async { task.call() }.asCompletableFuture()
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun Project.executeOnPooledIoThread(task: Runnable) {
coroutineScope.launch(Dispatchers.IO) { task.run() }
} | platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.kt | 3807328973 |
/*
Commandspy - A Minecraft server plugin to facilitate real-time usage of commands, and sign-changes
Copyright (C) 2014,2015 Evelyn Snow
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.evelyn.commandspy.util
import moe.evelyn.commandspy.Main
import java.io.Closeable
import java.io.InputStream
import java.io.Writer
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
inline fun <T :Closeable, R> T.with(block: (T) -> R): R
{
val a = block(this)
tryonly {
if (this is Writer) flush()
close()
}
return a
}
fun <R> tryonly(catch :(Exception) -> R? = { null }, lambda :() -> R) :R?
{
try {
return lambda()
} catch (e :Exception) {
return catch(e)
}
}
class Util
{
private constructor() { }
companion object
{
val util = Util()
fun join(a :Array<String>, delimiter :String, startIndex :Int) :String
{
var result = ""
for (i in startIndex..a.size - 1)
result += a[i] + if (i != a.size - 1) delimiter else ""
return result
}
}
/*
*/
fun sit(iStr :String, delimiter :Char, part :Int) :String
{
if (part == 0) {
if (!iStr.contains(delimiter))
return iStr
} else {
if (!iStr.contains(delimiter))
return ""
}
if (part == 0)
return iStr.substring(0, (iStr.indexOf(delimiter, 0)))
return iStr.substring(iStr.indexOf(delimiter, 0) + 1, iStr.length)
}
fun getPemResource(path :String) :X509Certificate
{
val ins : InputStream = Main::class.java.classLoader.getResource(path).openStream()
val cf = CertificateFactory.getInstance("X.509")
return cf.generateCertificate(ins) as X509Certificate
}
} | src/main/kotlin/moe/evelyn/commandspy/util/Util.kt | 2610849218 |
// IS_APPLICABLE: false
fun returnFun(fn: () -> Unit): (() -> Unit) -> Unit = {}
fun test() {
returnFun {} ()<caret> {}
} | plugins/kotlin/idea/tests/testData/intentions/removeEmptyParenthesesFromLambdaCall/afterLambda.kt | 3725049703 |
package name.gyger.jmoney.report
class ReportItem(val id: Long, val amount: Long) | src/main/kotlin/name/gyger/jmoney/report/ReportItem.kt | 1355840056 |
package uk.co.cacoethes.lazybones.config
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.util.ConfigObject
import groovy.util.ConfigSlurper
import groovy.util.logging.Log
import java.io.*
import java.net.URI
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
/**
* <p>Central configuration for Lazybones, although only the static data and methods
* are Lazybones specific. The instance-level API works on the basis of settings
* whose names are dot-separated and supplied from various sources: a base
* configuration (typically hard-coded in the app), an app-managed JSON file that
* can be updated at runtime, and a user-defined configuration.</p>
* <p>The user-defined configuration takes precedence over the app-managed one,
* which in turn takes precedence over the base config. When settings are changed
* at runtime, the class attempts to warn the caller if any setting change will be
* overridden by an existing user-defined value.</p>
* <p>This class also maintains a list of valid settings: if it comes across any
* settings that aren't in the list, it will throw an exception. It will also throw
* an exception if the value of a setting isn't of the registered type. This ensures
* that a user can get quick feedback about typos and other errors in their config.
* </p>
*/
class Configuration(
baseSettings : ConfigObject,
val overrideSettings : Map<String, Any>,
managedSettings : Map<String, Any>,
val validOptions : Map<String, Class<*>>,
val jsonConfigFile : File) {
private val settings : ConfigObject
private val managedSettings : ConfigObject
init {
this.settings = baseSettings
addConfigEntries(managedSettings, this.settings)
addConfigEntries(overrideSettings, this.settings)
this.managedSettings = ConfigObject()
addConfigEntries(managedSettings, this.managedSettings)
processSystemProperties(this.settings)
// Validate the provided settings to ensure that they are known and that
// they have a value of the appropriate type.
val invalidOptions = (this.settings.flatten() as Map<String, Any>).filter { entry ->
!validateSetting(entry.key, validOptions, entry.value)
}.keySet()
if (invalidOptions.isNotEmpty()) {
throw MultipleInvalidSettingsException(invalidOptions.toList())
}
}
/**
* Persists the managed config settings as JSON to the file located by
* {@link #jsonConfigFile}.
* @return A list of the keys in the managed config settings that are
* overridden by values in the user config and system properties
* (represented by a map of override settings).
*/
public fun storeSettings() : List<String> {
val sharedKeys = findIntersectKeys(managedSettings as Map<String, Any>, overrideSettings)
jsonConfigFile.writeText(JsonBuilder(managedSettings).toPrettyString(), ENCODING)
return sharedKeys
}
/**
* Retrieves the value of a setting by name.
* @param name The name of the setting as a dot-separated string.
* @return The current value of the requested setting.
* @throws UnknownSettingException If the setting name is not recognised,
* i.e. it isn't in the registered list of known settings.
*/
public fun getSetting(name : String) : Any? {
requireSettingType(name)
return getConfigOption(this.settings as Map<String, Any>, name)
}
/**
* Retrieves a parent key from the current settings. This method won't work
* for complete setting names (as defined in the known settings/valid
* options map). For example, if the configuration has multiple 'repo.url.*'
* entries, you can get all of them in one go by passing 'repo.url' to this
* method.
* @param rootSettingName The partial setting name (dot-separated) that you
* want.
* @return A map of the keys under the given setting name. The map will be empty
* if there are no settings under the given key.
* @throws UnknownSettingException If the partial setting name doesn't match
* any of the settings in the known settings map.
* @throws InvalidSettingException If the setting name is not partial but
* is a complete match for an entry in the known settings map.
*/
public fun getSubSettings(rootSettingName : String) : Map<String, Any> {
if (validOptions.containsKey(rootSettingName)) {
throw InvalidSettingException(rootSettingName, null, "'$rootSettingName' has no sub-settings")
}
val foundMatching = validOptions.any { entry ->
entry.key.startsWith(rootSettingName + NAME_SEPARATOR) ||
settingNameAsRegex(entry.key).toRegex().matches(rootSettingName)
}
if (!foundMatching) throw UnknownSettingException(rootSettingName)
val setting = getConfigOption(this.settings as Map<String, Any>, rootSettingName)
return (setting ?: hashMapOf<String, Any>()) as Map<String, Any>
}
/**
* Returns all the current settings as a flat map. In other words, the keys
* are the dot-separated names of the settings and there are no nested maps.
* It's similar to converting the hierarchical ConfigObject into a Properties
* object.
*/
public fun getAllSettings() : Map<String, Any> {
return settings.flatten() as Map<String, Any>
}
/**
* Adds a new setting to the current configuration or updates the value of
* an existing setting.
* @param name The name of the setting to add/update (in dot-separated form).
* @param value The new value for the setting. This value may be a
* {@code CharSequence}, in which case this method attempts to convert it to
* the appropriate type for the specified setting.
* @return {@code true} if the new value is <b>not</b> overridden by the
* existing user-defined configuration. If {@code false}, the new value will
* take effect immediately, but won't survive the recreation of the {@link
* Configuration} class.
* @throws UnknownSettingException If the setting name doesn't match any of
* those in the known settings map.
* @throws InvalidSettingException If the given value is not of the appropriate
* type for this setting, or if it cannot be converted to the correct type from
* a string.
*/
public fun putSetting(name : String, value : Any) : Boolean {
val settingType = requireSettingType(name)
val convertedValue : Any
try {
convertedValue =
if (value is CharSequence) Converters.requireConverter(settingType).toType(value.toString())
else requireValueOfType(name, value, settingType)
}
catch (all : Throwable) {
log.log(Level.FINEST, all.getMessage(), all)
throw InvalidSettingException(name, value)
}
setConfigOption(settings, name, convertedValue)
setConfigOption(managedSettings, name, convertedValue)
return getConfigOption(overrideSettings, name) == null
}
/**
* Adds an extra value to an array/list setting.
* @param name The dot-separated setting name to modify.
* @param value The new value to add. If this is a {@code CharSequence}
* then it is converted to the appropriate type.
* @return {@code true} if the new value is <b>not</b> overridden by the
* existing user-defined configuration. If {@code false}, the new value will
* take effect immediately, but won't survive the recreation of the {@link
* Configuration} class.
* @throws UnknownSettingException If the setting name doesn't match any of
* those in the known settings map.
* @throws InvalidSettingException If the given value is not of the appropriate
* type for this setting, or if it cannot be converted to the correct type from
* a string.
*/
public fun appendToSetting(name : String, value : Any) : Boolean {
val settingType = requireSettingType(name)
if (!settingType.isArray()) {
throw InvalidSettingException(
name, value,
"Setting '${name}' is not an array type, so you cannot add to it")
}
val convertedValue = if (value is CharSequence) {
Converters.requireConverter(settingType.getComponentType())?.toType(value.toString())
}
else {
requireValueOfType(name, value, settingType.getComponentType())
}
getConfigOptionAsList(settings, name).add(convertedValue)
getConfigOptionAsList(managedSettings, name).add(convertedValue)
return getConfigOption(overrideSettings, name) == null
}
/**
* Removes all values from an array/list setting.
* @param name The dot-separated name of the setting to clear.
* @throws UnknownSettingException If the setting name doesn't match any of
* those in the known settings map.
*/
public fun clearSetting(name : String) {
requireSettingType(name)
clearConfigOption(settings, name)
clearConfigOption(managedSettings, name)
}
/**
* Takes any config settings under the key "systemProp" and converts them
* into system properties. For example, a "systemProp.http.proxyHost" setting
* becomes an "http.proxyHost" system property in the current JVM.
* @param config The configuration to load system properties from.
*/
fun processSystemProperties(config : ConfigObject) {
(config.getProperty("systemProp") as ConfigObject).flatten().forEach { entry ->
System.setProperty(entry.key as String, entry.value?.toString())
}
}
fun requireSettingType(name : String) : Class<*> {
val settingType = getSettingType(name, validOptions)
if (settingType == null) {
throw UnknownSettingException(name)
}
return settingType
}
fun requireValueOfType(name : String, value : Any, settingType : Class<*>) : Any {
if (valueOfType(value, settingType)) {
return value
}
else {
throw InvalidSettingException(name, value)
}
}
fun valueOfType(value : Any, settingType : Class <*>) : Boolean {
if (settingType.isArray() && value is List<*>) {
return value.all { settingType.getComponentType().isAssignableFrom(it!!.javaClass) }
}
else {
return settingType.isAssignableFrom(value.javaClass)
}
}
}
val SYSPROP_OVERRIDE_PREFIX = "lazybones."
val ENCODING = "UTF-8"
val JSON_CONFIG_FILENAME = "managed-config.json"
val NAME_SEPARATOR = "."
val NAME_SEPARATOR_REGEX = "\\."
val CONFIG_FILE_SYSPROP = "lazybones.config.file"
val VALID_OPTIONS = hashMapOf(
"config.file" to javaClass<String>(),
"cache.dir" to javaClass<String>(),
"git.name" to javaClass<String>(),
"git.email" to javaClass<String>(),
"options.logLevel" to javaClass<String>(),
"options.verbose" to javaClass<Boolean>(),
"options.quiet" to javaClass<Boolean>(),
"options.info" to javaClass<Boolean>(),
"bintrayRepositories" to javaClass<Array<String>>(),
"templates.mappings.*" to javaClass<URI>(),
"systemProp.*" to javaClass<Any>()) +
if (System.getProperty(CONFIG_FILE_SYSPROP)?.endsWith("test-config.groovy") ?: false) {
hashMapOf(
"test.my.option" to javaClass<Int>(),
"test.option.override" to javaClass<String>(),
"test.option.array" to javaClass<Array<String>>(),
"test.integer.array" to javaClass<Array<Int>>(),
"test.other.array" to javaClass<Array<String>>(),
"test.adding.array" to javaClass<Array<String>>())
}
else hashMapOf()
val log = Logger.getLogger(javaClass<Configuration>().getName())
/**
* <ol>
* <li>Loads the default configuration file from the classpath</li>
* <li>Works out the location of the user config file (either the default
* or from a system property)</li>
* <li>Loads the user config file and merges with the default</li>
* <li>Overrides any config options with values provided as system properties</li>
* </ol>
* <p>The system properties take the form of 'lazybones.<config.option>'.</p>
*/
public fun initConfiguration() : Configuration {
val defaultConfig = loadDefaultConfig()
val userConfigFile = File(System.getProperty(CONFIG_FILE_SYSPROP) ?:
defaultConfig.flatten()["config.file"] as String)
val jsonConfigFile = getJsonConfigFile(userConfigFile)
return initConfiguration(
defaultConfig,
if (userConfigFile.exists()) BufferedReader(InputStreamReader(userConfigFile.inputStream(), ENCODING))
else StringReader(""),
jsonConfigFile)
}
public fun initConfiguration(baseConfig : ConfigObject, userConfigSource : Reader, jsonConfigFile : File) : Configuration {
val jsonConfig = HashMap<String, Any>()
if (jsonConfigFile?.exists()) {
jsonConfig.putAll(loadJsonConfig(BufferedReader(InputStreamReader(jsonConfigFile.inputStream(), ENCODING))))
}
val overrideConfig = loadConfig(userConfigSource)
// Load settings from system properties. These override all other sources.
loadConfigFromSystemProperties(overrideConfig)
return Configuration(baseConfig, overrideConfig as Map<String, Any>, jsonConfig, VALID_OPTIONS, jsonConfigFile)
}
/**
* Parses Groovy ConfigSlurper content and returns the corresponding
* configuration as a ConfigObject.
*/
fun loadConfig(r : Reader) : ConfigObject {
return ConfigSlurper().parse(r.readText())
}
fun loadJsonConfig(r : Reader) : Map<String, Any?> {
return JsonSlurper().parse(r) as Map<String, Any?>
}
fun loadDefaultConfig() : ConfigObject {
return ConfigSlurper().parse(javaClass<Configuration>().getResource("defaultConfig.groovy").readText(ENCODING))
}
fun getJsonConfigFile(userConfigFile : File) : File {
return File(userConfigFile.getParentFile(), JSON_CONFIG_FILENAME)
}
fun getSettingType(name : String, knownSettings : Map<String, Any>) : Class<*>? {
val type = knownSettings[name] ?: knownSettings[makeWildcard(name)]
return if (type != null) type as Class<*> else null
}
fun makeWildcard(dottedString : String) : String {
if (dottedString.indexOf(NAME_SEPARATOR) == -1) return dottedString
else return dottedString.split(NAME_SEPARATOR_REGEX.toRegex()).allButLast().join(NAME_SEPARATOR) + ".*"
}
fun matchingSetting(name : String, knownSettings : Map<String, Any>) : Map.Entry<String, Any>? {
return knownSettings.asSequence().firstOrNull { entry ->
entry.key == name || settingNameAsRegex(entry.key).toRegex().hasMatch(name)
}
}
fun settingNameAsRegex(name : String) : String {
return name.replace(NAME_SEPARATOR, NAME_SEPARATOR_REGEX).replace("*", "[\\w]+")
}
/**
* Checks whether
* @param name
* @param knownSettings
* @param value
* @return
*/
fun validateSetting(name : String, knownSettings : Map<String, Any>, value : Any) : Boolean {
val setting = matchingSetting(name, knownSettings)
if (setting == null) throw UnknownSettingException(name)
val converter = Converters.requireConverter(setting.value as Class<*>)
return value == null || converter.validate(value)
}
/**
* <p>Takes a dot-separated string, such as "test.report.dir", and gets the corresponding
* config object property, {@code root.test.report.dir}.</p>
* @param root The config object to retrieve the value from.
* @param dottedString The dot-separated string representing a configuration option.
* @return The required configuration value, or {@code null} if the setting doesn't exist.
*/
private fun getConfigOption(root : Map<String, Any>, dottedString : String) : Any? {
val parts = dottedString.split(NAME_SEPARATOR_REGEX.toRegex())
if (parts.size() == 1) return root.get(parts[0])
val firstParts = parts.allButLast()
val configEntry = firstParts.fold(root as Map<String, Any?>?) { config, keyPart ->
val value = config?.get(keyPart)
if (value != null) value as Map<String, Any?> else null
}
return configEntry?.get(parts.last())
}
private fun getConfigOptionAsList(root : ConfigObject, dottedString : String) : MutableList<Any> {
val initialValue = getConfigOption(root as Map<String, Any>, dottedString)
val newValue = if (initialValue is Collection<*>)
ArrayList<Any>(initialValue)
else if (initialValue != null)
arrayListOf(initialValue)
else ArrayList<Any>()
setConfigOption(root, dottedString, newValue)
return newValue
}
/**
* <p>Takes a dot-separated string, such as "test.report.dir", and sets the corresponding
* config object property, {@code root.test.report.dir}, to the given value.</p>
* <p><em>Note</em> the {@code @CompileDynamic} annotation is currently required due to
* issue <a href="https://jira.codehaus.org/browse/GROOVY-6480">GROOVY-6480</a>.</p>
* @param root The config object to set the value on.
* @param dottedString The dot-separated string representing a configuration option.
* @param value The new value for this option.
* @return The map containing the final part of the dot-separated string as a
* key. In other words, {@code retval.dir == value} for the dotted string example above.
*/
private fun setConfigOption(root : ConfigObject, dottedString : String, value : Any) : Map<String, Any> {
val parts = dottedString.split(NAME_SEPARATOR_REGEX.toRegex())
val firstParts = parts.subList(0, parts.size() - 1)
val configEntry = firstParts.fold(root) { config, keyPart ->
config.getProperty(keyPart) as ConfigObject
}
configEntry.setProperty(parts.last(), value)
return configEntry as Map<String, Any>
}
private fun clearConfigOption(root : ConfigObject, dottedString : String) {
val parts = dottedString.split(NAME_SEPARATOR_REGEX.toRegex())
val configParts = parts.subList(0, parts.size() - 1)
.fold(arrayListOf(root) as MutableList<ConfigObject>) { list, namePart ->
list.add(list.last().getProperty(namePart) as ConfigObject)
list
}
configParts.last().remove(parts.last())
if (parts.size() == 1) return
for (i in parts.size()-2..0) {
if (configParts[i].getProperty(parts[i]) != null) break
configParts[i].remove(parts[i])
}
}
private fun loadConfigFromSystemProperties(overrideConfig : ConfigObject) : Map<String, String> {
val props = (System.getProperties() as Map<String, String>).filter {
it.key.startsWith(SYSPROP_OVERRIDE_PREFIX)
}
props.forEach { entry ->
val settingName = entry.key.substringAfter(SYSPROP_OVERRIDE_PREFIX)
if (!validateSetting(settingName, VALID_OPTIONS, entry.value)) {
log.warning("Unknown option '$settingName' or its values are invalid: ${entry.value}")
}
setConfigOption(overrideConfig, settingName, entry.value)
}
return props
}
/**
* Adds the data from a map to a given Groovy configuration object. This
* works recursively, so any values in the source map that are maps themselves
* are treated as a set of sub-keys in the configuration.
*/
private fun addConfigEntries(data : Map<String, Any>, obj : ConfigObject) {
data.forEach { entry ->
if (entry.value is Map<*, *>) {
addConfigEntries(entry.value as Map<String, Any>, obj.getProperty(entry.key) as ConfigObject)
}
else obj.setProperty(entry.key, entry.value)
}
}
/**
* <p>Takes two maps and works out which keys are shared between two maps.
* Crucially, this method recurses such that it checks the keys of any
* nested maps as well. For example, if two maps have the same keys and
* sub-keys such as [one: [two: "test"]], then the key "one.two" is
* considered to be a shared key. Note how the keys of sub-maps are
* referenced using dot ('.') notation.</p>
* @param map1 The first map.
* @param map2 The map to compare against the first map.
* @return A list of the keys that both maps share. If either map is empty
* or the two share no keys at all, this method returns an empty list.
* Sub-keys are referenced using dot notation ("my.option.override") in the
* same way that <tt>ConfigObject</tt> keys are converted when the settings
* are flattened.
*/
private fun findIntersectKeys(map1 : Map<String, Any>, map2 : Map<String, Any>) : List<String> {
val keys = map1.keySet().intersect(map2.keySet())
val result : MutableList<String> = keys.toArrayList()
for (k in keys) {
if (map1[k] is Map<*, *> && map2[k] is Map<*, *>) {
result.remove(k)
result.addAll(findIntersectKeys(
map1[k] as Map<String, Any>,
map2[k] as Map<String, Any>).map { k + NAME_SEPARATOR + it })
}
}
return result
}
fun List<T>.allButLast<T>() : List<T> {
return this.take(this.size() - 1)
}
| lazybones-app/src/main/kotlin/uk/co/cacoethes/lazybones/config/Configuration.kt | 3663756140 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import kotlin.jvm.Throws
abstract class SimpleProvider: ArgumentsProvider {
override fun provideArguments(context: ExtensionContext) =
arguments().map { Arguments.of(it) }.stream()
@Throws(Exception::class)
abstract fun arguments(): List<Any>
} | okhttp-testing-support/src/main/kotlin/okhttp3/SimpleProvider.kt | 2495555266 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.ui.EmptyIcon
import org.junit.Test
import javax.swing.Icon
class IconLoaderTest {
@Test
fun reflectivePathCheck() {
assertThat(IconLoader.isReflectivePath("AllIcons.Actions.Diff")).isTrue()
assertThat(IconLoader.isReflectivePath("com.intellij.kubernetes.KubernetesIcons.Kubernetes_Y")).isTrue()
}
@Test
fun reflectivePathNestedClass() {
assertThat(IconLoader.getReflectiveIcon("com.intellij.ui.TestIcons.TestNestedIcons.ToolWindow",
TestIcons.TestNestedIcons::class.java.classLoader))
.isEqualTo(TestIcons.TestNestedIcons.ToolWindow)
}
@Test
fun reflectivePathNestedClassWithDollar() {
assertThat(IconLoader.getReflectiveIcon("com.intellij.ui.TestIcons\$TestNestedIcons.ToolWindow",
TestIcons.TestNestedIcons::class.java.classLoader))
.isEqualTo(TestIcons.TestNestedIcons.ToolWindow)
}
@Test
fun reflectivePath() {
assertThat(IconLoader.getReflectiveIcon("com.intellij.ui.TestIcons.NonNested",
TestIcons::class.java.classLoader))
.isEqualTo(TestIcons.NonNested)
}
@Test
fun reflectivePathAllIcons() {
assertThat(IconLoader.getReflectiveIcon("AllIcons.FileTypes.AddAny",
TestIcons::class.java.classLoader))
.isEqualTo(AllIcons.FileTypes.AddAny)
}
}
internal class TestIcons {
companion object {
@JvmField val NonNested: Icon = EmptyIcon.create(21)
}
class TestNestedIcons {
companion object {
@JvmField val ToolWindow: Icon = EmptyIcon.create(42)
}
}
} | platform/platform-tests/testSrc/com/intellij/ui/IconLoaderTest.kt | 105367818 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SystemProperties
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.coroutines.*
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFile
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.writeNewFile
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.time.LocalDate
import java.util.function.BiConsumer
import java.util.zip.Deflater
import kotlin.io.path.nameWithoutExtension
internal val MAC_CODE_SIGN_OPTIONS: PersistentMap<String, String> = persistentMapOf(
"mac_codesign_options" to "runtime",
"mac_codesign_force" to "true",
"mac_codesign_deep" to "true",
)
class MacDistributionBuilder(override val context: BuildContext,
private val customizer: MacDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns"
override val targetOs: OsFamily
get() = OsFamily.MACOS
private fun getDocTypes(): String {
val associations = mutableListOf<String>()
if (customizer.associateIpr) {
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>ipr</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${targetIcnsFileName}</string>
<key>CFBundleTypeName</key>
<string>${context.applicationInfo.productName} Project File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
for (fileAssociation in customizer.fileAssociations) {
val iconPath = fileAssociation.iconPath
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>${fileAssociation.extension}</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes
}
override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
withContext(Dispatchers.IO) {
doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true)
}
}
private suspend fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture, copyDistFiles: Boolean) {
@Suppress("SpellCheckingInspection")
val platformProperties = mutableListOf(
"\n#---------------------------------------------------------------------",
"# macOS-specific system properties",
"#---------------------------------------------------------------------",
"com.apple.mrj.application.live-resize=false",
"jbScreenMenuBar.enabled=true",
"apple.awt.fileDialogForDirectories=true",
"apple.awt.graphics.UseQuartz=true",
"apple.awt.fullscreencapturealldisplays=false"
)
customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") })
layoutMacApp(ideaPropertiesFile = ideaProperties!!,
platformProperties = platformProperties,
docTypes = getDocTypes(),
macDistDir = macDistDir,
arch = arch,
context = context)
generateBuildTxt(context, macDistDir.resolve("Resources"))
// if copyDistFiles false, it means that we will copy dist files directly without stage dir
if (copyDistFiles) {
copyDistFiles(context = context, newDir = macDistDir, os = OsFamily.MACOS, arch = arch)
}
customizer.copyAdditionalFiles(context = context, targetDirectory = macDistDir.toString())
customizer.copyAdditionalFiles(context = context, targetDirectory = macDistDir, arch = arch)
generateUnixScripts(distBinDir = macDistDir.resolve("bin"),
os = OsFamily.MACOS,
arch = arch,
context = context)
}
override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
withContext(Dispatchers.IO) {
doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false)
}
context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val publishSit = context.publishSitArchive
val publishZipOnly = !publishSit && context.options.buildStepsToSkip.contains(BuildOptions.MAC_DMG_STEP)
val binariesToSign = customizer.getBinariesToSign(context, arch)
if (!binariesToSign.isEmpty()) {
context.executeStep(spanBuilder("sign binaries for macOS distribution")
.setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) {
context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), MAC_CODE_SIGN_OPTIONS)
}
}
val macZip = (if (publishZipOnly) context.paths.artifactDir else context.paths.tempDir).resolve("$baseName.mac.${arch.name}.zip")
val macZipWithoutRuntime = macZip.resolveSibling(macZip.nameWithoutExtension + "-no-jdk.zip")
val zipRoot = getMacZipRoot(customizer, context)
val runtimeDist = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch)
val directories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDist)
val extraFiles = context.getDistFiles(os = OsFamily.MACOS, arch = arch)
val compressionLevel = if (publishSit || publishZipOnly) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED
if (context.options.buildMacArtifactsWithRuntime) {
buildMacZip(
targetFile = macZip,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule,
arch = arch,
javaExecutablePath = "../jbr/Contents/Home/bin/java",
context = context),
directories = directories,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(true),
compressionLevel = compressionLevel
)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
buildMacZip(
targetFile = macZipWithoutRuntime,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule,
arch = arch,
javaExecutablePath = null,
context = context),
directories = directories.filterNot { it == runtimeDist },
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(false),
compressionLevel = compressionLevel
)
}
if (publishZipOnly) {
Span.current().addEvent("skip DMG and SIT artifacts producing")
if (context.options.buildMacArtifactsWithRuntime) {
context.notifyArtifactBuilt(macZip)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
context.notifyArtifactBuilt(macZipWithoutRuntime)
}
}
else {
buildForArch(builtinModule = context.builtinModule,
arch = arch,
macZip = macZip,
macZipWithoutRuntime = macZipWithoutRuntime,
customizer = customizer,
context = context)
}
}
}
private fun layoutMacApp(ideaPropertiesFile: Path,
platformProperties: List<String>,
docTypes: String?,
macDistDir: Path,
arch: JvmArchitecture,
context: BuildContext) {
val macCustomizer = customizer
copyDirWithFileFilter(context.paths.communityHomeDir.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter)
copyDir(context.paths.communityHomeDir.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir)
val executable = context.productProperties.baseFileName
Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable"))
//noinspection SpellCheckingInspection
val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath)
val resourcesDistDir = macDistDir.resolve("Resources")
copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName))
for (fileAssociation in customizer.fileAssociations) {
if (!fileAssociation.iconPath.isEmpty()) {
val source = Path.of(fileAssociation.iconPath)
val dest = resourcesDistDir.resolve(source.fileName)
Files.deleteIfExists(dest)
copyFile(source, dest)
}
}
val fullName = context.applicationInfo.productName
//todo[nik] improve
val minor = context.applicationInfo.minorVersion
val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta")
val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}"
val isEap = if (isNotRelease) "-EAP" else ""
val properties = Files.readAllLines(ideaPropertiesFile)
properties.addAll(platformProperties)
Files.write(macDistDir.resolve("bin/idea.properties"), properties)
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList()
val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS, arch).toMutableList()
if (!bootClassPath.isEmpty()) {
//noinspection SpellCheckingInspection
additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath")
}
val predicate: (String) -> Boolean = { it.startsWith("-D") }
val launcherProperties = additionalJvmArgs.filter(predicate)
val launcherVmOptions = additionalJvmArgs.filterNot(predicate)
fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log")
fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof")
VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n")
val urlSchemes = macCustomizer.urlSchemes
val urlSchemesString = if (urlSchemes.isEmpty()) {
""
}
else {
"""
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>Stacktrace</string>
<key>CFBundleURLSchemes</key>
<array>
${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }}
</array>
</dict>
</array>
"""
}
val todayYear = LocalDate.now().year.toString()
//noinspection SpellCheckingInspection
substituteTemplatePlaceholders(
inputFile = macDistDir.resolve("Info.plist"),
outputFile = macDistDir.resolve("Info.plist"),
placeholder = "@@",
values = listOf(
Pair("build", context.fullBuildNumber),
Pair("doc_types", docTypes ?: ""),
Pair("executable", executable),
Pair("icns", targetIcnsFileName),
Pair("bundle_name", fullName),
Pair("product_state", isEap),
Pair("bundle_identifier", macCustomizer.bundleIdentifier),
Pair("year", todayYear),
Pair("version", version),
Pair("vm_options", optionsToXml(launcherVmOptions)),
Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))),
Pair("class_path", classPath),
Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')),
Pair("url_schemes", urlSchemesString),
Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" +
macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } +
" </array>"),
Pair("min_osx", macCustomizer.minOSXVersion),
)
)
val distBinDir = macDistDir.resolve("bin")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/mac/scripts")
Files.newDirectoryStream(sourceScriptDir).use { stream ->
val inspectCommandName = context.productProperties.inspectCommandName
for (file in stream) {
if (file.toString().endsWith(".sh")) {
var fileName = file.fileName.toString()
if (fileName == "inspect.sh" && inspectCommandName != "inspect") {
fileName = "${inspectCommandName}.sh"
}
val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "")
try {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
Files.writeString(sourceFileLf, Files.readString(file).replace("\r", ""))
val target = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
sourceFileLf,
target,
"@@",
listOf(
Pair("product_full", fullName),
Pair("script_name", executable),
Pair("inspectCommandName", inspectCommandName),
),
false,
)
}
finally {
Files.delete(sourceFileLf)
}
}
}
}
}
override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> {
var executableFilePatterns = persistentListOf(
"bin/*.sh",
"plugins/**/*.sh",
"bin/*.py",
"bin/fsnotifier",
"bin/printenv",
"bin/restarter",
"bin/repair",
"MacOS/*"
)
if (includeRuntime) {
executableFilePatterns = executableFilePatterns.addAll(context.bundledRuntime.executableFilesPatterns(OsFamily.MACOS))
}
return executableFilePatterns
.addAll(customizer.extraExecutables)
.addAll(context.getExtraExecutablePattern(OsFamily.MACOS))
}
private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
customizer: MacDistributionCustomizer,
context: BuildContext) {
spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name).useWithScope2 {
val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true)
withContext(Dispatchers.IO) {
buildForArch(builtinModule, arch, macZip, macZipWithoutRuntime, notarize, customizer, context)
Files.deleteIfExists(macZip)
}
}
}
private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
notarize: Boolean,
customizer: MacDistributionCustomizer,
context: BuildContext) {
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val archStr = arch.name
coroutineScope {
if (context.options.buildMacArtifactsWithRuntime) {
createSkippableJob(
spanBuilder("build DMG with Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr",
context
) {
signAndBuildDmg(builder = this@MacDistributionBuilder,
builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZip,
isRuntimeBundled = true,
suffix = suffix,
arch = arch,
notarize = notarize)
}
}
if (context.options.buildMacArtifactsWithoutRuntime) {
requireNotNull(macZipWithoutRuntime)
createSkippableJob(
spanBuilder("build DMG without Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr",
context
) {
signAndBuildDmg(builder = this@MacDistributionBuilder,
builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZipWithoutRuntime,
isRuntimeBundled = false,
suffix = "-no-jdk$suffix",
arch = arch,
notarize = notarize)
}
}
}
}
}
private fun optionsToXml(options: List<String>): String {
val buff = StringBuilder()
for (it in options) {
buff.append(" <string>").append(it).append("</string>\n")
}
return buff.toString().trim()
}
private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String {
val buff = StringBuilder()
for (it in properties) {
val p = it.indexOf('=')
buff.append(" <key>").append(it.substring(2, p)).append("</key>\n")
buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n")
}
moreProperties.forEach { (key, value) ->
buff.append(" <key>").append(key).append("</key>\n")
buff.append(" <string>").append(value).append("</string>\n")
}
return buff.toString().trim()
}
internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String =
"${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents"
internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
javaExecutablePath: String?,
context: BuildContext): String {
val executable = context.productProperties.baseFileName
return generateMultiPlatformProductJson(
relativePathToBin = "../bin",
builtinModules = builtinModule,
launch = listOf(ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
arch = arch.dirName,
launcherPath = "../MacOS/${executable}",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "../bin/${executable}.vmoptions",
startupWmClass = null,
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.MACOS, arch))),
context = context)
}
private fun MacDistributionBuilder.buildMacZip(targetFile: Path,
zipRoot: String,
productJson: String,
directories: List<Path>,
extraFiles: Collection<DistFile>,
executableFilePatterns: List<String>,
compressionLevel: Int) {
spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.use {
for (dir in directories) {
updateExecutablePermissions(dir, executableFilePatterns)
}
val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, _ ->
if (SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions(file)) {
entry.unixMode = executableFileUnixMode
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel, compress = context.options.compressZipFiles).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray())
val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath ->
if (relativePath.endsWith(".txt") && !relativePath.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile)
false
}
else {
true
}
}
for (dir in directories) {
zipOutStream.dir(dir, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
}
for (item in extraFiles) {
zipOutStream.entry(name = "$zipRoot/${item.relativePath}", file = item.file)
}
}
}
checkInArchive(archiveFile = targetFile, pathInArchive = "$zipRoot/Resources", context = context)
}
}
| platform/build-scripts/src/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt | 2329368909 |
package com.kronos.sample
import com.kronos.router.interceptor.Interceptor
import kotlinx.coroutines.*
/**
*
* @Author LiABao
* @Since 2021/3/31
*
*/
class DelayInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) {
GlobalScope.launch {
delay(5000)
withContext(Dispatchers.Main) {
chain.proceed()
}
}
}
} | app/src/main/java/com/kronos/sample/DelayInterceptor.kt | 4082130373 |
package org.stepik.android.domain.user_courses.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_list.model.UserCourseQuery
import org.stepik.android.domain.user_courses.model.UserCourse
interface UserCoursesRepository {
fun getAllUserCourses(userCourseQuery: UserCourseQuery = UserCourseQuery(page = 1), sourceType: DataSourceType = DataSourceType.CACHE): Single<List<UserCourse>>
fun getUserCourses(userCourseQuery: UserCourseQuery = UserCourseQuery(page = 1, isArchived = false), sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<UserCourse>>
fun getUserCourseByCourseId(courseId: Long, sourceType: DataSourceType = DataSourceType.CACHE): Maybe<UserCourse>
fun saveUserCourse(userCourse: UserCourse): Single<UserCourse>
/***
* Cached purpose only
*/
fun addUserCourse(userCourse: UserCourse): Completable
fun removeUserCourse(courseId: Long): Completable
} | app/src/main/java/org/stepik/android/domain/user_courses/repository/UserCoursesRepository.kt | 454691014 |
package fr.free.nrw.commons.notification
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
import fr.free.nrw.commons.databinding.ItemNotificationBinding
import org.wikipedia.util.StringUtil
fun notificationDelegate(onNotificationClicked: (Notification) -> Unit) =
adapterDelegateViewBinding<Notification, Notification, ItemNotificationBinding>({ layoutInflater, parent ->
ItemNotificationBinding.inflate(layoutInflater, parent, false)
}) {
binding.root.setOnClickListener { onNotificationClicked(item) }
bind {
binding.title.text = item.processedNotificationText
binding.time.text = item.date
}
}
private val Notification.processedNotificationText: CharSequence
get() = notificationText.trim()
.replace("(^\\s*)|(\\s*$)".toRegex(), "")
.let { StringUtil.fromHtml(it).toString() }
.let { if (it.length > 280) "${it.substring(0, 279)}..." else it } + " "
| app/src/main/java/fr/free/nrw/commons/notification/NotificationAdapterDelegates.kt | 837559912 |
package org.kodein.di.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import org.kodein.di.DI
/**
* Attaches a [DI] container to the underlying [Composable] tree
*
* @param builder the [DI] container configuration block
* @param content underlying [Composable] tree that will be able to consume the [DI] container
*/
@Composable
fun withDI(builder: DI.MainBuilder.() -> Unit, content: @Composable () -> Unit): Unit =
CompositionLocalProvider(LocalDI provides DI { builder() }) { content() }
/**
* Creates a [DI] container and imports [DI.Module]s before attaching it to the underlying [Composable] tree
*
* @param diModules the [DI.Module]s to import in the newly created [DI] container
* @param content underlying [Composable] tree that will be able to consume the [DI] container
*/
@Composable
fun withDI(vararg diModules: DI.Module, content: @Composable () -> Unit): Unit =
CompositionLocalProvider(LocalDI provides DI { importAll(*diModules) }) { content() }
/**
* Attaches a [DI] container to the underlying [Composable] tree
*
* @param di the [DI] container to attached to the [Composable] tree
* @param content underlying [Composable] tree that will be able to consume the [DI] container
*/
@Composable
fun withDI(di: DI, content: @Composable () -> Unit): Unit =
CompositionLocalProvider(LocalDI provides di) { content() }
| app/src/main/java/org/kodein/di/compose/WithDI.kt | 4279977839 |
object HandshakeCalculator {
private const val REVERSE_SIGNALS_BIT_POSITION = 4
fun calculateHandshake(number: Int): List<Signal> {
val result = Signal.values().filter {
signal -> isBitSet(signal.ordinal, number)
}
if (isBitSet(REVERSE_SIGNALS_BIT_POSITION, number)) {
return result.asReversed()
} else {
return result
}
}
private fun isBitSet(position: Int, number: Int): Boolean {
return number shr position and 1 == 1
}
}
| exercises/practice/secret-handshake/.meta/src/reference/kotlin/HandshakeCalculator.kt | 2967060330 |
package org.stepik.android.presentation.course_revenue
import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonthListItem
import ru.nobird.app.core.model.PagedList
interface CourseBenefitsMonthlyFeature {
sealed class State {
object Loading : State()
object Empty : State()
object Error : State()
data class Content(
val courseBenefitByMonthListDataItems: PagedList<CourseBenefitByMonthListItem.Data>,
val courseBenefitByMonthListItems: List<CourseBenefitByMonthListItem>
) : State()
}
sealed class Message {
data class TryAgain(val courseId: Long) : Message()
data class FetchCourseBenefitsByMonthNext(val courseId: Long) : Message()
data class FetchCourseBenefitsByMonthsSuccess(val courseBenefitByMonthListDataItems: PagedList<CourseBenefitByMonthListItem.Data>) : Message()
object FetchCourseBenefitsByMonthsFailure : Message()
}
sealed class Action {
data class FetchCourseBenefitsByMonths(val courseId: Long, val page: Int = 1) : Action()
sealed class ViewAction : Action()
}
} | app/src/main/java/org/stepik/android/presentation/course_revenue/CourseBenefitsMonthlyFeature.kt | 119856246 |
package me.tatarka.bindingcollectionadapter.sample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import me.tatarka.bindingcollectionadapter.sample.databinding.PagedRecyclerViewBinding
class FragmentPagedRecyclerView : Fragment() {
private val viewModel: ImmutableViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return PagedRecyclerViewBinding.inflate(inflater, container, false).also {
it.lifecycleOwner = this
it.viewModel = viewModel
it.listeners = viewModel
it.executePendingBindings()
}.root
}
}
| app/src/main/java/me/tatarka/bindingcollectionadapter/sample/FragmentPagedRecyclerView.kt | 3393091389 |
package ch.difty.scipamato.core.web.paper.csv
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.web.paper.jasper.ReportHeaderFields
import ch.difty.scipamato.core.web.paper.jasper.review.PaperReview
import com.univocity.parsers.csv.CsvFormat
import com.univocity.parsers.csv.CsvWriter
import com.univocity.parsers.csv.CsvWriterSettings
import java.io.Serializable
import java.io.StringWriter
/**
* CSV Adapter accepting a list of objects of type [T]
* and builds a full CSV file as a single String.
*
* Works well for small number of records but doesn't scale well.
*/
interface CsvAdapter<T> : Serializable {
fun build(types: List<T>): String
}
@Suppress("FunctionName")
abstract class AbstractCsvAdapter<T>(
private val rowMapper: (Collection<T>) -> List<Array<String>>,
private val headers: Array<String?>
) : CsvAdapter<T> {
override fun build(types: List<T>): String {
val rows: List<Array<String>> = rowMapper(types)
StringWriterWithBom().apply {
CsvWriter(this, SemicolonDelimitedSettings()).apply {
writeHeaders(*headers)
writeRowsAndClose(rows)
}
return toString()
}
}
private fun StringWriterWithBom() = StringWriter().apply { write("\ufeff") }
private fun SemicolonDelimitedSettings() = CsvWriterSettings().apply {
format = CsvFormat().apply { delimiter = ';' }
}
}
/**
* Adapter to build the Review CSV file, accepting a list of [Paper]s
*/
class ReviewCsvAdapter(private val rhf: ReportHeaderFields) : AbstractCsvAdapter<Paper>(
rowMapper = { types -> types.map { PaperReview(it, rhf).toRow() } },
headers = arrayOf(
rhf.numberLabel,
rhf.authorYearLabel,
rhf.populationPlaceLabel,
rhf.methodOutcomeLabel,
rhf.exposurePollutantLabel,
rhf.methodStudyDesignLabel,
rhf.populationDurationLabel,
rhf.populationParticipantsLabel,
rhf.exposureAssessmentLabel,
rhf.resultExposureRangeLabel,
rhf.methodConfoundersLabel,
rhf.resultEffectEstimateLabel,
rhf.conclusionLabel,
rhf.commentLabel,
rhf.internLabel,
rhf.goalsLabel,
rhf.populationLabel,
rhf.methodsLabel,
rhf.resultLabel,
),
) {
companion object {
const val FILE_NAME = "review.csv"
}
}
private fun PaperReview.toRow() = arrayOf(
number,
authorYear,
populationPlace,
methodOutcome,
exposurePollutant,
methodStudyDesign,
populationDuration,
populationParticipants,
exposureAssessment,
resultExposureRange,
methodConfounders,
resultEffectEstimate,
conclusion,
comment,
intern,
goals,
population,
methods,
result,
)
| core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/csv/CsvAdapter.kt | 1691190167 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.indices
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.impl.EntityId
import com.intellij.workspaceModel.storage.impl.containers.copy
import com.intellij.workspaceModel.storage.impl.containers.putAll
import org.jetbrains.annotations.TestOnly
open class MultimapStorageIndex private constructor(
internal open val index: BidirectionalMultiMap<EntityId, PersistentEntityId<*>>
) {
constructor() : this(BidirectionalMultiMap<EntityId, PersistentEntityId<*>>())
internal fun getIdsByEntry(entitySource: PersistentEntityId<*>): Set<EntityId> = index.getKeys(entitySource)
internal fun getEntriesById(id: EntityId): Set<PersistentEntityId<*>> = index.getValues(id)
internal fun entries(): Collection<PersistentEntityId<*>> = index.values
class MutableMultimapStorageIndex private constructor(
// Do not write to [index] directly! Create a method in this index and call [startWrite] before write.
override var index: BidirectionalMultiMap<EntityId, PersistentEntityId<*>>
) : MultimapStorageIndex(index) {
private var freezed = true
internal fun index(id: EntityId, elements: Set<PersistentEntityId<*>>? = null) {
startWrite()
index.removeKey(id)
if (elements == null) return
elements.forEach { index.put(id, it) }
}
internal fun index(id: EntityId, element: PersistentEntityId<*>) {
startWrite()
index.put(id, element)
}
internal fun remove(id: EntityId, element: PersistentEntityId<*>) {
startWrite()
index.remove(id, element)
}
@TestOnly
internal fun clear() {
startWrite()
index.clear()
}
@TestOnly
internal fun copyFrom(another: MultimapStorageIndex) {
startWrite()
this.index.putAll(another.index)
}
private fun startWrite() {
if (!freezed) return
freezed = false
index = copyIndex()
}
private fun copyIndex(): BidirectionalMultiMap<EntityId, PersistentEntityId<*>> = index.copy()
fun toImmutable(): MultimapStorageIndex {
freezed = true
return MultimapStorageIndex(index)
}
companion object {
fun from(other: MultimapStorageIndex): MutableMultimapStorageIndex {
if (other is MutableMultimapStorageIndex) other.freezed = true
return MutableMultimapStorageIndex(other.index)
}
}
}
}
| platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/MultimapStorageIndex.kt | 2165276354 |
// 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.internal.statistic.eventLog
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PlatformUtils
import com.intellij.util.containers.ContainerUtil
object StatisticsEventLogProviderUtil {
private val LOG = Logger.getInstance(StatisticsEventLogProviderUtil::class.java)
private val EP_NAME = ExtensionPointName<StatisticsEventLoggerProvider>("com.intellij.statistic.eventLog.eventLoggerProvider")
@JvmStatic
fun getEventLogProviders(): List<StatisticsEventLoggerProvider> {
val providers = EP_NAME.extensionsIfPointIsRegistered
if (providers.isEmpty()) {
return emptyList()
}
val isJetBrainsProduct = isJetBrainsProduct()
return ContainerUtil.filter(providers) { isProviderApplicable(isJetBrainsProduct, it.recorderId, it) }
}
@JvmStatic
fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider {
if (ApplicationManager.getApplication().extensionArea.hasExtensionPoint(EP_NAME.name)) {
val isJetBrainsProduct = isJetBrainsProduct()
val provider = EP_NAME.findFirstSafe { isProviderApplicable(isJetBrainsProduct, recorderId, it) }
provider?.let {
if (LOG.isTraceEnabled) {
LOG.trace("Use event log provider '${provider.javaClass.simpleName}' for recorder-id=${recorderId}")
}
return it
}
}
LOG.warn("Cannot find event log provider with recorder-id=${recorderId}")
return EmptyStatisticsEventLoggerProvider(recorderId)
}
private fun isJetBrainsProduct(): Boolean {
val appInfo = ApplicationInfo.getInstance()
if (appInfo == null || StringUtil.isEmpty(appInfo.shortCompanyName)) {
return true
}
return PlatformUtils.isJetBrainsProduct()
}
private fun isProviderApplicable(isJetBrainsProduct: Boolean, recorderId: String, extension: StatisticsEventLoggerProvider): Boolean {
if (recorderId == extension.recorderId) {
if (!isJetBrainsProduct || !StatisticsRecorderUtil.isBuildInRecorder(recorderId)) {
return true
}
return getPluginInfo(extension::class.java).type.isPlatformOrJetBrainsBundled()
}
return false
}
} | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogProviderUtil.kt | 3537759581 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.places.ktx.model
import com.google.android.libraries.places.api.model.AddressComponents
import com.google.android.libraries.places.ktx.api.model.addressComponent
import com.google.android.libraries.places.ktx.api.model.place
import org.junit.Assert.assertEquals
import org.junit.Test
internal class PlaceTest {
@Test
fun testBuilder() {
val place = place {
setAddress("address")
setAddressComponents(AddressComponents.newInstance(
listOf(
addressComponent("Main Street", listOf("street_address")) {
setShortName("Main St.")
}
)
))
}
assertEquals("address", place.address)
assertEquals(AddressComponents.newInstance(
listOf(
addressComponent("Main Street", listOf("street_address")) {
setShortName("Main St.")
}
)
), place.addressComponents)
}
} | places-ktx/src/test/java/com/google/android/libraries/places/ktx/model/PlaceTest.kt | 1890012542 |
package elastiko
import org.elasticsearch.client.Client
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.common.transport.TransportAddress
import org.elasticsearch.node.Node
import org.elasticsearch.node.NodeBuilder
import java.net.InetAddress
public fun TransportClient.Builder.settings(block: Settings.Builder.() -> Unit) {
val set = Settings.settingsBuilder()
.apply { block() }
.build()
this.settings(set)
}
public fun address(hostname: String, port: Int): TransportAddress {
return InetSocketTransportAddress(InetAddress.getByName(hostname), port)
}
public fun transportClient(nodes: List<TransportAddress>, block: TransportClient.Builder.() -> Unit): Client {
val client = TransportClient.builder()
.apply { block() }
.build()
nodes.forEach {
client.addTransportAddress(it)
}
return client
}
public fun <T : AutoCloseable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
close()
}
}
}
public fun NodeBuilder.settings(block: Settings.Builder.() -> Unit) {
val set = Settings.settingsBuilder()
.apply { block() }
.build()
this.settings(set)
}
public fun nodeClient(block: NodeBuilder.() -> Unit): Pair<Node, Client> {
val node = NodeBuilder.nodeBuilder().apply { block() }.node()
return node to node.client()
}
| src/main/kotlin/elastiko/Client.kt | 3272485713 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package kotlinx.coroutines.debug
import com.google.gson.*
import kotlinx.coroutines.*
import kotlinx.coroutines.debug.internal.*
import org.junit.Test
import kotlin.test.*
class EnhanceStackTraceWithTreadDumpAsJsonTest : DebugTestBase() {
private data class StackTraceElementInfoFromJson(
val declaringClass: String,
val methodName: String,
val fileName: String?,
val lineNumber: Int
)
@Test
fun testEnhancedStackTraceFormatWithDeferred() = runTest {
val deferred = async {
suspendingMethod()
assertTrue(true)
}
yield()
val coroutineInfo = DebugProbesImpl.dumpCoroutinesInfo()
assertEquals(coroutineInfo.size, 2)
val info = coroutineInfo[1]
val enhancedStackTraceAsJsonString = DebugProbesImpl.enhanceStackTraceWithThreadDumpAsJson(info)
val enhancedStackTraceFromJson = Gson().fromJson(enhancedStackTraceAsJsonString, Array<StackTraceElementInfoFromJson>::class.java)
val enhancedStackTrace = DebugProbesImpl.enhanceStackTraceWithThreadDump(info, info.lastObservedStackTrace)
assertEquals(enhancedStackTrace.size, enhancedStackTraceFromJson.size)
for ((frame, frameFromJson) in enhancedStackTrace.zip(enhancedStackTraceFromJson)) {
assertEquals(frame.className, frameFromJson.declaringClass)
assertEquals(frame.methodName, frameFromJson.methodName)
assertEquals(frame.fileName, frameFromJson.fileName)
assertEquals(frame.lineNumber, frameFromJson.lineNumber)
}
deferred.cancelAndJoin()
}
private suspend fun suspendingMethod() {
delay(Long.MAX_VALUE)
}
}
| kotlinx-coroutines-debug/test/EnhanceStackTraceWithTreadDumpAsJsonTest.kt | 1190008388 |
package com.antyzero.smoksmog.storage.model
sealed class Module {
private val _class: String = javaClass.canonicalName
/**
* Show AQI and it's type
*/
class AirQualityIndex(val type: Type = AirQualityIndex.Type.POLISH) : Module() {
enum class Type {
POLISH
}
}
/**
* List of measurements for particulates
*/
class Measurements : Module()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Module) return false
if (_class != other._class) return false
return true
}
override fun hashCode(): Int {
return _class.hashCode()
}
} | domain/src/main/kotlin/com/antyzero/smoksmog/storage/model/Module.kt | 122274384 |
/*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.example.android.uamp.MediaItemData.Companion.PLAYBACK_RES_CHANGED
import kotlinx.android.synthetic.main.fragment_mediaitem.view.albumArt
import kotlinx.android.synthetic.main.fragment_mediaitem.view.item_state
import kotlinx.android.synthetic.main.fragment_mediaitem.view.subtitle
import kotlinx.android.synthetic.main.fragment_mediaitem.view.title
/**
* [RecyclerView.Adapter] of [MediaItemData]s used by the [MediaItemFragment].
*/
class MediaItemAdapter(private val itemClickedListener: (MediaItemData) -> Unit
) : ListAdapter<MediaItemData, MediaViewHolder>(MediaItemData.diffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_mediaitem, parent, false)
return MediaViewHolder(view, itemClickedListener)
}
override fun onBindViewHolder(holder: MediaViewHolder,
position: Int,
payloads: MutableList<Any>) {
val mediaItem = getItem(position)
var fullRefresh = payloads.isEmpty()
if (payloads.isNotEmpty()) {
payloads.forEach { payload ->
when (payload) {
PLAYBACK_RES_CHANGED -> {
holder.playbackState.setImageResource(mediaItem.playbackRes)
}
// If the payload wasn't understood, refresh the full item (to be safe).
else -> fullRefresh = true
}
}
}
// Normally we only fully refresh the list item if it's being initially bound, but
// we might also do it if there was a payload that wasn't understood, just to ensure
// there isn't a stale item.
if (fullRefresh) {
holder.item = mediaItem
holder.titleView.text = mediaItem.title
holder.subtitleView.text = mediaItem.subtitle
holder.playbackState.setImageResource(mediaItem.playbackRes)
Glide.with(holder.albumArt)
.load(mediaItem.albumArtUri)
.into(holder.albumArt)
}
}
override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
onBindViewHolder(holder, position, mutableListOf())
}
}
class MediaViewHolder(view: View,
itemClickedListener: (MediaItemData) -> Unit
) : RecyclerView.ViewHolder(view) {
val titleView: TextView = view.title
val subtitleView: TextView = view.subtitle
val albumArt: ImageView = view.albumArt
val playbackState: ImageView = view.item_state
var item: MediaItemData? = null
init {
view.setOnClickListener {
item?.let { itemClickedListener(it) }
}
}
}
| app/src/main/java/com/example/android/uamp/MediaItemAdapter.kt | 730554142 |
package slatekit.query
/**
* Interface for building a delete statement with criteria
*/
abstract class Delete(converter: ((String) -> String)? = null,
encoder:((String) -> String)? = null)
: CriteriaBase<Delete>(converter, encoder), Stmt {
}
| src/lib/kotlin/slatekit-query/src/main/kotlin/slatekit/query/Delete.kt | 1912056470 |
@file:Suppress("unused")
package com.agoda.kakao.common.matchers
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.DrawableCompat
import com.agoda.kakao.common.extentions.toBitmap
import com.agoda.kakao.common.utilities.getResourceColor
import com.agoda.kakao.common.utilities.getResourceDrawable
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
/**
* Matches given drawable with current one
*
* @param resId Drawable resource to be matched (default is -1)
* @param drawable Drawable instance to be matched (default is null)
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
class DrawableMatcher(
@DrawableRes private val resId: Int = -1,
private val drawable: Drawable? = null,
@ColorRes private val tintColorId: Int? = null,
private val toBitmap: ((drawable: Drawable) -> Bitmap)? = null
) : TypeSafeMatcher<View>(View::class.java) {
override fun describeTo(desc: Description) {
desc.appendText("with drawable id $resId or provided instance")
}
override fun matchesSafely(view: View?): Boolean {
if (view !is ImageView && drawable == null) {
return false
}
if (resId < 0 && drawable == null) {
return (view as ImageView).drawable == null
}
return view?.let { imageView ->
var expectedDrawable: Drawable? = drawable ?: getResourceDrawable(resId)?.mutate()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tintColorId?.let { tintColorId ->
val tintColor = getResourceColor(tintColorId)
expectedDrawable?.apply {
setTintList(ColorStateList.valueOf(tintColor))
setTintMode(PorterDuff.Mode.SRC_IN)
}
}
}
if (expectedDrawable == null) {
return false
}
val convertDrawable = (imageView as ImageView).drawable.mutate()
val bitmap = toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()
val otherBitmap = toBitmap?.invoke(expectedDrawable) ?: expectedDrawable.toBitmap()
return bitmap.sameAs(otherBitmap)
} ?: false
}
}
| kakao/src/main/kotlin/com/agoda/kakao/common/matchers/DrawableMatcher.kt | 3556774593 |
// 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.execution.wsl.target
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.target.*
import com.intellij.execution.target.TargetEnvironmentAwareRunProfileState.TargetProgressIndicator
import com.intellij.execution.wsl.WSLCommandLineOptions
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.sizeOrNull
import java.io.IOException
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
class WslTargetEnvironment(wslRequest: WslTargetEnvironmentRequest,
private val distribution: WSLDistribution) : TargetEnvironment(wslRequest) {
private val myUploadVolumes: MutableMap<UploadRoot, UploadableVolume> = HashMap()
private val myDownloadVolumes: MutableMap<DownloadRoot, DownloadableVolume> = HashMap()
private val myTargetPortBindings: MutableMap<TargetPortBinding, Int> = HashMap()
private val myLocalPortBindings: MutableMap<LocalPortBinding, ResolvedPortBinding> = HashMap()
private val localPortBindingsSession : WslTargetLocalPortBindingsSession
override val uploadVolumes: Map<UploadRoot, UploadableVolume>
get() = Collections.unmodifiableMap(myUploadVolumes)
override val downloadVolumes: Map<DownloadRoot, DownloadableVolume>
get() = Collections.unmodifiableMap(myDownloadVolumes)
override val targetPortBindings: Map<TargetPortBinding, Int>
get() = Collections.unmodifiableMap(myTargetPortBindings)
override val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding>
get() = Collections.unmodifiableMap(myLocalPortBindings)
override val targetPlatform: TargetPlatform
get() = TargetPlatform(Platform.UNIX)
init {
for (uploadRoot in wslRequest.uploadVolumes) {
val targetRoot: String? = toLinuxPath(uploadRoot.localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myUploadVolumes[uploadRoot] = Volume(uploadRoot.localRootPath, targetRoot)
}
}
for (downloadRoot in wslRequest.downloadVolumes) {
val localRootPath = downloadRoot.localRootPath ?: FileUtil.createTempDirectory("intellij-target.", "").toPath()
val targetRoot: String? = toLinuxPath(localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myDownloadVolumes[downloadRoot] = Volume(localRootPath, targetRoot)
}
}
for (targetPortBinding in wslRequest.targetPortBindings) {
val theOnlyPort = targetPortBinding.target
if (targetPortBinding.local != null && targetPortBinding.local != theOnlyPort) {
throw UnsupportedOperationException("Local target's TCP port forwarder is not implemented")
}
myTargetPortBindings[targetPortBinding] = theOnlyPort
}
localPortBindingsSession = WslTargetLocalPortBindingsSession(distribution, wslRequest.localPortBindings)
localPortBindingsSession.start()
for (localPortBinding in wslRequest.localPortBindings) {
val targetHostPortFuture = localPortBindingsSession.getTargetHostPortFuture(localPortBinding)
val localHostPort = HostPort("localhost", localPortBinding.local)
var targetHostPort = localHostPort
try {
targetHostPort = targetHostPortFuture.get(10, TimeUnit.SECONDS)
}
catch (e: Exception) {
LOG.info("Cannot get target host and port for $localPortBinding")
}
myLocalPortBindings[localPortBinding] = ResolvedPortBinding(localHostPort, targetHostPort)
}
}
private fun toLinuxPath(localPath: String): String? {
val linuxPath = distribution.getWslPath(localPath)
if (linuxPath != null) {
return linuxPath
}
return convertUncPathToLinux(localPath)
}
private fun convertUncPathToLinux(localPath: String): String? {
val root: String = WSLDistribution.UNC_PREFIX + distribution.msId
val winLocalPath = FileUtil.toSystemDependentName(localPath)
if (winLocalPath.startsWith(root)) {
val linuxPath = winLocalPath.substring(root.length)
if (linuxPath.isEmpty()) {
return "/"
}
if (linuxPath.startsWith("\\")) {
return FileUtil.toSystemIndependentName(linuxPath)
}
}
return null
}
@Throws(ExecutionException::class)
override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process {
var line = GeneralCommandLine(commandLine.collectCommandsSynchronously())
line.environment.putAll(commandLine.environmentVariables)
val options = WSLCommandLineOptions().setRemoteWorkingDirectory(commandLine.workingDirectory)
line = distribution.patchCommandLine(line, null, options)
val process = line.createProcess()
localPortBindingsSession.stopWhenProcessTerminated(process)
return process
}
override fun shutdown() {}
private inner class Volume(override val localRoot: Path, override val targetRoot: String) : UploadableVolume, DownloadableVolume {
@Throws(IOException::class)
override fun resolveTargetPath(relativePath: String): String {
val localPath = FileUtil.toCanonicalPath(FileUtil.join(localRoot.toString(), relativePath))
return toLinuxPath(localPath)!!
}
@Throws(IOException::class)
override fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) {
}
@Throws(IOException::class)
override fun download(relativePath: String, progressIndicator: ProgressIndicator) {
// Synchronization may be slow -- let us wait until file size does not change
// in a reasonable amount of time
// (see https://github.com/microsoft/WSL/issues/4197)
val path = localRoot.resolve(relativePath)
var previousSize = -2L // sizeOrNull returns -1 if file does not exist
var newSize = path.sizeOrNull()
while (previousSize < newSize) {
Thread.sleep(100)
previousSize = newSize
newSize = path.sizeOrNull()
}
if (newSize == -1L) {
LOG.warn("Path $path was not found on local filesystem")
}
}
}
companion object {
val LOG = logger<WslTargetEnvironment>()
}
}
| platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironment.kt | 893623517 |
package codegen.delegatedProperty.simpleVal
import kotlin.test.*
import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(receiver: Any?, p: KProperty<*>): Int {
println(p.name)
return 42
}
}
class C {
val x: Int by Delegate()
}
@Test fun runTest() {
println(C().x)
} | backend.native/tests/codegen/delegatedProperty/simpleVal.kt | 1083769304 |
package codegen.coroutines.degenerate2
import kotlin.test.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resume(value: Any?) {}
override fun resumeWithException(exception: Throwable) { throw exception }
}
suspend fun s1(): Unit = suspendCoroutineOrReturn { x ->
println("s1")
x.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun s2() {
println("s2")
s1()
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
builder {
s2()
}
} | backend.native/tests/codegen/coroutines/degenerate2.kt | 3540206735 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.bluetooth.BluetoothDevice as FwkBluetoothDevice
import android.bluetooth.le.AdvertisingSetParameters as FwkAdvertisingSetParameters
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
/**
* TODO: Add docs
* TODO: Support API 21
*
* @hide
*/
@RequiresApi(Build.VERSION_CODES.O)
class AdvertisingSetParameters internal constructor(
internal val fwkInstance: FwkAdvertisingSetParameters
) : Bundleable {
companion object {
internal const val FIELD_FWK_ADVERTISING_SET_PARAMETERS = 0
val CREATOR: Bundleable.Creator<AdvertisingSetParameters> =
object : Bundleable.Creator<AdvertisingSetParameters> {
override fun fromBundle(bundle: Bundle): AdvertisingSetParameters {
val fwkAdvertisingSetParameters =
Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_ADVERTISING_SET_PARAMETERS),
android.bluetooth.le.AdvertisingSetParameters::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include a framework advertising set parameters"
)
return AdvertisingSetParameters(fwkAdvertisingSetParameters)
}
}
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
internal fun buildFwkAdvertisingSetParameters(
connectable: Boolean = false,
scannable: Boolean = false,
isLegacy: Boolean = false,
isAnonymous: Boolean = false,
includeTxPower: Boolean = false,
primaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
secondaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
txPowerLevel: Int = TX_POWER_MEDIUM
): FwkAdvertisingSetParameters {
val builder = FwkAdvertisingSetParameters.Builder()
.setConnectable(connectable)
.setScannable(scannable)
.setLegacyMode(isLegacy)
.setAnonymous(isAnonymous)
.setIncludeTxPower(includeTxPower)
.setPrimaryPhy(primaryPhy)
.setSecondaryPhy(secondaryPhy)
.setTxPowerLevel(txPowerLevel)
return builder.build()
}
/**
* Advertise on low frequency, around every 1000ms. This is the default and preferred
* advertising mode as it consumes the least power.
*/
const val INTERVAL_HIGH = FwkAdvertisingSetParameters.INTERVAL_HIGH
/**
* Advertise on medium frequency, around every 250ms. This is balanced between advertising
* frequency and power consumption.
*/
const val INTERVAL_MEDIUM = FwkAdvertisingSetParameters.INTERVAL_MEDIUM
/**
* Perform high frequency, low latency advertising, around every 100ms. This has the highest
* power consumption and should not be used for continuous background advertising.
*/
const val INTERVAL_LOW = FwkAdvertisingSetParameters.INTERVAL_LOW
/**
* Minimum value for advertising interval.
*/
const val INTERVAL_MIN = FwkAdvertisingSetParameters.INTERVAL_MIN
/**
* Maximum value for advertising interval.
*/
const val INTERVAL_MAX = FwkAdvertisingSetParameters.INTERVAL_MAX
/**
* Advertise using the lowest transmission (TX) power level. Low transmission power can be
* used to restrict the visibility range of advertising packets.
*/
const val TX_POWER_ULTRA_LOW = FwkAdvertisingSetParameters.TX_POWER_ULTRA_LOW
/**
* Advertise using low TX power level.
*/
const val TX_POWER_LOW = FwkAdvertisingSetParameters.TX_POWER_LOW
/**
* Advertise using medium TX power level.
*/
const val TX_POWER_MEDIUM = FwkAdvertisingSetParameters.TX_POWER_MEDIUM
/**
* Advertise using high TX power level. This corresponds to largest visibility range of the
* advertising packet.
*/
const val TX_POWER_HIGH = FwkAdvertisingSetParameters.TX_POWER_HIGH
/**
* Minimum value for TX power.
*/
const val TX_POWER_MIN = FwkAdvertisingSetParameters.TX_POWER_MIN
/**
* Maximum value for TX power.
*/
const val TX_POWER_MAX = FwkAdvertisingSetParameters.TX_POWER_MAX
/**
* The maximum limited advertisement duration as specified by the Bluetooth
* SIG
*/
private const val LIMITED_ADVERTISING_MAX_MILLIS = 180_000
}
val connectable: Boolean
get() = fwkInstance.isConnectable
val scannable: Boolean
get() = fwkInstance.isScannable
val isLegacy: Boolean
get() = fwkInstance.isLegacy
val isAnonymous: Boolean
get() = fwkInstance.isAnonymous
val includeTxPower: Boolean
get() = fwkInstance.includeTxPower()
val primaryPhy: Int
get() = fwkInstance.primaryPhy
val secondaryPhy: Int
get() = fwkInstance.secondaryPhy
val interval: Int
get() = fwkInstance.interval
val txPowerLevel: Int
get() = fwkInstance.txPowerLevel
constructor(
connectable: Boolean = false,
scannable: Boolean = false,
isLegacy: Boolean = false,
isAnonymous: Boolean = false,
includeTxPower: Boolean = false,
primaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
secondaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
txPowerLevel: Int = TX_POWER_MEDIUM
) : this(buildFwkAdvertisingSetParameters(
connectable,
scannable,
isLegacy,
isAnonymous,
includeTxPower,
primaryPhy,
secondaryPhy,
txPowerLevel
))
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(keyForField(FIELD_FWK_ADVERTISING_SET_PARAMETERS), fwkInstance)
return bundle
}
} | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/AdvertisingSetParameters.kt | 2080192211 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.i18n
import com.intellij.openapi.util.text.HtmlChunk
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.PropertyKey
object GitBundleExtensions {
fun messagePointer(@NotNull @PropertyKey(resourceBundle = GitBundle.BUNDLE) key: String, vararg params: Any): () -> String = {
GitBundle.message(key, *params)
}
@Nls
@JvmStatic
fun html(@NotNull @PropertyKey(resourceBundle = GitBundle.BUNDLE) key: String, vararg params: Any): String =
HtmlChunk.raw(GitBundle.message(key, *params)).wrapWith(HtmlChunk.html()).toString()
}
| plugins/git4idea/src/git4idea/i18n/GitBundleExtensions.kt | 3466850832 |
fun foo() {
if (a) {
<selection> <caret>f()
g()
</selection> }
} | plugins/kotlin/idea/tests/testData/wordSelection/IfBody/4.kt | 3242181422 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import training.learn.CourseManager
import training.statistic.LessonStartingWay
import training.statistic.StatisticBase
import training.util.getLearnToolWindowForProject
import training.util.getPreviousLessonForCurrent
import training.util.lessonOpenedInProject
private class PreviousLessonAction : AnAction(AllIcons.Actions.Back) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (getLearnToolWindowForProject(project) == null) return
val previousLesson = getPreviousLessonForCurrent()
StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.OPEN_NEXT_OR_PREV_LESSON)
CourseManager.instance.openLesson(project, previousLesson, LessonStartingWay.PREV_BUTTON)
}
override fun update(e: AnActionEvent) {
val project = e.project
val lesson = lessonOpenedInProject(project)
e.presentation.isEnabled = lesson != null && CourseManager.instance.lessonsForModules.firstOrNull() != lesson
}
}
| plugins/ide-features-trainer/src/training/actions/PreviousLessonAction.kt | 2102561091 |
// "class org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix" "false"
abstract class NewClass(val i: () -> Int)
@Deprecated("Text", ReplaceWith("NewClass({i})"))
abstract class OldClass(val i: Int)
class F : OldClass<caret> {
constructor(i: Int) : super(i)
constructor(i: () -> Int) : super(i())
} | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classUsages/secondaryConstructor.kt | 746446919 |
// 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.uast.test.kotlin
import com.intellij.psi.LambdaUtil
import com.intellij.psi.PsiClassType
import org.jetbrains.uast.UFile
import org.jetbrains.uast.ULambdaExpression
import org.jetbrains.uast.getContainingUMethod
import org.jetbrains.uast.visitor.AbstractUastVisitor
class KotlinULambdaExpressionTest : AbstractKotlinUastTest() {
override fun check(testName: String, file: UFile) {
val errors = mutableListOf<String>()
file.accept(object : AbstractUastVisitor() {
override fun visitLambdaExpression(node: ULambdaExpression): Boolean {
kotlin.runCatching {
val classResolveResult =
(node.getExpressionType() as? PsiClassType)?.resolveGenerics() ?: kotlin.test.fail("cannot resolve lambda")
val psiMethod =
LambdaUtil.getFunctionalInterfaceMethod(classResolveResult.element) ?: kotlin.test.fail("cannot get method signature")
val methodParameters = psiMethod.getSignature(classResolveResult.substitutor).parameterTypes.toList()
val lambdaParameters = node.parameters.map { it.type }
assertEquals("parameter lists size are different", methodParameters.size, lambdaParameters.size)
methodParameters.zip(lambdaParameters).forEachIndexed { index, (interfaceParamType, lambdaParamType) ->
assertTrue(
"unexpected types for param $index: $lambdaParamType cannot be assigned to $interfaceParamType",
interfaceParamType.isAssignableFrom(lambdaParamType)
)
}
}.onFailure {
errors += "${node.getContainingUMethod()?.name}: ${it.message}"
}
return super.visitLambdaExpression(node)
}
})
assertTrue(
errors.joinToString(separator = "\n", postfix = "", prefix = "") { it },
errors.isEmpty()
)
}
fun `test lambdas parameters`() = doTest("LambdaParameters")
} | plugins/kotlin/uast/uast-kotlin/tests/test/KotlinULambdaExpressionTest.kt | 3724771584 |
package org.runestar.client.patch
import net.bytebuddy.description.method.MethodDescription
import net.bytebuddy.dynamic.scaffold.InstrumentedType
import net.bytebuddy.implementation.Implementation
import net.bytebuddy.implementation.MethodCall
import net.bytebuddy.implementation.bytecode.constant.DefaultValue
internal fun MethodCall.withAllArgumentsThenDefaultValues(): MethodCall {
return with(object : MethodCall.ArgumentLoader.Factory, MethodCall.ArgumentLoader.ArgumentProvider {
override fun make(implementationTarget: Implementation.Target): MethodCall.ArgumentLoader.ArgumentProvider {
return this
}
override fun prepare(instrumentedType: InstrumentedType): InstrumentedType {
return instrumentedType
}
override fun resolve(
instrumentedMethod: MethodDescription,
invokedMethod: MethodDescription
): MutableList<MethodCall.ArgumentLoader> {
val argumentLoaders = ArrayList<MethodCall.ArgumentLoader>(invokedMethod.parameters.size)
for (parameterDescription in instrumentedMethod.parameters) {
argumentLoaders.add(MethodCall.ArgumentLoader.ForMethodParameter(parameterDescription.index, instrumentedMethod))
}
for (parameterDescription in invokedMethod.parameters.drop(argumentLoaders.size)) {
argumentLoaders.add(MethodCall.ArgumentLoader.ForStackManipulation(DefaultValue.of(parameterDescription.type), parameterDescription.type))
}
return argumentLoaders
}
})
} | patch-maven-plugin/src/main/java/org/runestar/client/patch/MethodCall.kt | 2406241249 |
package info.nightscout.androidaps.data
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
@RunWith(PowerMockRunner::class)
@PrepareForTest(VirtualPumpPlugin::class)
class ProfileIntervalsTest : TestBaseWithProfile() {
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
private val startDate = DateUtil.now()
var list = ProfileIntervals<ProfileSwitch>()
@Before
fun mock() {
`when`(activePluginProvider.activePump).thenReturn(virtualPumpPlugin)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription())
}
@Test
fun doTests() {
// create one 10h interval and test value in and out
list.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(10).mins().toInt()).profileName("1").profile(validProfile))
// for older date first record should be returned only if has zero duration
Assert.assertEquals(null, list.getValueToTime(startDate - T.secs(1).msecs()))
Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch?)!!.profileName)
Assert.assertEquals(null, list.getValueToTime(startDate + T.hours(10).msecs() + 1))
list.reset()
list.add(ProfileSwitch(profileInjector).date(startDate).profileName("1").profile(validProfile))
Assert.assertEquals("1", (list.getValueToTime(startDate - T.secs(1).msecs()) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("1", (list.getValueToTime(startDate + T.hours(10).msecs() + 1) as ProfileSwitch?)!!.profileName)
// switch to different profile after 5h
list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(5).msecs()).duration(0).profileName("2").profile(validProfile))
Assert.assertEquals("1", (list.getValueToTime(startDate - T.secs(1).msecs()) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("1", (list.getValueToTime(startDate + T.hours(5).msecs() - 1) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(5).msecs() + 1) as ProfileSwitch?)!!.profileName)
// insert 1h interval inside
list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(6).msecs()).duration(T.hours(1).mins().toInt()).profileName("3").profile(validProfile))
Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(6).msecs() - 1) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("3", (list.getValueToTime(startDate + T.hours(6).msecs() + 1) as ProfileSwitch?)!!.profileName)
Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(7).msecs() + 1) as ProfileSwitch?)!!.profileName)
}
@Test
fun testCopyConstructor() {
list.reset()
list.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(10).mins().toInt()).profileName("4").profile(validProfile))
val list2 = ProfileIntervals(list)
Assert.assertEquals(1, list2.list.size.toLong())
}
@Test fun invalidProfilesShouldNotBeReturned() {
list.reset()
list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(1).msecs()).profileName("6"))
Assert.assertEquals(null, list[0])
}
@Test fun testReversingArrays() {
val someList: MutableList<ProfileSwitch> = ArrayList()
someList.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(3).mins().toInt()).profileName("5").profile(validProfile))
someList.add(ProfileSwitch(profileInjector).date(startDate + T.hours(1).msecs()).duration(T.hours(1).mins().toInt()).profileName("6").profile(validProfile))
list.reset()
list.add(someList)
Assert.assertEquals(startDate, list[0].date)
Assert.assertEquals(startDate + T.hours(1).msecs(), list.getReversed(0).date)
Assert.assertEquals(startDate + T.hours(1).msecs(), list.reversedList[0].date)
}
} | app/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt | 2929310916 |
package de.fabmax.kool.platform.vk
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.platform.vk.util.vkBytesPerPx
import de.fabmax.kool.util.logD
import org.lwjgl.vulkan.VK10.vkDestroySampler
import java.util.concurrent.atomic.AtomicLong
class LoadedTextureVk(val sys: VkSystem, val format: TexFormat, val textureImage: Image,
val textureImageView: ImageView, val sampler: Long,
private val isSharedRes: Boolean = false) : VkResource(), LoadedTexture {
val texId = nextTexId.getAndIncrement()
override var width = 0
override var height = 0
override var depth = 0
init {
if (!isSharedRes) {
addDependingResource(textureImage)
addDependingResource(textureImageView)
sys.ctx.engineStats.textureAllocated(texId, Texture.estimatedTexSize(
textureImage.width, textureImage.height, textureImage.arrayLayers, textureImage.mipLevels, format.vkBytesPerPx))
}
logD { "Created texture: Image: ${textureImage.vkImage}, view: ${textureImageView.vkImageView}, sampler: $sampler" }
}
fun setSize(width: Int, height: Int, depth: Int) {
this.width = width
this.height = height
this.depth = depth
}
override fun freeResources() {
if (!isSharedRes) {
vkDestroySampler(sys.device.vkDevice, sampler, null)
sys.ctx.engineStats.textureDeleted(texId)
}
logD { "Destroyed texture" }
}
override fun dispose() {
if (!isDestroyed) {
// fixme: kinda hacky... also might be depending resource of something else than sys.device
sys.ctx.runDelayed(sys.swapChain?.nImages ?: 3) {
sys.device.removeDependingResource(this)
destroy()
}
}
}
companion object {
private val nextTexId = AtomicLong(1L)
fun fromTexData(sys: VkSystem, texProps: TextureProps, data: TextureData): LoadedTextureVk {
return when(data) {
is TextureData1d -> TextureLoader.loadTexture2d(sys, texProps, data)
is TextureData2d -> TextureLoader.loadTexture2d(sys, texProps, data)
is TextureData3d -> TextureLoader.loadTexture3d(sys, texProps, data)
is TextureDataCube -> TextureLoader.loadCubeMap(sys, texProps, data)
else -> TODO("texture data not implemented: ${data::class.java.name}")
}
}
}
}
| kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/LoadedTextureVk.kt | 366128370 |
package com.kickstarter.models
import com.kickstarter.services.apirequests.SignupBody
import junit.framework.TestCase
import org.junit.Test
class SignupBodyTest : TestCase() {
@Test
fun testDefaultInit() {
val email = "[email protected]"
val name = "test"
val password = "123"
val signupBody = SignupBody.builder()
.email(email)
.name(name)
.passwordConfirmation(password)
.password(password)
.newsletterOptIn(false)
.sendNewsletters(true)
.build()
assertEquals(signupBody.email(), email)
assertEquals(signupBody.name(), name)
assertEquals(signupBody.password(), password)
assertEquals(signupBody.passwordConfirmation(), password)
assertFalse(signupBody.newsletterOptIn())
assertTrue(signupBody.sendNewsletters())
}
@Test
fun testSignupBody_equalFalse() {
val email = "[email protected]"
val name = "test"
val password = "123"
val signupBody = SignupBody.builder().build()
val signupBody2 = SignupBody.builder().password(password).build()
val signupBody3 = SignupBody.builder().name(name).build()
val signupBody4 = SignupBody.builder().email(email).build()
assertFalse(signupBody == signupBody2)
assertFalse(signupBody == signupBody3)
assertFalse(signupBody == signupBody4)
assertFalse(signupBody3 == signupBody2)
assertFalse(signupBody3 == signupBody4)
}
@Test
fun testSignupBody_equalTrue() {
val signupBody1 = SignupBody.builder().build()
val signupBody2 = SignupBody.builder().build()
assertEquals(signupBody1, signupBody2)
}
@Test
fun testSignupBodyToBuilder() {
val email = "test"
val signupBody = SignupBody.builder().build().toBuilder()
.email(email).build()
assertEquals(signupBody.email(), email)
}
}
| app/src/test/java/com/kickstarter/models/SignupBodyTest.kt | 1167840291 |
package com.example
import com.example.bar.Foo
import java.math.BigDecimal
val a = Foo(BigDecimal(1)) | plugins/kotlin/idea/tests/testData/multiModuleHighlighting/multiplatform/platformTypeAliasInterchangebleWithAliasedClass/a_jvm_dep(fulljdk)/ExampleJvm.kt | 1955978642 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceIsEmptyWithIfEmptyInspection : AbstractKotlinInspection() {
private data class Replacement(
val conditionFunctionFqName: FqName,
val replacementFunctionName: String,
val negativeCondition: Boolean = false
)
companion object {
private val replacements = listOf(
Replacement(FqName("kotlin.collections.Collection.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.List.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.Set.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.Map.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.text.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.text.isBlank"), "ifBlank"),
Replacement(FqName("kotlin.collections.isNotEmpty"), "ifEmpty", negativeCondition = true),
Replacement(FqName("kotlin.text.isNotEmpty"), "ifEmpty", negativeCondition = true),
Replacement(FqName("kotlin.text.isNotBlank"), "ifBlank", negativeCondition = true),
).associateBy { it.conditionFunctionFqName }
private val conditionFunctionShortNames = replacements.keys.map { it.shortName().asString() }.toSet()
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = ifExpressionVisitor(fun(ifExpression: KtIfExpression) {
if (ifExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return
if (ifExpression.isElseIf()) return
val thenExpression = ifExpression.then ?: return
val elseExpression = ifExpression.`else` ?: return
if (elseExpression is KtIfExpression) return
val condition = ifExpression.condition ?: return
val conditionCallExpression = condition.getPossiblyQualifiedCallExpression() ?: return
val conditionCalleeExpression = conditionCallExpression.calleeExpression ?: return
if (conditionCalleeExpression.text !in conditionFunctionShortNames) return
val context = ifExpression.analyze(BodyResolveMode.PARTIAL)
val resultingDescriptor = conditionCallExpression.getResolvedCall(context)?.resultingDescriptor ?: return
val receiverParameter = resultingDescriptor.dispatchReceiverParameter ?: resultingDescriptor.extensionReceiverParameter
val receiverType = receiverParameter?.type ?: return
if (KotlinBuiltIns.isArrayOrPrimitiveArray(receiverType)) return
val conditionCallFqName = resultingDescriptor.fqNameOrNull() ?: return
val replacement = replacements[conditionCallFqName] ?: return
val selfBranch = if (replacement.negativeCondition) thenExpression else elseExpression
val selfValueExpression = selfBranch.blockExpressionsOrSingle().singleOrNull() ?: return
if (condition is KtDotQualifiedExpression) {
if (selfValueExpression.text != condition.receiverExpression.text) return
} else {
if (selfValueExpression !is KtThisExpression) return
}
val loop = ifExpression.getStrictParentOfType<KtLoopExpression>()
if (loop != null) {
val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression)
if (defaultValueExpression.anyDescendantOfType<KtExpression> {
(it is KtContinueExpression || it is KtBreakExpression) && (it as KtExpressionWithLabel).targetLoop(context) == loop
}
) return
}
holder.registerProblem(
ifExpression,
conditionCalleeExpression.textRangeIn(ifExpression),
KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}"),
ReplaceFix(replacement)
)
})
private class ReplaceFix(private val replacement: Replacement) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val ifExpression = descriptor.psiElement as? KtIfExpression ?: return
val condition = ifExpression.condition ?: return
val thenExpression = ifExpression.then ?: return
val elseExpression = ifExpression.`else` ?: return
val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression)
val psiFactory = KtPsiFactory(ifExpression)
val receiverText = (condition as? KtDotQualifiedExpression)?.receiverExpression?.text?.let { "$it." } ?: ""
val replacementFunctionName = replacement.replacementFunctionName
val newExpression = if (defaultValueExpression is KtBlockExpression) {
psiFactory.createExpression("${receiverText}$replacementFunctionName ${defaultValueExpression.text}")
} else {
psiFactory.createExpressionByPattern("${receiverText}$replacementFunctionName { $0 }", defaultValueExpression)
}
ifExpression.replace(newExpression)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceIsEmptyWithIfEmptyInspection.kt | 3836054559 |
/*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.proxies.local.lives
import android.arch.persistence.room.Embedded
import android.arch.persistence.room.Relation
import android.support.annotation.RestrictTo
@RestrictTo(RestrictTo.Scope.LIBRARY)
data class LocalIpTvPlaylistWithChannels(
@Embedded var playlist: LocalIpTvPlaylist = LocalIpTvPlaylist(""),
@Relation(entity = LocalIpTvLive::class, parentColumn = "name", entityColumn = "playlist_id")
var channels: List<LocalIpTvLive> = emptyList()
) | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/lives/LocalIpTvPlaylistWithChannels.kt | 4024660226 |
// PROBLEM: none
fun test(x:Boolean?) {
if (<caret>x != true) {
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/booleanBoxed.kt | 563003582 |
// 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.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
class RedundantNullableReturnTypeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitProperty(property: KtProperty) {
if (property.isVar) return
check(property)
}
private fun check(declaration: KtCallableDeclaration) {
val typeReference = declaration.typeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
if (typeElement.innerType == null) return
val questionMark = typeElement.questionMarkNode as? LeafPsiElement ?: return
if (declaration.isOverridable()) return
val (body, targetDeclaration) = when (declaration) {
is KtNamedFunction -> {
val body = declaration.bodyExpression
if (body != null) body to declaration else null
}
is KtProperty -> {
val initializer = declaration.initializer
val getter = declaration.accessors.singleOrNull { it.isGetter }
val getterBody = getter?.bodyExpression
when {
initializer != null -> initializer to declaration
getterBody != null -> getterBody to getter
else -> null
}
}
else -> null
} ?: return
val actualReturnTypes = body.actualReturnTypes(targetDeclaration)
if (actualReturnTypes.isEmpty() || actualReturnTypes.any { it.isNullable() }) return
val declarationName = declaration.nameAsSafeName.asString()
val description = if (declaration is KtProperty) {
KotlinBundle.message("0.is.always.non.null.type", declarationName)
} else {
KotlinBundle.message("0.always.returns.non.null.type", declarationName)
}
holder.registerProblem(
typeReference,
questionMark.textRangeIn(typeReference),
description,
MakeNotNullableFix()
)
}
}
@OptIn(FrontendInternals::class)
private fun KtExpression.actualReturnTypes(declaration: KtDeclaration): List<KotlinType> {
val context = analyze()
val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: return emptyList()
val dataFlowValueFactory = getResolutionFacade().frontendService<DataFlowValueFactory>()
val moduleDescriptor = findModuleDescriptor()
val languageVersionSettings = languageVersionSettings
val returnTypes = collectDescendantsOfType<KtReturnExpression> {
it.labelQualifier == null && it.getTargetFunctionDescriptor(context) == declarationDescriptor
}.flatMap {
it.returnedExpression.types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
return if (this is KtBlockExpression) {
returnTypes
} else {
returnTypes + types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
}
private fun KtExpression?.types(
context: BindingContext,
dataFlowValueFactory: DataFlowValueFactory,
moduleDescriptor: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<KotlinType> {
if (this == null) return emptyList()
val type = context.getType(this) ?: return emptyList()
val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return emptyList()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, moduleDescriptor)
val stableTypes = dataFlowInfo.getStableTypes(dataFlowValue, languageVersionSettings)
return if (stableTypes.isNotEmpty()) stableTypes.toList() else listOf(type)
}
private class MakeNotNullableFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("make.not.nullable")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val typeReference = descriptor.psiElement as? KtTypeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
val innerType = typeElement.innerType ?: return
typeElement.replace(innerType)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantNullableReturnTypeInspection.kt | 2394876385 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
package test
public data class KotlinDataClass(val <caret>foo: Int, val bar: String) {
} | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findParameterUsages/kotlinComponentFunctionParameterUsages.0.kt | 3353703842 |
@file:JvmName("Utils")
@file:JvmMultifileClass
package test
fun commonFun2() {}
fun publicDeletedFun2() {}
private val deletedVal2: Int = 20
private fun deletedFun2(): Int = 10
private fun changedFun2(arg: Int) {}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/packageMultifileClassOneFileWithPublicChanges/pkg2.kt | 3586806667 |
// 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.conversion.copy
import com.intellij.openapi.actionSystem.IdeActions
import org.jetbrains.kotlin.idea.AbstractCopyPasteTest
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import java.io.File
abstract class AbstractLiteralKotlinToKotlinCopyPasteTest : AbstractCopyPasteTest() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
fun doTest(unused: String) {
val fileName = fileName()
val testFile = testDataFile()
val expectedFile = File(testFile.parent, testFile.nameWithoutExtension + ".expected.kt")
myFixture.configureByFile(fileName)
myFixture.performEditorAction(IdeActions.ACTION_COPY)
configureTargetFile(fileName.replace(".kt", ".to.kt"))
myFixture.performEditorAction(IdeActions.ACTION_PASTE)
KotlinTestUtils.assertEqualsToFile(expectedFile, myFixture.file.text)
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/AbstractLiteralKotlinToKotlinCopyPasteTest.kt | 1246061969 |
/*
* 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 xyz.avarel.kaiper
import org.junit.Assert
import org.junit.Test
class ArrayTest {
@Test
fun `declare`() {
Assert.assertEquals(eval("[1, 2, 3]"), eval("[1,2,3]"))
}
@Test
fun `equality`() {
Assert.assertEquals(true, eval("[1..3] == [1,2,3]").toJava())
}
fun notMe(x: Int, y: Int = x + 2) = 2
}
| Kaiper-Interpreter/src/test/kotlin/xyz/avarel/kaiper/ArrayTest.kt | 620383617 |
package com.maly.presentation.building
/**
* @author Aleksander Brzozowski
*/
class CitySortedBuildingsModel(
val city: String,
val buildings: List<BuildingModel>
) | src/main/kotlin/com/maly/presentation/building/CitySortedBuildingsModel.kt | 792526934 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class FoldIfToFunctionCallIntention : SelfTargetingRangeIntention<KtIfExpression>(
KtIfExpression::class.java,
KotlinBundle.lazyMessage("lift.function.call.out.of.if"),
) {
override fun applicabilityRange(element: KtIfExpression): TextRange? =
if (canFoldToFunctionCall(element)) element.ifKeyword.textRange else null
override fun applyTo(element: KtIfExpression, editor: Editor?) {
foldToFunctionCall(element)
}
companion object {
fun branches(expression: KtExpression): List<KtExpression>? {
val branches = when (expression) {
is KtIfExpression -> expression.branches
is KtWhenExpression -> expression.entries.map { it.expression }
else -> emptyList()
}
val branchesSize = branches.size
if (branchesSize < 2) return null
return branches.filterNotNull().takeIf { it.size == branchesSize }
}
private fun canFoldToFunctionCall(element: KtExpression): Boolean {
val branches = branches(element) ?: return false
val callExpressions = branches.mapNotNull { it.callExpression() }
if (branches.size != callExpressions.size) return false
if (differentArgumentIndex(callExpressions) == null) return false
val headCall = callExpressions.first()
val tailCalls = callExpressions.drop(1)
val context = headCall.analyze(BodyResolveMode.PARTIAL)
val (headFunctionFqName, headFunctionParameters) = headCall.fqNameAndParameters(context) ?: return false
return tailCalls.all { call ->
val (fqName, parameters) = call.fqNameAndParameters(context) ?: return@all false
fqName == headFunctionFqName && parameters.zip(headFunctionParameters).all { it.first == it.second }
}
}
private fun foldToFunctionCall(element: KtExpression) {
val branches = branches(element) ?: return
val callExpressions = branches.mapNotNull { it.callExpression() }
val headCall = callExpressions.first()
val argumentIndex = differentArgumentIndex(callExpressions) ?: return
val hasNamedArgument = callExpressions.any { call -> call.valueArguments.any { it.getArgumentName() != null } }
val copiedIf = element.copy() as KtIfExpression
copiedIf.branches.forEach { branch ->
val call = branch.callExpression() ?: return
val argument = call.valueArguments[argumentIndex].getArgumentExpression() ?: return
call.getQualifiedExpressionForSelectorOrThis().replace(argument)
}
headCall.valueArguments[argumentIndex].getArgumentExpression()?.replace(copiedIf)
if (hasNamedArgument) {
headCall.valueArguments.forEach {
if (it.getArgumentName() == null) AddNameToArgumentIntention.apply(it)
}
}
element.replace(headCall.getQualifiedExpressionForSelectorOrThis()).reformatted()
}
private fun differentArgumentIndex(callExpressions: List<KtCallExpression>): Int? {
val headCall = callExpressions.first()
val headCalleeText = headCall.calleeText()
val tailCalls = callExpressions.drop(1)
if (headCall.valueArguments.any { it is KtLambdaArgument }) return null
val headArguments = headCall.valueArguments.mapNotNull { it.getArgumentExpression()?.text }
val headArgumentsSize = headArguments.size
if (headArgumentsSize != headCall.valueArguments.size) return null
val differentArgumentIndexes = tailCalls.mapNotNull { call ->
if (call.calleeText() != headCalleeText) return@mapNotNull null
val arguments = call.valueArguments.mapNotNull { it.getArgumentExpression()?.text }
if (arguments.size != headArgumentsSize) return@mapNotNull null
val differentArgumentIndexes = arguments.zip(headArguments).mapIndexedNotNull { index, (arg, headArg) ->
if (arg != headArg) index else null
}
differentArgumentIndexes.singleOrNull()
}
if (differentArgumentIndexes.size != tailCalls.size || differentArgumentIndexes.distinct().size != 1) return null
return differentArgumentIndexes.first()
}
private fun KtExpression?.callExpression(): KtCallExpression? {
return when (val expression = if (this is KtBlockExpression) statements.singleOrNull() else this) {
is KtCallExpression -> expression
is KtQualifiedExpression -> expression.callExpression
else -> null
}?.takeIf { it.calleeExpression != null }
}
private fun KtCallExpression.calleeText(): String {
val parent = this.parent
val (receiver, op) = if (parent is KtQualifiedExpression) {
parent.receiverExpression.text to parent.operationSign.value
} else {
"" to ""
}
return "$receiver$op${calleeExpression?.text.orEmpty()}"
}
private fun KtCallExpression.fqNameAndParameters(context: BindingContext): Pair<FqName, List<ValueParameterDescriptor>>? {
val resolvedCall = getResolvedCall(context) ?: return null
val fqName = resolvedCall.resultingDescriptor.fqNameOrNull() ?: return null
val parameters = valueArguments.mapNotNull { (resolvedCall.getArgumentMapping(it) as? ArgumentMatch)?.valueParameter }
return fqName to parameters
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToFunctionCallIntention.kt | 3616180854 |
// 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.openapi.externalSystem.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.externalSystem.statistics.ExternalSystemActionsCollector.Companion.EXTERNAL_SYSTEM_ID
class ProjectImportCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("project.import", 6)
@JvmField
val TASK_CLASS = EventFields.Class("task_class")
@JvmField
val IMPORT_ACTIVITY = GROUP.registerIdeActivity("import_project", startEventAdditionalFields = arrayOf(EXTERNAL_SYSTEM_ID, TASK_CLASS,
EventFields.PluginInfo))
@JvmField
val IMPORT_STAGE = GROUP.registerIdeActivity("stage", startEventAdditionalFields = arrayOf(TASK_CLASS),
parentActivity = IMPORT_ACTIVITY)
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ProjectImportCollector.kt | 1186595165 |
package katas.kotlin.permutation
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
class LehmerTests {
@Test fun `map permutation to Lehmer code`() {
emptyList<Int>().toLehmerCode() shouldEqual LehmerCode()
listOf(0).toLehmerCode() shouldEqual LehmerCode(0)
listOf(0, 1, 2).toLehmerCode() shouldEqual LehmerCode(0, 0, 0)
listOf(0, 2, 1).toLehmerCode() shouldEqual LehmerCode(0, 1, 0)
listOf(1, 0, 2).toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
listOf(1, 2, 0).toLehmerCode() shouldEqual LehmerCode(1, 1, 0)
listOf(2, 0, 1).toLehmerCode() shouldEqual LehmerCode(2, 0, 0)
listOf(2, 1, 0).toLehmerCode() shouldEqual LehmerCode(2, 1, 0)
listOf(1, 0, 4, 3, 2).toLehmerCode() shouldEqual LehmerCode(1, 0, 2, 1, 0)
}
@Test fun `map Lehmer code to a number`() {
LehmerCode().toLong() shouldEqual 0
LehmerCode(123).toLong() shouldEqual 0
LehmerCode(0, 0, 0).toLong() shouldEqual 0
LehmerCode(0, 1, 0).toLong() shouldEqual 1
LehmerCode(1, 0, 0).toLong() shouldEqual 2
LehmerCode(1, 1, 0).toLong() shouldEqual 3
LehmerCode(2, 0, 0).toLong() shouldEqual 4
LehmerCode(2, 1, 0).toLong() shouldEqual 5
LehmerCode(0, 0, 0, 0, 1).toLong() shouldEqual 0
LehmerCode(0, 0, 0, 1, 0).toLong() shouldEqual 1
LehmerCode(0, 0, 1, 0, 0).toLong() shouldEqual 2
LehmerCode(0, 1, 0, 0, 0).toLong() shouldEqual 6
LehmerCode(1, 0, 0, 0, 0).toLong() shouldEqual 24
LehmerCode(1, 0, 2, 1, 0).toLong() shouldEqual 29
}
@Test fun `map number to a Lehmer code`() {
0.toLehmerCode() shouldEqual LehmerCode(0)
0.toLehmerCode(size = 1) shouldEqual LehmerCode(0)
0.toLehmerCode(size = 2) shouldEqual LehmerCode(0, 0)
0.toLehmerCode() shouldEqual LehmerCode(0)
1.toLehmerCode() shouldEqual LehmerCode(1, 0)
2.toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
3.toLehmerCode() shouldEqual LehmerCode(1, 1, 0)
4.toLehmerCode() shouldEqual LehmerCode(2, 0, 0)
5.toLehmerCode() shouldEqual LehmerCode(2, 1, 0)
0.toLehmerCode() shouldEqual LehmerCode(0)
1.toLehmerCode() shouldEqual LehmerCode(1, 0)
2.toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
6.toLehmerCode() shouldEqual LehmerCode(1, 0, 0, 0)
24.toLehmerCode() shouldEqual LehmerCode(1, 0, 0, 0, 0)
29.toLehmerCode() shouldEqual LehmerCode(1, 0, 2, 1, 0)
}
@Test fun `map Lehmer code to a permutation`() {
LehmerCode().toPermutation() shouldEqual emptyList()
LehmerCode(0).toPermutation() shouldEqual listOf(0)
LehmerCode(0, 0, 0).toPermutation() shouldEqual listOf(0, 1, 2)
LehmerCode(0, 1, 0).toPermutation() shouldEqual listOf(0, 2, 1)
LehmerCode(1, 0, 0).toPermutation() shouldEqual listOf(1, 0, 2)
LehmerCode(1, 1, 0).toPermutation() shouldEqual listOf(1, 2, 0)
LehmerCode(2, 0, 0).toPermutation() shouldEqual listOf(2, 0, 1)
LehmerCode(2, 1, 0).toPermutation() shouldEqual listOf(2, 1, 0)
LehmerCode(1, 0, 2, 1, 0).toPermutation() shouldEqual listOf(1, 0, 4, 3, 2)
LehmerCode(1, 0, 2, 1, 0).toPermutation(listOf(1, 2, 3, 4, 5)) shouldEqual listOf(2, 1, 5, 4, 3)
LehmerCode(1, 0, 2, 1, 0).toPermutation(listOf('a', 'b', 'c', 'd', 'e')) shouldEqual listOf('b', 'a', 'e', 'd', 'c')
}
}
data class LehmerCode(val value: List<Int>) {
constructor(vararg value: Int): this(value.toList())
fun toLong(): Long {
var factorial = 1
var result = 0L
value.dropLast(1).asReversed().forEachIndexed { index, n ->
factorial *= index + 1
result += n * factorial
}
return result
}
fun toPermutation(): List<Int> {
val indices = value.indices.toMutableList()
return value.map {
indices.removeAt(it)
}
}
fun <T> toPermutation(list: List<T>): List<T> {
return toPermutation().map { list[it] }
}
}
fun List<Int>.toLehmerCode(): LehmerCode {
val bitSet = BitSet(size)
return LehmerCode(map {
bitSet[it] = true
it - bitSet.get(0, it).cardinality()
})
}
fun Int.toLehmerCode(size: Int = -1): LehmerCode = toLong().toLehmerCode(size)
fun Long.toLehmerCode(size: Int = -1): LehmerCode {
val result = ArrayList<Int>()
result.add(0)
var value = this
var factorial = 1
var iteration = 1
while (value != 0L) {
factorial *= iteration
iteration += 1
val divisor = value / factorial
val remainder = divisor % iteration
result.add(0, remainder.toInt())
value -= remainder * factorial
}
if (size != -1) {
IntRange(result.size, size - 1).forEach { result.add(0, 0) }
}
return LehmerCode(result)
} | kotlin/src/katas/kotlin/permutation/Lehmer.kt | 2870090524 |
package taiwan.no1.app.ssfm.features.main
import android.os.Bundle
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.features.base.BaseActivity
/**
* Just for testing the custom view.
*
* @author jieyi
* @since 6/8/17
*/
class TestActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.part_main_preference)
}
} | app/src/main/kotlin/taiwan/no1/app/ssfm/features/main/TestActivity.kt | 1975264346 |
package app.entryscreen.splash
import android.app.Activity
import app.entryscreen.EntryScreenScope
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import reporter.CrashReporter
import javax.inject.Named
@Module
internal class SplashModule {
@Provides
@EntryScreenScope
fun loggedInCheckCoordinator(
@Named("io") asyncExecutionScheduler: Scheduler,
@Named("main") postExecutionScheduler: Scheduler,
crashReporter: CrashReporter,
loggedInCheckResultCallback: LoggedInCheckCoordinator.ResultCallback) = LoggedInCheckCoordinator(
asyncExecutionScheduler,
postExecutionScheduler,
loggedInCheckResultCallback,
crashReporter)
@Provides
@EntryScreenScope
fun versionCheckCoordinator(
activity: Activity,
@Named("io") asyncExecutionScheduler: Scheduler,
@Named("main") postExecutionScheduler: Scheduler,
versionCheckCoordinatorResultCallback: VersionCheckCoordinator.ResultCallback) = VersionCheckCoordinator(
activity,
asyncExecutionScheduler,
postExecutionScheduler,
versionCheckCoordinatorResultCallback)
}
| app/src/main/kotlin/app/entryscreen/splash/SplashModule.kt | 1368046067 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.samples
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.unit.dp
@Composable
fun CustomTouchSlopSample() {
val originalTouchSlop = LocalViewConfiguration.current.touchSlop
CustomTouchSlopProvider(newTouchSlop = originalTouchSlop * 3) {
LazyColumn {
items(100) {
Spacer(Modifier.padding(10.dp))
LongListOfItems(originalTouchSlop)
}
}
}
}
@Composable
fun CustomTouchSlopProvider(
newTouchSlop: Float,
content: @Composable () -> Unit
) {
CompositionLocalProvider(
LocalViewConfiguration provides CustomTouchSlopAngle(
newTouchSlop,
LocalViewConfiguration.current
)
) {
content()
}
}
class CustomTouchSlopAngle(
private val customTouchSlop: Float,
currentConfiguration: ViewConfiguration
) : ViewConfiguration by currentConfiguration {
override val touchSlop: Float
get() = customTouchSlop
}
@Composable
fun LongListOfItems(originalTouchSlop: Float) {
CustomTouchSlopProvider(newTouchSlop = originalTouchSlop / 3) {
LazyRow {
items(100) {
Box(modifier = Modifier.size(80.dp).padding(4.dp).background(Color.Gray)) {
Text(text = it.toString(), modifier = Modifier.align(Alignment.Center))
}
}
}
}
} | compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/CustomTouchSlopSample.kt | 255870999 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.paging.guava
import android.database.Cursor
import androidx.arch.core.executor.testing.CountingTaskExecutorRule
import androidx.paging.LoadType
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingSource.LoadResult
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.paging.util.ThreadSafeInvalidationObserver
import androidx.room.util.getColumnIndexOrThrow
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.TestExecutor
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures.addCallback
import com.google.common.util.concurrent.ListenableFuture
import java.util.LinkedList
import java.util.concurrent.CancellationException
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private const val tableName: String = "TestItem"
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
@SmallTest
class LimitOffsetListenableFuturePagingSourceTest {
@JvmField
@Rule
val countingTaskExecutorRule = CountingTaskExecutorRule()
@Test
fun initialLoad_registersInvalidationObserver() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
val listenableFuture = pagingSource.refresh()
assertFalse(pagingSource.privateObserver().privateRegisteredState().get())
// observer registration is queued up on queryExecutor by refresh() call
queryExecutor.executeAll()
assertTrue(pagingSource.privateObserver().privateRegisteredState().get())
// note that listenableFuture is not done yet
// The future has been transformed into a ListenableFuture<LoadResult> whose result
// is still pending
assertFalse(listenableFuture.isDone)
}
@Test
fun initialEmptyLoad_futureIsDone() = setupAndRun { db ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
runTest {
val listenableFuture = pagingSource.refresh()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).isEmpty()
assertTrue(listenableFuture.isDone)
}
}
@Test
fun initialLoad_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
val listenableFuture = pagingSource.refresh()
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
assertThat(pagingSource.itemCount.get()).isEqualTo(-1)
queryExecutor.executeAll() // run loadFuture
transactionExecutor.executeAll() // start initialLoad callable + load data
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.append(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
// run transformAsync and async function
queryExecutor.executeAll()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
// run transformAsync and async function
queryExecutor.executeAll()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_returnsInvalid() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 50)
pagingSource.invalidate() // imitate refreshVersionsAsync invalidating the PagingSource
assertTrue(pagingSource.invalid)
queryExecutor.executeAll() // run transformAsync and async function
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_returnsInvalid() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 50)
pagingSource.invalidate() // imitate refreshVersionsAsync invalidating the PagingSource
assertTrue(pagingSource.invalid)
queryExecutor.executeAll() // run transformAsync and async function
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_consecutively() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val pagingSource2 = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture1 = pagingSource.refresh(key = 10)
val listenableFuture2 = pagingSource2.refresh(key = 15)
// check that first Future completes first. If the first future didn't complete first,
// this await() would not return.
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(10, 25)
)
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 30)
)
}
@Test
fun append_consecutively() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
val listenableFuture1 = pagingSource.append(key = 10)
val listenableFuture2 = pagingSource.append(key = 15)
// both load futures are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first transformAsync
queryExecutor.executeNext() // second transformAsync
// both async functions are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first async function
queryExecutor.executeNext() // second async function
// both nonInitial loads are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first db load
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(10, 15)
)
queryExecutor.executeNext() // second db load
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture1.isDone)
assertTrue(listenableFuture2.isDone)
}
@Test
fun prepend_consecutively() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
val listenableFuture1 = pagingSource.prepend(key = 25)
val listenableFuture2 = pagingSource.prepend(key = 20)
// both load futures are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first transformAsync
queryExecutor.executeNext() // second transformAsync
// both async functions are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first async function
queryExecutor.executeNext() // second async function
// both nonInitial loads are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first db load
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
queryExecutor.executeNext() // second db load
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture1.isDone)
assertTrue(listenableFuture2.isDone)
}
@Test
fun refresh_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 30)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(30, 45)
)
onSuccessReceived = true
}
// wait until Room db's refresh load is complete
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
assertTrue(listenableFuture.isDone)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
onSuccessReceived = true
}
// let room db complete load
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 40)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(35, 40)
)
onSuccessReceived = true
}
// let room db complete load
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_cancelBeforeObserverRegistered_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // transformAsync
// cancel before observer has been registered. This queues up another task which is
// the cancelled async function
listenableFuture.cancel(true)
// even though future is cancelled, transformAsync was already queued up which means
// observer will still get registered
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// start async function but doesn't proceed further
queryExecutor.executeAll()
// ensure initial load is not queued up
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun refresh_cancelAfterObserverRegistered_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
// start transformAsync and register observer
queryExecutor.executeNext()
// cancel after observer registration
listenableFuture.cancel(true)
// start the async function but it has been cancelled so it doesn't queue up
// initial load
queryExecutor.executeNext()
// initialLoad not queued
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun refresh_cancelAfterLoadIsQueued_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
queryExecutor.executeAll() // run loadFuture and queue up initial load
listenableFuture.cancel(true)
// initialLoad has been queued
assertThat(transactionExecutor.queuedSize()).isEqualTo(1)
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
transactionExecutor.executeAll() // room starts transaction but doesn't complete load
queryExecutor.executeAll() // InvalidationTracker from end of transaction
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun append_awaitThrowsCancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
listenableFuture.cancel(true)
queryExecutor.executeAll()
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// although query was executed, it should not complete due to the cancellation signal.
// If query was completed, paging source would call refreshVersionsAsync manually
// and queuedSize() would be 1 instead of 0 with InvalidationTracker queued up
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
}
@Test
fun prepend_awaitThrowsCancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the prepend first
val listenableFuture = pagingSource.prepend(key = 30)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
listenableFuture.cancel(true)
queryExecutor.executeAll()
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// although query was executed, it should not complete due to the cancellation signal.
// If query was completed, paging source would call refreshVersionsAsync manually
// and queuedSize() would be 1 instead of 0 with InvalidationTracker queued up
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
}
@Test
fun refresh_canceledFutureRunsOnFailureCallback() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 30)
queryExecutor.executeAll() // start transformAsync & async function
assertThat(transactionExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the refresh load. The refresh should not complete.
listenableFuture.cancel(true)
transactionExecutor.executeAll()
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_canceledFutureRunsOnFailureCallback2() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the append load. The append should not complete.
listenableFuture.cancel(true)
queryExecutor.executeNext() // transformAsync
queryExecutor.executeNext() // nonInitialLoad
// if load was erroneously completed, InvalidationTracker would be queued
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_canceledFutureRunsOnFailureCallback() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the prepend first
val listenableFuture = pagingSource.prepend(key = 30)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the prepend which should not complete.
listenableFuture.cancel(true)
queryExecutor.executeNext() // transformAsync
queryExecutor.executeNext() // nonInitialLoad
// if load was erroneously completed, InvalidationTracker would be queued
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_AfterCancellation() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 50)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// new gen after query from previous gen was cancelled
val pagingSource2 = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture2 = pagingSource2.refresh()
val result = listenableFuture2.await() as LoadResult.Page
// the new generation should load as usual
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
}
@Test
fun appendAgain_afterFutureCanceled() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 30)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
assertTrue(listenableFuture.isDone)
assertFalse(pagingSource.invalid)
val listenableFuture2 = pagingSource.append(key = 30)
val result = listenableFuture2.await() as LoadResult.Page
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(30, 35)
)
assertTrue(listenableFuture2.isDone)
}
@Test
fun prependAgain_afterFutureCanceled() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 30)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
assertFalse(pagingSource.invalid)
assertTrue(listenableFuture.isDone)
val listenableFuture2 = pagingSource.prepend(key = 30)
val result = listenableFuture2.await() as LoadResult.Page
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(25, 30)
)
assertTrue(listenableFuture2.isDone)
}
@Test
fun append_insertInvalidatesPagingSource() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
queryExecutor.executeNext() // start transformAsync
queryExecutor.executeNext() // start async function
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // nonInitialLoad is queued up
// run this async separately from queryExecutor
run {
db.dao.addItem(TestItem(101))
}
// tasks in queue [nonInitialLoad, InvalidationTracker(from additem)]
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// run nonInitialLoad first. The InvalidationTracker
// is still queued up. This imitates delayed notification from Room.
queryExecutor.executeNext()
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertThat(pagingSource.invalid)
}
@Test
fun prepend_insertInvalidatesPagingSource() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.prepend(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
queryExecutor.executeNext() // start transformAsync
queryExecutor.executeNext() // start async function
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // nonInitialLoad is queued up
// run this async separately from queryExecutor
run {
db.dao.addItem(TestItem(101))
}
// tasks in queue [nonInitialLoad, InvalidationTracker(from additem)]
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// run nonInitialLoad first. The InvalidationTracker
// is still queued up. This imitates delayed notification from Room.
queryExecutor.executeNext()
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertThat(pagingSource.invalid)
}
@Test
fun test_jumpSupport() = setupAndRun { db ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
assertTrue(pagingSource.jumpingSupported)
}
@Test
fun refresh_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
val listenableFuture = pagingSource.refresh()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.append(key = 50)
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(50, 55)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.prepend(key = 50)
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(45, 50)
)
assertTrue(listenableFuture.isDone)
}
private fun setupAndRun(
test: suspend (LimitOffsetTestDb) -> Unit
) {
val db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
LimitOffsetTestDb::class.java
).build()
runTest {
test(db)
}
tearDown(db)
}
private fun setupAndRunWithTestExecutor(
test: suspend (LimitOffsetTestDb, TestExecutor, TestExecutor) -> Unit
) {
val queryExecutor = TestExecutor()
val transactionExecutor = TestExecutor()
val db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
LimitOffsetTestDb::class.java
)
.setTransactionExecutor(transactionExecutor)
.setQueryExecutor(queryExecutor)
.build()
runTest {
db.dao.addAllItems(ITEMS_LIST)
queryExecutor.executeAll() // InvalidationTracker from the addAllItems
test(db, queryExecutor, transactionExecutor)
}
tearDown(db)
}
private fun tearDown(db: LimitOffsetTestDb) {
if (db.isOpen) db.close()
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
assertThat(countingTaskExecutorRule.isIdle).isTrue()
}
}
private class LimitOffsetListenableFuturePagingSourceImpl(
db: RoomDatabase,
registerObserver: Boolean = false,
queryString: String = "SELECT * FROM $tableName ORDER BY id ASC",
) : LimitOffsetListenableFuturePagingSource<TestItem>(
sourceQuery = RoomSQLiteQuery.acquire(
queryString,
0
),
db = db,
tables = arrayOf(tableName)
) {
init {
// bypass register check and avoid registering observer
if (!registerObserver) {
privateObserver().privateRegisteredState().set(true)
}
}
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
private fun convertRowsHelper(cursor: Cursor): List<TestItem> {
val cursorIndexOfId = getColumnIndexOrThrow(cursor, "id")
val data = mutableListOf<TestItem>()
while (cursor.moveToNext()) {
val tmpId = cursor.getInt(cursorIndexOfId)
data.add(TestItem(tmpId))
}
return data
}
@Suppress("UNCHECKED_CAST")
private fun TestExecutor.executeNext() {
val tasks = javaClass.getDeclaredField("mTasks").let {
it.isAccessible = true
it.get(this)
} as LinkedList<Runnable>
if (!tasks.isEmpty()) {
val task = tasks.poll()
task?.run()
}
}
@Suppress("UNCHECKED_CAST")
private fun TestExecutor.queuedSize(): Int {
val tasks = javaClass.getDeclaredField("mTasks").let {
it.isAccessible = true
it.get(this)
} as LinkedList<Runnable>
return tasks.size
}
@Suppress("UNCHECKED_CAST")
private fun ThreadSafeInvalidationObserver.privateRegisteredState(): AtomicBoolean {
return ThreadSafeInvalidationObserver::class.java
.getDeclaredField("registered")
.let {
it.isAccessible = true
it.get(this)
} as AtomicBoolean
}
@Suppress("UNCHECKED_CAST")
private fun LimitOffsetListenableFuturePagingSource<TestItem>.privateObserver():
ThreadSafeInvalidationObserver {
return LimitOffsetListenableFuturePagingSource::class.java
.getDeclaredField("observer")
.let {
it.isAccessible = true
it.get(this)
} as ThreadSafeInvalidationObserver
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.refresh(
key: Int? = null,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.REFRESH,
key = key,
)
)
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.append(
key: Int? = -1,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.APPEND,
key = key,
)
)
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.prepend(
key: Int? = -1,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.PREPEND,
key = key,
)
)
}
private val CONFIG = PagingConfig(
pageSize = 5,
enablePlaceholders = true,
initialLoadSize = 15
)
private val ITEMS_LIST = createItemsForDb(0, 100)
private fun createItemsForDb(startId: Int, count: Int): List<TestItem> {
return List(count) {
TestItem(
id = it + startId,
)
}
}
private fun createLoadParam(
loadType: LoadType,
key: Int? = null,
initialLoadSize: Int = CONFIG.initialLoadSize,
pageSize: Int = CONFIG.pageSize,
placeholdersEnabled: Boolean = CONFIG.enablePlaceholders
): PagingSource.LoadParams<Int> {
return when (loadType) {
LoadType.REFRESH -> {
PagingSource.LoadParams.Refresh(
key = key,
loadSize = initialLoadSize,
placeholdersEnabled = placeholdersEnabled
)
}
LoadType.APPEND -> {
PagingSource.LoadParams.Append(
key = key ?: -1,
loadSize = pageSize,
placeholdersEnabled = placeholdersEnabled
)
}
LoadType.PREPEND -> {
PagingSource.LoadParams.Prepend(
key = key ?: -1,
loadSize = pageSize,
placeholdersEnabled = placeholdersEnabled
)
}
}
}
private fun ListenableFuture<LoadResult<Int, TestItem>>.onSuccess(
executor: Executor,
onSuccessCallback: (LoadResult<Int, TestItem>?) -> Unit,
) {
addCallback(
this,
object : FutureCallback<LoadResult<Int, TestItem>> {
override fun onSuccess(result: LoadResult<Int, TestItem>?) {
onSuccessCallback(result)
}
override fun onFailure(t: Throwable) {
assertWithMessage("Expected onSuccess callback instead of onFailure, " +
"received ${t.localizedMessage}").fail()
}
},
executor
)
}
private fun ListenableFuture<LoadResult<Int, TestItem>>.onFailure(
executor: Executor,
onFailureCallback: (Throwable) -> Unit,
) {
addCallback(
this,
object : FutureCallback<LoadResult<Int, TestItem>> {
override fun onSuccess(result: LoadResult<Int, TestItem>?) {
assertWithMessage("Expected onFailure callback instead of onSuccess, " +
"received result $result").fail()
}
override fun onFailure(t: Throwable) {
onFailureCallback(t)
}
},
executor
)
}
@Database(entities = [TestItem::class], version = 1, exportSchema = false)
abstract class LimitOffsetTestDb : RoomDatabase() {
abstract val dao: TestItemDao
}
@Entity(tableName = "TestItem")
data class TestItem(
@PrimaryKey val id: Int,
val value: String = "item $id"
)
@Dao
interface TestItemDao {
@Insert
fun addAllItems(testItems: List<TestItem>)
@Insert
fun addItem(testItem: TestItem)
}
| room/room-paging-guava/src/androidTest/kotlin/androidx/room/paging/guava/LimitOffsetListenableFuturePagingSourceTest.kt | 1996983673 |
package com.onyx.interactors.relationship.data
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
/**
* Created by timothy.osborn on 3/19/15.
*
* Reference of a relationship
*/
class RelationshipReference @JvmOverloads constructor(var identifier: Any? = "", var partitionId: Long = 0L) : BufferStreamable, Comparable<RelationshipReference> {
override fun read(buffer: BufferStream) {
partitionId = buffer.long
identifier = buffer.value
}
override fun write(buffer: BufferStream) {
buffer.putLong(partitionId)
buffer.putObject(identifier)
}
override fun compareTo(other: RelationshipReference): Int = when {
this.partitionId < other.partitionId -> -1
this.partitionId > other.partitionId -> 1
other.identifier!!.javaClass == this.identifier!!.javaClass && this.identifier is Comparable<*> -> @Suppress("UNCHECKED_CAST") (this.identifier as Comparable<Any>).compareTo(other.identifier!! as Comparable<Any>)
else -> 0
}
override fun hashCode(): Int = when (identifier) {
null -> partitionId.hashCode()
else -> identifier!!.hashCode() + partitionId.hashCode()
}
override fun equals(other:Any?):Boolean = other != null && (other as RelationshipReference).partitionId == partitionId && other.identifier == identifier
} | onyx-database/src/main/kotlin/com/onyx/interactors/relationship/data/RelationshipReference.kt | 935511230 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ui.docking.impl
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorComposite
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.*
import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer.DockableEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.FrameWrapper
import com.intellij.openapi.util.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.toolWindow.ToolWindowButtonManager
import com.intellij.toolWindow.ToolWindowPane
import com.intellij.toolWindow.ToolWindowPaneNewButtonManager
import com.intellij.toolWindow.ToolWindowPaneOldButtonManager
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.ScreenUtil
import com.intellij.ui.awt.DevicePoint
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.VerticalBox
import com.intellij.ui.docking.*
import com.intellij.ui.docking.DockContainer.ContentResponse
import com.intellij.util.IconUtil
import com.intellij.util.ObjectUtils
import com.intellij.util.containers.sequenceOfNotNull
import com.intellij.util.ui.EdtInvocationManager
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jdom.Element
import org.jetbrains.annotations.Contract
import java.awt.*
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.util.*
import java.util.function.Predicate
import javax.swing.*
@State(name = "DockManager", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class DockManagerImpl(private val project: Project) : DockManager(), PersistentStateComponent<Element?> {
private val factories = HashMap<String, DockContainerFactory>()
private val containers = HashSet<DockContainer>()
private val containerToWindow = HashMap<DockContainer, DockWindow>()
private var currentDragSession: MyDragSession? = null
private val busyObject: BusyObject.Impl = object : BusyObject.Impl() {
override fun isReady(): Boolean = currentDragSession == null
}
private var windowIdCounter = 1
private var loadedState: Element? = null
companion object {
val SHOW_NORTH_PANEL = Key.create<Boolean>("SHOW_NORTH_PANEL")
val WINDOW_DIMENSION_KEY = Key.create<String>("WINDOW_DIMENSION_KEY")
@JvmField
val REOPEN_WINDOW = Key.create<Boolean>("REOPEN_WINDOW")
@JvmField
val ALLOW_DOCK_TOOL_WINDOWS = Key.create<Boolean>("ALLOW_DOCK_TOOL_WINDOWS")
@JvmStatic
fun isSingletonEditorInWindow(editors: List<FileEditor>): Boolean {
return editors.any { FileEditorManagerImpl.SINGLETON_EDITOR_IN_WINDOW.get(it, false) || EditorWindow.HIDE_TABS.get(it, false) }
}
private fun getWindowDimensionKey(content: DockableContent<*>): String? {
return if (content is DockableEditor) getWindowDimensionKey(content.file) else null
}
private fun getWindowDimensionKey(file: VirtualFile): String? = WINDOW_DIMENSION_KEY.get(file)
@JvmStatic
fun isNorthPanelVisible(uiSettings: UISettings): Boolean {
return uiSettings.showNavigationBar && !uiSettings.presentationMode
}
@JvmStatic
fun isNorthPanelAvailable(editors: List<FileEditor>): Boolean {
val defaultNorthPanelVisible = isNorthPanelVisible(UISettings.getInstance())
for (editor in editors) {
if (SHOW_NORTH_PANEL.isIn(editor)) {
return SHOW_NORTH_PANEL.get(editor, defaultNorthPanelVisible)
}
}
return defaultNorthPanelVisible
}
}
override fun register(container: DockContainer, parentDisposable: Disposable) {
containers.add(container)
Disposer.register(parentDisposable) { containers.remove(container) }
}
override fun register(id: String, factory: DockContainerFactory, parentDisposable: Disposable) {
factories.put(id, factory)
if (parentDisposable !== project) {
Disposer.register(parentDisposable) { factories.remove(id) }
}
readStateFor(id)
}
fun readState() {
for (id in factories.keys) {
readStateFor(id)
}
}
override fun getContainers(): Set<DockContainer> = allContainers.toSet()
override fun getIdeFrame(container: DockContainer): IdeFrame? {
return ComponentUtil.findUltimateParent(container.containerComponent) as? IdeFrame
}
override fun getDimensionKeyForFocus(key: String): String {
val owner = IdeFocusManager.getInstance(project).focusOwner ?: return key
val window = containerToWindow.get(getContainerFor(owner) { _ -> true })
return if (window == null) key else "$key#${window.id}"
}
@Suppress("OVERRIDE_DEPRECATION", "removal")
override fun getContainerFor(c: Component): DockContainer? {
return getContainerFor(c) { true }
}
@Contract("null, _ -> null")
override fun getContainerFor(c: Component?, filter: Predicate<in DockContainer>): DockContainer? {
if (c == null) {
return null
}
for (eachContainer in allContainers) {
if (SwingUtilities.isDescendingFrom(c, eachContainer.containerComponent) && filter.test(eachContainer)) {
return eachContainer
}
}
val parent = ComponentUtil.findUltimateParent(c)
for (eachContainer in allContainers) {
if (parent === ComponentUtil.findUltimateParent(eachContainer.containerComponent) && filter.test(eachContainer)) {
return eachContainer
}
}
return null
}
override fun createDragSession(mouseEvent: MouseEvent, content: DockableContent<*>): DragSession {
stopCurrentDragSession()
for (each in allContainers) {
if (each.isEmpty && each.isDisposeWhenEmpty) {
val window = containerToWindow.get(each)
window?.setTransparent(true)
}
}
currentDragSession = MyDragSession(mouseEvent, content)
return currentDragSession!!
}
fun stopCurrentDragSession() {
if (currentDragSession != null) {
currentDragSession!!.cancelSession()
currentDragSession = null
busyObject.onReady()
for (each in allContainers) {
if (!each.isEmpty) {
val window = containerToWindow.get(each)
window?.setTransparent(false)
}
}
}
}
private val ready: ActionCallback
get() = busyObject.getReady(this)
private inner class MyDragSession(mouseEvent: MouseEvent, content: DockableContent<*>) : DragSession {
private val window: JDialog
private var dragImage: Image?
private val defaultDragImage: Image
private val content: DockableContent<*>
val startDragContainer: DockContainer?
private var currentOverContainer: DockContainer? = null
private val imageContainer: JLabel
init {
window = JDialog(ComponentUtil.getWindow(mouseEvent.component))
window.isUndecorated = true
this.content = content
@Suppress("DEPRECATION")
startDragContainer = getContainerFor(mouseEvent.component)
val buffer = ImageUtil.toBufferedImage(content.previewImage)
val requiredSize = 220.0
val width = buffer.getWidth(null).toDouble()
val height = buffer.getHeight(null).toDouble()
val ratio = if (width > height) requiredSize / width else requiredSize / height
defaultDragImage = buffer.getScaledInstance((width * ratio).toInt(), (height * ratio).toInt(), Image.SCALE_SMOOTH)
dragImage = defaultDragImage
imageContainer = JLabel(object : Icon {
override fun getIconWidth(): Int = defaultDragImage.getWidth(window)
override fun getIconHeight(): Int = defaultDragImage.getHeight(window)
@Synchronized
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
StartupUiUtil.drawImage(g, defaultDragImage, x, y, window)
}
})
window.contentPane = imageContainer
setLocationFrom(mouseEvent)
window.isVisible = true
val windowManager = WindowManagerEx.getInstanceEx()
windowManager.setAlphaModeEnabled(window, true)
windowManager.setAlphaModeRatio(window, 0.1f)
}
private fun setLocationFrom(me: MouseEvent) {
val devicePoint = DevicePoint(me)
val showPoint = devicePoint.locationOnScreen
val size = imageContainer.size
showPoint.x -= size.width / 2
showPoint.y -= size.height / 2
window.bounds = Rectangle(showPoint, size)
}
override fun getResponse(e: MouseEvent): ContentResponse {
val point = DevicePoint(e)
for (each in allContainers) {
val rec = each.acceptArea
if (rec.contains(point)) {
val component = each.containerComponent
if (component.graphicsConfiguration != null) {
val response = each.getContentResponse(content, point.toRelativePoint(component))
if (response.canAccept()) {
return response
}
}
}
}
return ContentResponse.DENY
}
override fun process(e: MouseEvent) {
val devicePoint = DevicePoint(e)
var img: Image? = null
if (e.id == MouseEvent.MOUSE_DRAGGED) {
val over = findContainerFor(devicePoint, content)
if (currentOverContainer != null && currentOverContainer !== over) {
currentOverContainer!!.resetDropOver(content)
currentOverContainer = null
}
if (currentOverContainer == null && over != null) {
currentOverContainer = over
val point = devicePoint.toRelativePoint(over.containerComponent)
img = currentOverContainer!!.startDropOver(content, point)
}
if (currentOverContainer != null) {
val point = devicePoint.toRelativePoint(currentOverContainer!!.containerComponent)
img = currentOverContainer!!.processDropOver(content, point)
}
if (img == null) {
img = defaultDragImage
}
if (img !== dragImage) {
dragImage = img
imageContainer.icon = IconUtil.createImageIcon(dragImage!!)
window.pack()
}
setLocationFrom(e)
}
else if (e.id == MouseEvent.MOUSE_RELEASED) {
if (currentOverContainer == null) {
// This relative point might be relative to a component that's on a different screen, with a different DPI scaling factor than
// the target location. Ideally, we should pass the DevicePoint to createNewDockContainerFor, but that will change the API. We'll
// fix it up inside createNewDockContainerFor
val point = RelativePoint(e)
createNewDockContainerFor(content, point)
e.consume() //Marker for DragHelper: drag into separate window is not tabs reordering
}
else {
val point = devicePoint.toRelativePoint(currentOverContainer!!.containerComponent)
currentOverContainer!!.add(content, point)
ObjectUtils.consumeIfCast(currentOverContainer,
DockableEditorTabbedContainer::class.java) { container: DockableEditorTabbedContainer ->
//Marker for DragHelper, not 'refined' drop in tab-set shouldn't affect ABC-order setting
if (container.currentDropSide == SwingConstants.CENTER) e.consume()
}
}
stopCurrentDragSession()
}
}
override fun cancel() {
stopCurrentDragSession()
}
fun cancelSession() {
window.dispose()
if (currentOverContainer != null) {
currentOverContainer!!.resetDropOver(content)
currentOverContainer = null
}
}
}
private fun findContainerFor(devicePoint: DevicePoint, content: DockableContent<*>): DockContainer? {
val containers = containers.toMutableList()
FileEditorManagerEx.getInstanceEx(project)?.dockContainer?.let(containers::add)
val startDragContainer = currentDragSession?.startDragContainer
if (startDragContainer != null) {
containers.remove(startDragContainer)
containers.add(0, startDragContainer)
}
for (each in containers) {
val rec = each.acceptArea
if (rec.contains(devicePoint) && each.getContentResponse(content, devicePoint.toRelativePoint(each.containerComponent)).canAccept()) {
return each
}
}
for (each in containers) {
val rec = each.acceptAreaFallback
if (rec.contains(devicePoint) && each.getContentResponse(content, devicePoint.toRelativePoint(each.containerComponent)).canAccept()) {
return each
}
}
return null
}
private fun getFactory(type: String): DockContainerFactory? {
assert(factories.containsKey(type)) { "No factory for content type=$type" }
return factories.get(type)
}
fun createNewDockContainerFor(content: DockableContent<*>, point: RelativePoint) {
val container = getFactory(content.dockContainerType)!!.createContainer(content)
val canReopenWindow = content.presentation.getClientProperty(REOPEN_WINDOW)
val reopenWindow = canReopenWindow == null || canReopenWindow
val window = createWindowFor(getWindowDimensionKey(content), null, container, reopenWindow)
val isNorthPanelAvailable = if (content is DockableEditor) content.isNorthPanelAvailable else isNorthPanelVisible(UISettings.getInstance())
if (isNorthPanelAvailable) {
window.setupNorthPanel()
}
val canDockToolWindows = content.presentation.getClientProperty(ALLOW_DOCK_TOOL_WINDOWS)
if (canDockToolWindows == null || canDockToolWindows) {
window.setupToolWindowPane()
}
val size = content.preferredSize
// The given relative point might be relative to a component on a different screen, using different DPI screen coordinates. Convert to
// device coordinates first. Ideally, we would be given a DevicePoint
val showPoint = DevicePoint(point).locationOnScreen
showPoint.x -= size.width / 2
showPoint.y -= size.height / 2
val target = Rectangle(showPoint, size)
ScreenUtil.moveRectangleToFitTheScreen(target)
ScreenUtil.cropRectangleToFitTheScreen(target)
window.setLocation(target.location)
window.dockContentUiContainer.preferredSize = target.size
window.show(false)
window.getFrame().pack()
container.add(content, RelativePoint(target.location))
SwingUtilities.invokeLater { window.uiContainer.preferredSize = null }
}
fun createNewDockContainerFor(file: VirtualFile,
fileEditorManager: FileEditorManagerImpl): FileEditorComposite {
val container = getFactory(DockableEditorContainerFactory.TYPE)!!.createContainer(null)
// Order is important here. Create the dock window, then create the editor window. That way, any listeners can check to see if the
// parent window is floating.
val window = createWindowFor(getWindowDimensionKey(file), null, container, REOPEN_WINDOW.get(file, true))
if (!ApplicationManager.getApplication().isHeadlessEnvironment && !ApplicationManager.getApplication().isUnitTestMode) {
window.show(true)
}
val editorWindow = (container as DockableEditorTabbedContainer).splitters.getOrCreateCurrentWindow(file)
val result = fileEditorManager.openFileImpl2(editorWindow, file, FileEditorOpenOptions(requestFocus = true))
if (!isSingletonEditorInWindow(result.allEditors)) {
window.setupToolWindowPane()
}
val isNorthPanelAvailable = isNorthPanelAvailable(result.allEditors)
if (isNorthPanelAvailable) {
window.setupNorthPanel()
}
container.add(
EditorTabbedContainer.createDockableEditor(project, null, file, Presentation(file.name), editorWindow, isNorthPanelAvailable),
null
)
SwingUtilities.invokeLater { window.uiContainer.preferredSize = null }
return result
}
private fun createWindowFor(dimensionKey: String?,
id: String?,
container: DockContainer,
canReopenWindow: Boolean): DockWindow {
val window = DockWindow(dimensionKey = dimensionKey,
id = id ?: (windowIdCounter++).toString(),
project = project,
container = container,
isDialog = container is DockContainer.Dialog,
supportReopen = canReopenWindow)
containerToWindow.put(container, window)
return window
}
private fun getOrCreateWindowFor(id: String, container: DockContainer): DockWindow {
val existingWindow = containerToWindow.values.firstOrNull { it.id == id }
if (existingWindow != null) {
val oldContainer = existingWindow.replaceContainer(container)
containerToWindow.remove(oldContainer)
containerToWindow.put(container, existingWindow)
if (oldContainer is Disposable) {
Disposer.dispose(oldContainer)
}
return existingWindow
}
return createWindowFor(dimensionKey = null, id = id, container = container, canReopenWindow = true)
}
private inner class DockWindow(dimensionKey: String?,
val id: String,
project: Project,
private var container: DockContainer,
isDialog: Boolean,
val supportReopen: Boolean) : FrameWrapper(project, dimensionKey ?: "dock-window-$id", isDialog) {
var northPanelAvailable = false
private val northPanel = VerticalBox()
private val northExtensions = LinkedHashMap<String, JComponent>()
val uiContainer: NonOpaquePanel
private val centerPanel = JPanel(BorderLayout(0, 2))
val dockContentUiContainer: JPanel
var toolWindowPane: ToolWindowPane? = null
init {
if (!ApplicationManager.getApplication().isHeadlessEnvironment && container !is DockContainer.Dialog) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
if (statusBar != null) {
val frame = getFrame()
if (frame is IdeFrame) {
this.statusBar = statusBar.createChild(frame)
}
}
}
uiContainer = NonOpaquePanel(BorderLayout())
centerPanel.isOpaque = false
dockContentUiContainer = JPanel(BorderLayout())
dockContentUiContainer.isOpaque = false
dockContentUiContainer.add(container.containerComponent, BorderLayout.CENTER)
centerPanel.add(dockContentUiContainer, BorderLayout.CENTER)
uiContainer.add(centerPanel, BorderLayout.CENTER)
statusBar?.let {
uiContainer.add(it.component, BorderLayout.SOUTH)
}
component = uiContainer
IdeEventQueue.getInstance().addPostprocessor({ e ->
if (e is KeyEvent) {
if (currentDragSession != null) {
stopCurrentDragSession()
}
}
false
}, this)
container.addListener(object : DockContainer.Listener {
override fun contentRemoved(key: Any) {
ready.doWhenDone(Runnable(::closeIfEmpty))
}
}, this)
}
fun setupToolWindowPane() {
if (ApplicationManager.getApplication().isUnitTestMode || getFrame() !is JFrame || toolWindowPane != null) {
return
}
val paneId = dimensionKey!!
val buttonManager: ToolWindowButtonManager
if (ExperimentalUI.isNewUI()) {
buttonManager = ToolWindowPaneNewButtonManager(paneId, false)
buttonManager.add(dockContentUiContainer)
buttonManager.initMoreButton()
}
else {
buttonManager = ToolWindowPaneOldButtonManager(paneId)
}
val containerComponent = container.containerComponent
toolWindowPane = ToolWindowPane((getFrame() as JFrame), this, paneId, buttonManager)
toolWindowPane!!.setDocumentComponent(containerComponent)
dockContentUiContainer.remove(containerComponent)
dockContentUiContainer.add(toolWindowPane!!, BorderLayout.CENTER)
// Close the container if it's empty, and we've just removed the last tool window
project.messageBus.connect(this).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager, eventType: ToolWindowManagerEventType) {
if (eventType == ToolWindowManagerEventType.ActivateToolWindow ||
eventType == ToolWindowManagerEventType.MovedOrResized ||
eventType == ToolWindowManagerEventType.SetContentUiType) {
return
}
ready.doWhenDone(Runnable(::closeIfEmpty))
}
})
}
fun replaceContainer(container: DockContainer): DockContainer {
val newContainerComponent = container.containerComponent
if (toolWindowPane != null) {
toolWindowPane!!.setDocumentComponent(newContainerComponent)
}
else {
dockContentUiContainer.remove(this.container.containerComponent)
dockContentUiContainer.add(newContainerComponent)
}
val oldContainer = this.container
this.container = container
if (container is Activatable && getFrame().isVisible) {
(container as Activatable).showNotify()
}
return oldContainer
}
private fun closeIfEmpty() {
if (container.isEmpty && (toolWindowPane == null || !toolWindowPane!!.buttonManager.hasButtons())) {
close()
containers.remove(container)
}
}
fun setupNorthPanel() {
if (northPanelAvailable) {
return
}
centerPanel.add(northPanel, BorderLayout.NORTH)
northPanelAvailable = true
project.messageBus.connect(this).subscribe(UISettingsListener.TOPIC, UISettingsListener { uiSettings ->
val visible = isNorthPanelVisible(uiSettings)
if (northPanel.isVisible != visible) {
updateNorthPanel(visible)
}
})
updateNorthPanel(isNorthPanelVisible(UISettings.getInstance()))
}
override fun getNorthExtension(key: String?): JComponent? = northExtensions.get(key)
private fun updateNorthPanel(visible: Boolean) {
if (ApplicationManager.getApplication().isUnitTestMode || !northPanelAvailable) {
return
}
northPanel.removeAll()
northExtensions.clear()
northPanel.isVisible = visible && container !is DockContainer.Dialog
for (extension in IdeRootPaneNorthExtension.EP_NAME.extensionList) {
val component = extension.createComponent(project, true) ?: continue
northExtensions.put(extension.key, component)
northPanel.add(component)
}
northPanel.revalidate()
northPanel.repaint()
}
fun setTransparent(transparent: Boolean) {
val windowManager = WindowManagerEx.getInstanceEx()
if (transparent) {
windowManager.setAlphaModeEnabled(getFrame(), true)
windowManager.setAlphaModeRatio(getFrame(), 0.5f)
}
else {
windowManager.setAlphaModeEnabled(getFrame(), true)
windowManager.setAlphaModeRatio(getFrame(), 0f)
}
}
override fun dispose() {
super.dispose()
containerToWindow.remove(container)
if (container is Disposable) {
Disposer.dispose((container as Disposable))
}
northExtensions.clear()
}
override fun createJFrame(parent: IdeFrame): JFrame {
val frame = super.createJFrame(parent)
installListeners(frame)
return frame
}
override fun createJDialog(parent: IdeFrame): JDialog {
val frame = super.createJDialog(parent)
installListeners(frame)
return frame
}
private fun installListeners(frame: Window) {
val uiNotifyConnector = if (container is Activatable) {
UiNotifyConnector((frame as RootPaneContainer).contentPane, (container as Activatable))
}
else {
null
}
frame.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent) {
container.closeAll()
if (uiNotifyConnector != null) {
Disposer.dispose(uiNotifyConnector)
}
}
})
}
}
override fun getState(): Element {
val root = Element("state")
for (each in allContainers) {
val eachWindow = containerToWindow.get(each)
if (eachWindow != null && eachWindow.supportReopen && each is DockContainer.Persistent) {
val eachWindowElement = Element("window")
eachWindowElement.setAttribute("id", eachWindow.id)
eachWindowElement.setAttribute("withNorthPanel", eachWindow.northPanelAvailable.toString())
eachWindowElement.setAttribute("withToolWindowPane", (eachWindow.toolWindowPane != null).toString())
val content = Element("content")
content.setAttribute("type", each.dockContainerType)
content.addContent(each.state)
eachWindowElement.addContent(content)
root.addContent(eachWindowElement)
}
}
return root
}
private val allContainers: Sequence<DockContainer>
get() {
return sequenceOfNotNull(FileEditorManagerEx.getInstanceEx (project)?.dockContainer) +
containers.asSequence () +
containerToWindow.keys
}
override fun loadState(state: Element) {
loadedState = state
}
private fun readStateFor(type: String) {
for (windowElement in (loadedState ?: return).getChildren("window")) {
val eachContent = windowElement.getChild("content") ?: continue
val eachType = eachContent.getAttributeValue("type")
if (type != eachType || !factories.containsKey(eachType)) {
continue
}
val factory = factories.get(eachType) as? DockContainerFactory.Persistent ?: continue
val container = factory.loadContainerFrom(eachContent)
// If the window already exists, reuse it, otherwise create it. This handles changes in tasks & contexts. When we clear the current
// context, all open editors are closed, but a floating editor container with a docked tool window will remain open. Switching to a
// new context will reuse the window and open editors in that editor container. If the new context doesn't use this window, or it's
// a default clean context, the window will remain open, containing only the docked tool windows.
val window = getOrCreateWindowFor(windowElement.getAttributeValue("id"), container)
// If the window already exists, we can't remove the north panel or tool window pane, but we can add them
if (windowElement.getAttributeValue("withNorthPanel", "true").toBoolean()) {
window.setupNorthPanel()
}
if (windowElement.getAttributeValue("withToolWindowPane", "true").toBoolean()) {
window.setupToolWindowPane()
}
// If the window exists, it's already visible. Don't show multiple times as this will set up additional listeners and window decoration
EdtInvocationManager.invokeLaterIfNeeded {
if (!window.getFrame().isVisible) {
window.show()
}
}
}
}
} | platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.kt | 1878307462 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.test
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.psi.PsiElementVisitor
import com.intellij.testIntegration.TestFailedLineManager
import com.intellij.uast.UastHintedVisitorAdapter
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
class TestFailedLineInspection : AbstractBaseUastLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
UastHintedVisitorAdapter.create(holder.file.language, TestFailedVisitor(holder, isOnTheFly), arrayOf(UCallExpression::class.java), true)
class TestFailedVisitor(private val holder: ProblemsHolder, private val isOnTheFly: Boolean) : AbstractUastNonRecursiveVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
val sourceNode = node.sourcePsi ?: return true
val testFailProvider = TestFailedLineManager.getInstance(holder.project)
val testInfo = testFailProvider.getTestInfo(sourceNode) ?: return true
if (testInfo.magnitude < TEST_FAILED_MAGNITUDE) return true // don't highlight skipped tests
val fixes = listOfNotNull(
testFailProvider.getDebugQuickFix(sourceNode, testInfo.topStackTraceLine),
testFailProvider.getRunQuickFix(sourceNode)
).toTypedArray()
val identifier = node.methodIdentifier?.sourcePsi ?: return true
val descriptor = InspectionManager.getInstance(holder.project).createProblemDescriptor(
identifier, testInfo.errorMessage, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING
).apply { setTextAttributes(CodeInsightColors.RUNTIME_ERROR) }
holder.registerProblem(descriptor)
return true
}
}
companion object {
const val TEST_FAILED_MAGNITUDE = 6 // see TestStateInfo#Magnitude
}
} | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/TestFailedLineInspection.kt | 2372391748 |
package com.module.views.photoview
import android.view.View
/**
* Interface definition for a callback to be invoked when the target
* is experiencing a tap event.
*/
interface OnViewTapListener {
/**
* A callback to receive where the user taps on a target view. You will receive a callback if
* the user taps anywhere on the view, tapping on 'whitespace' will not be ignored.
*
* @param view - View the user tapped.
* @param x - where the user tapped from the left of the View.
* @param y - where the user tapped from the top of the View.
*/
fun onViewTap(view: View?, x: Float, y: Float)
} | library/ui/src/main/java/com/module/views/photoview/OnViewTapListener.kt | 3278030660 |
package com.reactnativenavigation.views.touch
import android.view.MotionEvent
import androidx.annotation.VisibleForTesting
import com.reactnativenavigation.options.params.Bool
import com.reactnativenavigation.options.params.NullBool
import com.reactnativenavigation.react.ReactView
import com.reactnativenavigation.utils.coordinatesInsideView
import com.reactnativenavigation.views.component.ComponentLayout
open class OverlayTouchDelegate(private val component: ComponentLayout, private val reactView: ReactView) {
var interceptTouchOutside: Bool = NullBool()
fun onInterceptTouchEvent(event: MotionEvent): Boolean {
return when (interceptTouchOutside.hasValue() && event.actionMasked == MotionEvent.ACTION_DOWN) {
true -> handleDown(event)
false -> component.superOnInterceptTouchEvent(event)
}
}
@VisibleForTesting
open fun handleDown(event: MotionEvent) = when (event.coordinatesInsideView(reactView.getChildAt(0))) {
true -> component.superOnInterceptTouchEvent(event)
false -> interceptTouchOutside.isFalse
}
} | lib/android/app/src/main/java/com/reactnativenavigation/views/touch/OverlayTouchDelegate.kt | 3847086602 |
// IS_APPLICABLE: false
// WITH_RUNTIME
fun foo() {
<caret>object : Runnable {
override fun run() {
this.hashCode()
}
}.run()
} | plugins/kotlin/idea/tests/testData/intentions/objectLiteralToLambda/ExplicitThis.kt | 1815742402 |
package bar
import foo.AGrandChild | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/common/exportedDependency/module4_importAGrandChild.kt | 1274305147 |
// "Add non-null asserted (!!) call" "true"
// ACTION: Cast expression 'a' to 'Foo'
interface Foo {
fun bar()
}
open class MyClass {
open val a: Foo? = null
fun foo() {
if (a != null) {
<caret>a.bar()
}
}
}
| plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/addExclExclWhenSmartCastImpossible.kt | 576418445 |
// FIR_COMPARISON
package bar
import javapackage.SomeClass
fun buz {
SomeClass.<caret>
}
// ABSENT: aProc
// EXIST: CONST_A
// EXIST: aStaticProc
// EXIST: getA
// EXIST: FooBar
// NOTHING_ELSE | plugins/kotlin/completion/tests/testData/basic/multifile/StaticMembersOfImportedClassFromJava/StaticMembersOfImportedClassFromJava.kt | 2872915347 |
// 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.tools.projectWizard.wizard.service
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.framework.ui.ConfigureDialogWithModulesAndVersion
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.asNullable
import org.jetbrains.kotlin.tools.projectWizard.core.safe
import org.jetbrains.kotlin.tools.projectWizard.core.service.EapVersionDownloader
import org.jetbrains.kotlin.tools.projectWizard.core.service.KotlinVersionProviderService
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardKotlinVersion
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.runWithProgressBar
@NonNls
private const val SNAPSHOT_TAG = "snapshot"
class IdeaKotlinVersionProviderService : KotlinVersionProviderService(), IdeaWizardService {
override fun getKotlinVersion(projectKind: ProjectKind): WizardKotlinVersion {
if (projectKind == ProjectKind.COMPOSE) {
val version = Versions.KOTLIN_VERSION_FOR_COMPOSE
return kotlinVersionWithDefaultValues(version)
}
val version = getPatchedKotlinVersion()
?: getKotlinVersionFromCompiler()
?: VersionsDownloader.downloadLatestEapOrStableKotlinVersion()
?: Versions.KOTLIN
return kotlinVersionWithDefaultValues(version)
}
private fun getPatchedKotlinVersion() =
if (isApplicationInternalMode()) {
System.getProperty(KOTLIN_COMPILER_VERSION_TAG)?.let { Version.fromString(it) }
} else {
null
}
companion object {
private const val KOTLIN_COMPILER_VERSION_TAG = "kotlin.compiler.version"
private fun getKotlinVersionFromCompiler(): Version? {
val kotlinCompilerVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
val kotlinArtifactVersion = kotlinCompilerVersion.takeUnless { it.isSnapshot }?.artifactVersion ?: return null
return Version.fromString(kotlinArtifactVersion)
}
}
}
private object VersionsDownloader {
fun downloadLatestEapOrStableKotlinVersion(): Version? =
runWithProgressBar(KotlinNewProjectWizardUIBundle.message("version.provider.downloading.kotlin.version")) {
val latestEap = EapVersionDownloader.getLatestEapVersion()
val latestStable = getLatestStableVersion()
when {
latestEap == null -> latestStable
latestStable == null -> latestEap
VersionComparatorUtil.compare(latestEap.text, latestStable.text) > 0 -> latestEap
else -> latestStable
}
}
private fun getLatestStableVersion() = safe {
ConfigureDialogWithModulesAndVersion.loadVersions("1.0.0")
}.asNullable?.firstOrNull { !it.contains(SNAPSHOT_TAG, ignoreCase = true) }?.let { Version.fromString(it) }
}
| plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/service/IdeaKotlinVersionProviderService.kt | 926351379 |
/*
* Copyright 2010-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 kotlin.annotation
import kotlin.annotation.AnnotationTarget.*
/**
* Contains the list of code elements which are the possible annotation targets
*/
public enum class AnnotationTarget {
/** Class, interface or object, annotation class is also included */
CLASS,
/** Annotation class only */
ANNOTATION_CLASS,
/** Generic type parameter (unsupported yet) */
TYPE_PARAMETER,
/** Property */
PROPERTY,
/** Field, including property's backing field */
FIELD,
/** Local variable */
LOCAL_VARIABLE,
/** Value parameter of a function or a constructor */
VALUE_PARAMETER,
/** Constructor only (primary or secondary) */
CONSTRUCTOR,
/** Function (constructors are not included) */
FUNCTION,
/** Property getter only */
PROPERTY_GETTER,
/** Property setter only */
PROPERTY_SETTER,
/** Type usage */
TYPE,
/** Any expression */
EXPRESSION,
/** File */
FILE,
/** Type alias */
@SinceKotlin("1.1")
TYPEALIAS
}
/**
* Contains the list of possible annotation's retentions.
*
* Determines how an annotation is stored in binary output.
*/
public enum class AnnotationRetention {
/** Annotation isn't stored in binary output */
SOURCE,
/** Annotation is stored in binary output, but invisible for reflection */
BINARY,
/** Annotation is stored in binary output and visible for reflection (default retention) */
RUNTIME
}
/**
* This meta-annotation indicates the kinds of code elements which are possible targets of an annotation.
*
* If the target meta-annotation is not present on an annotation declaration, the annotation is applicable to the following elements:
* [CLASS], [PROPERTY], [FIELD], [LOCAL_VARIABLE], [VALUE_PARAMETER], [CONSTRUCTOR], [FUNCTION], [PROPERTY_GETTER], [PROPERTY_SETTER].
*
* @property allowedTargets list of allowed annotation targets
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
@MustBeDocumented
public annotation class Target(vararg val allowedTargets: AnnotationTarget)
/**
* This meta-annotation determines whether an annotation is stored in binary output and visible for reflection. By default, both are true.
*
* @property value necessary annotation retention (RUNTIME, BINARY or SOURCE)
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
public annotation class Retention(val value: AnnotationRetention = AnnotationRetention.RUNTIME)
/**
* This meta-annotation determines that an annotation is applicable twice or more on a single code element
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
public annotation class Repeatable
/**
* This meta-annotation determines that an annotation is a part of public API and therefore should be included in the generated
* documentation for the element to which the annotation is applied.
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
public annotation class MustBeDocumented | runtime/src/main/kotlin/kotlin/annotation/Annotations.kt | 3286068341 |
package com.intellij.ide.starter.plugins
enum class PluginInstalledState {
BUNDLED_TO_IDE,
INSTALLED,
NOT_INSTALLED,
DISABLED
} | tools/intellij.ide.starter/src/com/intellij/ide/starter/plugins/PluginInstalledState.kt | 4272325895 |
package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityWithSymbolicId
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleSymbolicIdEntityImpl(val dataSource: SimpleSymbolicIdEntityData) : SimpleSymbolicIdEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val version: Int get() = dataSource.version
override val name: String
get() = dataSource.name
override val related: SimpleId
get() = dataSource.related
override val sealedClassWithLinks: SealedClassWithLinks
get() = dataSource.sealedClassWithLinks
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SimpleSymbolicIdEntityData?) : ModifiableWorkspaceEntityBase<SimpleSymbolicIdEntity, SimpleSymbolicIdEntityData>(
result), SimpleSymbolicIdEntity.Builder {
constructor() : this(SimpleSymbolicIdEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleSymbolicIdEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field SimpleSymbolicIdEntity#name should be initialized")
}
if (!getEntityData().isRelatedInitialized()) {
error("Field SimpleSymbolicIdEntity#related should be initialized")
}
if (!getEntityData().isSealedClassWithLinksInitialized()) {
error("Field SimpleSymbolicIdEntity#sealedClassWithLinks should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleSymbolicIdEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.version != dataSource.version) this.version = dataSource.version
if (this.name != dataSource.name) this.name = dataSource.name
if (this.related != dataSource.related) this.related = dataSource.related
if (this.sealedClassWithLinks != dataSource.sealedClassWithLinks) this.sealedClassWithLinks = dataSource.sealedClassWithLinks
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData(true).version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData(true).name = value
changedProperty.add("name")
}
override var related: SimpleId
get() = getEntityData().related
set(value) {
checkModificationAllowed()
getEntityData(true).related = value
changedProperty.add("related")
}
override var sealedClassWithLinks: SealedClassWithLinks
get() = getEntityData().sealedClassWithLinks
set(value) {
checkModificationAllowed()
getEntityData(true).sealedClassWithLinks = value
changedProperty.add("sealedClassWithLinks")
}
override fun getEntityClass(): Class<SimpleSymbolicIdEntity> = SimpleSymbolicIdEntity::class.java
}
}
class SimpleSymbolicIdEntityData : WorkspaceEntityData.WithCalculableSymbolicId<SimpleSymbolicIdEntity>() {
var version: Int = 0
lateinit var name: String
lateinit var related: SimpleId
lateinit var sealedClassWithLinks: SealedClassWithLinks
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isRelatedInitialized(): Boolean = ::related.isInitialized
fun isSealedClassWithLinksInitialized(): Boolean = ::sealedClassWithLinks.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SimpleSymbolicIdEntity> {
val modifiable = SimpleSymbolicIdEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleSymbolicIdEntity {
return getCached(snapshot) {
val entity = SimpleSymbolicIdEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return SimpleId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleSymbolicIdEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleSymbolicIdEntity(version, name, related, sealedClassWithLinks, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SimpleSymbolicIdEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.related != other.related) return false
if (this.sealedClassWithLinks != other.sealedClassWithLinks) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SimpleSymbolicIdEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.related != other.related) return false
if (this.sealedClassWithLinks != other.sealedClassWithLinks) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + related.hashCode()
result = 31 * result + sealedClassWithLinks.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + related.hashCode()
result = 31 * result + sealedClassWithLinks.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(SimpleId::class.java)
collector.add(SealedClassWithLinks.Many.Unordered::class.java)
collector.add(SealedClassWithLinks.Many::class.java)
collector.add(SealedClassWithLinks.Single::class.java)
collector.add(SealedClassWithLinks::class.java)
collector.add(SealedClassWithLinks.Many.Ordered::class.java)
collector.addObject(SealedClassWithLinks.Nothing::class.java)
this.sealedClassWithLinks?.let { collector.add(it::class.java) }
collector.sameForAllEntities = true
}
}
| plugins/devkit/intellij.devkit.workspaceModel/tests/testData/symbolicId/after/gen/SimpleSymbolicIdEntityImpl.kt | 632820711 |
// PSI_ELEMENT: com.intellij.psi.PsiField
// OPTIONS: usages
// FIND_BY_REF
// FIR_COMPARISON
package usages
import library.Foo
fun test() {
Foo.<caret>X = 1
} | plugins/kotlin/idea/tests/testData/findUsages/libraryUsages/javaLibrary/LibraryStaticFieldUsages.0.kt | 611610268 |
package second
class Some
// Two function to prevent automatic insert
fun Some.extensionFunction1(): Int = 12
fun Some.extensionFunction2(): Int = 12
fun foo(): Some = Some() | plugins/kotlin/completion/tests/testData/basic/multifile/ExtensionFunctionOnImportedFunction/ExtensionFunctionOnImportedFunction.dependency.kt | 1268395630 |
package zielu.gittoolbox.extension.autofetch
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
internal class AutoFetchAllowedExtension(private val project: Project) {
fun isFetchAllowed(): Boolean {
return extensions().all { ext -> ext.isAllowed(project) }
}
private fun extensions(): List<AutoFetchAllowed> {
return EXTENSION_POINT_NAME.extensionList
.map { ext -> ext.instantiate() }
}
}
private val EXTENSION_POINT_NAME: ExtensionPointName<AutoFetchAllowedEP> = ExtensionPointName.create(
"zielu.gittoolbox.autoFetchAllowed"
)
| src/main/kotlin/zielu/gittoolbox/extension/autofetch/AutoFetchAllowedExtension.kt | 1690715831 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.actionSystem.impl.segmentedActionBar
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import javax.swing.JComponent
import javax.swing.border.Border
open class SegmentedActionToolbarComponent(place: String, group: ActionGroup, val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) {
companion object {
internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY"
internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST"
internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST"
internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE"
internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE"
const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION"
private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java)
internal val segmentedButtonLook = object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
SegmentedBarPainter.paintActionButtonBackground(g, component, state)
}
}
fun isCustomBar(component: Component): Boolean {
if (component !is JComponent) return false
return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let {
it != CONTROL_BAR_SINGLE
} ?: false
}
fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean {
return SegmentedBarPainter.paintButtonDecorations(g, c, paint)
}
}
init {
layoutPolicy = NOWRAP_LAYOUT_POLICY
}
private var isActive = false
private var visibleActions: MutableList<out AnAction>? = null
override fun getInsets(): Insets {
return JBInsets.emptyInsets()
}
override fun setBorder(border: Border?) {
}
override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent {
if (!isActive) {
return super.createCustomComponent(action, presentation)
}
var component = super.createCustomComponent(action, presentation)
if (action is ComboBoxAction) {
UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let {
component.remove(it)
component = it
}
}
else if (component is ActionButton) {
val actionButton = component as ActionButton
updateActionButtonLook(actionButton)
}
component.border = JBUI.Borders.empty()
return component
}
override fun createToolbarButton(action: AnAction,
look: ActionButtonLook?,
place: String,
presentation: Presentation,
minimumSize: Dimension): ActionButton {
if (!isActive) {
return super.createToolbarButton(action, look, place, presentation, minimumSize)
}
val createToolbarButton = super.createToolbarButton(action, segmentedButtonLook, place, presentation, minimumSize)
updateActionButtonLook(createToolbarButton)
return createToolbarButton
}
private fun updateActionButtonLook(actionButton: ActionButton) {
actionButton.border = JBUI.Borders.empty(0, 3)
actionButton.setLook(segmentedButtonLook)
}
override fun fillToolBar(actions: MutableList<out AnAction>, layoutSecondaries: Boolean) {
if (!isActive) {
super.fillToolBar(actions, layoutSecondaries)
return
}
val rightAligned: MutableList<AnAction> = ArrayList()
for (i in actions.indices) {
val action = actions[i]
if (action is RightAlignedToolbarAction) {
rightAligned.add(action)
continue
}
if (action is CustomComponentAction) {
val component = getCustomComponent(action)
addMetadata(component, i, actions.size)
add(CUSTOM_COMPONENT_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
else {
val component = createToolbarButton(action)
addMetadata(component, i, actions.size)
add(ACTION_BUTTON_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
}
}
protected open fun isSuitableAction(action: AnAction): Boolean {
return true
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
paintActiveBorder(g)
}
private fun paintActiveBorder(g: Graphics) {
if((isActive || paintBorderForSingleItem) && visibleActions != null) {
SegmentedBarPainter.paintActionBarBorder(this, g)
}
}
override fun paintBorder(g: Graphics) {
super.paintBorder(g)
paintActiveBorder(g)
}
override fun paint(g: Graphics) {
super.paint(g)
paintActiveBorder(g)
}
private fun addMetadata(component: JComponent, index: Int, count: Int) {
if (count == 1) {
component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE)
return
}
val property = when (index) {
0 -> CONTROL_BAR_FIRST
count - 1 -> CONTROL_BAR_LAST
else -> CONTROL_BAR_MIDDLE
}
component.putClientProperty(CONTROL_BAR_PROPERTY, property)
}
protected open fun logNeeded() = false
protected fun forceUpdate() {
if(logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate")
visibleActions?.let {
update(true, it)
revalidate()
repaint()
}
}
override fun actionsUpdated(forced: Boolean, newVisibleActions: MutableList<out AnAction>) {
visibleActions = newVisibleActions
update(forced, newVisibleActions)
}
private var lastIds: List<String> = emptyList()
private fun update(forced: Boolean, newVisibleActions: MutableList<out AnAction>) {
val filtered = newVisibleActions.filter { isSuitableAction(it) }
val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList()
val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList()
if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar")
lastIds = filteredIds
isActive = filtered.size > 1
super.actionsUpdated(forced, if (isActive) filtered else newVisibleActions)
}
override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
bounds.clear()
for (i in 0 until componentCount) {
bounds.add(Rectangle())
}
var offset = 0
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += d.width
}
}
} | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt | 3218930984 |
fun some(body: () -> Unit) = body()
fun oneMore() <fold text='{...}' expand='true'>{
some <fold text='{...}' expand='true'>{
// this is a comment
val v1 = "Body"
val v2 = "of"
val v3 = "function"
}</fold>
}</fold>
// Generated from: idea/testData/folding/checkCollapse/block.kt | plugins/kotlin/idea/tests/testData/folding/checkCollapse/functionLiteral.kt | 927029120 |
// "Import" "true"
// ERROR: Unresolved reference: /
package h
interface H
fun f(h: H) {
h <caret>/ 3
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/divOperator.before.Main.kt | 436036396 |
package com.cognifide.gradle.aem
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.common.utils.Patterns
import org.gradle.api.JavaVersion
class AemVersion(val value: String) : Comparable<AemVersion> {
private val base = Formats.asVersion(value)
val version get() = base.version
fun atLeast(other: AemVersion) = this >= other
fun atLeast(other: String) = atLeast(AemVersion(other))
fun atMost(other: AemVersion) = other <= this
fun atMost(other: String) = atMost(AemVersion(other))
fun inRange(range: String): Boolean = range.contains("-") && this in unclosedRange(range, "-")
/**
* Indicates repository restructure performed in AEM 6.4.0 / preparations for making AEM available on cloud.
*
* After this changes, nodes under '/apps' or '/libs' are frozen and some features (like workflow manager)
* requires to copy these nodes under '/var' by plugin (or AEM itself).
*
* @see <https://docs.adobe.com/content/help/en/experience-manager-64/deploying/restructuring/repository-restructuring.html>
*/
val frozen get() = atLeast(VERSION_6_4_0)
/**
* Cloud manager version contains time in the end
*/
val cloud get() = Patterns.wildcard(value, "*.*.*.*T*Z")
val type get() = when {
cloud -> "cloud"
else -> "on-prem"
}
// === Overriddes ===
override fun toString() = "$value ($type)"
override fun compareTo(other: AemVersion): Int = base.compareTo(other.base)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AemVersion
if (base != other.base) return false
return true
}
override fun hashCode(): Int = base.hashCode()
class UnclosedRange(val start: AemVersion, val end: AemVersion) {
operator fun contains(version: AemVersion) = version >= start && version < end
}
companion object {
val UNKNOWN = AemVersion("0.0.0")
val VERSION_6_0_0 = AemVersion("6.0.0")
val VERSION_6_1_0 = AemVersion("6.1.0")
val VERSION_6_2_0 = AemVersion("6.2.0")
val VERSION_6_3_0 = AemVersion("6.3.0")
val VERSION_6_4_0 = AemVersion("6.4.0")
val VERSION_6_5_0 = AemVersion("6.5.0")
fun unclosedRange(value: String, delimiter: String = "-"): UnclosedRange {
val versions = value.split(delimiter)
if (versions.size != 2) {
throw AemException("AEM version range has invalid format: '$value'!")
}
val (start, end) = versions.map { AemVersion(it) }
return UnclosedRange(start, end)
}
}
}
fun String.javaVersions(delimiter: String = ",") = this.split(delimiter).map { JavaVersion.toVersion(it) }
| src/main/kotlin/com/cognifide/gradle/aem/AemVersion.kt | 4101709909 |
package com.intellij.aws.cloudformation
import com.intellij.aws.cloudformation.model.CfnNode
import com.intellij.json.psi.JsonFile
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiFile
import org.jetbrains.yaml.psi.YAMLFile
import java.lang.reflect.AccessibleObject
import java.lang.reflect.Field
import java.lang.reflect.Modifier
object CloudFormationParser {
private val PARSED_KEY = Key.create<CloudFormationParsedFile>("CFN_PARSED_FILE")
fun parse(psiFile: PsiFile): CloudFormationParsedFile {
val cached = psiFile.getUserData(PARSED_KEY)
if (cached != null && cached.fileModificationStamp == psiFile.modificationStamp) {
return cached
}
assert(CloudFormationPsiUtils.isCloudFormationFile(psiFile)) { psiFile.name + " is not a CloudFormation file" }
val parsed = when (psiFile) {
is JsonFile -> JsonCloudFormationParser.parse(psiFile)
is YAMLFile -> YamlCloudFormationParser.parse(psiFile)
else -> error("Unsupported PSI file type: " + psiFile.javaClass.name)
}
assertAllNodesAreMapped(parsed)
psiFile.putUserData(PARSED_KEY, parsed)
return parsed
}
private fun assertAllNodesAreMapped(parsed: CloudFormationParsedFile) {
fun isGoodField(field: Field): Boolean =
field.name.indexOf('$') == -1 && !Modifier.isTransient(field.modifiers) && !Modifier.isStatic(field.modifiers)
val seen = mutableSetOf<Any>()
fun processInstance(obj: Any, parent: Any) {
if (seen.contains(obj)) return
seen.add(obj)
if (obj is CfnNode) {
try {
parsed.getPsiElement(obj)
} catch (t: Throwable) {
error("Node $obj under $parent is not mapped")
}
}
if (obj is Collection<*>) {
obj.forEach { it?.let { processInstance(it, parent) } }
return
}
val fields = obj.javaClass.declaredFields
AccessibleObject.setAccessible(fields, true)
fields
.filter { isGoodField(it) }
.mapNotNull { it.get(obj) }
.forEach { processInstance(it, obj) }
}
processInstance(parsed.root, parsed.root)
}
} | src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationParser.kt | 2778845108 |
package com.cognifide.gradle.aem.common.instance.service.pkg
import java.util.regex.Pattern
data class ErrorPattern(val pattern: Pattern, val printStackTrace: Boolean, val message: String = "")
| src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/pkg/ErrorPattern.kt | 2585071984 |
package bj.vinylbrowser.model.artist
import android.os.Parcel
import android.os.Parcelable
/**
* Created by Josh Laird on 19/05/2017.
*/
data class ArtistWantedUrl(val url: String,
val displayText: String,
val hexCode: String,
val fontAwesomeString: String) : Parcelable {
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(url)
dest.writeString(displayText)
dest.writeString(hexCode)
dest.writeString(fontAwesomeString)
}
override fun describeContents(): Int {
return 0
}
} | app/src/main/java/bj/vinylbrowser/model/artist/ArtistWantedUrl.kt | 1053597953 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.patterns.PlatformPatterns
import com.intellij.util.ProcessingContext
import com.jetbrains.extensions.python.afterDefInMethod
import com.jetbrains.python.PyNames
import com.jetbrains.python.psi.LanguageLevel
class PySpecialMethodNamesCompletionContributor : CompletionContributor() {
override fun handleAutoCompletionPossibility(context: AutoCompletionContext) = autoInsertSingleItem(context)
init {
extend(CompletionType.BASIC, PlatformPatterns.psiElement().afterDefInMethod(), MyCompletionProvider)
}
private object MyCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val pyClass = parameters.getPyClass() ?: return
val typeEvalContext = parameters.getTypeEvalContext()
PyNames.getBuiltinMethods(LanguageLevel.forElement(pyClass))
?.forEach {
addMethodToResult(result, pyClass, typeEvalContext, it.key, it.value.signature) { it.withTypeText("predefined") }
}
}
}
} | python/src/com/jetbrains/python/codeInsight/completion/PySpecialMethodNamesCompletionContributor.kt | 3375144880 |
/*
* Copyright 2016 Andy Bao
*
* 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 xyz.nulldev.ts.api.http.auth
import spark.Request
import spark.Response
import xyz.nulldev.ts.api.http.TachiWebRoute
/**
* Simple route to check if an auth password is correct.
*
* If the auth password is correct, the user is authenticated.
*/
class CheckSessionRoute: TachiWebRoute(requiresAuth = false) {
override fun handleReq(request: Request, response: Response): Any {
val session: String = request.attribute("session")
val password = request.queryParams("password")
val authPw = SessionManager.authPassword()
val valid = if(password.isEmpty())
authPw.isEmpty()
else
authPw.isNotEmpty() && PasswordHasher.check(password, authPw)
return if (valid) {
sessionManager.authenticateSession(session)
success().put(KEY_TOKEN, session)
} else {
error("Incorrect password!")
}
}
companion object {
val KEY_TOKEN = "token"
}
}
| TachiServer/src/main/java/xyz/nulldev/ts/api/http/auth/CheckSessionRoute.kt | 2006542789 |
// GENERATED
package com.fkorotkov.kubernetes.admissionregistration.v1
import io.fabric8.kubernetes.api.model.admissionregistration.v1.ServiceReference as v1_ServiceReference
import io.fabric8.kubernetes.api.model.admissionregistration.v1.WebhookClientConfig as v1_WebhookClientConfig
fun v1_WebhookClientConfig.`service`(block: v1_ServiceReference.() -> Unit = {}) {
if(this.`service` == null) {
this.`service` = v1_ServiceReference()
}
this.`service`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/admissionregistration/v1/service.kt | 3371463902 |
/*
* Copyright 2017 Obsidian Foundation
*
* 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.obsidian.compiler.daemon
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
import org.glassfish.grizzly.http.server.HttpServer
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory
import org.glassfish.jersey.server.ResourceConfig
import javax.ws.rs.core.UriBuilder
import java.net.URI
/**
*
* The daemon's responsibility is to intercept requests from external entities such as editors (VSCode's Language
* Server, for example), debuggers, and anything a person would want to build to use Obsidian's compiler and analysis
* output really.
*
* The daemon provides a RESTful interface to various aspects of Obsidian's internals. These
* internals include, but are not limited to: * Static Analysis * Complexity Analysis
* * Linting * Runtime Debugging
*/
class Daemon : Thread() {
override fun run() {
server = startHttpServer()
}
companion object {
/**
* Where the daemon will listen as its root address
* @TODO Make configurable via command-line arguments
*/
val URI_BASE = UriBuilder.fromUri("http://localhost/").port(9090).path("obsidian/").build()
fun startHttpServer(): HttpServer {
val mapper = ObjectMapper()
val provider = JacksonJaxbJsonProvider()
provider.setMapper(mapper)
// Scans this package for JAX-RS resources needed to build endpoints and responses
val rc = ResourceConfig()
.packages(true, "com.obsidian.compiler.daemon.resources")
.register(provider)
return GrizzlyHttpServerFactory.createHttpServer(URI_BASE, rc)
}
}
var server: HttpServer? = null
init {
if(server != null){
server = startHttpServer()
}
}
}
| src/com/obsidian/compiler/daemon/Daemon.kt | 2369718743 |
package co.upcurve.mystiquesample.items
import android.view.View
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import co.upcurve.mystique.MystiqueItemPresenter
import co.upcurve.mystiquesample.R
import co.upcurve.mystiquesample.models.BannerModel
/**
* Created by rahulchowdhury on 5/29/17.
*/
class BannerItem(var bannerModel: BannerModel = BannerModel()) : MystiqueItemPresenter() {
@BindView(R.id.heading_banner)
lateinit var bannerHeading: TextView
override fun loadModel(model: Any) {
bannerModel = model as BannerModel
}
override fun getModel() = bannerModel
override fun setListener(listener: Any?) {
}
override fun getLayout() = R.layout.view_item_banner
override fun displayView(itemView: View) {
ButterKnife.bind(this, itemView)
bannerHeading.text = bannerModel.heading
}
override fun handleClickEvents(itemView: View) {
}
} | app/src/main/java/co/upcurve/mystiquesample/items/BannerItem.kt | 2390521479 |
package com.evalab.core.cli.option
import com.evalab.core.cli.exception.IllegalOptionValueException
import java.text.ParseException
public class DoubleOption : Option<Double> {
constructor(
longForm: String,
isRequired: Boolean,
shortForm: Char? = null,
helpDesc: String? = null
) : super(longForm, true, isRequired, shortForm, helpDesc)
@Throws(IllegalOptionValueException::class)
override fun parse(arg: String): Double {
try {
return arg.toDouble()
} catch (e: ParseException) {
throw IllegalOptionValueException(this, arg)
}
}
} | src/com/evalab/core/cli/option/DoubleOption.kt | 1135823201 |
package co.upcurve.mystiquesample.models
import co.upcurve.mystique.Presenter
import co.upcurve.mystiquesample.items.PostItem
/**
* Created by rahulchowdhury on 5/29/17.
*/
@Presenter(PostItem::class)
data class PostModel(var title: String = "", var description: String = "", var imageUrl: String = "") | app/src/main/java/co/upcurve/mystiquesample/models/PostModel.kt | 3892934121 |
package io.sentry.protocol
import io.sentry.SpanContext
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNotSame
import org.junit.Test
class ContextsTest {
@Test
fun `copying contexts wont have the same references`() {
val contexts = Contexts()
contexts.setApp(App())
contexts.setBrowser(Browser())
contexts.setDevice(Device())
contexts.setOperatingSystem(OperatingSystem())
contexts.setRuntime(SentryRuntime())
contexts.setGpu(Gpu())
contexts.trace = SpanContext("op")
val clone = Contexts(contexts)
assertNotNull(clone)
assertNotSame(contexts, clone)
assertNotSame(contexts.app, clone.app)
assertNotSame(contexts.browser, clone.browser)
assertNotSame(contexts.device, clone.device)
assertNotSame(contexts.operatingSystem, clone.operatingSystem)
assertNotSame(contexts.runtime, clone.runtime)
assertNotSame(contexts.gpu, clone.gpu)
assertNotSame(contexts.trace, clone.trace)
}
@Test
fun `copying contexts will have the same values`() {
val contexts = Contexts()
contexts["some-property"] = "some-value"
contexts.trace = SpanContext("op")
contexts.trace!!.description = "desc"
val clone = Contexts(contexts)
assertNotNull(clone)
assertNotSame(contexts, clone)
assertEquals(contexts["some-property"], clone["some-property"])
assertEquals(contexts.trace!!.description, clone.trace!!.description)
}
}
| sentry/src/test/java/io/sentry/protocol/ContextsTest.kt | 3890690576 |
package coffee.cypher.mcextlib.util.coroutines
import coffee.cypher.mcextlib.util.coroutines.TickCoroutineDispatcher.ExecutionConfiguration.Companion.once
import net.minecraft.util.ITickable
import kotlin.coroutines.experimental.*
@Suppress("EXPERIMENTAL_FEATURE_WARNING")
@RestrictsSuspension
class TickCoroutineDispatcher : ITickable {
private val currentContinuations = mutableListOf<Continuation<Unit>>()
val activeTasks
get() = currentContinuations.mapNotNull { it.context[TaskHandle] }
override fun update() {
currentContinuations.removeIf {
it.context[TaskHandle]?.state == TaskHandle.State.STOPPED
}
currentContinuations.forEach {
if (it.context[TaskHandle]?.state == TaskHandle.State.RUNNING) {
it.context[TaskHandle]!!.untilNextExecution--
}
}
val toRun = currentContinuations.filter {
it.context[TaskHandle]!!.untilNextExecution <= 0
}
currentContinuations -= toRun
toRun.forEach { it.resume(Unit) }
}
fun startTask(
name: String,
configuration: ExecutionConfiguration = once(),
block: suspend TickCoroutineDispatcher.() -> Unit
): TaskHandle {
return when (configuration) {
is ExecutionConfiguration.Infinite -> startTask(name, once(configuration.initialDelay)) {
while (true) {
block()
skipTicks(configuration.pause)
}
}
is ExecutionConfiguration.Repeat -> startTask(name, once(configuration.initialDelay)) {
for (i in 1..configuration.times) {
block()
skipTicks(configuration.pause)
}
}
is ExecutionConfiguration.Once -> {
val handle = TaskHandle(name)
if (configuration.initialDelay == 0) {
block.startCoroutine(this, object : Continuation<Unit> {
override val context = handle
override fun resume(value: Unit) {
context[TaskHandle]?.stop()
}
override fun resumeWithException(exception: Throwable) {
context[TaskHandle]?.stop()
throw TaskExecutionException(name, exception)
}
})
} else {
currentContinuations += block.createCoroutine(this, object : Continuation<Unit> {
override val context = handle.apply { untilNextExecution = configuration.initialDelay }
override fun resume(value: Unit) {
context[TaskHandle]?.stop()
}
override fun resumeWithException(exception: Throwable) {
context[TaskHandle]?.stop()
throw TaskExecutionException(name, exception)
}
})
}
return handle
}
}
}
suspend fun endTick() {
skipTicks(1)
}
suspend fun skipTicks(ticks: Int) {
if (ticks > 0) {
suspendCoroutine<Unit> {
it.context[TaskHandle]!!.untilNextExecution = ticks
currentContinuations += it
}
}
}
private fun matchesHandle(handle: TaskHandle): (Continuation<Unit>) -> Boolean = {
it.context[TaskHandle]?.name == handle.name
}
class TaskHandle internal constructor(val name: String) : AbstractCoroutineContextElement(TaskHandle) {
companion object Key : CoroutineContext.Key<TaskHandle>
var state: State = State.RUNNING
private set
fun pause() {
if (state != State.STOPPED) {
state = State.PAUSED
}
}
fun resume() {
if (state != State.STOPPED) {
state = State.RUNNING
}
}
fun stop() {
state = State.STOPPED
}
internal var untilNextExecution = -1
enum class State { RUNNING, PAUSED, STOPPED }
}
class TaskExecutionException internal constructor(name: String, cause: Throwable) : RuntimeException("Exception in task $name", cause)
sealed class ExecutionConfiguration {
companion object {
fun once(initialDelay: Int = 1): TickCoroutineDispatcher.ExecutionConfiguration {
require(initialDelay >= 0) { "initialDelay must be non-negative, was $initialDelay" }
return TickCoroutineDispatcher.ExecutionConfiguration.Once(initialDelay)
}
fun infinite(initialDelay: Int = 1, pause: Int = 0): TickCoroutineDispatcher.ExecutionConfiguration {
require(initialDelay >= 0) { "initialDelay must be non-negative, was $initialDelay" }
require(pause >= 0) { "pause must be non-negative, was $pause" }
return TickCoroutineDispatcher.ExecutionConfiguration.Infinite(initialDelay, pause)
}
fun repeat(initialDelay: Int = 1, pause: Int = 0, times: Int = 1): TickCoroutineDispatcher.ExecutionConfiguration {
require(initialDelay >= 0) { "initialDelay must be non-negative, was $initialDelay" }
require(pause >= 0) { "pause must be non-negative, was $pause" }
require(times > 0) { "times must be positive, was $times" }
return TickCoroutineDispatcher.ExecutionConfiguration.Repeat(initialDelay, pause, times)
}
}
internal class Once(val initialDelay: Int) : ExecutionConfiguration()
class Infinite(val initialDelay: Int, val pause: Int) : ExecutionConfiguration()
class Repeat(val initialDelay: Int, val pause: Int, val times: Int) : ExecutionConfiguration()
}
} | src/main/kotlin/coffee/cypher/mcextlib/util/coroutines/TickCoroutineDispatcher.kt | 3348817541 |
/*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.text
import com.jtransc.text.Indenter.Companion
import java.util.*
object INDENTS {
private val INDENTS = arrayListOf<String>("")
operator fun get(index: Int): String {
if (index >= INDENTS.size) {
val calculate = INDENTS.size * 10
var indent = INDENTS[INDENTS.size - 1]
while (calculate >= INDENTS.size) {
indent += "\t"
INDENTS.add(indent)
}
}
return if (index <= 0) "" else INDENTS[index]
}
}
class Indenter(private val actions: ArrayList<Action> = arrayListOf<Indenter.Action>()) : ToString {
interface Action {
data class Marker(val data: Any) : Action
data class Line(val str: String) : Action
data class LineDeferred(val callback: () -> Indenter) : Action
object Indent : Action
object Unindent : Action
}
val noIndentEmptyLines = true
companion object {
fun genString(init: Indenter.() -> Unit) = this(init).toString()
val EMPTY = Indenter { }
inline operator fun invoke(init: Indenter.() -> Unit): Indenter {
val indenter = Indenter()
indenter.init()
return indenter
}
@Deprecated("", ReplaceWith("this(str)", "com.jtransc.text.Indenter.Companion"))
fun single(str: String): Indenter = this(str)
operator fun invoke(str: String): Indenter = Indenter(arrayListOf(Action.Line(str)))
fun replaceString(templateString: String, replacements: Map<String, String>): String {
val pattern = Regex("\\$(\\w+)")
return pattern.replace(templateString) { result ->
replacements[result.groupValues[1]] ?: ""
}
}
}
var out: String = ""
fun line(indenter: Indenter) = this.apply { this.actions.addAll(indenter.actions) }
fun line(str: String) = this.apply { this.actions.add(Action.Line(str)) }
fun line(str: String?) {
if (str != null) line(str)
}
fun mark(data: Any) = this.apply { this.actions.add(Action.Marker(data)) }
fun linedeferred(init: Indenter.() -> Unit): Indenter {
this.actions.add(Action.LineDeferred({
val indenter = Indenter()
indenter.init()
indenter
}))
return this
}
fun lines(strs: List<String>): Indenter = this.apply {
for (str in strs) line(str)
}
inline fun line(str: String, callback: () -> Unit): Indenter {
line(if (str.isEmpty()) "{" else "$str {")
indent(callback)
line("}")
return this
}
inline fun line(str: String, after: String = "", after2:String = "", callback: () -> Unit): Indenter {
line(if (str.isEmpty()) "{ $after" else "$str { $after")
indent(callback)
line("}$after2")
return this
}
inline fun indent(callback: () -> Unit): Indenter {
_indent()
try {
callback()
} finally {
_unindent()
}
return this
}
fun _indent() {
actions.add(Action.Indent)
}
fun _unindent() {
actions.add(Action.Unindent)
}
fun toString(markHandler: ((sb: StringBuilder, line: Int, data: Any) -> Unit)?, doIndent: Boolean): String {
val out = StringBuilder()
var line = 0
var indentIndex = 0
fun eval(actions: List<Action>) {
for (action in actions) {
when (action) {
is Action.Line -> {
if (noIndentEmptyLines && action.str.isEmpty()) {
if (doIndent) out.append('\n')
line++
} else {
if (doIndent) out.append(INDENTS[indentIndex]) else out.append(" ")
out.append(action.str)
line += action.str.count { it == '\n' }
if (doIndent) out.append('\n')
line++
}
}
is Action.LineDeferred -> eval(action.callback().actions)
Action.Indent -> indentIndex++
Action.Unindent -> indentIndex--
is Action.Marker -> {
markHandler?.invoke(out, line, action.data)
}
}
}
}
eval(actions)
return out.toString()
}
fun toString(markHandler: ((sb: StringBuilder, line: Int, data: Any) -> Unit)?): String = toString(markHandler = markHandler, doIndent = true)
fun toString(doIndent: Boolean = true): String = toString(markHandler = null, doIndent = doIndent)
override fun toString(): String = toString(null, doIndent = true)
}
| jtransc-utils/src/com/jtransc/text/indent.kt | 353584522 |
/*
* Copyright (C) 2018 CenturyLink, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.mdw.kotlin
import org.jetbrains.kotlin.cli.common.repl.InvokeWrapper
import org.jetbrains.kotlin.cli.common.repl.ReplEvalResult
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import org.jetbrains.kotlin.cli.common.repl.renderReplStackTrace
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.net.URLClassLoader
import javax.script.Bindings
open class ScriptEvaluator(
val baseClasspath: Iterable<File>,
val baseClassloader: ClassLoader? = Thread.currentThread().contextClassLoader,
protected val fallbackScriptArgs: ScriptArgsWithTypes? = null
) {
fun eval(compileResult: ScriptCompileResult.CompiledClasses,
scriptArgs: ScriptArgsWithTypes?,
invokeWrapper: InvokeWrapper?): ReplEvalResult {
val (classLoader, scriptClass) = try {
processClasses(compileResult)
}
catch (e: Exception) {
e.printStackTrace() // TODO
return@eval ReplEvalResult.Error.Runtime(e.message ?: "unknown", e)
}
val currentScriptArgs = scriptArgs ?: fallbackScriptArgs
val useScriptArgs = currentScriptArgs?.scriptArgs
val useScriptArgsTypes = currentScriptArgs?.scriptArgsTypes?.map { it.java }
val constructorParams: Array<Class<*>> = emptyArray<Class<*>>() +
(useScriptArgs?.mapIndexed { i, it -> useScriptArgsTypes?.getOrNull(i) ?: it?.javaClass ?: Any::class.java } ?: emptyList())
val constructorArgs: Array<out Any?> = useScriptArgs.orEmpty()
// TODO: try/catch ?
val scriptInstanceConstructor = scriptClass.getConstructor(*constructorParams)
val scriptInstance =
try {
if (invokeWrapper != null) invokeWrapper.invoke { scriptInstanceConstructor.newInstance(*constructorArgs) }
else scriptInstanceConstructor.newInstance(*constructorArgs)
}
catch (e: InvocationTargetException) {
// ignore everything in the stack trace until this constructor call
return@eval ReplEvalResult.Error.Runtime(renderReplStackTrace(e.cause!!, startFromMethodName = "${scriptClass.name}.<init>"), e.targetException as? Exception)
}
catch (e: Throwable) {
// ignore everything in the stack trace until this constructor call
return@eval ReplEvalResult.Error.Runtime(renderReplStackTrace(e.cause!!, startFromMethodName = "${scriptClass.name}.<init>"), e as? Exception)
}
val resultField = scriptClass.getDeclaredField(SCRIPT_RESULT_FIELD_NAME).apply { isAccessible = true }
val resultValue: Any? = resultField.get(scriptInstance)
if (currentScriptArgs != null) {
val bindings = currentScriptArgs.scriptArgs[0] as Bindings
val vars = currentScriptArgs.scriptArgs[1] as Map<String,Any?>
for ((key, value) in vars) {
bindings[key] = value
}
}
return if (compileResult.hasResult) ReplEvalResult.ValueResult(resultValue, compileResult.type)
else ReplEvalResult.UnitResult()
}
companion object {
private val SCRIPT_RESULT_FIELD_NAME = "\$\$result"
}
private fun processClasses(compileResult: ScriptCompileResult.CompiledClasses
): Pair<ClassLoader, Class<out Any>> {
var mainLineClassName: String? = null
val classLoader = makeScriptClassLoader(baseClassloader, compileResult.classpathAddendum)
fun classNameFromPath(path: String) = JvmClassName.byInternalName(path.removeSuffix(".class"))
fun compiledClassesNames() = compileResult.classes.map { classNameFromPath(it.path).internalName.replace('/', '.') }
val expectedClassName = compileResult.mainClassName
compileResult.classes.filter { it.path.endsWith(".class") }
.forEach {
val className = classNameFromPath(it.path)
if (className.internalName == expectedClassName || className.internalName.endsWith("/$expectedClassName")) {
mainLineClassName = className.internalName.replace('/', '.')
}
classLoader.addClass(className, it.bytes)
}
val scriptClass = try {
classLoader.loadClass(mainLineClassName!!)
}
catch (t: Throwable) {
throw Exception("Error loading class $mainLineClassName: known classes: ${compiledClassesNames()}", t)
}
return Pair(classLoader, scriptClass)
}
fun makeScriptClassLoader(baseClassloader: ClassLoader?, baseClasspath: Iterable<File>) =
ScriptClassLoader(URLClassLoader(baseClasspath.map { it.toURI().toURL() }.toTypedArray(), baseClassloader))
} | mdw-workflow/assets/com/centurylink/mdw/kotlin/ScriptEvaluator.kt | 3074381568 |
package com.quran.data.model
import com.quran.data.model.QuranRef.QuranId
import java.io.Serializable
data class AyahWord(
@JvmField val ayah: SuraAyah,
@JvmField val wordPosition: Int
) : Comparable<AyahWord>, Serializable, QuranId {
override fun compareTo(other: AyahWord): Int {
return when {
this == other -> 0
ayah != other.ayah -> ayah.compareTo(other.ayah)
else -> wordPosition.compareTo(other.wordPosition)
}
}
override fun toString(): String {
return "(${ayah.sura}:${ayah.ayah}:$wordPosition)"
}
}
| common/data/src/main/java/com/quran/data/model/AyahWord.kt | 54163293 |
package ru.timakden.aoc.year2016.day10
import ru.timakden.aoc.util.Constants.Part
import ru.timakden.aoc.util.Constants.Part.PART_ONE
import ru.timakden.aoc.util.Constants.Part.PART_TWO
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solve(input.toMutableList(), listOf(17, 61), PART_ONE)}")
println("Part Two: ${solve(input.toMutableList(), listOf(17, 61), PART_TWO)}")
}
}
fun solve(input: MutableList<String>, valuesToCompare: List<Int>, part: Part): Int {
val bots = mutableMapOf<Int, MutableList<Int>>()
val outputs = mutableMapOf<Int, Int>()
while (input.isNotEmpty()) {
val iterator = input.listIterator()
while (iterator.hasNext()) {
val instruction = iterator.next()
if (instruction.startsWith("value")) {
val botNumber = instruction.substringAfter("bot ").toInt()
val chipValue = instruction.substringAfter("value ").substringBefore(" goes").toInt()
if (bots.contains(botNumber)) {
bots[botNumber]?.add(chipValue)
} else {
bots[botNumber] = mutableListOf(chipValue)
}
iterator.remove()
} else {
val botNumber = instruction.substringAfter("bot ").substringBefore(" gives").toInt()
if (bots.contains(botNumber) && bots[botNumber]?.size == 2) {
val lowTo = instruction.substringAfter("low to ").substringBefore(" and high")
val lowToNumber = lowTo.substringAfter(" ").toInt()
val highTo = instruction.substringAfter("high to ")
val highToNumber = highTo.substringAfter(" ").toInt()
val lowValue = bots[botNumber]?.minOrNull()!!
val highValue = bots[botNumber]?.maxOrNull()!!
if (lowTo.contains("bot")) {
if (bots.contains(lowToNumber)) {
bots[lowToNumber]?.add(lowValue)
} else {
bots[lowToNumber] = mutableListOf(lowValue)
}
} else {
outputs[lowToNumber] = lowValue
}
if (highTo.contains("bot")) {
if (bots.contains(highToNumber)) {
bots[highToNumber]?.add(highValue)
} else {
bots[highToNumber] = mutableListOf(highValue)
}
} else {
outputs[highToNumber] = highValue
}
bots.remove(botNumber)
iterator.remove()
}
}
if (part == PART_ONE) {
for ((key, value) in bots) {
if (value.size == 2 && value.containsAll(valuesToCompare)) {
return key
}
}
}
if (part == PART_TWO && outputs.contains(0) && outputs.contains(1) && outputs.contains(2)) {
return outputs[0]!! * outputs[1]!! * outputs[2]!!
}
}
}
return -1
}
| src/main/kotlin/ru/timakden/aoc/year2016/day10/Puzzle.kt | 257601840 |
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Event(
val title: String,
val beginDateTime: String,
val endDateTime: String
)
fun main() {
val expected = Event(
title = "Team retro",
beginDateTime = "20.08.2020 16:00",
endDateTime = "20.08.2020 17:00",
)
val json = Json.encodeToString(expected)
val actual = Json.decodeFromString(Event.serializer(), json)
println(json)
println(actual)
}
| src/main/kotlin/JsonPlayground.kt | 4080105699 |
/*
* Copyright 2020 Hazuki
*
* 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 jp.hazuki.yuzubrowser.adblock.filter.unified
import java.util.*
object Tag {
fun create(url: String): List<String> {
return url.toLowerCase(Locale.ENGLISH).getTagCandidates().also {
it += ""
}
}
fun createBest(pattern: String): String {
var maxLength = 0
var tag = ""
val candidates = pattern.toLowerCase(Locale.ENGLISH).getTagCandidates()
for (i in 0 until candidates.size) {
val candidate = candidates[i]
if (candidate.length > maxLength) {
maxLength = candidate.length
tag = candidate
}
}
return tag
}
private fun String.getTagCandidates(): MutableList<String> {
var start = 0
val list = mutableListOf<String>()
for (i in 0 until length) {
when (get(i)) {
in 'a'..'z', in '0'..'9', '%' -> continue
else -> {
if (i != start && i - start >= 3) {
val tag = substring(start, i)
if (!isPrevent(tag)) {
list += tag
}
}
start = i + 1
}
}
}
if (length != start && length - start >= 3) {
val tag = substring(start, length)
if (!isPrevent(tag)) {
list += tag
}
}
return list
}
private fun isPrevent(tag: String): Boolean {
return when (tag) {
"http", "https", "html", "jpg", "png" -> true
else -> false
}
}
}
| module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/Tag.kt | 1654185115 |
package com.piticlistudio.playednext.ui
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import com.piticlistudio.playednext.ui.game.search.GameSearchFragment
import com.piticlistudio.playednext.util.ext.setContentFragment
import dagger.android.AndroidInjection
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class FooActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentFragment(android.R.id.content, { GameSearchFragment() })
}
override fun supportFragmentInjector() = fragmentInjector
} | app/src/main/java/com/piticlistudio/playednext/ui/FooActivity.kt | 4070855481 |
package chat.rocket.android.servers.di
import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.servers.presentation.ServersView
import chat.rocket.android.servers.ui.ServersBottomSheetFragment
import dagger.Module
import dagger.Provides
@Module
class ServersBottomSheetFragmentModule {
@Provides
@PerFragment
fun serversView(frag: ServersBottomSheetFragment): ServersView = frag
} | app/src/main/java/chat/rocket/android/servers/di/ServersBottomSheetFragmentModule.kt | 1976052836 |
package com.github.prologdb.parser.parser
private const val FEEDBACK_NOTE = "Please send the stacktrace and steps to reproduce to the author of this library."
open class InternalParserError private constructor(actualMessage: Any) : Exception(actualMessage.toString()) {
// the (Any) constructor serves a purpose:
// Calling InternalParserError() should result in ex.message == FEEDBACK_NOTE
// Calling InternalParserError(someMessage) should result in ex.message == someMessage + " " + FEEDBACK_NOTE
// The any constructor is used so that (String) can be declared separately; otherwise the signatures would be
// equal and the code would not compile.
constructor() : this(FEEDBACK_NOTE as Any)
constructor(message: String) : this(("$message $FEEDBACK_NOTE") as Any)
} | parser/src/main/kotlin/com/github/prologdb/parser/parser/InternalParserError.kt | 1191540788 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.