content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.feed
import com.google.samples.apps.iosched.model.Announcement
import com.google.samples.apps.iosched.shared.data.feed.AnnouncementDataSource
import com.google.samples.apps.iosched.test.data.TestData
object TestAnnouncementDataSource : AnnouncementDataSource {
override fun getAnnouncements(): List<Announcement> = TestData.announcements
}
| shared/src/test/java/com/google/samples/apps/iosched/shared/domain/feed/TestAnnouncementDataSource.kt | 3454905005 |
package com.github.vhromada.catalog.web.connector.entity
/**
* A class represents request for changing song.
*
* @author Vladimir Hromada
*/
data class ChangeSongRequest(
/**
* Name
*/
val name: String,
/**
* Length
*/
val length: Int,
/**
* Note
*/
val note: String?
)
| web/src/main/kotlin/com/github/vhromada/catalog/web/connector/entity/ChangeSongRequest.kt | 2911264078 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.run
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.CompilerModuleExtension
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.KotlinCodeInsightTestCase
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase.addJdk
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.idea.util.projectStructure.sdk
import java.io.File
abstract class AbstractRunConfigurationTest : KotlinCodeInsightTestCase() {
private companion object {
const val DEFAULT_MODULE_NAME = "module"
}
protected sealed class Platform {
abstract fun configure(module: Module)
abstract fun addJdk(testRootDisposable: Disposable)
class Jvm(private val sdk: Sdk = IdeaTestUtil.getMockJdk18()) : Platform() {
override fun configure(module: Module) {
ConfigLibraryUtil.configureSdk(module, sdk)
ConfigLibraryUtil.configureKotlinRuntime(module)
}
override fun addJdk(testRootDisposable: Disposable) {
addJdk(testRootDisposable) { sdk }
}
}
object JavaScript : Platform() {
override fun configure(module: Module) {
ConfigLibraryUtil.configureSdk(module, IdeaTestUtil.getMockJdk18())
ConfigLibraryUtil.configureKotlinStdlibJs(module)
}
override fun addJdk(testRootDisposable: Disposable) {
addJdk(testRootDisposable, IdeaTestUtil::getMockJdk18)
}
}
}
protected var configuredModules: List<ConfiguredModule> = emptyList()
private set
protected val defaultConfiguredModule: ConfiguredModule
get() = getConfiguredModule(DEFAULT_MODULE_NAME)
protected fun getConfiguredModule(name: String): ConfiguredModule {
for (configuredModule in configuredModules) {
val matches =
(configuredModule.module == this.module && name == DEFAULT_MODULE_NAME)
|| configuredModule.module.name == name
if (matches) {
return configuredModule
}
}
error("Configured module with name $name not found")
}
override fun tearDown() {
runAll(
ThrowableRunnable { unconfigureDefaultModule() },
ThrowableRunnable { unconfigureOtherModules() },
ThrowableRunnable { configuredModules = emptyList() },
ThrowableRunnable { super.tearDown() }
)
}
private fun unconfigureOtherModules() {
val moduleManager = ModuleManager.getInstance(project)
val otherConfiguredModules = configuredModules.filter { it.module != this.module }
for (configuredModule in otherConfiguredModules) {
moduleManager.disposeModule(configuredModule.module)
}
}
private fun unconfigureDefaultModule() {
ModuleRootModificationUtil.updateModel(module) { model ->
model.clear()
model.sdk = module.sdk
val compilerModuleExtension = model.getModuleExtension(CompilerModuleExtension::class.java)
compilerModuleExtension.inheritCompilerOutputPath(true)
compilerModuleExtension.setCompilerOutputPath(null as String?)
compilerModuleExtension.setCompilerOutputPathForTests(null as String?)
}
}
protected fun configureProject(platform: Platform = Platform.Jvm(),
testDirectory: String = getTestName(false)) {
runWriteAction {
val projectBaseDir = testDataDirectory.resolve(testDirectory)
val projectDir = PlatformTestUtil.getOrCreateProjectBaseDir(project)
val projectBaseVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectBaseDir)
?: error("Can't find VirtualFile for $projectBaseDir")
projectBaseVirtualFile.refresh(false, true)
VfsUtil.copyDirectory(this, projectBaseVirtualFile, projectDir, null)
platform.addJdk(testRootDisposable)
configuredModules = configureModules(projectDir, projectBaseDir, platform)
}
}
private fun configureModules(projectDir: VirtualFile, projectBaseDir: File, platform: Platform): List<ConfiguredModule> {
val outDir = projectDir.createChildDirectory(this, "out")
val srcOutDir = outDir.createChildDirectory(this, "production")
val testOutDir = outDir.createChildDirectory(this, "test")
val configuredModules = mutableListOf<ConfiguredModule>()
val mainModuleBaseDir = projectBaseDir.resolve("module")
if (mainModuleBaseDir.exists()) {
configuredModules += configureModule(module, platform, mainModuleBaseDir, projectDir, srcOutDir, testOutDir)
}
val otherModuleNames = projectBaseDir.listFiles { f -> f.name != "module" }.orEmpty()
for (moduleBaseDir in otherModuleNames) {
val module = createModule(projectDir, moduleBaseDir.name)
configuredModules += configureModule(module, platform, moduleBaseDir, projectDir, srcOutDir, testOutDir)
}
return configuredModules
}
private fun createModule(projectDir: VirtualFile, name: String): Module {
val moduleDir = projectDir.findFileByRelativePath(name) ?: error("Directory for module $name not found")
val moduleImlPath = moduleDir.toNioPath().resolve("$name.iml")
return ModuleManager.getInstance(project).newModule(moduleImlPath, StdModuleTypes.JAVA.id)
}
private fun configureModule(
module: Module,
platform: Platform,
moduleBaseDir: File,
projectDir: VirtualFile,
srcOutDir: VirtualFile,
testOutDir: VirtualFile
): ConfiguredModule {
val moduleDir = projectDir.findFileByRelativePath(moduleBaseDir.name) ?: error("Directory for module ${module.name} not found")
fun addSourceRoot(name: String, isTestSource: Boolean): VirtualFile? {
val sourceRootDir = moduleDir.findFileByRelativePath(name) ?: return null
PsiTestUtil.addSourceRoot(module, sourceRootDir, isTestSource)
return sourceRootDir
}
val srcDir = addSourceRoot("src", isTestSource = false)
val testDir = addSourceRoot("test", isTestSource = true)
val srcOutputDir = srcOutDir.createChildDirectory(this, moduleBaseDir.name)
val testOutputDir = testOutDir.createChildDirectory(this, moduleBaseDir.name)
PsiTestUtil.setCompilerOutputPath(module, srcOutputDir.url, false)
PsiTestUtil.setCompilerOutputPath(module, testOutputDir.url, true)
platform.configure(module)
return ConfiguredModule(module, srcDir, testDir, srcOutputDir, testOutputDir)
}
protected class ConfiguredModule(
val module: Module,
val srcDir: VirtualFile?,
val testDir: VirtualFile?,
val srcOutputDir: VirtualFile,
val testOutputDir: VirtualFile
)
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/run/AbstractRunConfigurationTest.kt | 759906630 |
package com.nononsenseapps.feeder.ui.compose.feed
import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.paging.compose.LazyPagingItems
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.archmodel.FeedItemStyle
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.model.LocaleOverride
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeletableFeed
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeleteFeedDialog
import com.nononsenseapps.feeder.ui.compose.empty.NothingToRead
import com.nononsenseapps.feeder.ui.compose.feedarticle.FeedScreenViewState
import com.nononsenseapps.feeder.ui.compose.readaloud.HideableTTSPlayer
import com.nononsenseapps.feeder.ui.compose.text.withBidiDeterminedLayoutDirection
import com.nononsenseapps.feeder.ui.compose.theme.LocalDimens
import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder
import com.nononsenseapps.feeder.ui.compose.utils.addMargin
import com.nononsenseapps.feeder.ui.compose.utils.addMarginLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.threeten.bp.Instant
@Composable
fun FeedListContent(
viewState: FeedScreenViewState,
onOpenNavDrawer: () -> Unit,
onAddFeed: () -> Unit,
markAsUnread: (Long, Boolean) -> Unit,
markBeforeAsRead: (Int) -> Unit,
markAfterAsRead: (Int) -> Unit,
onItemClick: (Long) -> Unit,
onSetPinned: (Long, Boolean) -> Unit,
onSetBookmarked: (Long, Boolean) -> Unit,
listState: LazyListState,
pagedFeedItems: LazyPagingItems<FeedListItem>,
modifier: Modifier,
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
Box(modifier = modifier) {
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = !viewState.haveVisibleFeedItems,
) {
// Keeping the Box behind so the scrollability doesn't override clickable
// Separate box because scrollable will ignore max size.
Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
)
NothingToRead(
modifier = modifier,
onOpenOtherFeed = onOpenNavDrawer,
onAddFeed = onAddFeed
)
}
val arrangement = when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> Arrangement.spacedBy(LocalDimens.current.margin)
FeedItemStyle.COMPACT -> Arrangement.spacedBy(0.dp)
FeedItemStyle.SUPER_COMPACT -> Arrangement.spacedBy(0.dp)
}
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = viewState.haveVisibleFeedItems,
) {
LazyColumn(
state = listState,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = arrangement,
contentPadding = if (viewState.isBottomBarVisible) PaddingValues(0.dp) else WindowInsets.navigationBars.only(
WindowInsetsSides.Bottom
).run {
when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> addMargin(horizontal = LocalDimens.current.margin)
FeedItemStyle.COMPACT, FeedItemStyle.SUPER_COMPACT -> addMarginLayout(start = LocalDimens.current.margin)
}
}
.asPaddingValues(),
modifier = Modifier.fillMaxSize()
) {
/*
This is a trick to make the list stay at item 0 when updates come in IF it is
scrolled to the top.
*/
item {
Spacer(modifier = Modifier.fillMaxWidth())
}
items(
pagedFeedItems.itemCount,
key = { itemIndex ->
pagedFeedItems.itemSnapshotList.items[itemIndex].id
}
) { itemIndex ->
val previewItem = pagedFeedItems[itemIndex]
?: return@items
SwipeableFeedItemPreview(
onSwipe = { currentState ->
markAsUnread(
previewItem.id,
!currentState
)
},
swipeAsRead = viewState.swipeAsRead,
onlyUnread = viewState.onlyUnread,
item = previewItem,
showThumbnail = viewState.showThumbnails,
feedItemStyle = viewState.feedItemStyle,
onMarkAboveAsRead = {
if (itemIndex > 0) {
markBeforeAsRead(itemIndex)
if (viewState.onlyUnread) {
coroutineScope.launch {
listState.scrollToItem(0)
}
}
}
},
onMarkBelowAsRead = {
markAfterAsRead(itemIndex)
},
onShareItem = {
val intent = Intent.createChooser(
Intent(Intent.ACTION_SEND).apply {
if (previewItem.link != null) {
putExtra(Intent.EXTRA_TEXT, previewItem.link)
}
putExtra(Intent.EXTRA_TITLE, previewItem.title)
type = "text/plain"
},
null
)
context.startActivity(intent)
},
onItemClick = {
onItemClick(previewItem.id)
},
onTogglePinned = {
onSetPinned(previewItem.id, !previewItem.pinned)
},
onToggleBookmarked = {
onSetBookmarked(previewItem.id, !previewItem.bookmarked)
},
)
if (viewState.feedItemStyle != FeedItemStyle.CARD) {
if (itemIndex < pagedFeedItems.itemCount - 1) {
Divider(
modifier = Modifier
.height(1.dp)
.fillMaxWidth()
)
}
}
}
/*
This item is provide padding for the FAB
*/
if (viewState.showFab && !viewState.isBottomBarVisible) {
item {
Spacer(
modifier = Modifier
.fillMaxWidth()
.height((56 + 16).dp)
)
}
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FeedGridContent(
viewState: FeedScreenViewState,
onOpenNavDrawer: () -> Unit,
onAddFeed: () -> Unit,
markBeforeAsRead: (Int) -> Unit,
markAfterAsRead: (Int) -> Unit,
onItemClick: (Long) -> Unit,
onSetPinned: (Long, Boolean) -> Unit,
onSetBookmarked: (Long, Boolean) -> Unit,
gridState: LazyStaggeredGridState,
pagedFeedItems: LazyPagingItems<FeedListItem>,
modifier: Modifier,
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
Box(modifier = modifier) {
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = !viewState.haveVisibleFeedItems,
) {
// Keeping the Box behind so the scrollability doesn't override clickable
// Separate box because scrollable will ignore max size.
Box(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
)
NothingToRead(
modifier = modifier,
onOpenOtherFeed = onOpenNavDrawer,
onAddFeed = onAddFeed
)
}
val arrangement = when (viewState.feedItemStyle) {
FeedItemStyle.CARD -> Arrangement.spacedBy(LocalDimens.current.gutter)
FeedItemStyle.COMPACT -> Arrangement.spacedBy(LocalDimens.current.gutter)
FeedItemStyle.SUPER_COMPACT -> Arrangement.spacedBy(LocalDimens.current.gutter)
}
val minItemWidth = when (viewState.feedItemStyle) {
// 300 - 16 - 16/2 : so that 600dp screens should get two columns
FeedItemStyle.CARD -> 276.dp
FeedItemStyle.COMPACT -> 400.dp
FeedItemStyle.SUPER_COMPACT -> 276.dp
}
AnimatedVisibility(
enter = fadeIn(),
exit = fadeOut(),
visible = viewState.haveVisibleFeedItems,
) {
LazyVerticalStaggeredGrid(
state = gridState,
columns = StaggeredGridCells.Adaptive(minItemWidth),
contentPadding = if (viewState.isBottomBarVisible) PaddingValues(0.dp) else WindowInsets.navigationBars.only(
WindowInsetsSides.Bottom
).addMargin(LocalDimens.current.margin)
.asPaddingValues(),
verticalArrangement = arrangement,
horizontalArrangement = arrangement,
modifier = Modifier.fillMaxSize(),
) {
items(
pagedFeedItems.itemCount,
key = { itemIndex ->
pagedFeedItems.itemSnapshotList.items[itemIndex].id
}
) { itemIndex ->
val previewItem = pagedFeedItems[itemIndex]
?: return@items
FixedFeedItemPreview(
item = previewItem,
showThumbnail = viewState.showThumbnails,
feedItemStyle = viewState.feedItemStyle,
onMarkAboveAsRead = {
if (itemIndex > 0) {
markBeforeAsRead(itemIndex)
if (viewState.onlyUnread) {
coroutineScope.launch {
gridState.scrollToItem(0)
}
}
}
},
onMarkBelowAsRead = {
markAfterAsRead(itemIndex)
},
onShareItem = {
val intent = Intent.createChooser(
Intent(Intent.ACTION_SEND).apply {
if (previewItem.link != null) {
putExtra(Intent.EXTRA_TEXT, previewItem.link)
}
putExtra(Intent.EXTRA_TITLE, previewItem.title)
type = "text/plain"
},
null
)
context.startActivity(intent)
},
onItemClick = {
onItemClick(previewItem.id)
},
onTogglePinned = {
onSetPinned(previewItem.id, !previewItem.pinned)
},
onToggleBookmarked = {
onSetBookmarked(previewItem.id, !previewItem.bookmarked)
},
)
}
}
}
}
}
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class,
ExperimentalMaterialApi::class
)
@Composable
fun FeedScreen(
viewState: FeedScreenViewState,
onRefreshVisible: () -> Unit,
onOpenNavDrawer: () -> Unit,
onMarkAllAsRead: () -> Unit,
ttsOnPlay: () -> Unit,
ttsOnPause: () -> Unit,
ttsOnStop: () -> Unit,
ttsOnSkipNext: () -> Unit,
ttsOnSelectLanguage: (LocaleOverride) -> Unit,
onDismissDeleteDialog: () -> Unit,
onDismissEditDialog: () -> Unit,
onDelete: (Iterable<Long>) -> Unit,
onEditFeed: (Long) -> Unit,
toolbarActions: @Composable() (RowScope.() -> Unit),
modifier: Modifier = Modifier,
content: @Composable (Modifier) -> Unit,
) {
var lastMaxPoint by remember {
mutableStateOf(Instant.EPOCH)
}
val isRefreshing by remember(viewState.latestSyncTimestamp, lastMaxPoint) {
derivedStateOf {
viewState.latestSyncTimestamp.isAfter(
maxOf(
lastMaxPoint,
Instant.now().minusSeconds(20)
)
)
}
}
val pullRefreshState = rememberPullRefreshState(
refreshing = isRefreshing,
onRefresh = onRefreshVisible,
)
LaunchedEffect(viewState.latestSyncTimestamp) {
// GUI will only display refresh indicator for 10 seconds at most.
// Fixes an issue where sync was triggered but no feed needed syncing, meaning no DB updates
delay(10_000L)
lastMaxPoint = Instant.now()
}
val floatingActionButton: @Composable () -> Unit = {
FloatingActionButton(
onClick = onMarkAllAsRead,
modifier = Modifier.navigationBarsPadding(),
) {
Icon(
Icons.Default.DoneAll,
contentDescription = stringResource(R.string.mark_all_as_read)
)
}
}
val bottomBarVisibleState = remember { MutableTransitionState(viewState.isBottomBarVisible) }
LaunchedEffect(viewState.isBottomBarVisible) {
bottomBarVisibleState.targetState = viewState.isBottomBarVisible
}
Scaffold(
topBar = {
TopAppBar(
title = {
val text = viewState.feedScreenTitle.title
?: stringResource(id = R.string.all_feeds)
withBidiDeterminedLayoutDirection(paragraph = text) {
Text(
text,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
navigationIcon = {
IconButton(
onClick = onOpenNavDrawer
) {
Icon(
Icons.Default.Menu,
contentDescription = stringResource(R.string.navigation_drawer_open)
)
}
},
actions = toolbarActions,
)
},
bottomBar = {
HideableTTSPlayer(
visibleState = bottomBarVisibleState,
currentlyPlaying = viewState.isTTSPlaying,
onPlay = ttsOnPlay,
onPause = ttsOnPause,
onStop = ttsOnStop,
onSkipNext = ttsOnSkipNext,
onSelectLanguage = ttsOnSelectLanguage,
languages = ImmutableHolder(viewState.ttsLanguages),
floatingActionButton = when (viewState.showFab) {
true -> floatingActionButton
false -> null
}
)
},
floatingActionButton = {
if (viewState.showFab) {
AnimatedVisibility(
visible = bottomBarVisibleState.isIdle && !bottomBarVisibleState.targetState,
enter = scaleIn(animationSpec = tween(256)),
exit = scaleOut(animationSpec = tween(256)),
) {
floatingActionButton()
}
}
},
modifier = modifier
.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal)),
contentWindowInsets = WindowInsets.statusBars,
) { padding ->
Box(
modifier = Modifier
.pullRefresh(pullRefreshState)
) {
content(Modifier.padding(padding))
PullRefreshIndicator(
isRefreshing,
pullRefreshState,
Modifier
.padding(padding)
.align(Alignment.TopCenter)
)
}
if (viewState.showDeleteDialog) {
DeleteFeedDialog(
feeds = ImmutableHolder(
viewState.visibleFeeds.map {
DeletableFeed(it.id, it.displayTitle)
}
),
onDismiss = onDismissDeleteDialog,
onDelete = onDelete
)
}
if (viewState.showEditDialog) {
EditFeedDialog(
feeds = ImmutableHolder(
viewState.visibleFeeds.map {
DeletableFeed(
it.id,
it.displayTitle
)
}
),
onDismiss = onDismissEditDialog,
onEdit = onEditFeed
)
}
}
}
@Immutable
data class FeedOrTag(
val id: Long,
val tag: String,
)
val FeedOrTag.isFeed
get() = id > ID_UNSET
| app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/FeedScreen.kt | 2739210652 |
package com.psvoid.quiz
import android.os.Bundle
import android.preference.PreferenceFragment
/**
* A placeholder fragment containing a simple view.
*/
class SettingsActivityFragment : PreferenceFragment() {
/**
* Creates preferences GUI from preferences.xml file in res/xml
*/
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
// load from XML
addPreferencesFromResource(R.xml.preferences)
}
}
| app/src/main/java/com/psvoid/quiz/SettingsActivityFragment.kt | 968987412 |
package org.stepik.android.view.certificate.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.certificate_item.view.*
import org.stepic.droid.R
import org.stepic.droid.model.CertificateListItem
import org.stepik.android.model.Certificate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class CertificatesAdapterDelegate(
private val onItemClick: (String) -> Unit,
private val onShareButtonClick: (CertificateListItem.Data) -> Unit,
private val onChangeNameClick: (CertificateListItem.Data) -> Unit,
private val isCurrentUser: Boolean
) : AdapterDelegate<CertificateListItem, DelegateViewHolder<CertificateListItem>>() {
override fun isForViewType(position: Int, data: CertificateListItem): Boolean =
data is CertificateListItem.Data
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CertificateListItem> =
ViewHolder(createView(parent, R.layout.certificate_item))
private inner class ViewHolder(
root: View
) : DelegateViewHolder<CertificateListItem>(root) {
private val certificateTitleView = root.certificate_title
private val certificateIcon = root.certificate_icon
private val certificateGradeView = root.certificate_grade
private val certificateDescription = root.certificate_description
private val certificateShareButton = root.certificate_share_button
private val certificateNameChangeButton = root.certificate_name_change_button
private val certificatePlaceholder =
ContextCompat.getDrawable(context, R.drawable.general_placeholder)
init {
root.setOnClickListener { (itemData as? CertificateListItem.Data)?.let { onItemClick(it.certificate.url ?: "") } }
certificateShareButton.setOnClickListener { onShareButtonClick(itemData as CertificateListItem.Data) }
certificateNameChangeButton.setOnClickListener { (itemData as? CertificateListItem.Data)?.let(onChangeNameClick) }
}
override fun onBind(data: CertificateListItem) {
data as CertificateListItem.Data
certificateTitleView.text = data.title ?: ""
certificateDescription.text =
when (data.certificate.type) {
Certificate.Type.DISTINCTION ->
context.resources.getString(R.string.certificate_distinction_with_substitution, data.title ?: "")
Certificate.Type.REGULAR ->
context.resources.getString(R.string.certificate_regular_with_substitution, data.title ?: "")
else ->
""
}
certificateGradeView.text =
context.resources.getString(R.string.certificate_result_with_substitution, data.certificate.grade ?: "")
certificateGradeView.isVisible = data.certificate.isWithScore
certificateNameChangeButton.isVisible = data.certificate.editsCount < data.certificate.allowedEditsCount && isCurrentUser
Glide.with(context)
.load(data.coverFullPath ?: "")
.placeholder(certificatePlaceholder)
.into(certificateIcon)
}
}
} | app/src/main/java/org/stepik/android/view/certificate/ui/adapter/delegate/CertificatesAdapterDelegate.kt | 1105197469 |
package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.editor.picker.SearchFilter
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.ui.*
class SearchBar<S : ToolboksScreen<*, *>>(screenWidth: Float, val editor: Editor, val editorStage: EditorStage,
val palette: UIPalette, parent: UIElement<S>, camera: OrthographicCamera)
: Stage<S>(parent, camera) {
enum class Filter(val tag: String) {
GAME_NAME("gameName"),
ENTITY_NAME("entityName"),
FAVOURITES("favourites"),
USE_IN_REMIX("useInRemix"),
CALL_AND_RESPONSE("callAndResponse");
companion object {
val VALUES = values().toList()
}
val localizationKey = "editor.search.filter.$tag"
}
init {
this.location.set(screenWidth = screenWidth)
this.updatePositions()
}
private val searchFilter: SearchFilter get() = editorStage.searchFilter
val textField = object : TextField<S>(palette, this@SearchBar, this@SearchBar) {
init {
this.textWhenEmptyColor = Color.LIGHT_GRAY
}
override fun render(screen: S, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
super.render(screen, batch, shapeRenderer)
this.textWhenEmpty = Localization["picker.search"]
}
override fun onTextChange(oldText: String) {
super.onTextChange(oldText)
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
val hadFocus = hasFocus
super.onLeftClick(xPercent, yPercent)
editor.pickerSelection.filter = searchFilter
editorStage.updateSelected(
if (!hadFocus) EditorStage.DirtyType.SEARCH_DIRTY else EditorStage.DirtyType.DIRTY)
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
hasFocus = true
text = ""
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
editor.pickerSelection.filter = searchFilter
}
}
val clearButton: ClearButton = ClearButton()
val filterButton: FilterButton = FilterButton()
init {
this.updatePositions()
val height = location.realHeight
val width = percentageOfWidth(height)
filterButton.apply {
this.location.set(screenWidth = width)
this.location.set(screenX = 1f - this.location.screenWidth)
this.background = false
this.updateLabel()
}
clearButton.apply {
this.location.set(screenWidth = width)
this.location.set(screenX = filterButton.location.screenX - this.location.screenWidth)
this.background = false
this.addLabel(ImageLabel(palette, this, this.stage).apply {
this.image = TextureRegion(AssetRegistry.get<Texture>("ui_search_clear"))
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
this.tint.a = 0.75f
})
}
textField.apply {
this.location.set(screenWidth = clearButton.location.screenX)
}
elements += textField
elements += clearButton
elements += filterButton
}
inner class FilterButton : Button<S>(palette, this, this) {
var filter: Filter = Filter.GAME_NAME
private set
private val imageLabel = ImageLabel(palette, this, this.stage).apply {
this.tint.a = 0.75f
this.background = false
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
}
private val textures by lazy {
Filter.VALUES.associate { it to TextureRegion(AssetRegistry.get<Texture>("ui_search_filter_${it.tag}")) }
}
init {
addLabel(imageLabel)
updateLabel()
}
override var tooltipText: String?
set(_) {}
get() = Localization[filter.localizationKey]
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
var index = Filter.VALUES.indexOf(filter) + 1
if (index >= Filter.VALUES.size) {
index = 0
}
filter = Filter.VALUES[index]
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
updateLabel()
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
var index = Filter.VALUES.indexOf(filter) - 1
if (index < 0) {
index = Filter.VALUES.size - 1
}
filter = Filter.VALUES[index]
editorStage.updateSelected(EditorStage.DirtyType.SEARCH_DIRTY)
updateLabel()
}
fun updateLabel() {
imageLabel.image = textures[filter]
}
}
inner class ClearButton : Button<S>(palette, this, this) {
override var tooltipText: String?
set(_) {}
get() = Localization["editor.search.clear"]
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
textField.text = ""
textField.touchDown((textField.location.realX + textField.location.realWidth / 2).toInt(),
(textField.location.realY + textField.location.realHeight / 2).toInt(),
0, Input.Buttons.LEFT)
textField.hasFocus = true
}
}
} | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/SearchBar.kt | 3297766423 |
package io.github.chrislo27.rhre3.track.timesignature
import io.github.chrislo27.rhre3.oopsies.ReversibleAction
import io.github.chrislo27.rhre3.track.Remix
class TimeSignatureAction(val remix: Remix, val timeSig: TimeSignature, val remove: Boolean) : ReversibleAction<Remix> {
private val container: TimeSignatures
get() = remix.timeSignatures
private fun add() {
container.add(timeSig)
}
private fun remove() {
container.remove(timeSig)
}
override fun redo(context: Remix) {
if (remove) {
remove()
} else {
add()
}
context.recomputeCachedData()
}
override fun undo(context: Remix) {
if (remove) {
add()
} else {
remove()
}
context.recomputeCachedData()
}
} | core/src/main/kotlin/io/github/chrislo27/rhre3/track/timesignature/TimeSignatureAction.kt | 3833600860 |
package com.glodanif.bluetoothchat.data.service.connection
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.graphics.BitmapFactory
import android.os.Environment
import androidx.core.app.NotificationCompat
import androidx.core.app.Person
import com.glodanif.bluetoothchat.ChatApplication
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.data.entity.ChatMessage
import com.glodanif.bluetoothchat.data.entity.Conversation
import com.glodanif.bluetoothchat.data.model.ConversationsStorage
import com.glodanif.bluetoothchat.data.model.MessagesStorage
import com.glodanif.bluetoothchat.data.model.ProfileManager
import com.glodanif.bluetoothchat.data.model.UserPreferences
import com.glodanif.bluetoothchat.data.service.message.Contract
import com.glodanif.bluetoothchat.data.service.message.Message
import com.glodanif.bluetoothchat.data.service.message.PayloadType
import com.glodanif.bluetoothchat.data.service.message.TransferringFile
import com.glodanif.bluetoothchat.ui.view.NotificationView
import com.glodanif.bluetoothchat.ui.widget.ShortcutManager
import com.glodanif.bluetoothchat.utils.LimitedQueue
import com.glodanif.bluetoothchat.utils.Size
import kotlinx.coroutines.*
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.coroutines.CoroutineContext
class ConnectionController(private val application: ChatApplication,
private val subject: ConnectionSubject,
private val view: NotificationView,
private val conversationStorage: ConversationsStorage,
private val messagesStorage: MessagesStorage,
private val preferences: UserPreferences,
private val profileManager: ProfileManager,
private val shortcutManager: ShortcutManager,
private val uiContext: CoroutineDispatcher = Dispatchers.Main,
private val bgContext: CoroutineDispatcher = Dispatchers.IO) : CoroutineScope {
private val blAppName = application.getString(R.string.bl_app_name)
private val blAppUUID = UUID.fromString(application.getString(R.string.bl_app_uuid))
private var acceptThread: AcceptJob? = null
private var connectThread: ConnectJob? = null
private var dataTransferThread: DataTransferThread? = null
@Volatile
private var connectionState: ConnectionState = ConnectionState.NOT_CONNECTED
@Volatile
private var connectionType: ConnectionType? = null
private var currentSocket: BluetoothSocket? = null
private var currentConversation: Conversation? = null
private var contract = Contract()
private var justRepliedFromNotification = false
private val imageText: String by lazy {
application.getString(R.string.chat__image_message, "\uD83D\uDCCE")
}
private val me: Person by lazy {
Person.Builder().setName(application.getString(R.string.notification__me)).build()
}
private val shallowHistory = LimitedQueue<NotificationCompat.MessagingStyle.Message>(4)
var onNewForegroundMessage: ((String) -> Unit)? = null
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + uiContext
fun createForegroundNotification(message: String) = view.getForegroundNotification(message)
@Synchronized
fun prepareForAccept() {
cancelConnections()
if (subject.isRunning()) {
acceptThread = AcceptJob()
acceptThread?.start()
onNewForegroundMessage?.invoke(application.getString(R.string.notification__ready_to_connect))
}
}
@Synchronized
fun disconnect() {
dataTransferThread?.cancel(true)
dataTransferThread = null
prepareForAccept()
}
@Synchronized
fun connect(device: BluetoothDevice) {
if (connectionState == ConnectionState.CONNECTING) {
connectThread?.cancel()
connectThread = null
}
dataTransferThread?.cancel(true)
acceptThread?.cancel()
dataTransferThread = null
acceptThread = null
currentSocket = null
currentConversation = null
contract.reset()
connectionType = null
connectThread = ConnectJob(device)
connectThread?.start()
launch { subject.handleConnectingInProgress() }
}
private fun cancelConnections() {
connectThread?.cancel()
connectThread = null
dataTransferThread?.cancel()
dataTransferThread = null
currentSocket = null
currentConversation = null
contract.reset()
connectionType = null
justRepliedFromNotification = false
}
private fun cancelAccept() {
acceptThread?.cancel()
acceptThread = null
}
private fun connectionFailed() {
currentSocket = null
currentConversation = null
contract.reset()
launch { subject.handleConnectionFailed() }
connectionState = ConnectionState.NOT_CONNECTED
prepareForAccept()
}
@Synchronized
fun stop() {
cancelConnections()
cancelAccept()
connectionState = ConnectionState.NOT_CONNECTED
job.cancel()
}
@Synchronized
fun connected(socket: BluetoothSocket, type: ConnectionType) {
cancelConnections()
connectionType = type
currentSocket = socket
cancelAccept()
val transferEventsListener = object : DataTransferThread.TransferEventsListener {
override fun onMessageReceived(message: String) {
launch {
[email protected](message)
}
}
override fun onMessageSent(message: String) {
launch {
[email protected](message)
}
}
override fun onMessageSendingFailed() {
launch {
[email protected]()
}
}
override fun onConnectionPrepared(type: ConnectionType) {
onNewForegroundMessage?.invoke(application.getString(R.string.notification__connected_to, socket.remoteDevice.name
?: "?"))
connectionState = ConnectionState.PENDING
if (type == ConnectionType.OUTCOMING) {
contract.createConnectMessage(profileManager.getUserName(), profileManager.getUserColor()).let { message ->
dataTransferThread?.write(message.getDecodedMessage())
}
}
}
override fun onConnectionCanceled() {
currentSocket = null
currentConversation = null
contract.reset()
}
override fun onConnectionLost() {
connectionLost()
}
}
val fileEventsListener = object : DataTransferThread.OnFileListener {
override fun onFileSendingStarted(file: TransferringFile) {
subject.handleFileSendingStarted(file.name, file.size)
currentConversation?.let {
val silently = application.currentChat != null && currentSocket != null &&
application.currentChat.equals(currentSocket?.remoteDevice?.address)
view.showFileTransferNotification(it.displayName, it.deviceName,
it.deviceAddress, file, 0, silently)
}
}
override fun onFileSendingProgress(file: TransferringFile, sentBytes: Long) {
launch {
subject.handleFileSendingProgress(sentBytes, file.size)
if (currentConversation != null) {
view.updateFileTransferNotification(sentBytes, file.size)
}
}
}
override fun onFileSendingFinished(uid: Long, path: String) {
contract.createFileEndMessage().let { message ->
dataTransferThread?.write(message.getDecodedMessage())
}
currentSocket?.let { socket ->
val message = ChatMessage(uid, socket.remoteDevice.address, Date(), true, "").apply {
seenHere = true
messageType = PayloadType.IMAGE
filePath = path
}
launch(bgContext) {
val size = getImageSize(path)
message.fileInfo = "${size.width}x${size.height}"
message.fileExists = true
messagesStorage.insertMessage(message)
shallowHistory.add(NotificationCompat.MessagingStyle.Message(imageText, message.date.time, me))
launch(uiContext) {
subject.handleFileSendingFinished()
subject.handleMessageSent(message)
view.dismissFileTransferNotification()
currentConversation?.let {
shortcutManager.addConversationShortcut(message.deviceAddress, it.displayName, it.color)
}
}
}
}
}
override fun onFileSendingFailed() {
launch {
subject.handleFileSendingFailed()
view.dismissFileTransferNotification()
}
}
override fun onFileReceivingStarted(file: TransferringFile) {
launch {
subject.handleFileReceivingStarted(file.size)
currentConversation?.let {
val silently = application.currentChat != null && currentSocket != null &&
application.currentChat.equals(currentSocket?.remoteDevice?.address)
view.showFileTransferNotification(it.displayName, it.deviceName,
it.deviceAddress, file, 0, silently)
}
}
}
override fun onFileReceivingProgress(file: TransferringFile, receivedBytes: Long) {
launch {
subject.handleFileReceivingProgress(receivedBytes, file.size)
if (currentConversation != null) {
view.updateFileTransferNotification(receivedBytes, file.size)
}
}
}
override fun onFileReceivingFinished(uid: Long, path: String) {
currentSocket?.remoteDevice?.let { device ->
val address = device.address
val message = ChatMessage(uid, address, Date(), false, "").apply {
messageType = PayloadType.IMAGE
filePath = path
}
val partner = Person.Builder().setName(currentConversation?.displayName
?: "?").build()
shallowHistory.add(NotificationCompat.MessagingStyle.Message(imageText, message.date.time, partner))
if (!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(address)) {
//FIXME: Fixes not appearing notification
view.dismissMessageNotification()
view.showNewMessageNotification(imageText, currentConversation?.displayName,
device.name, address, shallowHistory, preferences.isSoundEnabled())
} else {
message.seenHere = true
}
launch(bgContext) {
val size = getImageSize(path)
message.fileInfo = "${size.width}x${size.height}"
message.fileExists = true
messagesStorage.insertMessage(message)
launch(uiContext) {
subject.handleFileReceivingFinished()
subject.handleMessageReceived(message)
view.dismissFileTransferNotification()
currentConversation?.let {
shortcutManager.addConversationShortcut(address, it.displayName, it.color)
}
}
}
}
}
override fun onFileReceivingFailed() {
launch {
subject.handleFileReceivingFailed()
view.dismissFileTransferNotification()
}
}
override fun onFileTransferCanceled(byPartner: Boolean) {
launch {
subject.handleFileTransferCanceled(byPartner)
view.dismissFileTransferNotification()
}
}
}
val eventsStrategy = TransferEventStrategy()
val filesDirectory = File(Environment.getExternalStorageDirectory(), application.getString(R.string.app_name))
dataTransferThread =
object : DataTransferThread(socket, type, transferEventsListener, filesDirectory, fileEventsListener, eventsStrategy) {
override fun shouldRun(): Boolean {
return isConnectedOrPending()
}
}
dataTransferThread?.prepare()
dataTransferThread?.start()
launch { subject.handleConnected(socket.remoteDevice) }
}
fun getCurrentConversation() = currentConversation
fun getCurrentContract() = contract
fun isConnected() = connectionState == ConnectionState.CONNECTED
fun isPending() = connectionState == ConnectionState.PENDING
fun isConnectedOrPending() = isConnected() || isPending()
fun replyFromNotification(text: String) {
contract.createChatMessage(text).let { message ->
justRepliedFromNotification = true
sendMessage(message)
}
}
fun sendMessage(message: Message) {
if (isConnectedOrPending()) {
val disconnect = message.type == Contract.MessageType.CONNECTION_REQUEST && !message.flag
dataTransferThread?.write(message.getDecodedMessage(), disconnect)
if (disconnect) {
dataTransferThread?.cancel(disconnect)
dataTransferThread = null
prepareForAccept()
}
}
if (message.type == Contract.MessageType.CONNECTION_RESPONSE) {
if (message.flag) {
connectionState = ConnectionState.CONNECTED
} else {
disconnect()
}
view.dismissConnectionNotification()
}
}
fun sendFile(file: File, type: PayloadType) {
if (isConnected()) {
contract.createFileStartMessage(file, type).let { message ->
dataTransferThread?.write(message.getDecodedMessage())
dataTransferThread?.writeFile(message.uid, file)
}
}
}
fun approveConnection() {
sendMessage(contract.createAcceptConnectionMessage(
profileManager.getUserName(), profileManager.getUserColor()))
}
fun rejectConnection() {
sendMessage(contract.createRejectConnectionMessage(
profileManager.getUserName(), profileManager.getUserColor()))
}
fun getTransferringFile(): TransferringFile? {
return dataTransferThread?.getTransferringFile()
}
fun cancelFileTransfer() {
dataTransferThread?.cancelFileTransfer()
view.dismissFileTransferNotification()
}
private fun onMessageSent(messageBody: String) = currentSocket?.let { socket ->
val device = socket.remoteDevice
val message = Message(messageBody)
val sentMessage = ChatMessage(message.uid, socket.remoteDevice.address, Date(), true, message.body)
if (message.type == Contract.MessageType.MESSAGE) {
sentMessage.seenHere = true
launch(bgContext) {
messagesStorage.insertMessage(sentMessage)
shallowHistory.add(NotificationCompat.MessagingStyle.Message(sentMessage.text, sentMessage.date.time, me))
if ((!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(device.address)) && justRepliedFromNotification) {
view.showNewMessageNotification(message.body, currentConversation?.displayName,
device.name, device.address, shallowHistory, preferences.isSoundEnabled())
justRepliedFromNotification = false
}
launch(uiContext) { subject.handleMessageSent(sentMessage) }
currentConversation?.let {
shortcutManager.addConversationShortcut(sentMessage.deviceAddress, it.displayName, it.color)
}
}
}
}
private fun onMessageReceived(messageBody: String) {
val message = Message(messageBody)
if (message.type == Contract.MessageType.MESSAGE && currentSocket != null) {
handleReceivedMessage(message.uid, message.body)
} else if (message.type == Contract.MessageType.DELIVERY) {
if (message.flag) {
subject.handleMessageDelivered(message.uid)
} else {
subject.handleMessageNotDelivered(message.uid)
}
} else if (message.type == Contract.MessageType.SEEING) {
if (message.flag) {
subject.handleMessageSeen(message.uid)
}
} else if (message.type == Contract.MessageType.CONNECTION_RESPONSE) {
if (message.flag) {
handleConnectionApproval(message)
} else {
connectionState = ConnectionState.REJECTED
prepareForAccept()
subject.handleConnectionRejected()
}
} else if (message.type == Contract.MessageType.CONNECTION_REQUEST && currentSocket != null) {
if (message.flag) {
handleConnectionRequest(message)
} else {
disconnect()
subject.handleDisconnected()
}
} else if (message.type == Contract.MessageType.FILE_CANCELED) {
dataTransferThread?.cancelFileTransfer()
}
}
private fun onMessageSendingFailed() {
subject.handleMessageSendingFailed()
}
private fun handleReceivedMessage(uid: Long, text: String) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val receivedMessage = ChatMessage(uid, device.address, Date(), false, text)
val partner = Person.Builder().setName(currentConversation?.displayName ?: "?").build()
shallowHistory.add(NotificationCompat.MessagingStyle.Message(
receivedMessage.text, receivedMessage.date.time, partner))
if (!subject.isAnybodyListeningForMessages() || application.currentChat == null || !application.currentChat.equals(device.address)) {
view.showNewMessageNotification(text, currentConversation?.displayName,
device.name, device.address, shallowHistory, preferences.isSoundEnabled())
} else {
receivedMessage.seenHere = true
}
launch(bgContext) {
messagesStorage.insertMessage(receivedMessage)
launch(uiContext) { subject.handleMessageReceived(receivedMessage) }
currentConversation?.let {
shortcutManager.addConversationShortcut(device.address, it.displayName, it.color)
}
}
}
private fun handleConnectionRequest(message: Message) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val parts = message.body.split(Contract.DIVIDER)
val conversation = Conversation(device.address, device.name
?: "?", parts[0], parts[1].toInt())
launch(bgContext) { conversationStorage.insertConversation(conversation) }
currentConversation = conversation
contract setupWith if (parts.size >= 3) parts[2].trim().toInt() else 0
subject.handleConnectedIn(conversation)
if (!application.isConversationsOpened && !(application.currentChat != null && application.currentChat.equals(device.address))) {
view.showConnectionRequestNotification(
"${conversation.displayName} (${conversation.deviceName})", conversation.deviceAddress, preferences.isSoundEnabled())
}
}
private fun handleConnectionApproval(message: Message) = currentSocket?.let { socket ->
val device: BluetoothDevice = socket.remoteDevice
val parts = message.body.split(Contract.DIVIDER)
val conversation = Conversation(device.address, device.name
?: "?", parts[0], parts[1].toInt())
launch(bgContext) { conversationStorage.insertConversation(conversation) }
currentConversation = conversation
contract setupWith if (parts.size >= 3) parts[2].trim().toInt() else 0
connectionState = ConnectionState.CONNECTED
subject.handleConnectionAccepted()
subject.handleConnectedOut(conversation)
}
private fun connectionLost() {
currentSocket = null
currentConversation = null
contract.reset()
if (isConnectedOrPending()) {
launch {
if (isPending() && connectionType == ConnectionType.INCOMING) {
connectionState = ConnectionState.NOT_CONNECTED
subject.handleConnectionWithdrawn()
} else {
connectionState = ConnectionState.NOT_CONNECTED
subject.handleConnectionLost()
}
prepareForAccept()
}
} else {
prepareForAccept()
}
}
private fun getImageSize(path: String): Size {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(path, options)
return Size(options.outWidth, options.outHeight)
}
private inner class AcceptJob : Thread() {
private var serverSocket: BluetoothServerSocket? = null
init {
try {
serverSocket = BluetoothAdapter.getDefaultAdapter()
?.listenUsingRfcommWithServiceRecord(blAppName, blAppUUID)
} catch (e: IOException) {
e.printStackTrace()
}
connectionState = ConnectionState.LISTENING
}
override fun run() {
while (!isConnectedOrPending()) {
try {
serverSocket?.accept()?.let { socket ->
when (connectionState) {
ConnectionState.LISTENING, ConnectionState.CONNECTING -> {
connected(socket, ConnectionType.INCOMING)
}
ConnectionState.NOT_CONNECTED, ConnectionState.CONNECTED, ConnectionState.PENDING, ConnectionState.REJECTED -> try {
socket.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
} catch (e: IOException) {
e.printStackTrace()
break
}
}
}
fun cancel() {
try {
serverSocket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private inner class ConnectJob(private val bluetoothDevice: BluetoothDevice) : Thread() {
private var socket: BluetoothSocket? = null
override fun run() {
try {
socket = bluetoothDevice.createRfcommSocketToServiceRecord(blAppUUID)
} catch (e: IOException) {
e.printStackTrace()
}
connectionState = ConnectionState.CONNECTING
try {
socket?.connect()
} catch (connectException: IOException) {
connectException.printStackTrace()
try {
socket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
connectionFailed()
return
}
synchronized(this@ConnectionController) {
connectThread = null
}
socket?.let {
connected(it, ConnectionType.OUTCOMING)
}
}
fun cancel() {
try {
socket?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
| app/src/main/kotlin/com/glodanif/bluetoothchat/data/service/connection/ConnectionController.kt | 4145080607 |
// 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.
@file:JvmName("GrModifierListUtil")
package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.util.parentOfType
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.GrModifierConstant
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrModifierListImpl.NAME_TO_MODIFIER_FLAG_MAP
import org.jetbrains.plugins.groovy.lang.psi.impl.findDeclaredDetachedValue
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.GrTypeDefinitionImpl
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isInterface
import org.jetbrains.plugins.groovy.transformations.immutable.hasImmutableAnnotation
private val visibilityModifiers = setOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL, PsiModifier.PRIVATE)
private const val explicitVisibilityModifiersMask = GrModifierFlags.PUBLIC_MASK or GrModifierFlags.PRIVATE_MASK or GrModifierFlags.PROTECTED_MASK
private const val packageScopeAnno = "groovy.transform.PackageScope"
private const val packageScopeTarget = "groovy.transform.PackageScopeTarget"
fun Int.hasMaskModifier(@GrModifierConstant @NonNls name: String): Boolean {
return and(NAME_TO_MODIFIER_FLAG_MAP.getInt(name)) != 0
}
internal fun hasExplicitVisibilityModifiers(modifierList: GrModifierList): Boolean {
return explicitVisibilityModifiersMask and modifierList.modifierFlags != 0
}
internal fun hasExplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return modifierList.modifierFlags.hasMaskModifier(name)
}
@JvmOverloads
internal fun hasModifierProperty(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String, includeSynthetic: Boolean = true): Boolean {
return hasExplicitModifier(modifierList, name) ||
hasImplicitModifier(modifierList, name) ||
(includeSynthetic && hasSyntheticModifier(modifierList, name))
}
private fun hasImplicitModifier(modifierList: GrModifierList, @GrModifierConstant @NonNls name: String): Boolean {
return when (name) {
PsiModifier.ABSTRACT -> modifierList.isAbstract()
PsiModifier.FINAL -> modifierList.isFinal()
PsiModifier.STATIC -> modifierList.isStatic()
else -> name in visibilityModifiers && name == getImplicitVisibility(modifierList)
}
}
internal fun hasCodeModifierProperty(owner : PsiModifierListOwner, @GrModifierConstant @NonNls modifierName : String) : Boolean {
return (owner.modifierList as? GrModifierList)?.let { hasModifierProperty(it, modifierName, false) } ?: false
}
private fun hasSyntheticModifier(modifierList: GrModifierList, name: String) : Boolean {
val containingTypeDefinition = modifierList.parentOfType<GrTypeDefinition>() as? GrTypeDefinitionImpl ?: return false
return containingTypeDefinition.getSyntheticModifiers(modifierList).contains(name)
}
private fun GrModifierList.isAbstract(): Boolean {
return when (val owner = parent) {
is GrMethod -> owner.isAbstractMethod()
is GrTypeDefinition -> owner.isAbstractClass()
else -> false
}
}
private fun GrMethod.isAbstractMethod(): Boolean =
containingClass?.let { it.isInterface && !GrTraitUtil.isTrait(it) } ?: false
private fun GrTypeDefinition.isAbstractClass(): Boolean {
if (isEnum) {
if (GroovyConfigUtils.getInstance().isVersionAtLeast(this, GroovyConfigUtils.GROOVY2_0)) {
return codeMethods.any { it.modifierList.hasExplicitModifier(PsiModifier.ABSTRACT) }
}
}
return isInterface
}
private fun GrModifierList.isFinal(): Boolean {
return when (val owner = parent) {
is GrTypeDefinition -> owner.isFinalClass()
is GrVariableDeclaration -> owner.isFinalField(this)
is GrEnumConstant -> true
else -> false
}
}
private fun GrTypeDefinition.isFinalClass(): Boolean {
return isEnum && codeFields.none { it is GrEnumConstant && it.initializingClass != null }
}
private fun GrVariableDeclaration.isFinalField(modifierList: GrModifierList): Boolean {
val containingClass = containingClass
return isInterface(containingClass)
|| !modifierList.hasExplicitVisibilityModifiers()
&& (containingClass?.let(::hasImmutableAnnotation) ?: false)
}
private fun GrModifierList.isStatic(): Boolean {
val owner = parent
val containingClass = when (owner) {
is GrTypeDefinition -> owner.containingClass
is GrVariableDeclaration -> owner.containingClass
is GrEnumConstant -> return true
else -> null
}
return containingClass != null && (owner is GrEnumTypeDefinition || isInterface(containingClass))
}
private fun getImplicitVisibility(grModifierList: GrModifierList): String? {
if (hasExplicitVisibilityModifiers(grModifierList)) return null
when (val owner = grModifierList.parent) {
is GrTypeDefinition -> return if (grModifierList.hasPackageScope(owner, "CLASS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
is GrMethod -> {
val containingClass = owner.containingClass as? GrTypeDefinition ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
val targetName = if (owner.isConstructor) "CONSTRUCTORS" else "METHODS"
return if (grModifierList.hasPackageScope(containingClass, targetName)) PsiModifier.PACKAGE_LOCAL else PsiModifier.PUBLIC
}
is GrVariableDeclaration -> {
val containingClass = owner.containingClass ?: return null
if (isInterface(containingClass)) return PsiModifier.PUBLIC
return if (grModifierList.hasPackageScope(containingClass, "FIELDS")) PsiModifier.PACKAGE_LOCAL else PsiModifier.PRIVATE
}
is GrEnumConstant -> return PsiModifier.PUBLIC
else -> return null
}
}
private fun GrModifierList.hasPackageScope(clazz: GrTypeDefinition?, targetName: String): Boolean {
if (hasOwnEmptyPackageScopeAnnotation()) return true
val annotation = clazz?.modifierList?.findAnnotation(packageScopeAnno) as? GrAnnotation ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return false // annotation without value
val scopeTargetEnum = JavaPsiFacade.getInstance(project).findClass(packageScopeTarget, resolveScope) ?: return false
val scopeTarget = scopeTargetEnum.findFieldByName(targetName, false) ?: return false
val resolved = when (value) {
is GrReferenceExpression -> value.resolve()?.let { listOf(it) } ?: emptyList()
is GrAnnotationArrayInitializer -> value.initializers.mapNotNull {
(it as? GrReferenceExpression)?.resolve()
}
else -> emptyList()
}
return scopeTarget in resolved
}
private fun GrModifierList.hasOwnEmptyPackageScopeAnnotation(): Boolean {
val annotation = findAnnotation(packageScopeAnno) ?: return false
val value = annotation.findDeclaredDetachedValue(null) ?: return true
return value is GrAnnotationArrayInitializer && value.initializers.isEmpty()
}
private val GrVariableDeclaration.containingClass get() = (parent as? GrTypeDefinitionBody)?.parent as? GrTypeDefinition
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/modifiers.kt | 1307797766 |
package com.munzenberger.feed.source
import com.munzenberger.feed.Feed
import javax.xml.stream.XMLEventReader
interface XMLFeedParser {
fun parse(eventReader: XMLEventReader): Feed
fun parseCharacterData(eventReader: XMLEventReader): String {
var value = ""
val event = eventReader.nextEvent()
if (event.isCharacters) {
value = event.asCharacters().data
}
return value
}
}
| src/main/kotlin/com/munzenberger/feed/source/XMLFeedParser.kt | 1896320564 |
package com.aemtools.reference.htl.reference
import com.aemtools.lang.htl.psi.HtlVariableName
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceBase
/**
* Reference to template argument.
*
* @author Dmytro Troynikov
*/
class HtlTemplateArgumentReference(
val variable: HtlVariableName,
holder: PsiElement,
range: TextRange
) : PsiReferenceBase<PsiElement>(holder, range, true) {
override fun resolve(): PsiElement? = variable
override fun getVariants(): Array<Any> = emptyArray()
}
| aem-intellij-core/src/main/kotlin/com/aemtools/reference/htl/reference/HtlTemplateArgumentReference.kt | 3136408663 |
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.coroutines.*
import java.util.concurrent.*
import java.util.concurrent.CancellationException
import kotlin.test.*
class ThreadSafeHeapStressTest : TestBase() {
private class DisposableNode : EventLoopImplBase.DelayedTask(1L) {
override fun run() {
}
}
@Test
fun testConcurrentRemoveDispose() = runTest {
val heap = EventLoopImplBase.DelayedTaskQueue(1)
repeat(10_000 * stressTestMultiplierSqrt) {
withContext(Dispatchers.Default) {
val node = DisposableNode()
val barrier = CyclicBarrier(2)
launch {
heap.addLast(node)
barrier.await()
heap.remove(node)
}
launch {
barrier.await()
Thread.yield()
node.dispose()
}
}
}
}
@Test()
fun testConcurrentAddDispose() = runTest {
repeat(10_000 * stressTestMultiplierSqrt) {
val jobToCancel = Job()
val barrier = CyclicBarrier(2)
val jobToJoin = launch(Dispatchers.Default) {
barrier.await()
jobToCancel.cancelAndJoin()
}
try {
runBlocking { // Use event loop impl
withContext(jobToCancel) {
// This one is to work around heap allocation optimization
launch(start = CoroutineStart.UNDISPATCHED) {
delay(100_000)
}
barrier.await()
delay(100_000)
}
}
} catch (e: CancellationException) {
// Expected exception
}
jobToJoin.join()
}
}
}
| kotlinx-coroutines-core/jvm/test/internal/ThreadSafeHeapStressTest.kt | 177263167 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project.impl
import com.intellij.ide.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.PathUtil
import com.intellij.util.containers.ContainerUtil
import org.jdom.JDOMException
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import java.io.IOException
@RunsInEdt
class RecentProjectsTest {
companion object {
@ClassRule
@JvmField
val appRule = ApplicationRule()
@ClassRule
@JvmField
val edtRule = EdtRule()
}
@Rule
@JvmField
val busConnection = RecentProjectManagerListenerRule()
@Rule
@JvmField
val tempDir = TemporaryDirectory()
@Test
fun testMostRecentOnTop() {
val p1 = createAndOpenProject("p1")
val p2 = createAndOpenProject("p2")
val p3 = createAndOpenProject("p3")
checkRecents("p3", "p2", "p1")
doReopenCloseAndCheck(p2, "p2", "p3", "p1")
doReopenCloseAndCheck(p1, "p1", "p2", "p3")
doReopenCloseAndCheck(p3, "p3", "p1", "p2")
}
@Test
fun testGroupsOrder() {
val p1 = createAndOpenProject("p1")
val p2 = createAndOpenProject("p2")
val p3 = createAndOpenProject("p3")
val p4 = createAndOpenProject("p4")
val manager = RecentProjectsManager.getInstance()
val g1 = ProjectGroup("g1")
val g2 = ProjectGroup("g2")
manager.addGroup(g1)
manager.addGroup(g2)
g1.addProject(p1)
g1.addProject(p2)
g2.addProject(p3)
checkGroups(listOf("g2", "g1"))
doReopenCloseAndCheckGroups(p4, listOf("g2", "g1"))
doReopenCloseAndCheckGroups(p1, listOf("g1", "g2"))
doReopenCloseAndCheckGroups(p3, listOf("g2", "g1"))
}
@Test
fun testTimestampForOpenProjectUpdatesWhenGetStateCalled() {
var project: Project? = null
try {
val path = tempDir.newPath("z1")
project = HeavyPlatformTestCase.createProject(path)
ProjectOpeningTest.closeProject(project)
project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(path)
val timestamp = getProjectOpenTimestamp("z1")
RecentProjectsManagerBase.instanceEx.updateLastProjectPath()
// "Timestamp for opened project has not been updated"
assertThat(getProjectOpenTimestamp("z1")).isGreaterThan(timestamp)
}
finally {
ProjectOpeningTest.closeProject(project)
}
}
private fun getProjectOpenTimestamp(projectName: String): Long {
val additionalInfo = RecentProjectsManagerBase.instanceEx.state!!.additionalInfo
for (s in additionalInfo.keys) {
if (s.endsWith(projectName)) {
return additionalInfo.get(s)!!.projectOpenTimestamp
}
}
return -1
}
@Throws(IOException::class, JDOMException::class)
private fun doReopenCloseAndCheck(projectPath: String, vararg results: String) {
val project = ProjectManager.getInstance().loadAndOpenProject(projectPath)
ProjectOpeningTest.closeProject(project)
checkRecents(*results)
}
@Throws(IOException::class, JDOMException::class)
private fun doReopenCloseAndCheckGroups(projectPath: String, results: List<String>) {
val project = ProjectManager.getInstance().loadAndOpenProject(projectPath)
ProjectOpeningTest.closeProject(project)
checkGroups(results)
}
private fun checkRecents(vararg recents: String) {
val recentProjects = listOf(*recents)
val state = (RecentProjectsManager.getInstance() as RecentProjectsManagerBase).state
val projects = state!!.additionalInfo.keys.asSequence()
.map { s -> PathUtil.getFileName(s).substringAfterLast("_") }
.filter { recentProjects.contains(it) }
.toList()
assertThat(ContainerUtil.reverse(projects)).isEqualTo(recentProjects)
}
private fun checkGroups(groups: List<String>) {
val recentGroups = RecentProjectListActionProvider.getInstance().getActions(false, true).asSequence()
.filter { a -> a is ProjectGroupActionGroup }
.map { a -> (a as ProjectGroupActionGroup).group.name }
.toList()
assertThat(recentGroups).isEqualTo(groups)
}
private fun createAndOpenProject(name: String): String {
var project: Project? = null
try {
val path = tempDir.newPath(name)
project = HeavyPlatformTestCase.createProject(path)
PlatformTestUtil.saveProject(project)
ProjectOpeningTest.closeProject(project)
project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(path)
return project!!.basePath!!
}
finally {
ProjectOpeningTest.closeProject(project)
}
}
}
class RecentProjectManagerListenerRule : ExternalResource() {
private val disposable = Disposer.newDisposable()
override fun before() {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, RecentProjectsManagerBase.MyProjectListener())
connection.subscribe(AppLifecycleListener.TOPIC, RecentProjectsManagerBase.MyAppLifecycleListener())
}
override fun after() {
Disposer.dispose(disposable)
}
} | platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.kt | 2794015264 |
/*
* 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.weather
import android.support.annotation.RestrictTo
/**
* Created by darel on 16.09.17.
*
* Local Daily Weather
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
data class LocalDaily(val summary: String, val icon: String, val data: List<LocalDailyData>) | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/weather/LocalDaily.kt | 3773068808 |
// WITH_RUNTIME
// IGNORE_BACKEND: JS, NATIVE
package test
import test.Derived.p
open class Base(val b: Boolean)
object Derived : Base(::p.isInitialized) {
lateinit var p: String
}
fun box(): String {
return if (Derived.b) "Fail" else "OK"
}
| backend.native/tests/external/codegen/box/properties/lateinit/isInitializedAndDeinitialize/propertyImportedFromObject.kt | 3866695679 |
package com.github.triplet.gradle.play.tasks.shared
import com.github.triplet.gradle.common.utils.safeCreateNewFile
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest.Companion.DEFAULT_TASK_VARIANT
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome.NO_SOURCE
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.ValueSource
import java.io.File
interface ArtifactIntegrationTests : SharedIntegrationTest {
fun customArtifactName(name: String = "foo"): String
fun assertCustomArtifactResults(result: BuildResult, executed: Boolean = true)
@Test
fun `Rebuilding artifact on-the-fly uses cached build`() {
val result1 = execute("", taskName())
val result2 = execute("", taskName())
result1.requireTask(outcome = SUCCESS)
result2.requireTask(outcome = UP_TO_DATE)
}
@Test
fun `Using non-existent custom artifact skips build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
val result = execute(config, taskName())
assertCustomArtifactResults(result, executed = false)
result.requireTask(outcome = NO_SOURCE)
}
@Test
fun `Using custom artifact skips on-the-fly build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Using custom artifact file skips on-the-fly build`() {
val app = File(playgroundDir, customArtifactName()).safeCreateNewFile()
// language=gradle
val config = """
play {
artifactDir = file('${app.escaped()}')
}
"""
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@ParameterizedTest
@CsvSource(value = [
"false,false,",
"false,true,",
"true,false,",
"true,true,",
"false,false,$DEFAULT_TASK_VARIANT",
"false,true,$DEFAULT_TASK_VARIANT",
"true,false,$DEFAULT_TASK_VARIANT",
"true,true,$DEFAULT_TASK_VARIANT"
])
fun `Using custom artifact file with supported 3P dep skips on-the-fly build`(
eager: Boolean,
cliParam: Boolean,
taskVariant: String?,
) {
val app = File(playgroundDir, customArtifactName()).safeCreateNewFile()
// language=gradle
File(appDir, "build.gradle").writeText("""
buildscript {
repositories.google()
dependencies.classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
}
plugins {
id 'com.android.application'
id 'com.github.triplet.play'
}
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdk 31
defaultConfig {
applicationId "com.supercilex.test"
minSdk 31
targetSdk 31
versionCode 1
versionName "1.0"
}
buildTypes.release {
shrinkResources true
minifyEnabled true
proguardFiles(getDefaultProguardFile("proguard-android.txt"))
}
}
play {
serviceAccountCredentials = file('creds.json')
${if (cliParam) "" else "artifactDir = file('${app.escaped()}')"}
}
${if (eager) "tasks.all {}" else ""}
$factoryInstallerStatement
""")
val result = executeGradle(expectFailure = false) {
withArguments(taskName(taskVariant.orEmpty()))
if (cliParam) {
withArguments(arguments + listOf("--artifact-dir=${app}"))
}
}
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Reusing custom artifact uses cached build`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result1 = execute(config, taskName())
val result2 = execute(config, taskName())
result1.requireTask(outcome = SUCCESS)
result2.requireTask(outcome = UP_TO_DATE)
}
@Test
fun `Using custom artifact correctly tracks dependencies`() {
// language=gradle
val config = """
abstract class CustomTask extends DefaultTask {
@OutputDirectory
abstract DirectoryProperty getAppDir()
@TaskAction
void doStuff() {
appDir.get().file("${customArtifactName()}").asFile.createNewFile()
}
}
def c = tasks.register("myCustomTask", CustomTask) {
appDir.set(layout.projectDirectory.dir('${playgroundDir.escaped()}'))
}
play {
artifactDir = c.flatMap { it.appDir }
}
"""
val result = execute(config, taskName())
result.requireTask(":myCustomTask", outcome = SUCCESS)
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@ParameterizedTest
@ValueSource(strings = ["", DEFAULT_TASK_VARIANT])
fun `Using custom artifact CLI arg skips on-the-fly build`(taskVariant: String) {
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute("", taskName(taskVariant), "--artifact-dir=${playgroundDir}")
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertThat(result.output).contains(customArtifactName())
assertCustomArtifactResults(result)
}
@Test
fun `Eagerly evaluated global CLI artifact-dir param skips on-the-fly build`() {
// language=gradle
val config = """
tasks.all {}
"""
File(playgroundDir, customArtifactName()).safeCreateNewFile()
val result = execute(
config,
taskName(/* No variant: */ ""),
"--artifact-dir=$playgroundDir"
)
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(playgroundDir.name)
assertCustomArtifactResults(result)
}
@Test
fun `Using custom artifact with multiple files uploads each one`() {
// language=gradle
val config = """
play {
artifactDir = file('${playgroundDir.escaped()}')
}
"""
File(playgroundDir, customArtifactName("1")).safeCreateNewFile()
File(playgroundDir, customArtifactName("2")).safeCreateNewFile()
val result = execute(config, taskName())
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains(customArtifactName("1"))
assertThat(result.output).contains(customArtifactName("2"))
}
}
| play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/shared/ArtifactIntegrationTests.kt | 451574844 |
package com.rizafu.coachmark
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
/**
* Created by RizaFu on 11/7/16.
*/
class CoachMarkOverlay : View {
private lateinit var paint: Paint
private var rectF: RectF? = null
private var radius: Int = 0
private var x: Int = 0
private var y: Int = 0
private var isCircle: Boolean = false
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
isDrawingCacheEnabled = true
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
fun addRect(x: Int, y: Int, width: Int, height: Int, radius: Int, padding: Int, isCircle: Boolean) {
this.isCircle = isCircle
this.radius = radius + padding
this.x = x
this.y = y
paint = Paint()
paint.isAntiAlias = true
paint.color = Color.TRANSPARENT
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
val r = x + width
val b = y + height
rectF = RectF((x - padding).toFloat(), (y - padding).toFloat(), (r + padding).toFloat(), (b + padding).toFloat())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (isCircle) {
canvas.drawCircle(x.toFloat(), y.toFloat(), radius.toFloat(), paint)
} else {
rectF?.let { canvas.drawRoundRect(it, radius.toFloat(), radius.toFloat(), paint) }
}
}
}
| coachmark/src/main/java/com/rizafu/coachmark/CoachMarkOverlay.kt | 1447742237 |
operator fun Int.component1() = this + 1
operator fun Int.component2() = this + 2
fun doTest(): String {
var s = ""
for ((a, b) in 0.rangeTo(2)) {
s += {"$a:$b;"}()
}
return s
}
fun box(): String {
val s = doTest()
return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s"
} | backend.native/tests/external/codegen/box/multiDecl/forRange/explicitRangeToWithDot/int/MultiDeclForComponentExtensionsValCaptured.kt | 1127102536 |
fun box(): String {
var fx = 1
var fy = 1
do {
var tmp = fy
fy = fx + fy
fx = tmp
} while (fy < 100)
return if (fy == 144) "OK" else "Fail $fx $fy"
}
| backend.native/tests/external/codegen/box/controlStructures/doWhileFib.kt | 45471098 |
/*
* Copyright 2021 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.datastore.core
import androidx.kruth.assertThat
import androidx.kruth.assertThrows
import java.util.concurrent.CancellationException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Timeout
@OptIn(ExperimentalCoroutinesApi::class)
class SimpleActorTest {
@get:Rule
val timeout = Timeout(10, TimeUnit.SECONDS)
@Test
fun testSimpleActor() = runTest(UnconfinedTestDispatcher()) {
val msgs = mutableListOf<Int>()
val actor = SimpleActor<Int>(
this,
onComplete = {},
onUndeliveredElement = { _, _ -> }
) {
msgs.add(it)
}
actor.offer(1)
actor.offer(2)
actor.offer(3)
actor.offer(4)
assertThat(msgs).isEqualTo(listOf(1, 2, 3, 4))
}
@Test
fun testOnCompleteIsCalledWhenScopeIsCancelled() = runBlocking<Unit> {
val scope = CoroutineScope(Job())
val called = AtomicBoolean(false)
val actor = SimpleActor<Int>(
scope,
onComplete = {
assertThat(called.compareAndSet(false, true)).isTrue()
},
onUndeliveredElement = { _, _ -> }
) {
// do nothing
}
actor.offer(123)
scope.coroutineContext.job.cancelAndJoin()
assertThat(called.get()).isTrue()
}
@Test
fun testManyConcurrentCalls() = runBlocking<Unit> {
val scope = CoroutineScope(Job() + Executors.newFixedThreadPool(4).asCoroutineDispatcher())
val numCalls = 100000
val volatileIntHolder = VolatileIntHolder()
val latch = CountDownLatch(numCalls)
val actor = SimpleActor<Int>(
scope,
onComplete = {},
onUndeliveredElement = { _, _ -> }
) {
val newValue = volatileIntHolder.int + 1
// This should be safe because there shouldn't be any concurrent calls
volatileIntHolder.int = newValue
latch.countDown()
}
repeat(numCalls) {
scope.launch {
actor.offer(it)
}
}
latch.await(5, TimeUnit.SECONDS)
assertThat(volatileIntHolder.int).isEqualTo(numCalls)
}
@Test
fun testManyConcurrentCalls_withDelayBeforeSettingValue() = runBlocking<Unit> {
val scope = CoroutineScope(Job() + Executors.newFixedThreadPool(4).asCoroutineDispatcher())
val numCalls = 500
val volatileIntHolder = VolatileIntHolder()
val latch = CountDownLatch(numCalls)
val actor = SimpleActor<Int>(
scope,
onComplete = {},
onUndeliveredElement = { _, _ -> }
) {
val newValue = volatileIntHolder.int + 1
delay(1)
// This should be safe because there shouldn't be any concurrent calls
volatileIntHolder.int = newValue
latch.countDown()
}
repeat(numCalls) {
scope.launch {
actor.offer(it)
}
}
assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue()
assertThat(volatileIntHolder.int).isEqualTo(numCalls)
}
@Test
fun testMessagesAreConsumedInProvidedScope() = runBlocking {
val scope = CoroutineScope(TestElement("test123"))
val latch = CompletableDeferred<Unit>()
val actor = SimpleActor<Int>(
scope,
onComplete = {},
onUndeliveredElement = { _, _ -> }
) {
assertThat(getTestElement().name).isEqualTo("test123")
latch.complete(Unit)
}
actor.offer(123)
latch.await()
}
@Test
fun testOnUndeliveredElementsCallback() = runBlocking<Unit> {
val scope = CoroutineScope(Job())
val actor = SimpleActor<CompletableDeferred<Unit>>(
scope,
onComplete = {},
onUndeliveredElement = { msg, ex ->
msg.completeExceptionally(ex!!)
}
) {
awaitCancellation()
}
actor.offer(CompletableDeferred()) // first one won't be completed...
val deferreds = mutableListOf<CompletableDeferred<Unit>>()
repeat(100) {
CompletableDeferred<Unit>().also {
deferreds.add(it)
actor.offer(it)
}
}
scope.coroutineContext.job.cancelAndJoin()
deferreds.forEach {
assertThrows<CancellationException> { it.await() }
}
}
@Test
fun testAllMessagesAreConsumedIfOfferSucceeds() = runBlocking<Unit> {
val actorScope = CoroutineScope(Job())
val actor = SimpleActor<CompletableDeferred<Unit>>(
actorScope,
onComplete = {},
onUndeliveredElement = { msg, _ -> msg.complete(Unit) }
) {
try {
awaitCancellation()
} finally {
it.complete(Unit)
}
}
val senderScope =
CoroutineScope(Job() + Executors.newFixedThreadPool(4).asCoroutineDispatcher())
val sender = senderScope.async {
repeat(500) {
launch {
try {
val msg = CompletableDeferred<Unit>()
// If `offer` doesn't throw CancellationException, the msg must be processed.
actor.offer(msg)
msg.await() // This must complete even though we've completed.
} catch (canceled: CancellationException) {
// This is OK.
}
}
}
}
actorScope.coroutineContext.job.cancelAndJoin()
sender.await()
}
@Ignore // b/250077079
@Test
fun testAllMessagesAreRespondedTo() = runBlocking<Unit> {
val myScope =
CoroutineScope(Job() + Executors.newFixedThreadPool(4).asCoroutineDispatcher())
val actorScope = CoroutineScope(Job())
val actor = SimpleActor<CompletableDeferred<Unit?>>(
actorScope,
onComplete = {},
onUndeliveredElement = { msg, _ ->
msg.complete(null)
}
) {
it.complete(Unit)
}
val waiters = myScope.async {
repeat(100_000) { _ ->
launch {
try {
CompletableDeferred<Unit?>().also {
actor.offer(it)
}.await()
} catch (cancelled: CancellationException) {
// This is OK
}
}
}
}
delay(100)
actorScope.coroutineContext.job.cancelAndJoin()
waiters.await()
}
class TestElement(val name: String) : AbstractCoroutineContextElement(Key) {
companion object Key : CoroutineContext.Key<TestElement>
}
private suspend fun getTestElement(): TestElement {
return coroutineContext[TestElement]!!
}
private class VolatileIntHolder {
@Volatile
var int = 0
}
} | datastore/datastore-core/src/jvmTest/kotlin/androidx/datastore/core/SimpleActorTest.kt | 1772846981 |
class C {
private var x = ""
fun getX(): String {
return x
}
fun setX(x: String) {
println("setter invoked")
this.x = x
}
fun foo() {
x = "a"
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/SetterWithSideEffect2.kt | 3835924544 |
package com.intellij.codeInspection.tests.java
import com.intellij.codeInspection.tests.JUnitRuleInspectionTestBase
import com.intellij.jvm.analysis.JavaJvmAnalysisTestUtil
import com.intellij.testFramework.TestDataPath
private const val inspectionPath = "/codeInspection/junitrule"
@TestDataPath("\$CONTENT_ROOT/testData$inspectionPath")
class JavaJUnitRuleInspectionTest : JUnitRuleInspectionTestBase() {
override fun getBasePath() = JavaJvmAnalysisTestUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH + inspectionPath
fun `test @Rule highlighting`() {
myFixture.testHighlighting("RuleTest.java")
}
fun `test @Rule quickFixes`() {
val quickfixes = myFixture.getAllQuickFixes("RuleQfTest.java")
quickfixes.forEach { myFixture.launchAction(it) }
myFixture.checkResultByFile("RuleQfTest.after.java")
}
fun `test @ClassRule highlighting`() {
myFixture.testHighlighting("ClassRuleTest.java")
}
fun `test @ClassRule quickFixes`() {
val quickfixes = myFixture.getAllQuickFixes("ClassRuleQfTest.java")
quickfixes.forEach { myFixture.launchAction(it) }
myFixture.checkResultByFile("ClassRuleQfTest.after.java")
}
} | jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/JavaJUnitRuleInspectionTest.kt | 1541769337 |
// "Rename to 'remAssign'" "true"
// DISABLE-ERRORS
object Rem {
operator fun mod(x: Int) {}
operator<caret> fun modAssign(x: Int) {}
}
fun test() {
Rem % 1
Rem.mod(1)
Rem.modAssign(1)
val c = Rem
c %= 1
} | plugins/kotlin/idea/tests/testData/quickfix/renameToRem/modAssignAsMember.kt | 664040485 |
fun typeAliasUsage(m: MyAlias) {
m.isProperty
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/members/isProperty/TypeAliasUsage.kt | 3867753237 |
// 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.codeInsight.gradle
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.task.TaskCallback
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderEntry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.VfsTestUtil
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.idea.test.GradleProcessOutputInterceptor
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.test.AndroidStudioTestUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase
import org.jetbrains.plugins.gradle.service.project.open.createLinkSettings
import org.jetbrains.plugins.gradle.settings.GradleSystemSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Assume
import org.junit.runners.Parameterized
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
@Suppress("ACCIDENTAL_OVERRIDE")
abstract class KotlinGradleImportingTestCase : GradleImportingTestCase() {
public override fun getModule(name: String?): Module = super.getModule(name)
protected open fun testDataDirName(): String = ""
protected open fun clearTextFromMarkup(text: String): String = text
protected open fun testDataDirectory(): File {
val baseDir = IDEA_TEST_DATA_DIR.resolve("gradle/${testDataDirName()}")
return File(baseDir, getTestName(true).substringBefore("_").substringBefore(" "))
}
override fun setUp() {
Assume.assumeFalse(AndroidStudioTestUtils.skipIncompatibleTestAgainstAndroidStudio())
super.setUp()
GradleSystemSettings.getInstance().gradleVmOptions =
"-XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${System.getProperty("user.dir")}"
GradleProcessOutputInterceptor.install(testRootDisposable)
}
protected open fun configureKotlinVersionAndProperties(text: String, properties: Map<String, String>? = null): String {
var result = text
(properties ?: defaultProperties).forEach { (key, value) ->
result = result.replace(Regex("""\{\s*\{\s*${key}\s*}\s*}"""), value)
}
return result
}
protected open val defaultProperties: Map<String, String> = mapOf("kotlin_plugin_version" to LATEST_STABLE_GRADLE_PLUGIN_VERSION)
protected open fun configureByFiles(properties: Map<String, String>? = null): List<VirtualFile> {
val rootDir = testDataDirectory()
assert(rootDir.exists()) { "Directory ${rootDir.path} doesn't exist" }
return rootDir.walk().mapNotNull {
when {
it.isDirectory -> null
!it.name.endsWith(AFTER_SUFFIX) -> {
val text = configureKotlinVersionAndProperties(
clearTextFromMarkup(FileUtil.loadFile(it, /* convertLineSeparators = */ true)),
properties
)
val virtualFile = createProjectSubFile(it.path.substringAfter(rootDir.path + File.separator), text)
// Real file with expected testdata allows to throw nicer exceptions in
// case of mismatch, as well as open interactive diff window in IDEA
virtualFile.putUserData(VfsTestUtil.TEST_DATA_FILE_PATH, it.absolutePath)
virtualFile
}
else -> null
}
}.toList()
}
protected fun createLocalPropertiesSubFileForAndroid() {
createProjectSubFile(
"local.properties",
"sdk.dir=/${KotlinTestUtils.getAndroidSdkSystemIndependentPath()}"
)
}
protected fun checkFiles(files: List<VirtualFile>) {
FileDocumentManager.getInstance().saveAllDocuments()
files.filter {
it.name == GradleConstants.DEFAULT_SCRIPT_NAME
|| it.name == GradleConstants.KOTLIN_DSL_SCRIPT_NAME
|| it.name == GradleConstants.SETTINGS_FILE_NAME
}
.forEach {
if (it.name == GradleConstants.SETTINGS_FILE_NAME && !File(testDataDirectory(), it.name + AFTER_SUFFIX).exists()) return@forEach
val actualText = configureKotlinVersionAndProperties(LoadTextUtil.loadText(it).toString())
val expectedFileName = if (File(testDataDirectory(), it.name + ".$gradleVersion" + AFTER_SUFFIX).exists()) {
it.name + ".$gradleVersion" + AFTER_SUFFIX
} else {
it.name + AFTER_SUFFIX
}
val expectedFile = File(testDataDirectory(), expectedFileName)
KotlinTestUtils.assertEqualsToFile(expectedFile, actualText) { s -> configureKotlinVersionAndProperties(s) }
}
}
override fun importProject(skipIndexing: Boolean?) {
AndroidStudioTestUtils.specifyAndroidSdk(File(projectPath))
super.importProject(skipIndexing)
}
protected fun importProjectFromTestData(): List<VirtualFile> {
val files = configureByFiles()
importProject()
return files
}
protected fun getSourceRootInfos(moduleName: String): List<Pair<String, JpsModuleSourceRootType<*>>> {
return ModuleRootManager.getInstance(getModule(moduleName)).contentEntries.flatMap { contentEntry ->
contentEntry.sourceFolders.map { sourceFolder ->
sourceFolder.url.replace(projectPath, "") to sourceFolder.rootType
}
}
}
override fun handleImportFailure(errorMessage: String, errorDetails: String?) {
val gradleOutput = GradleProcessOutputInterceptor.getInstance()?.getOutput().orEmpty()
// Typically Gradle error message consists of a line with the description of the error followed by
// a multi-line stacktrace. The idea is to cut off the stacktrace if it is already contained in
// the intercepted Gradle process output to avoid unnecessary verbosity.
val compactErrorMessage = when (val indexOfNewLine = errorMessage.indexOf('\n')) {
-1 -> errorMessage
else -> {
val compactErrorMessage = errorMessage.substring(0, indexOfNewLine)
val theRest = errorMessage.substring(indexOfNewLine + 1)
if (theRest in gradleOutput) compactErrorMessage else errorMessage
}
}
val failureMessage = buildString {
append("Gradle import failed: ").append(compactErrorMessage).append('\n')
if (!errorDetails.isNullOrBlank()) append("Error details: ").append(errorDetails).append('\n')
append("Gradle process output (BEGIN):\n")
append(gradleOutput)
if (!gradleOutput.endsWith('\n')) append('\n')
append("Gradle process output (END)")
}
fail(failureMessage)
}
protected open fun assertNoModuleDepForModule(moduleName: String, depName: String) {
assertEmpty("No dependency '$depName' was expected", collectModuleDeps<ModuleOrderEntry>(moduleName, depName))
}
protected open fun assertNoLibraryDepForModule(moduleName: String, depName: String) {
assertEmpty("No dependency '$depName' was expected", collectModuleDeps<LibraryOrderEntry>(moduleName, depName))
}
private inline fun <reified T : OrderEntry> collectModuleDeps(moduleName: String, depName: String): List<T> {
return getRootManager(moduleName).orderEntries.asList().filterIsInstanceWithChecker { it.presentableName == depName }
}
protected fun linkProject(projectFilePath: String = projectPath) {
val localFileSystem = LocalFileSystem.getInstance()
val projectFile = localFileSystem.refreshAndFindFileByPath(projectFilePath)
?: error("Failed to find projectFile: $projectFilePath")
ExternalSystemUtil.linkExternalProject(
/* externalSystemId = */ GradleConstants.SYSTEM_ID,
/* projectSettings = */ createLinkSettings(projectFile.toNioPath(), myProject),
/* project = */ myProject,
/* importResultCallback = */ null,
/* isPreviewMode = */ false,
/* progressExecutionMode = */ ProgressExecutionMode.MODAL_SYNC
)
}
protected fun runTaskAndGetErrorOutput(projectPath: String, taskName: String, scriptParameters: String = ""): String {
val taskErrOutput = StringBuilder()
val stdErrListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
if (!stdOut) {
taskErrOutput.append(text)
}
}
}
val notificationManager = ExternalSystemProgressNotificationManager.getInstance()
notificationManager.addNotificationListener(stdErrListener)
try {
val settings = ExternalSystemTaskExecutionSettings()
settings.externalProjectPath = projectPath
settings.taskNames = listOf(taskName)
settings.scriptParameters = scriptParameters
settings.externalSystemIdString = GradleConstants.SYSTEM_ID.id
val future = CompletableFuture<String>()
ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID,
object : TaskCallback {
override fun onSuccess() {
future.complete(taskErrOutput.toString())
}
override fun onFailure() {
future.complete(taskErrOutput.toString())
}
}, ProgressExecutionMode.IN_BACKGROUND_ASYNC)
return future.get(10, TimeUnit.SECONDS)
}
finally {
notificationManager.removeNotificationListener(stdErrListener)
}
}
companion object {
const val AFTER_SUFFIX = ".after"
const val MINIMAL_SUPPORTED_GRADLE_PLUGIN_VERSION = "1.3.0"
const val LATEST_STABLE_GRADLE_PLUGIN_VERSION = "1.3.70"
val SUPPORTED_GRADLE_VERSIONS: List<Array<Any>> = listOf(arrayOf("4.9"), arrayOf("5.6.4"), arrayOf("6.0.1"))
@JvmStatic
@Suppress("ACCIDENTAL_OVERRIDE")
@Parameterized.Parameters(name = "{index}: with Gradle-{0}")
fun data(): Collection<Array<Any>> = SUPPORTED_GRADLE_VERSIONS
}
}
| plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradleImportingTestCase.kt | 1914045152 |
fun main(args: Array<String>) {
listO<caret>f(20, 30).map { if(it == 20) null else it }.count()
} | plugins/kotlin/jvm-debugger/test/testData/sequence/psi/collection/positive/types/PrimitiveToNullableAny.kt | 4217021056 |
package dependency
object AnObject
val Foo.extProp: () -> Unit get() = {}
| plugins/kotlin/idea/tests/testData/shortenRefs/extensionForObject2.dependency.kt | 1491238887 |
val x = 1.apply {
th<caret>is
}
// TYPE: this -> <html>Int</html>
| plugins/kotlin/idea/tests/testData/codeInsight/expressionType/ThisInLambda.kt | 3859099053 |
// IS_APPLICABLE: false
class Test {
var x<caret> = 1
get() = field
set(value) {
field = value
}
} | plugins/kotlin/idea/tests/testData/intentions/addPropertyAccessors/setter/hasAccessor.kt | 2357728685 |
// SET_INT: CALL_PARAMETERS_WRAP = 0
// SET_TRUE: ALLOW_TRAILING_COMMA
fun foo() {
testtest(foofoo, foofoo, foofoo,
foofoo, bar)
testtest(
foofoo, foofoo, foofoo, foofoo, bar
)
testtest(foofoo, foofoo, foofoo, foofoo, bar
)
testtest(foofoo, foofoo, foofoo, foofoo,
bar
)
testtest(foofoo
)
testtest(
foofoo)
testtest(
foofoo
)
testtest(foofoo)
testtest(foofoo, testtest(testtest(foofoo)))
testtest(foofoo, fososos, testtest(testtest(foofoo)))
testtest(foofoo, testtest(testtest(foofoo)), testsa)
testtest(foofoo, seee, testtest(testtest(foofoo)), testsa)
useCallable("A", Callable { println("Hello world") })
useCallable("B", "C", Callable {
println("Hello world")
}, Callable {
println("Hello world")
})
useCallable(Callable { println("Hello world") })
useCallable(Callable { println("Hello world") })
useCallable(Callable { println("Hello world") }
)
useCallable(Callable { println("Hello world") }) {
}
useCallable(
Callable { println("Hello world") })
useCallable("A", { println("Hello world") })
useCallable("B", "C", {
println("Hello world")
}, {
println("Hello world")
})
useCallable({ println("Hello world") })
useCallable({ println("Hello world") })
useCallable({ println("Hello world") }
)
useCallable({ println("Hello world") }) {
}
useCallable(
{ println("Hello world") })
useCallable("A", foo() { println("Hello world") })
useCallable("B", "C", foo() {
println("Hello world")
}, foo() {
println("Hello world")
})
useCallable(foo() { println("Hello world") })
useCallable(foo() { println("Hello world") })
useCallable(foo() { println("Hello world") }
)
useCallable(foo() { println("Hello world") }) {
}
useCallable(
foo() { println("Hello world") })
useCallable("A", object : Callable<Unit> {
override fun call() {
println("Hello world")
}
})
useCallable("A", object : Callable<Unit> {
override fun call() {
println("Hello world")
}
})
useCallable("B", "C", object : Callable<Unit> {
override fun call() {
println("Hello world")
}
}, foo() {
println("Hello world")
})
useCallable(object : Callable<Unit> {
override fun call() {
println("Hello world")
}
})
useCallable(
object : Callable<Unit> {
override fun call() {
println("Hello world")
}
},
)
useCallable(object : Callable<Unit> {
override fun call() {
println("Hello world")
}
}
)
useCallable(object : Callable<Unit> {
override fun call() {
println("Hello world")
}
}) {
}
useCallable(
object : Callable<Unit> {
override fun call() {
println("Hello world")
}
})
testtest(
foofoo, foofoo, foofoo, foofoo,
bar /*
*/, /* */ foo
)
testtest(/*
*/foofoo, foofoo, foofoo, /*
*/
foofoo, bar)
testtest(foofoo, foofoo, foofoo, foofoo, bar/*
*/)
testtest(foofoo, foofoo, foofoo, foofoo, bar // awdawda
)
testtest(foofoo, foofoo, foofoo, foofoo, /*
*/
bar
)
testtest(foofoo // fd
)
testtest( /**/
foofoo
)
testtest(foofoo/**/)
testtest(foofoo, foofoo, foofoo, foofoo/*
*/, /* */ bar
)
testtest(foofoo // fd
)
testtest( /**/
foofoo
)
testtest(foofoo/**/)
testtest(
foofoo, fososos,/*
*/
testtest(testtest(foofoo)),
)
testtest(foofoo, testtest(testtest(foofoo)), /**/testsa)
testtest(foofoo, testtest(testtest(foofoo))/* */, /**/testsa)
testtest(foofoo, testtest(testtest(foofoo))/*
*/, testsa)
testtest(foofoo, seee, testtest(testtest(foofoo)), /**/testsa)
testtest(foofoo, seee, testtest(testtest(foofoo)), /*
*/testsa)
useCallable("B", "C", Callable {
println("Hello world")
}, /* */ Callable {
println("Hello world")
})
useCallable(Callable { println("Hello world") } // ffd
)
useCallable(
object : Callable<Unit> {
override fun call() {
println("Hello world")
}
},
)
useCallable(
foo() {
println("Hello world")
},
)
useCallable(
{
println("Hello world")
},
)
useCallable(
Callable { println("Hello world") },
)
testtest(foofoo, testtest(testtest(
foofoo,
)), testsa)
testtest(
foofoo, fososos, testtest(testtest(foofoo)),
)
}
fun test() {
baz(
f = fun(it: Int): String = "$it", /*dwdwd
*/
name = "", /*
*/
)
}
| plugins/kotlin/idea/tests/testData/formatter/trailingComma/valueArguments/ArgumentListDoNotWrap.after.kt | 1026067674 |
// WITH_STDLIB
// IS_APPLICABLE: false
fun <T : CharSequence> foo(a: Iterable<T>) {
val b = kotlin.sequences.sequenceOf("a", "b", "c", "e")
val c = a - <caret>b
}
| plugins/kotlin/idea/tests/testData/intentions/convertArgumentToSet/iterableMinusSequenceOfIndirectQualified.kt | 1152253518 |
package info.nightscout.androidaps.plugins.profile.local.events
import info.nightscout.androidaps.events.Event
class EventLocalProfileChanged : Event() {
} | app/src/main/java/info/nightscout/androidaps/plugins/profile/local/events/EventLocalProfileChanged.kt | 3939873544 |
package uy.kohesive.iac.model.aws.codegen
import com.amazonaws.codegen.model.intermediate.IntermediateModel
import com.amazonaws.codegen.utils.ModelLoaderUtils
import org.reflections.Reflections
import org.reflections.scanners.ResourcesScanner
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class AWSModelProvider {
companion object {
val IntermediateFilenameRegexp = "(.*)-(\\d{4}-\\d{2}-\\d{2})-intermediate\\.json".toRegex()
}
private val intermediateFiles: Set<String>
= Reflections("models", ResourcesScanner()).getResources(IntermediateFilenameRegexp.toPattern())
// Service name -> version -> file
private val serviceShortNameToVersions: Map<String, SortedMap<String, String>> by lazy {
intermediateFiles.map { filePath ->
IntermediateFilenameRegexp.find(filePath.takeLastWhile { it != '/' })?.groupValues?.let {
val serviceName = it[1]
val apiVersion = it[2].replace("-", "")
serviceName to (apiVersion to filePath)
}
}.filterNotNull().groupBy { it.first }.mapValues {
it.value.map { it.second }.toMap().toSortedMap()
}
}
private val modelCache = ConcurrentHashMap<String, IntermediateModel>()
fun getModel(service: String, apiVersion: String? = null): IntermediateModel {
return serviceShortNameToVersions[service]?.let { versionToFilepath ->
val filePath = if (apiVersion == null) {
versionToFilepath.values.first()
} else {
versionToFilepath[apiVersion.replace("-", "").replace("_", "")] ?: versionToFilepath.values.first()
}
modelCache.getOrPut(filePath) {
ModelLoaderUtils.getRequiredResourceAsStream(filePath).use { stream ->
loadModel<IntermediateModel>(stream)
}
}
} ?: throw IllegalArgumentException("Unknown service: $service")
}
} | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/codegen/AWSModelProvider.kt | 2110244248 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected
import com.intellij.codeInsight.intention.impl.QuickEditAction
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.lang.injection.MultiHostInjector
import com.intellij.lang.injection.MultiHostRegistrar
import com.intellij.lang.injection.MultiHostRegistrarPlaceholderHelper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.TestDialog
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.injection.Injectable
import com.intellij.psi.util.parentOfType
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.InjectionTestFixture
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
import com.intellij.util.SmartList
import com.intellij.util.ui.UIUtil
import junit.framework.TestCase
import org.intellij.plugins.intelliLang.StoringFixPresenter
import org.intellij.plugins.intelliLang.inject.InjectLanguageAction
import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction
import org.jetbrains.uast.expressions.UStringConcatenationsFacade
class JavaInjectedFileChangesHandlerTest : JavaCodeInsightFixtureTestCase() {
fun `test edit multiline in fragment-editor`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"bca\":<caret> \n" +
"1}";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("JSON")
TestCase.assertEquals("{\"bca\": \n1}", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
}
}
fun `test temp injection survive on host death and no edit in uninjected`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"bca\":<caret> \n1}";
}
}
""".trimIndent())
InjectLanguageAction.invokeImpl(project,
myFixture.editor,
myFixture.file,
Injectable.fromLanguage(Language.findLanguageByID("JSON")))
val quickEditHandler = QuickEditAction().invokeImpl(project, editor, file)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\"bca\": \n1}", fragmentFile.text)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
class A {
void foo() {
String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
injectionTestFixture.assertInjectedLangAtCaret("JSON")
UnInjectLanguageAction.invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
injectionTestFixture.assertInjectedLangAtCaret(null)
TestCase.assertFalse(quickEditHandler.isValid)
fragmentFile.edit { insertString(text.indexOf(":"), " ") }
checkResult("""
class A {
void foo() {
String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent())
}
}
fun `test delete in multiple hosts`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "<html>line\n" +
"anotherline<caret>\n" +
"finalLine</html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html>line\nanotherline\nfinalLine</html>", fragmentFile.text)
fragmentFile.edit {
findAndDelete("ne\nanot")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>li" +
"herline\n" +
"finalLine</html>";
}
}
""".trimIndent())
}
}
fun `test edit multipart in 4 steps`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "{\"a\"<caret>: 1}";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("JSON")
TestCase.assertEquals("{\"a\": 1}", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("a"), "bc") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\": 1}";
}
}
""".trimIndent())
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf("1"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\": \n" +
"1}";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
fragmentFile.edit { insertString(text.indexOf(":"), "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
injectionTestFixture.assertInjectedLangAtCaret("JSON")
}
}
fun `test delete-insert-delete`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"<caret>\n" +
": \n" +
"1}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
TestCase.assertEquals("", fragmentFile.text)
fragmentFile.edit { insertString(0, "{\"bca\"\n: \n1}") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
TestCase.assertEquals("", fragmentFile.text)
fragmentFile.edit { insertString(0, "{\"bca\"\n: \n1}") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\"bca\"\n" +
": \n" +
"1}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("{\"bca\"\n: \n1}", fragmentFile.text)
fragmentFile.edit { deleteString(0, textLength) }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "";
}
}
""".trimIndent(), true)
}
}
fun `test complex insert-commit-broken-reformat`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"innerMap1" +
"\": {\n" +
" " +
"\"field2\": 1,\n" +
" " +
" \"field3\": 3<caret>\n" +
" " +
"}\n" +
"}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("{\n" +
" \"field1\": 1,\n" +
" \"innerMap1\": {\n" +
" \"field2\": 1,\n" +
" \"field3\": 3\n" +
" }\n" +
"}",
fragmentFile.text)
fragmentFile.edit("insert json") {
val pos = text.indexAfter("\"field3\": 3")
replaceString(pos - 1, pos, "\"brokenInnerMap\": {\n" +
" \"broken1\": 1,\n" +
" \"broken2\": 2,\n" +
" \"broken3\": 3\n" +
" }")
}
PsiDocumentManager.getInstance(project).commitAllDocuments()
fragmentFile.edit("reformat") {
CodeStyleManager.getInstance(psiManager).reformatRange(
fragmentFile, 0, fragmentFile.textLength, false)
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"innerMap1" +
"\": {\n" +
" " +
"\"field2\": 1,\n" +
" " +
" \"field3\": \"brokenInnerMap\"\n" +
" : {\n" +
" \"broken1\": 1,\n" +
" \"broken2\": 2,\n" +
" \"broken3\": 3\n" +
"}\n" +
"}\n" +
"}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
"innerMap1": {
"field2": 1,
"field3": "brokenInnerMap"
: {
"broken1": 1,
"broken2": 2,
"broken3": 3
}
}
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test suffix-prefix-edit-reformat`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language(value = "JSON", prefix = "{\n", suffix = "\n}\n}")
String a =
" \"field1\": 1,\n<caret>" +
" \"container\": {\n" +
" \"innerField\": 2";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2
}
}
""".trimIndent(), fragmentFile.text)
openFileInEditor(fragmentFile.virtualFile)
editor.caretModel.moveToOffset(fragmentFile.text.indexAfter("\"innerField\": 2"))
type("\n\"anotherInnerField\": 3")
PsiDocumentManager.getInstance(project).commitAllDocuments()
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2,
"anotherInnerField": 3
}
}
""".trimIndent(), fragmentFile.text)
fragmentFile.edit("reformat") {
CodeStyleManager.getInstance(psiManager).reformatRange(
fragmentFile, 0, fragmentFile.textLength, false)
}
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language(value = "JSON", prefix = "{\n", suffix = "\n}\n}")
String a =
" \"field1\": 1,\n" +
" \"container\": {\n" +
" \"innerField\": 2,\n" +
" \"anotherInnerField\": 3";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2,
"anotherInnerField": 3
}
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test text block trim indent`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
@Language("HTML")
String s = ""${'"'}
<html>
<body>
<h1>title</h1>
<p>
this is a test.<caret>
</p>
</body>
</html>""${'"'};
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals(
"""|<html>
| <body>
| <h1>title</h1>
| <p>
| this is a test.
| </p>
| </body>
|</html>""".trimMargin(), fragmentFile.text)
}
}
fun `test delete-commit-delete`() {
with(myFixture) {
configureByText("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
" \"container\"<caret>: {\n" +
" \"innerField\": 2\n" +
" }\n" +
"}";
}
}
""".trimIndent())
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("""
{
"field1": 1,
"container": {
"innerField": 2
}
}
""".trimIndent(), fragmentFile.text)
fragmentFile.edit("delete json") {
findAndDelete(" \"container\": {\n \"innerField\": 2\n }")
}
PsiDocumentManager.getInstance(project).commitAllDocuments()
fragmentFile.edit("delete again") {
val pos = text.indexAfter("1,\n")
deleteString(pos - 1, pos)
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON")
String a = "{\n" +
" \"field1\": 1,\n" +
"}";
}
}
""".trimIndent(), true)
TestCase.assertEquals("""
{
"field1": 1,
}
""".trimIndent(), fragmentFile.text)
}
}
fun `test delete empty line`() {
with(myFixture) {
configureByText("classA.java", """
class A {
void foo() {
String a = "<html>line\n<caret>" +
"\n" +
"finalLine</html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html>line\n\nfinalLine</html>", fragmentFile.text)
fragmentFile.edit {
findAndDelete("\n")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>line\n" +
"finalLine</html>";
}
}
""".trimIndent())
fragmentFile.edit {
findAndDelete("\n")
}
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html>line" +
"finalLine</html>";
}
}
""".trimIndent())
}
}
fun `test type new lines in fe then delete`() {
with(myFixture) {
val hostFile = configureByText("classA.java", """
class A {
void foo() {
String a = "<html></html><caret>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html></html>", fragmentFile.text)
openFileInEditor(fragmentFile.virtualFile)
assertHostIsReachable(hostFile, file)
moveCaret(fragmentFile.text.length)
type("\n")
type("\n")
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html></html>\n" +
"\n";
}
}
""".trimIndent(), true)
assertHostIsReachable(hostFile, file)
type("\b")
type("\b")
checkResult("classA.java", """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("HTML") String a = "<html></html>";
}
}
""".trimIndent(), true)
assertHostIsReachable(hostFile, file)
}
}
private fun assertHostIsReachable(hostFile: PsiFile, injectedFile: PsiFile) {
TestCase.assertEquals("host file should be reachable from the context",
hostFile.virtualFile,
injectedFile.context?.containingFile?.virtualFile)
}
fun `test edit with guarded blocks`() {
with(myFixture) {
myFixture.configureByText("classA.java", """
class A {
void foo(String bodyText) {
String headText = "someText1";
String concatenation = "<html><head>" + headText + "</head><caret><body>" + bodyText + "</body></html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html><head>someText1</head><body>missingValue</body></html>", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("<body>"), "someInner") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String headText = "someText1";
@Language("HTML") String concatenation = "<html><head>" + headText + "</head>someInner<body>" + bodyText + "</body></html>";
}
}
""".trimIndent(), true)
fragmentFile.edit { insertString(text.indexOf("<body>") + "<body>".length, "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String headText = "someText1";
@Language("HTML") String concatenation = "<html><head>" + headText + "</head>someInner<body>\n" + bodyText + "</body></html>";
}
}
""".trimIndent())
}
}
fun `test edit guarded blocks ending`() {
with(myFixture) {
myFixture.configureByText("classA.java", """
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
String concatenation = "<html><head></head><caret><body>" + end + "</body></html>";
}
}
""".trimIndent())
val fragmentFile = injectAndOpenInFragmentEditor("HTML")
TestCase.assertEquals("<html><head></head><body>missingValue</body></html>", fragmentFile.text)
fragmentFile.edit { findAndDelete("</body></html>") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
@Language("HTML") String concatenation = "<html><head></head><body>" + end;
}
}
""".trimIndent(), true)
fragmentFile.edit { insertString(text.indexOf("<body>") + "<body>".length, "\n") }
checkResult("""
import org.intellij.lang.annotations.Language;
class A {
void foo(String bodyText) {
String bodyText = "someTextInBody";
@Language("HTML") String concatenation = "<html><head></head><body>\n" + end;
}
}
""".trimIndent())
}
}
fun `test sequential add in fragment editor undo-repeat`() {
with(myFixture) {
val fileName = "classA.java"
val initialText = """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\n" +
" \"begin\": true,\n" +
" \"fieldstart\": -1,\n" +
" \"end\": false\n" +
"}";
}
}
""".trimIndent()
val fiveFieldsFilled = """
import org.intellij.lang.annotations.Language;
class A {
void foo() {
@Language("JSON") String a = "{\n" +
" \"begin\": true,\n" +
" \"fieldstart\": -1,\n" +
" \"field0\": 0,\n" +
" \"field1\": 1,\n" +
" \"field2\": 2,\n" +
" \"field3\": 3,\n" +
" \"field4\": 4,\n" +
" \"end\": false\n" +
"}";
}
}
""".trimIndent()
configureByText(fileName, initialText)
myFixture.editor.caretModel.moveToOffset(file.text.indexAfter("-1"))
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
injectionTestFixture.assertInjectedLangAtCaret("JSON")
openFileInEditor(fragmentFile.virtualFile)
fun fillFields(num: Int) {
var shift = fragmentFile.text.indexAfter("-1,\n")
repeat(num) {
quickEditHandler.newFile.edit("add field$it") {
val s = " \"field$it\": $it,\n"
insertString(shift, s)
shift += s.length
}
}
}
fillFields(5)
PsiDocumentManager.getInstance(project).commitAllDocuments()
checkResult(fileName, fiveFieldsFilled, true)
repeat(5) {
undo(editor)
}
checkResult(fileName, initialText, true)
fillFields(5)
PsiDocumentManager.getInstance(project).commitAllDocuments()
checkResult(fileName, fiveFieldsFilled, true)
}
}
fun `test edit inner within multiple injections`() {
with(myFixture) {
InjectedLanguageManager.getInstance(project).registerMultiHostInjector(JsonMultiInjector(), testRootDisposable)
configureByText("classA.java", """
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html><caret></html>\"\n" +
"}";
}
}
""".trimIndent())
injectionTestFixture.getAllInjections().map { it.second }.distinct().let { allInjections ->
UsefulTestCase.assertContainsElements(
allInjections.map { it.text },
"{\\n \\\"html\\\": \\\"HTML\\\"\\n}",
"<html></html>")
}
val quickEditHandler = QuickEditAction().invokeImpl(project, injectionTestFixture.topLevelEditor, injectionTestFixture.topLevelFile)
val fragmentFile = quickEditHandler.newFile
TestCase.assertEquals("<html></html>", fragmentFile.text)
fragmentFile.edit { insertString(text.indexOf("</html>"), " ") }
checkResult("""
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html> </html>\"\n" +
"}";
}
}
""".trimIndent())
fragmentFile.edit {
val htmlBodyEnd = text.indexOf("</html>")
deleteString(htmlBodyEnd - 1, htmlBodyEnd)
}
checkResult("""
class A {
void foo() {
String injectjson = "{\n" +
" \"html\": \"<html></html>\"\n" +
"}";
}
}
""".trimIndent())
}
}
private fun injectAndOpenInFragmentEditor(language: String): PsiFile {
with(myFixture) {
StoringFixPresenter().apply {
InjectLanguageAction.invokeImpl(project,
myFixture.editor,
myFixture.file,
Injectable.fromLanguage(Language.findLanguageByID(language)),
this
)
}.process()
val quickEditHandler = QuickEditAction().invokeImpl(project, editor, file)
return quickEditHandler.newFile
}
}
private fun undo(editor: Editor) = runWithUndoManager(editor, UndoManager::undo)
private fun redo(editor: Editor) = runWithUndoManager(editor, UndoManager::redo)
private fun runWithUndoManager(editor: Editor, action: (UndoManager, TextEditor) -> Unit) {
UIUtil.invokeAndWaitIfNeeded(Runnable {
val oldTestDialog = Messages.setTestDialog(TestDialog.OK)
try {
val undoManager = UndoManager.getInstance(project)
val textEditor = TextEditorProvider.getInstance().getTextEditor(editor)
action(undoManager, textEditor)
}
finally {
Messages.setTestDialog(oldTestDialog)
}
})
}
private fun PsiFile.edit(actionName: String = "change doc", groupId: Any = actionName, docFunction: Document.() -> Unit) {
CommandProcessor.getInstance().executeCommand(project, {
ApplicationManager.getApplication().runWriteAction {
val manager = PsiDocumentManager.getInstance(project)
val document = manager.getDocument(this) ?: throw AssertionError("document is null")
document.docFunction()
}
}, actionName, groupId)
}
private fun commit() = PsiDocumentManager.getInstance(project).commitDocument(myFixture.editor.document)
private fun moveCaret(shift: Int, columnShift: Int = 0) =
myFixture.editor.caretModel.moveCaretRelatively(shift, columnShift, false, false, false)
private fun Document.findAndDelete(substring: String) {
val start = this.text.indexOf(substring)
deleteString(start, start + substring.length)
}
private val injectionTestFixture: InjectionTestFixture get() = InjectionTestFixture(myFixture)
}
private fun String.indexAfter(string: String): Int {
val r = indexOf(string)
return if (r == -1) -1 else r + string.length
}
private class JsonMultiInjector : MultiHostInjector {
private val VAR_NAME = "injectjson"
override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) {
val concatenationsFacade = UStringConcatenationsFacade.create(context)?.takeIf { it.uastOperands.any() } ?: return
context.parentOfType<PsiVariable>()?.takeIf { it.name == VAR_NAME } ?: return
val cssReg = """"html"\s*:\s*"(.*)"""".toRegex()
val mhRegistrar = MultiHostRegistrarPlaceholderHelper(registrar)
mhRegistrar.startInjecting(Language.findLanguageByID("JSON")!!)
val cssInjections = SmartList<Pair<PsiLanguageInjectionHost, TextRange>>()
for (host in concatenationsFacade.psiLanguageInjectionHosts) {
val manipulator = ElementManipulators.getManipulator(host)
val fullRange = manipulator.getRangeInElement(host)
val escaper = host.createLiteralTextEscaper()
val decoded: CharSequence = StringBuilder().apply { escaper.decode(fullRange, this) }
val cssRanges = cssReg.find(decoded)?.groups?.get(1)?.range
?.let { TextRange.create(it.first, it.last + 1) }
?.let { cssRangeInDecoded ->
listOf(TextRange.create(
escaper.getOffsetInHost(cssRangeInDecoded.startOffset, fullRange),
escaper.getOffsetInHost(cssRangeInDecoded.endOffset, fullRange)
))
}.orEmpty()
mhRegistrar.addHostPlaces(host, cssRanges.map { it to "HTML" })
cssInjections.addAll(cssRanges.map { host to it })
}
mhRegistrar.doneInjecting()
for ((host, cssRange) in cssInjections) {
registrar.startInjecting(Language.findLanguageByID("HTML")!!)
registrar.addPlace(null, null, host, cssRange)
registrar.doneInjecting()
}
}
override fun elementsToInjectIn() = listOf(PsiElement::class.java)
}
| plugins/IntelliLang/IntelliLang-tests/test/com/intellij/psi/impl/source/tree/injected/JavaInjectedFileChangesHandlerTest.kt | 1843364065 |
// PROBLEM: none
// WITH_RUNTIME
val map = mutableMapOf(42 to "foo")
fun foo() = map.<caret>put(60, "bar")
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replacePutWithAssignment/putAsExpression.kt | 4142622281 |
// 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.idea.devkit.actions
import com.intellij.ide.actions.CreateElementActionBase
import com.intellij.ide.actions.CreateTemplateInPackageAction
import com.intellij.ide.actions.JavaCreateTemplateInPackageAction
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.util.xml.DomManager
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.IdeaPlugin
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import java.util.function.Consumer
import java.util.function.Predicate
class NewMessageBundleAction : CreateElementActionBase(), UpdateInBackground {
override fun invokeDialog(project: Project, directory: PsiDirectory, elementsConsumer: Consumer<Array<PsiElement>>) {
val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return
if (module.name.endsWith(".impl") && ModuleManager.getInstance(project).findModuleByName(module.name.removeSuffix(".impl")) != null) {
Messages.showErrorDialog(project, DevKitBundle.message(
"action.DevKit.NewMessageBundle.error.message.do.not.put.bundle.to.impl.module"), errorTitle)
return
}
val validator = MyInputValidator(project, directory)
val defaultName = generateDefaultBundleName(module)
val result = Messages.showInputDialog(project, DevKitBundle.message("action.DevKit.NewMessageBundle.label.bundle.name"),
DevKitBundle.message("action.DevKit.NewMessageBundle.title.create.new.message.bundle"), null,
defaultName, validator)
if (result != null) {
elementsConsumer.accept(validator.createdElements)
}
}
override fun create(newName: String, directory: PsiDirectory): Array<PsiElement> {
val bundleClass = DevkitActionsUtil.createSingleClass(newName, "MessageBundle.java", directory)
val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return emptyArray()
val pluginXml = PluginModuleType.getPluginXml(module)
if (pluginXml != null) {
DescriptorUtil.patchPluginXml({ xmlFile, psiClass ->
val fileElement = DomManager.getDomManager(module.project).getFileElement(xmlFile,
IdeaPlugin::class.java)
if (fileElement != null) {
val resourceBundle = fileElement.rootElement.resourceBundle
if (!resourceBundle.exists()) {
resourceBundle.value = "messages.$newName"
}
}
}, bundleClass, pluginXml)
}
val resourcesRoot = getOrCreateResourcesRoot(module)
if (resourcesRoot == null) return arrayOf(bundleClass)
val propertiesFile = runWriteAction {
val messagesDirName = "messages"
val messagesDir = resourcesRoot.findSubdirectory(messagesDirName) ?: resourcesRoot.createSubdirectory(messagesDirName)
messagesDir.createFile("$newName.properties")
}
return arrayOf(bundleClass, propertiesFile)
}
private fun getOrCreateResourcesRoot(module: Module): PsiDirectory? {
fun reportError(@Nls message: String): Nothing? {
val notification =
Notification("DevKit Errors",
DevKitBundle.message("action.DevKit.NewMessageBundle.notification.title.cannot.create.resources.root.for.properties.file"),
DevKitBundle.message("action.DevKit.NewMessageBundle.notification.content.cannot.create.resources.root.for.properties.file",
message),
NotificationType.ERROR)
Notifications.Bus.notify(notification, module.project)
return null
}
fun createResourcesRoot(): VirtualFile? {
val contentRoot = ModuleRootManager.getInstance(module).contentRoots.singleOrNull()
?: return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.multiple.content.roots.for.module", module.name))
@NonNls val resourcesDirName = "resources"
if (contentRoot.findChild(resourcesDirName) != null) {
return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.folder.already.exists",
resourcesDirName, contentRoot.path))
}
if (ProjectFileIndex.getInstance(module.project).isInSource(contentRoot)) {
return reportError(DevKitBundle.message("action.DevKit.NewMessageBundle.error.message.under.sources.root", contentRoot.path))
}
return runWriteAction {
val resourcesDir = contentRoot.createChildDirectory(this, resourcesDirName)
ModuleRootModificationUtil.updateModel(module) {
it.contentEntries.single().addSourceFolder(resourcesDir, JavaResourceRootType.RESOURCE)
}
resourcesDir
}
}
val resourcesRoot = ModuleRootManager.getInstance(module).getSourceRoots(JavaResourceRootType.RESOURCE).firstOrNull()
?: createResourcesRoot()
?: return null
return PsiManager.getInstance(module.project).findDirectory(resourcesRoot)
}
override fun isAvailable(dataContext: DataContext): Boolean {
if (!super.isAvailable(dataContext)) {
return false
}
if (!PsiUtil.isIdeaProject(dataContext.getData(CommonDataKeys.PROJECT))) return false
return CreateTemplateInPackageAction.isAvailable(dataContext, JavaModuleSourceRootTypes.SOURCES,
Predicate { JavaCreateTemplateInPackageAction.doCheckPackageExists(it) })
}
override fun startInWriteAction(): Boolean {
return false
}
override fun getErrorTitle(): String {
return DevKitBundle.message("action.DevKit.NewMessageBundle.error.title.cannot.create.new.message.bundle")
}
override fun getActionName(directory: PsiDirectory?, newName: String?): String {
return DevKitBundle.message("action.DevKit.NewMessageBundle.action.name.create.new.message.bundle", newName)
}
}
@Suppress("HardCodedStringLiteral")
internal fun generateDefaultBundleName(module: Module): String {
val nameWithoutPrefix = module.name.removePrefix("intellij.").removeSuffix(".impl")
val commonGroupNames = listOf("platform", "vcs", "tools", "clouds")
val commonPrefix = commonGroupNames.find { nameWithoutPrefix.startsWith("$it.") }
val shortenedName = if (commonPrefix != null) nameWithoutPrefix.removePrefix("$commonPrefix.") else nameWithoutPrefix
return shortenedName.split(".").joinToString("") { StringUtil.capitalize(it) } + "Bundle"
}
| plugins/devkit/devkit-core/src/actions/NewMessageBundleAction.kt | 1750823377 |
package com.intellij.openapi.editor.colors.impl
import com.intellij.util.messages.Topic
interface EditorColorsManagerListener {
fun schemesReloaded()
companion object {
@JvmField
val TOPIC = Topic(EditorColorsManagerListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN, true)
}
} | platform/platform-impl/src/com/intellij/openapi/editor/colors/impl/EditorColorsManagerListener.kt | 1286150068 |
// WITH_RUNTIME
fun foo() {
val foo: String? = null
foo?.let<caret> {
text ->
text.length
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/letWithParameter.kt | 1095678269 |
package com.zhou.android.kotlin
import android.content.Context
import android.graphics.Canvas
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import com.zhou.android.R
import com.zhou.android.common.BaseActivity
import com.zhou.android.common.CommonRecyclerAdapter
import com.zhou.android.common.PaddingItemDecoration
import kotlinx.android.synthetic.main.activity_recycler_view.*
import java.util.*
/**
* 长按拖拽 RV
* Created by mxz on 2020/5/29.
*/
class AnimRecyclerActivity : BaseActivity() {
private val data = arrayListOf<String>()
private lateinit var simpleAdapter: CommonRecyclerAdapter<String, CommonRecyclerAdapter.ViewHolder>
override fun setContentView() {
setContentView(R.layout.activity_recycler_view)
}
override fun init() {
for (i in 1..40) {
data.add("example $i")
}
simpleAdapter = object : CommonRecyclerAdapter<String, CommonRecyclerAdapter.ViewHolder>(this, data) {
override fun onBind(holder: ViewHolder, item: String, pos: Int) {
holder.getView<TextView>(R.id.text).text = item
}
override fun getViewHolder(context: Context, parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.layout_shape_text, parent, false)
return ViewHolder(view)
}
}
recyclerView.apply {
layoutManager = LinearLayoutManager(this@AnimRecyclerActivity, LinearLayoutManager.VERTICAL, false)
addItemDecoration(PaddingItemDecoration(this@AnimRecyclerActivity, 20, 12, 20, 0))
adapter = simpleAdapter
}
val itemHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int {
return makeMovementFlags(ItemTouchHelper.UP.or(ItemTouchHelper.DOWN),
ItemTouchHelper.LEFT)
}
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
simpleAdapter.notifyItemMoved(viewHolder?.adapterPosition
?: 0, target?.adapterPosition ?: 0)
Collections.swap(data, viewHolder?.adapterPosition ?: 0, target?.adapterPosition
?: 0)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
val p = viewHolder?.adapterPosition ?: 0
data.removeAt(p)
simpleAdapter.notifyItemRemoved(p)
}
override fun canDropOver(recyclerView: RecyclerView?, current: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?) = true
override fun isLongPressDragEnabled(): Boolean = true
override fun isItemViewSwipeEnabled(): Boolean = true
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) {
super.clearView(recyclerView, viewHolder)
viewHolder?.itemView?.apply {
scaleX = 1.0f
scaleY = 1.0f
}
}
override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
viewHolder?.itemView?.apply {
if (isCurrentlyActive) {
translationX = 60f
scaleX = 1.2f
scaleY = 1.2f
} else {
translationX = 0f
scaleX = 1.0f
scaleY = 1.0f
}
}
} else
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
})
itemHelper.attachToRecyclerView(recyclerView)
}
override fun addListener() {
}
} | app/src/main/java/com/zhou/android/kotlin/AnimRecyclerActivity.kt | 661850216 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereFoundElementInfo
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlSessionService.Companion.RECORDER_CODE
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.StatisticsEventLogProviderUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.NonUrgentExecutor
import kotlin.math.round
internal class SearchEverywhereMLStatisticsCollector {
private val loggerProvider = StatisticsEventLogProviderUtil.getEventLogProvider(RECORDER_CODE)
fun onItemSelected(project: Project?, seSessionId: Int, searchIndex: Int,
experimentGroup: Int, orderByMl: Boolean,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
selectedIndices: IntArray,
closePopup: Boolean,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val data = arrayListOf<Pair<String, Any>>(
CLOSE_POPUP_KEY to closePopup,
EXPERIMENT_GROUP to experimentGroup,
ORDER_BY_ML_GROUP to orderByMl
)
reportElements(project, SESSION_FINISHED, seSessionId, searchIndex, elementIdProvider, context, cache, data, selectedIndices, elementsProvider)
}
fun onSearchFinished(project: Project?, seSessionId: Int, searchIndex: Int,
experimentGroup: Int, orderByMl: Boolean,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val additional = listOf(
CLOSE_POPUP_KEY to true,
EXPERIMENT_GROUP to experimentGroup,
ORDER_BY_ML_GROUP to orderByMl
)
reportElements(project, SESSION_FINISHED, seSessionId, searchIndex, elementIdProvider, context, cache, additional, EMPTY_ARRAY, elementsProvider)
}
fun onSearchRestarted(project: Project?, seSessionId: Int, searchIndex: Int,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
cache: SearchEverywhereMlSearchState,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
reportElements(project, SEARCH_RESTARTED, seSessionId, searchIndex, elementIdProvider, context, cache, emptyList(), EMPTY_ARRAY, elementsProvider)
}
private fun reportElements(project: Project?, eventId: String,
seSessionId: Int, searchIndex: Int,
elementIdProvider: SearchEverywhereMlItemIdProvider,
context: SearchEverywhereMLContextInfo,
state: SearchEverywhereMlSearchState,
additional: List<Pair<String, Any>>,
selectedElements: IntArray,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
val elements = elementsProvider.invoke()
NonUrgentExecutor.getInstance().execute {
val data = hashMapOf<String, Any>()
data[PROJECT_OPENED_KEY] = project != null
data[SESSION_ID_LOG_DATA_KEY] = seSessionId
data[SEARCH_INDEX_DATA_KEY] = searchIndex
data[TOTAL_NUMBER_OF_ITEMS_DATA_KEY] = elements.size
data[SE_TAB_ID_KEY] = state.tabId
data[SEARCH_START_TIME_KEY] = state.searchStartTime
data[TYPED_SYMBOL_KEYS] = state.keysTyped
data[TYPED_BACKSPACES_DATA_KEY] = state.backspacesTyped
data[REBUILD_REASON_KEY] = state.searchStartReason
data.putAll(additional)
data.putAll(context.features)
if (selectedElements.isNotEmpty()) {
data[SELECTED_INDEXES_DATA_KEY] = selectedElements.map { it.toString() }
data[SELECTED_ELEMENTS_DATA_KEY] = selectedElements.map {
if (it < elements.size) {
val element = elements[it].element
if (element is GotoActionModel.MatchedValue) {
return@map elementIdProvider.getId(element)
}
}
return@map -1
}
}
val actionManager = ActionManager.getInstance()
data[COLLECTED_RESULTS_DATA_KEY] = elements.take(REPORTED_ITEMS_LIMIT).map {
val result: HashMap<String, Any> = hashMapOf(
CONTRIBUTOR_ID_KEY to it.contributor.searchProviderId
)
if (it.element is GotoActionModel.MatchedValue) {
val elementId = elementIdProvider.getId(it.element)
val itemInfo = state.getElementFeatures(elementId, it.element, it.contributor, state.queryLength)
if (itemInfo.features.isNotEmpty()) {
result[FEATURES_DATA_KEY] = itemInfo.features
}
state.getMLWeightIfDefined(elementId)?.let { score ->
result[ML_WEIGHT_KEY] = roundDouble(score)
}
itemInfo.id.let { id ->
result[ID_KEY] = id
}
if (it.element.value is GotoActionModel.ActionWrapper) {
val action = it.element.value.action
result[ACTION_ID_KEY] = actionManager.getId(action) ?: action.javaClass.name
}
}
result
}
loggerProvider.logger.logAsync(GROUP, eventId, data, false)
}
}
companion object {
private val GROUP = EventLogGroup("mlse.log", 5)
private val EMPTY_ARRAY = IntArray(0)
private const val REPORTED_ITEMS_LIMIT = 100
// events
private const val SESSION_FINISHED = "sessionFinished"
private const val SEARCH_RESTARTED = "searchRestarted"
private const val ORDER_BY_ML_GROUP = "orderByMl"
private const val EXPERIMENT_GROUP = "experimentGroup"
// context fields
private const val PROJECT_OPENED_KEY = "projectOpened"
private const val SE_TAB_ID_KEY = "seTabId"
private const val CLOSE_POPUP_KEY = "closePopup"
private const val SEARCH_START_TIME_KEY = "startTime"
private const val REBUILD_REASON_KEY = "rebuildReason"
private const val SESSION_ID_LOG_DATA_KEY = "sessionId"
private const val SEARCH_INDEX_DATA_KEY = "searchIndex"
private const val TYPED_SYMBOL_KEYS = "typedSymbolKeys"
private const val TOTAL_NUMBER_OF_ITEMS_DATA_KEY = "totalItems"
private const val TYPED_BACKSPACES_DATA_KEY = "typedBackspaces"
private const val COLLECTED_RESULTS_DATA_KEY = "collectedItems"
private const val SELECTED_INDEXES_DATA_KEY = "selectedIndexes"
private const val SELECTED_ELEMENTS_DATA_KEY = "selectedIds"
// item fields
internal const val ID_KEY = "id"
internal const val ACTION_ID_KEY = "actionId"
internal const val FEATURES_DATA_KEY = "features"
internal const val CONTRIBUTOR_ID_KEY = "contributorId"
internal const val ML_WEIGHT_KEY = "mlWeight"
private fun roundDouble(value: Double): Double {
if (!value.isFinite()) return -1.0
return round(value * 100000) / 100000
}
}
} | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMLStatisticsCollector.kt | 304114153 |
// WITH_RUNTIME
fun main(args: Array<String>) {
val map = hashMapOf(1 to 1)
for (<caret>entry in map) {
val key = entry.key
val value = entry.value
println(key)
println(value)
}
} | plugins/kotlin/idea/tests/testData/intentions/iterationOverMap/Simple.kt | 4253043920 |
package eu.kanade.tachiyomi.data.database.models
import java.io.Serializable
interface Manga : Serializable {
var id: Long?
var source: String
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var favorite: Boolean
var last_update: Long
var initialized: Boolean
var viewer: Int
var chapter_flags: Int
var unread: Int
var category: Int
fun copyFrom(other: Manga) {
if (other.author != null)
author = other.author
if (other.artist != null)
artist = other.artist
if (other.description != null)
description = other.description
if (other.genre != null)
genre = other.genre
if (other.thumbnail_url != null)
thumbnail_url = other.thumbnail_url
status = other.status
initialized = true
}
fun setChapterOrder(order: Int) {
setFlags(order, SORT_MASK)
}
private fun setFlags(flag: Int, mask: Int) {
chapter_flags = chapter_flags and mask.inv() or (flag and mask)
}
fun sortDescending(): Boolean {
return chapter_flags and SORT_MASK == SORT_DESC
}
// Used to display the chapter's title one way or another
var displayMode: Int
get() = chapter_flags and DISPLAY_MASK
set(mode) = setFlags(mode, DISPLAY_MASK)
var readFilter: Int
get() = chapter_flags and READ_MASK
set(filter) = setFlags(filter, READ_MASK)
var downloadedFilter: Int
get() = chapter_flags and DOWNLOADED_MASK
set(filter) = setFlags(filter, DOWNLOADED_MASK)
var sorting: Int
get() = chapter_flags and SORTING_MASK
set(sort) = setFlags(sort, SORTING_MASK)
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
const val SORT_DESC = 0x00000000
const val SORT_ASC = 0x00000001
const val SORT_MASK = 0x00000001
// Generic filter that does not filter anything
const val SHOW_ALL = 0x00000000
const val SHOW_UNREAD = 0x00000002
const val SHOW_READ = 0x00000004
const val READ_MASK = 0x00000006
const val SHOW_DOWNLOADED = 0x00000008
const val SHOW_NOT_DOWNLOADED = 0x00000010
const val DOWNLOADED_MASK = 0x00000018
const val SORTING_SOURCE = 0x00000000
const val SORTING_NUMBER = 0x00000100
const val SORTING_MASK = 0x00000100
const val DISPLAY_NAME = 0x00000000
const val DISPLAY_NUMBER = 0x00100000
const val DISPLAY_MASK = 0x00100000
fun create(source: String): Manga = MangaImpl().apply {
this.source = source
}
fun create(pathUrl: String, source: String = "TEST"): Manga = MangaImpl().apply {
url = pathUrl
this.source = source
}
}
} | app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt | 1165358014 |
// 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.application.options.CodeStyle
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState
import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor
import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import javax.swing.JComponent
import kotlin.properties.Delegates
class TrailingCommaInspection(
@JvmField
var addCommaWarning: Boolean = false
) : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() {
override val recursively: Boolean = false
private var useTrailingComma by Delegates.notNull<Boolean>()
override fun process(trailingCommaContext: TrailingCommaContext) {
val element = trailingCommaContext.ktElement
val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings
useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element)
when (trailingCommaContext.state) {
TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> {
checkCommaPosition(element)
checkLineBreaks(element)
}
else -> Unit
}
checkTrailingComma(trailingCommaContext)
}
private fun checkLineBreaks(commaOwner: KtElement) {
val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) {
first.nextSibling?.let {
registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION)
}
}
val last = TrailingCommaHelper.elementAfterLastElement(commaOwner)
if (last?.prevLeaf(true)?.isLineBreak() == false) {
registerProblemForLineBreak(
commaOwner,
last,
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
}
private fun checkCommaPosition(commaOwner: KtElement) {
for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) {
reportProblem(
invalidComma,
KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"),
KotlinBundle.message("inspection.trailing.comma.fix.comma.position")
)
}
}
private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) {
val commaOwner = trailingCommaContext.ktElement
val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return
when (trailingCommaContext.state) {
TrailingCommaState.MISSING -> {
if (!trailingCommaAllowedInModule(commaOwner)) return
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"),
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
TrailingCommaState.REDUNDANT -> {
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
checkTrailingCommaSettings = false,
)
}
else -> Unit
}
}
private fun reportProblem(
commaOrElement: PsiElement,
message: String,
fixMessage: String,
highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
checkTrailingCommaSettings: Boolean = true,
) {
val commaOwner = commaOrElement.parent as KtElement
// case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list
val problemOwner = commonParent(commaOwner, commaOrElement)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemOwner,
message,
highlightTypeWithAppliedCondition,
commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset),
createQuickFix(fixMessage, commaOwner),
)
}
}
private fun registerProblemForLineBreak(
commaOwner: KtElement,
elementForTextRange: PsiElement,
highlightType: ProblemHighlightType,
) {
val problemElement = commonParent(commaOwner, elementForTextRange)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemElement,
KotlinBundle.message("inspection.trailing.comma.missing.line.break"),
highlightTypeWithAppliedCondition,
TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset),
createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner),
)
}
}
private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement =
PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange)
?: throw KotlinExceptionWithAttachments("Common parent not found")
.withAttachment("commaOwner", commaOwner.text)
.withAttachment("commaOwnerRange", commaOwner.textRange)
.withAttachment("elementForTextRange", elementForTextRange.text)
.withAttachment("elementForTextRangeRange", elementForTextRange.textRange)
.withAttachment("parent", commaOwner.parent.text)
.withAttachment("parentRange", commaOwner.parent.textRange)
private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when {
ApplicationManager.getApplication().isUnitTestMode -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING
condition -> this
else -> ProblemHighlightType.INFORMATION
}
private fun createQuickFix(
fixMessage: String,
commaOwner: KtElement,
): LocalQuickFix = object : LocalQuickFix {
val commaOwnerPointer = commaOwner.createSmartPointer()
override fun getFamilyName(): String = fixMessage
override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) {
val element = commaOwnerPointer.element ?: return
val range = createFormatterTextRange(element)
val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile))
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true
CodeStyle.doWithTemporarySettings(project, settings, Runnable {
CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset)
})
}
}
private fun createFormatterTextRange(commaOwner: KtElement): TextRange {
val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner
val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner
return TextRange.create(startElement.startOffset, endElement.endOffset)
}
private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange
get() {
val textRange = textRange
if (isComma) return textRange
return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let {
TextRange.create(it - 1, it).intersection(textRange)
} ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset)
}
}
override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel(
KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"),
this,
"addCommaWarning",
)
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt | 227863231 |
// 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.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class JavaCollectionsStaticMethodInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return dotQualifiedExpressionVisitor(fun(expression) {
val (methodName, firstArg) = getTargetMethodOnMutableList(expression) ?: return
holder.registerProblem(
expression,
KotlinBundle.message("java.collections.static.method.call.should.be.replaced.with.kotlin.stdlib"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithStdLibFix(methodName, firstArg.text)
)
})
}
companion object {
fun getTargetMethodOnImmutableList(expression: KtDotQualifiedExpression) =
getTargetMethod(expression) { isListOrSubtype() && !isMutableListOrSubtype() }
private fun getTargetMethodOnMutableList(expression: KtDotQualifiedExpression) =
getTargetMethod(expression) { isMutableListOrSubtype() }
private fun getTargetMethod(
expression: KtDotQualifiedExpression,
isValidFirstArgument: KotlinType.() -> Boolean
): Pair<String, KtValueArgument>? {
val callExpression = expression.callExpression ?: return null
val args = callExpression.valueArguments
val firstArg = args.firstOrNull() ?: return null
val context = expression.analyze(BodyResolveMode.PARTIAL)
if (firstArg.getArgumentExpression()?.getType(context)?.isValidFirstArgument() != true) return null
val descriptor = expression.getResolvedCall(context)?.resultingDescriptor as? JavaMethodDescriptor ?: return null
val fqName = descriptor.importableFqName?.asString() ?: return null
if (!canReplaceWithStdLib(expression, fqName, args)) return null
val methodName = fqName.split(".").last()
return methodName to firstArg
}
private fun canReplaceWithStdLib(expression: KtDotQualifiedExpression, fqName: String, args: List<KtValueArgument>): Boolean {
if (!fqName.startsWith("java.util.Collections.")) return false
val size = args.size
return when (fqName) {
"java.util.Collections.fill" -> checkApiVersion(ApiVersion.KOTLIN_1_2, expression) && size == 2
"java.util.Collections.reverse" -> size == 1
"java.util.Collections.shuffle" -> checkApiVersion(ApiVersion.KOTLIN_1_2, expression) && (size == 1 || size == 2)
"java.util.Collections.sort" -> {
size == 1 || (size == 2 && args.getOrNull(1)?.getArgumentExpression() is KtLambdaExpression)
}
else -> false
}
}
private fun checkApiVersion(requiredVersion: ApiVersion, expression: KtDotQualifiedExpression): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(expression) ?: return true
return module.languageVersionSettings.apiVersion >= requiredVersion
}
}
}
private fun KotlinType.isMutableList() =
constructor.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.mutableList
private fun KotlinType.isMutableListOrSubtype(): Boolean {
return isMutableList() || constructor.supertypes.reversed().any { it.isMutableList() }
}
private fun KotlinType.isList() =
constructor.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.list
private fun KotlinType.isListOrSubtype(): Boolean {
return isList() || constructor.supertypes.reversed().any { it.isList() }
}
private class ReplaceWithStdLibFix(private val methodName: String, private val receiver: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.std.lib.fix.text", receiver, methodName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtDotQualifiedExpression ?: return
val callExpression = expression.callExpression ?: return
val valueArguments = callExpression.valueArguments
val firstArg = valueArguments.getOrNull(0)?.getArgumentExpression() ?: return
val secondArg = valueArguments.getOrNull(1)?.getArgumentExpression()
val factory = KtPsiFactory(project)
val newExpression = if (secondArg != null) {
if (methodName == "sort") {
factory.createExpressionByPattern("$0.sortWith(Comparator $1)", firstArg, secondArg.text)
} else {
factory.createExpressionByPattern("$0.$methodName($1)", firstArg, secondArg)
}
} else {
factory.createExpressionByPattern("$0.$methodName()", firstArg)
}
expression.replace(newExpression)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaCollectionsStaticMethodInspection.kt | 2132810045 |
// PROBLEM: none
// WITH_RUNTIME
fun test(x: Any) {
val s = run {
<caret>x as? String ?: return
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/safeCastWithReturn/lambdaLastStatement.kt | 3945816619 |
import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1
// Check permutation order. Each is greater than the last
var orderOk = true
val uniqueMap: MutableMap<String, Int> = HashMap()
uniqueMap[s] = 1
while (next(s).also { s = it }.compareTo("0") != 0) {
count++
if (s.toLong() < sPrev.toLong()) {
orderOk = false
}
uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
sPrev = s
}
println(" Order: OK = $orderOk")
// Test last permutation
val reverse = StringBuilder(sOrig).reverse().toString()
println(" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}")
// Check permutations unique
var unique = true
for (key in uniqueMap.keys) {
if (uniqueMap[key]!! > 1) {
unique = false
}
}
println(" Permutations unique: OK = $unique")
// Check expected count.
val charMap: MutableMap<Char, Int> = HashMap()
for (c in sOrig.toCharArray()) {
charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
}
var permCount = factorial(sOrig.length.toLong())
for (c in charMap.keys) {
permCount /= factorial(charMap[c]!!.toLong())
}
println(" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}")
}
private fun factorial(n: Long): Long {
var fact: Long = 1
for (num in 2..n) {
fact *= num
}
return fact
}
private fun next(s: String): String {
val sb = StringBuilder()
var index = s.length - 1
// Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
while (index > 0 && s[index - 1] >= s[index]) {
index--
}
// Reached beginning. No next number.
if (index == 0) {
return "0"
}
// Find digit on the right that is both more than it, and closest to it.
var index2 = index
for (i in index + 1 until s.length) {
if (s[i] < s[index2] && s[i] > s[index - 1]) {
index2 = i
}
}
// Found data, now build string
// Beginning of String
if (index > 1) {
sb.append(s.subSequence(0, index - 1))
}
// Append found, place next
sb.append(s[index2])
// Get remaining characters
val chars: MutableList<Char> = ArrayList()
chars.add(s[index - 1])
for (i in index until s.length) {
if (i != index2) {
chars.add(s[i])
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort()
for (c in chars) {
sb.append(c)
}
return sb.toString()
}
| Next_highest_int_from_digits/Kotlin/src/NextHighestIntFromDigits.kt | 1153688797 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.assistant.actions.model.actions
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
@XmlRootElement(name="actions")
data class ActionsRoot(
@set:XmlElement(name="action")
var actions: List<Action> = mutableListOf(),
@set:XmlElement(name="entity-set")
var entitySets: List<EntitySet> = mutableListOf(),
)
//
// Children of ActionsRoot
//
data class Action(
@set:XmlAttribute(required = true)
var intentName: String? = null,
@set:XmlAttribute
var queryPatterns: String? = null,
@set:XmlElement(name="fulfillment", required = true)
var fulfillments: List<Fulfillment> = mutableListOf(),
@set:XmlElement(name="parameter", required = true)
var parameters: List<Parameter> = mutableListOf(),
@set:XmlElement(name="entity-set", required = false)
var entitySets: List<EntitySet> = mutableListOf(),
)
data class EntitySet(
@set:XmlAttribute(required = true)
var entitySetId: String? = null,
@set:XmlElement(name="entity", required = true)
var entities: List<Entity> = mutableListOf(),
)
//
// Children of Action
//
data class Fulfillment(
@set:XmlAttribute(required = true)
var urlTemplate: String? = null,
@set:XmlAttribute
var fulfillmentMode: String? = null,
@set:XmlAttribute
var requiredForegroundActivity: String? = null,
@set:XmlElement(name="parameter-mapping")
var parameterMappings: List<ParameterMapping> = mutableListOf(),
)
data class Parameter(
@set:XmlAttribute(required = true)
var name: String? = null,
@set:XmlAttribute
var type: String? = null,
@set:XmlElement(name = "entity-set-reference")
var entitySetReference: EntitySetReference? = null,
)
//
// Children of Fulfillment
//
data class ParameterMapping(
@set:XmlAttribute(required = true)
var intentParameter: String? = null,
@set:XmlAttribute(required = true)
var urlParameter: String? = null,
@set:XmlAttribute
var required: String? = null,
@set:XmlAttribute
var entityMatchRequired: String? = null,
)
//
// Children of Parameter
//
data class EntitySetReference(
@set:XmlAttribute
var entitySetId: String? = null,
@set:XmlAttribute
var urlFilter: String? = null,
)
//
// Children of EntitySet
//
data class Entity(
@set:XmlAttribute
var name: String? = null,
@set:XmlAttribute
var alternateName: String? = null,
@set:XmlAttribute
var sameAs: String? = null,
@set:XmlAttribute
var identifier: String? = null,
@set:XmlAttribute
var url: String? = null,
)
| src/main/kotlin/com/google/assistant/actions/model/actions/ActionsModel.kt | 4088521915 |
// 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.core.platform.impl
import com.intellij.execution.PsiLocation
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JsCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.framework.JSLibraryKind
import org.jetbrains.kotlin.idea.framework.JSLibraryStdDescription
import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil
import org.jetbrains.kotlin.idea.js.KotlinJSRunConfigurationData
import org.jetbrains.kotlin.idea.js.KotlinJSRunConfigurationDataProvider
import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling
import org.jetbrains.kotlin.idea.platform.getGenericTestIcon
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.idea.run.multiplatform.KotlinMultiplatformRunLocationsProvider
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.utils.PathUtil
import org.jetbrains.kotlin.utils.ifEmpty
import javax.swing.Icon
class JsIdePlatformKindTooling : IdePlatformKindTooling() {
companion object {
private const val MAVEN_OLD_JS_STDLIB_ID = "kotlin-js-library"
}
override val kind = JsIdePlatformKind
override fun compilerArgumentsForProject(project: Project) = Kotlin2JsCompilerArgumentsHolder.getInstance(project).settings
override val mavenLibraryIds = listOf(PathUtil.JS_LIB_NAME, MAVEN_OLD_JS_STDLIB_ID)
override val gradlePluginId = "kotlin-platform-js"
override val gradlePlatformIds: List<KotlinPlatform> get() = listOf(KotlinPlatform.JS)
override val libraryKind = JSLibraryKind
override fun getLibraryDescription(project: Project) = JSLibraryStdDescription(project)
override fun getLibraryVersionProvider(project: Project) = { library: Library ->
JsLibraryStdDetectionUtil.getJsLibraryStdVersion(library, project)
}
override fun getTestIcon(
declaration: KtNamedDeclaration,
descriptorProvider: () -> DeclarationDescriptor?,
includeSlowProviders: Boolean?
): Icon? = getGenericTestIcon(declaration, descriptorProvider) {
val contexts by lazy { computeConfigurationContexts(declaration) }
val runConfigData = RunConfigurationProducer
.getProducers(declaration.project)
.asSequence()
.filterIsInstance<KotlinJSRunConfigurationDataProvider<*>>()
.filter { it.isForTests }
.flatMap { provider -> contexts.map { context -> provider.getConfigurationData(context) } }
.firstOrNull { it != null }
?: return@getGenericTestIcon null
val location = if (runConfigData is KotlinJSRunConfigurationData) {
FileUtil.toSystemDependentName(runConfigData.jsOutputFilePath)
} else {
declaration.containingKtFile.packageFqName.asString()
}
return@getGenericTestIcon SmartList(location)
}
override fun acceptsAsEntryPoint(function: KtFunction): Boolean {
val contexts by lazy { computeConfigurationContexts(function) }
return RunConfigurationProducer
.getProducers(function.project)
.asSequence()
.filterIsInstance<KotlinJSRunConfigurationDataProvider<*>>()
.filter { !it.isForTests }
.flatMap { provider -> contexts.map { context -> provider.getConfigurationData(context) } }
.any { it != null }
}
private fun computeConfigurationContexts(declaration: KtNamedDeclaration): Sequence<ConfigurationContext> {
val location = PsiLocation(declaration)
return KotlinMultiplatformRunLocationsProvider().getAlternativeLocations(location).map {
ConfigurationContext.createEmptyContextForLocation(it)
}.ifEmpty { listOf(ConfigurationContext.createEmptyContextForLocation(location)) }.asSequence()
}
} | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/platform/JsIdePlatformKindTooling.kt | 2155133165 |
/*
* Copyright 2010-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.
*/
import kotlinx.cinterop.*
import kotlin.native.Platform
fun enableMemoryChecker() {
Platform.isMemoryLeakCheckerActive = true
}
fun leakMemory() {
StableRef.create(Any())
}
| backend.native/tests/interop/memory_leaks/lib.kt | 3150372276 |
/*
* 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.coroutines.native.internal
// TODO: support coroutines debugging in Kotlin/Native.
import kotlin.coroutines.Continuation
import kotlin.coroutines.intrinsics.*
/**
* This probe is invoked when coroutine is being created and it can replace completion
* with its own wrapped object to intercept completion of this coroutine.
*
* This probe is invoked from stdlib implementation of [createCoroutineUnintercepted] function.
*
* Once created, coroutine is repeatedly [resumed][probeCoroutineResumed] and [suspended][probeCoroutineSuspended],
* until it is complete. On completion, the object that was returned by this probe is invoked.
*
* ```
* +-------+ probeCoroutineCreated +-----------+
* | START | ---------------------->| SUSPENDED |
* +-------+ +-----------+
* probeCoroutineResumed | ^ probeCoroutineSuspended
* V |
* +------------+ completion invoked +-----------+
* | RUNNING | ------------------->| COMPLETED |
* +------------+ +-----------+
* ```
*
* While the coroutine is resumed and suspended, it is represented by the pointer to its `frame`
* which always extends [BaseContinuationImpl] and represents a pointer to the topmost frame of the
* coroutine. Each [BaseContinuationImpl] object has [completion][BaseContinuationImpl.completion] reference
* that points either to another frame (extending [BaseContinuationImpl]) or to the completion object
* that was returned by this `probeCoroutineCreated` function.
*
* When coroutine is [suspended][probeCoroutineSuspended], then it is later [resumed][probeCoroutineResumed]
* with a reference to the same frame. However, while coroutine is running it can unwind its frames and
* invoke other suspending functions, so its next suspension can happen with a different frame pointer.
*/
@SinceKotlin("1.3")
internal fun <T> probeCoroutineCreated(completion: Continuation<T>): Continuation<T> {
return completion
}
/**
* This probe is invoked when coroutine is resumed using [Continuation.resumeWith].
*
* This probe is invoked from stdlib implementation of [BaseContinuationImpl.resumeWith] function.
*
* Coroutines machinery implementation guarantees that the actual [frame] instance extends
* [BaseContinuationImpl] class, despite the fact that the declared type of [frame]
* parameter in this function is `Continuation<*>`. See [probeCoroutineCreated] for details.
*/
@Suppress("UNUSED_PARAMETER")
@SinceKotlin("1.3")
internal fun probeCoroutineResumed(frame: Continuation<*>) {
}
/**
* This probe is invoked when coroutine is suspended using [suspendCoroutineUninterceptedOrReturn], that is
* when the corresponding `block` returns [COROUTINE_SUSPENDED].
*
* This probe is invoked from compiler-generated intrinsic for [suspendCoroutineUninterceptedOrReturn] function.
*
* Coroutines machinery implementation guarantees that the actual [frame] instance extends
* [BaseContinuationImpl] class, despite the fact that the declared type of [frame]
* parameter in this function is `Continuation<*>`. See [probeCoroutineCreated] for details.
*/
@Suppress("UNUSED_PARAMETER")
@SinceKotlin("1.3")
internal fun probeCoroutineSuspended(frame: Continuation<*>) {
}
| runtime/src/main/kotlin/kotlin/coroutines/DebugProbes.kt | 2263558806 |
// 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.codeInliner
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.psi.BuilderByPattern
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.ImportPath
private val POST_INSERTION_ACTION: Key<(KtElement) -> Unit> = Key("POST_INSERTION_ACTION")
private val PRE_COMMIT_ACTION: Key<(KtElement) -> Unit> = Key("PRE_COMMIT_ACTION_KEY")
internal class MutableCodeToInline(
var mainExpression: KtExpression?,
val statementsBefore: MutableList<KtExpression>,
val fqNamesToImport: MutableCollection<ImportPath>,
val alwaysKeepMainExpression: Boolean,
var extraComments: CommentHolder?,
) {
fun <TElement : KtElement> addPostInsertionAction(element: TElement, action: (TElement) -> Unit) {
assert(element in this)
@Suppress("UNCHECKED_CAST")
element.putCopyableUserData(POST_INSERTION_ACTION, action as (KtElement) -> Unit)
}
fun <TElement : KtElement> addPreCommitAction(element: TElement, action: (TElement) -> Unit) {
@Suppress("UNCHECKED_CAST")
element.putCopyableUserData(PRE_COMMIT_ACTION, action as (KtElement) -> Unit)
}
fun performPostInsertionActions(elements: Collection<PsiElement>) {
for (element in elements) {
element.forEachDescendantOfType<KtElement> { performAction(it, POST_INSERTION_ACTION) }
}
}
fun addExtraComments(commentHolder: CommentHolder) {
extraComments = extraComments?.merge(commentHolder) ?: commentHolder
}
fun BuilderByPattern<KtExpression>.appendExpressionsFromCodeToInline(postfixForMainExpression: String = "") {
for (statement in statementsBefore) {
appendExpression(statement)
appendFixedText("\n")
}
if (mainExpression != null) {
appendExpression(mainExpression)
appendFixedText(postfixForMainExpression)
}
}
fun replaceExpression(oldExpression: KtExpression, newExpression: KtExpression): KtExpression {
assert(oldExpression in this)
if (oldExpression == mainExpression) {
mainExpression = newExpression
return newExpression
}
val index = statementsBefore.indexOf(oldExpression)
if (index >= 0) {
statementsBefore[index] = newExpression
return newExpression
}
return oldExpression.replace(newExpression) as KtExpression
}
val expressions: Collection<KtExpression>
get() = statementsBefore + listOfNotNull(mainExpression)
operator fun contains(element: PsiElement): Boolean = expressions.any { it.isAncestor(element) }
}
internal fun CodeToInline.toMutable(): MutableCodeToInline = MutableCodeToInline(
mainExpression?.copied(),
statementsBefore.asSequence().map { it.copied() }.toMutableList(),
fqNamesToImport.toMutableSet(),
alwaysKeepMainExpression,
extraComments,
)
private fun performAction(element: KtElement, actionKey: Key<(KtElement) -> Unit>) {
val action = element.getCopyableUserData(actionKey)
if (action != null) {
element.putCopyableUserData(actionKey, null)
action.invoke(element)
}
}
private fun performPreCommitActions(expressions: Collection<KtExpression>) = expressions.asSequence()
.flatMap { it.collectDescendantsOfType<KtElement> { element -> element.getCopyableUserData(PRE_COMMIT_ACTION) != null } }
.sortedWith(compareByDescending(KtElement::startOffset).thenBy(PsiElement::getTextLength))
.forEach { performAction(it, PRE_COMMIT_ACTION) }
internal fun MutableCodeToInline.toNonMutable(): CodeToInline {
performPreCommitActions(expressions)
return CodeToInline(
mainExpression,
statementsBefore,
fqNamesToImport,
alwaysKeepMainExpression,
extraComments
)
}
internal inline fun <reified T : PsiElement> MutableCodeToInline.collectDescendantsOfType(noinline predicate: (T) -> Boolean = { true }): List<T> {
return expressions.flatMap { it.collectDescendantsOfType({ true }, predicate) }
}
internal inline fun <reified T : PsiElement> MutableCodeToInline.forEachDescendantOfType(noinline action: (T) -> Unit) {
expressions.forEach { it.forEachDescendantOfType(action) }
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt | 3568133017 |
/*
* Copyright (C) 2014 Saúl Díaz
*
* 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.sefford.brender.components
/**
* Abstracts the behavior of a Renderer.
*
* @author Saul Diaz <sefford></sefford>@gmail.com>
*/
interface Renderer<T> {
/**
* Unique ID of the Renderer
*
* @return Renderer ID
*/
val id: Int
/**
* Hooks up the listeners of the Renderer
*/
fun hookUpListeners(renderable: T)
/**
* Renders the view
*
* @param renderable Renderable item to set the info from
* @param position current position of the adapter
* @param first Is first of the list
* @param last is last of the list
*/
fun render(renderable: T, position: Int, first: Boolean, last: Boolean)
/**
* Refreshes the renderer with the payloads it received
*
* @param renderable Renderable item to set the info from
* @param payloads
*/
fun refresh(renderable: T, payloads: List<*>) {
}
/**
* Releases ViewHolder resources
*/
fun clean() {
}
}
| modules/brender-components/src/main/kotlin/com/sefford/brender/components/Renderer.kt | 2619538317 |
package taiwan.no1.app.ssfm.models.data.remote.config
/**
*
* @author jieyi
* @since 5/21/17
*/
class Music3Config : IApiConfig {
companion object {
const val API_REQUEST = "2.0/"
// All basic http api url of KoGou Detail Music.
private const val BASE_URL = "http://ws.audioscrobbler.com/"
}
override fun getApiBaseUrl(): String = BASE_URL
} | app/src/main/kotlin/taiwan/no1/app/ssfm/models/data/remote/config/Music3Config.kt | 627617241 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui
/**
* Unstable API for use only between `compose-ui` modules sharing the same exact version,
* subject to change without notice in major, minor, or patch releases.
*/
@RequiresOptIn(
"Unstable API for use only between compose-ui modules sharing the same exact version, " +
"subject to change without notice in major, minor, or patch releases."
)
@Retention(AnnotationRetention.BINARY)
annotation class InternalComposeUiApi
| compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/InternalComposeUiApi.kt | 1496130158 |
package com.sedsoftware.yaptalker.presentation.feature.userprofile
import com.arellomobile.mvp.MvpView
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
import com.sedsoftware.yaptalker.presentation.base.CanShowErrorMessage
import com.sedsoftware.yaptalker.presentation.model.base.UserProfileModel
interface UserProfileView : MvpView, CanShowErrorMessage {
@StateStrategyType(SkipStrategy::class)
fun displayProfile(profile: UserProfileModel)
@StateStrategyType(AddToEndSingleStrategy::class)
fun updateCurrentUiState(title: String)
}
| app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/userprofile/UserProfileView.kt | 237507279 |
package org.open.openstore.file
/**
* 配置对象用于配置贡献点以及贡献者。使用者可以通过贡献点获取到指定的贡献者,然后从
* 贡献者中获取指定的配置信息,构造可运行对象等
*/
interface IContributConfig {
/**
* 获取指定的属性
*/
fun getAttr(name:String): String?
/**
* 获取此配置的所有配置属性名
*/
fun getAttrNames():Array<String>
/**
* 获取配置名称
*/
fun getName(): String
/**
* 获取唯一id(可用namespace指定)
*/
fun getId():String
/**
* 获取所有子配置
*/
fun getChildren():Array<IContributConfig>
/**
* 获取指定名称的所有子配置
*/
fun getChild(name:String):Array<IContributConfig>
/**
* 获取此配置所在的贡献者
*/
fun getContributor():IContributor
/**
* 获取此配置的父对象:如果此配置直接在贡献者之下声明,则返回IContributor,否则强转成IContributConfig
*/
fun getParent():Any?
/**
* Contributor将调用此方法创建attr指定的可运行对象。构造的对象必须具有空构造函数
*/
fun createExecutable(attr:String):Any?
} | src/main/kotlin/org/open/openstore/file/IContributConfig.kt | 1869759616 |
/*
* 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.emoji2.emojipicker
import android.content.Context
import android.content.res.TypedArray
import androidx.core.content.res.use
import androidx.emoji2.emojipicker.utils.FileCache
import androidx.emoji2.emojipicker.utils.UnicodeRenderableManager
import androidx.emoji2.text.EmojiCompat
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
/**
* A data loader that loads the following objects either from file based caches or from resources.
*
* @property categorizedEmojiData: a list that holds bundled emoji separated by category, filtered
* by renderability check. This is the data source for EmojiPickerView.
*
* @property emojiVariantsLookup: a map of emoji variants in bundled emoji, keyed by the base
* emoji. This allows faster variants lookup.
*/
internal object BundledEmojiListLoader {
private var categorizedEmojiData: List<EmojiDataCategory>? = null
private var emojiVariantsLookup: Map<String, List<String>>? = null
private var primaryEmojiLookup: Map<String, String>? = null
private var deferred: List<Deferred<EmojiDataCategory>>? = null
internal suspend fun load(context: Context) {
val categoryNames = context.resources.getStringArray(R.array.category_names)
val resources = if (UnicodeRenderableManager.isEmoji12Supported())
R.array.emoji_by_category_raw_resources_gender_inclusive
else
R.array.emoji_by_category_raw_resources
val emojiFileCache = FileCache.getInstance(context)
deferred = context.resources
.obtainTypedArray(resources)
.use { ta -> loadEmojiAsync(ta, categoryNames, emojiFileCache, context) }
}
internal suspend fun getCategorizedEmojiData() =
categorizedEmojiData ?: deferred?.awaitAll()?.also {
categorizedEmojiData = it
} ?: throw IllegalStateException("BundledEmojiListLoader.load is not called")
internal suspend fun getEmojiVariantsLookup() =
emojiVariantsLookup ?: getCategorizedEmojiData()
.flatMap { it.emojiDataList }
.filter { it.variants.isNotEmpty() }
.associate { it.emoji to it.variants }
.also { emojiVariantsLookup = it }
internal suspend fun getPrimaryEmojiLookup() =
primaryEmojiLookup ?: getCategorizedEmojiData()
.flatMap { it.emojiDataList }
.filter { it.variants.isNotEmpty() }
.flatMap { it.variants.associateWith { _ -> it.emoji }.entries }
.associate { it.toPair() }
.also { primaryEmojiLookup = it }
private suspend fun loadEmojiAsync(
ta: TypedArray,
categoryNames: Array<String>,
emojiFileCache: FileCache,
context: Context
): List<Deferred<EmojiDataCategory>> = coroutineScope {
(0 until ta.length()).map {
async {
emojiFileCache.getOrPut(getCacheFileName(it)) {
loadSingleCategory(context, ta.getResourceId(it, 0))
}.let { data -> EmojiDataCategory(categoryNames[it], data) }
}
}
}
private fun loadSingleCategory(
context: Context,
resId: Int,
): List<EmojiViewItem> =
context.resources
.openRawResource(resId)
.bufferedReader()
.useLines { it.toList() }
.map { filterRenderableEmojis(it.split(",")) }
.filter { it.isNotEmpty() }
.map { EmojiViewItem(it.first(), it.drop(1)) }
private fun getCacheFileName(categoryIndex: Int) =
StringBuilder().append("emoji.v1.")
.append(if (EmojiCompat.isConfigured()) 1 else 0)
.append(".")
.append(categoryIndex)
.append(".")
.append(if (UnicodeRenderableManager.isEmoji12Supported()) 1 else 0)
.toString()
/**
* To eliminate 'Tofu' (the fallback glyph when an emoji is not renderable), check the
* renderability of emojis and keep only when they are renderable on the current device.
*/
private fun filterRenderableEmojis(emojiList: List<String>) =
emojiList.filter {
UnicodeRenderableManager.isEmojiRenderable(it)
}.toList()
internal data class EmojiDataCategory(
val categoryName: String,
val emojiDataList: List<EmojiViewItem>
)
} | emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/BundledEmojiListLoader.kt | 3110985157 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.projectView.actions
import com.intellij.ide.projectView.impl.ProjectRootsUtil
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
class MarkAsContentRootAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
val module = MarkRootActionBase.getModule(e, files)
if (module == null || files == null) {
e.presentation.isEnabledAndVisible = false
return
}
val fileIndex = ProjectRootManager.getInstance(module.project).fileIndex
e.presentation.isEnabledAndVisible = files.all {
it.isDirectory && fileIndex.isExcluded(it) && ProjectRootsUtil.findExcludeFolder(module, it) == null
}
}
override fun actionPerformed(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return
val module = MarkRootActionBase.getModule(e, files) ?: return
val model = ModuleRootManager.getInstance(module).modifiableModel
files.forEach {
model.addContentEntry(it)
}
MarkRootActionBase.commitModel(module, model)
}
}
| platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkAsContentRootAction.kt | 1198405881 |
// WITH_STDLIB
// IS_APPLICABLE: false
fun foo(list: List<String>): Int? {
var index = 0
<caret>for (s in list) {
val x = s.length * index++
index++
if (x > 0) return x
}
return null
} | plugins/kotlin/idea/tests/testData/intentions/useWithIndex/indexIncrementTwice.kt | 1413541982 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package ppp
class C {
fun foo() {
xx<caret>
}
}
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "() for Any in dependency1", typeText: "Int", icon: "Function"}
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "() for C in dependency2", typeText: "Int", icon: "Function"}
// NOTHING_ELSE
| plugins/kotlin/completion/testData/basic/multifile/MoreSpecificExtensionInDifferentPackage/MoreSpecificExtensionInDifferentPackage.kt | 1276934612 |
// "Convert string to character literal" "false"
// ACTION: Convert to 'buildString' call
// ACTION: Enable a trailing comma by default in the formatter
// ACTION: To raw string literal
// ERROR: Incompatible types: String and Char
fun test(c: Char) {
when (c) {
<caret>".." -> {}
}
}
| plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/incompatibleTypes/char2.kt | 458203266 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.psi.PsiElement
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.psi.KtTypeParameter
class RenameKotlinTypeParameterProcessor : RenameKotlinPsiProcessor() {
override fun canProcessElement(element: PsiElement) = element is KtTypeParameter
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: MutableMap<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element as? KtTypeParameter ?: return
checkRedeclarations(declaration, newName, result)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinTypeParameterProcessor.kt | 1759623281 |
internal annotation class Ann
internal annotation class Foo(@get:Ann val value: String, @get:Ann val value2: String = "test")
| plugins/kotlin/j2k/new/tests/testData/newJ2k/annotations/annotationsOnAnnotationMethod.kt | 122954202 |
package pl.ches.citybikes.presentation.common.base.view
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import pl.ches.citybikes.presentation.common.base.host.HostView
import pl.ches.citybikes.presentation.common.base.host.HostedMvpView
import com.hannesdorfmann.mosby.mvp.MvpPresenter
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateFragment
/**
* @author Michał Seroczyński <[email protected]>
*/
abstract class BaseViewStateFragment<V : HostedMvpView, P : MvpPresenter<V>> : MvpViewStateFragment<V, P>(), HostedMvpView {
override var hostView: HostView? = null
protected abstract val layoutRes: Int
protected abstract fun injectDependencies()
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
hostView = context as HostView
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + " must implement ${HostView::class.java.simpleName}")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(layoutRes, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
injectDependencies()
super.onViewCreated(view, savedInstanceState)
}
}
| app/src/main/kotlin/pl/ches/citybikes/presentation/common/base/view/BaseViewStateFragment.kt | 1896188586 |
package com.kingz.base
interface BaseApiService {
} | base/src/main/java/com/kingz/base/BaseApiService.kt | 2548049554 |
// 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
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import com.intellij.AbstractBundle
@NonNls
private const val BUNDLE = "messages.KotlinNewProjectWizardBundle"
object KotlinNewProjectWizardBundle : AbstractBundle(BUNDLE) {
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/KotlinNewProjectWizardBundle.kt | 1576264495 |
// 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.scripting.gradle
import org.gradle.api.internal.file.IdentityFileResolver
import org.gradle.groovy.scripts.TextResourceScriptSource
import org.gradle.internal.exceptions.LocationAwareException
import org.gradle.internal.resource.UriTextResource
import org.jetbrains.kotlin.idea.scripting.gradle.importing.parsePositionFromException
import org.junit.Test
import kotlin.io.path.*
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class KotlinDslScriptModelTest {
@OptIn(ExperimentalPathApi::class)
@Test
fun testExceptionPositionParsing() {
val file = createTempDirectory("kotlinDslTest") / "build.gradle.kts"
val line = 10
val mockScriptSource = TextResourceScriptSource(UriTextResource("build file", file.toFile(), IdentityFileResolver()))
val mockException = LocationAwareException(RuntimeException(), mockScriptSource, line)
val fromException = parsePositionFromException(mockException.stackTraceToString())
assertNotNull(fromException, "Position should be parsed")
assertEquals(fromException.first, file.toAbsolutePath().toString(), "Wrong file name parsed")
assertEquals(fromException.second.line, line, "Wrong line number parsed")
file.parent.deleteExisting()
}
} | plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/idea/scripting/gradle/KotlinDslScriptModelTest.kt | 745660090 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.favorite.links
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.links.LinksApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinksInteractor
@Module
class LinksFavoriteFragmentModule {
@Provides
fun provideLinksFavoritePresenter(schedulers: Schedulers, linksApi: LinksApi, linksInteractor: LinksInteractor) =
LinksFavoritePresenter(schedulers, linksApi, linksInteractor)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/favorite/links/LinksFavoriteFragmentModule.kt | 3289550986 |
import platform.darwin.*
import platform.Foundation.*
class Z
fun foo() = NSLog("zzz", Z())
| backend.native/tests/compilerChecks/t16.kt | 2294793822 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.highlighter.visitors
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.highlighter.isAnnotationClass
import org.jetbrains.kotlin.idea.highlighter.textAttributesKeyForTypeDeclaration
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.highlighter.NameHighlighter
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors
internal class TypeHighlightingVisitor(
analysisSession: KtAnalysisSession,
holder: AnnotationHolder
) : FirAfterResolveHighlightingVisitor(analysisSession, holder) {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (!NameHighlighter.namesHighlightingEnabled) return
if (expression.isCalleeExpression()) return
val parent = expression.parent
if (parent is KtInstanceExpressionWithLabel) {
// Do nothing: 'super' and 'this' are highlighted as a keyword
return
}
val target = expression.mainReference.resolve() ?: return
if (isAnnotationCall(expression, target)) {
// higlighted by AnnotationEntryHiglightingVisitor
return
}
textAttributesKeyForTypeDeclaration(target)?.let { key ->
if (expression.isConstructorCallReference() && key != Colors.ANNOTATION) {
// Do not highlight constructor call as class reference
return@let
}
highlightName(expression.textRange, key)
}
}
private fun isAnnotationCall(expression: KtSimpleNameExpression, target: PsiElement): Boolean {
val expressionRange = expression.textRange
val isKotlinAnnotation = target is KtPrimaryConstructor && target.parent.isAnnotationClass()
if (!isKotlinAnnotation && !target.isAnnotationClass()) return false
val annotationEntry = PsiTreeUtil.getParentOfType(
expression, KtAnnotationEntry::class.java, /* strict = */false, KtValueArgumentList::class.java
)
return annotationEntry?.atSymbol != null
}
}
private fun KtSimpleNameExpression.isCalleeExpression() =
(parent as? KtCallExpression)?.calleeExpression == this
private fun KtSimpleNameExpression.isConstructorCallReference(): Boolean {
val type = parent as? KtUserType ?: return false
val typeReference = type.parent as? KtTypeReference ?: return false
val constructorCallee = typeReference.parent as? KtConstructorCalleeExpression ?: return false
return constructorCallee.constructorReferenceExpression == this
} | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/highlighter/visitors/TypeHighlightingVisitor.kt | 2953935814 |
// "Create local variable 'foo'" "false"
// ACTION: Convert property initializer to getter
// ACTION: Convert to lazy property
// ACTION: Create property 'foo'
// ACTION: Do not show return expression hints
// ACTION: Rename reference
// ERROR: Unresolved reference: foo
val t: Int = <caret>foo | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/localVariable/onTopLevel.kt | 2922982909 |
// 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.ide.konan.analyzer
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.caches.resolve.resolution
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.di.createContainerForLazyResolve
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.resolve.CodeAnalyzerInitializer
import org.jetbrains.kotlin.resolve.SealedClassInheritorsProvider
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.resolve.konan.platform.NativePlatformAnalyzerServices
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService.Companion.createDeclarationProviderFactory
class NativeResolverForModuleFactory(
private val platformAnalysisParameters: PlatformAnalysisParameters,
private val targetEnvironment: TargetEnvironment,
private val targetPlatform: TargetPlatform
) : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,
moduleContent: ModuleContent<M>,
resolverForProject: ResolverForProject<M>,
languageVersionSettings: LanguageVersionSettings,
sealedInheritorsProvider: SealedClassInheritorsProvider
): ResolverForModule {
val declarationProviderFactory = createDeclarationProviderFactory(
moduleContext.project,
moduleContext.storageManager,
moduleContent.syntheticFiles,
moduleContent.moduleContentScope,
moduleContent.moduleInfo
)
val container = createContainerForLazyResolve(
moduleContext,
declarationProviderFactory,
CodeAnalyzerInitializer.getInstance(moduleContext.project).createTrace(),
moduleDescriptor.platform!!,
NativePlatformAnalyzerServices,
targetEnvironment,
languageVersionSettings
)
var packageFragmentProvider = container.get<ResolveSession>().packageFragmentProvider
val klibPackageFragmentProvider =
NativePlatforms.unspecifiedNativePlatform.idePlatformKind.resolution.createKlibPackageFragmentProvider(
moduleContent.moduleInfo,
moduleContext.storageManager,
languageVersionSettings,
moduleDescriptor
)
if (klibPackageFragmentProvider != null) {
packageFragmentProvider = CompositePackageFragmentProvider(
listOf(packageFragmentProvider, klibPackageFragmentProvider),
"CompositeProvider@NativeResolver for $moduleDescriptor"
)
}
return ResolverForModule(packageFragmentProvider, container)
}
}
| plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/analyzer/NativeResolverForModuleFactory.kt | 1339369168 |
// 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.idea.eclipse
import com.intellij.testFramework.junit5.TestApplication
import com.intellij.testFramework.rules.TempDirectoryExtension
import com.intellij.testFramework.rules.TestNameExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
@TestApplication
class EclipseEml2ModulesTest {
@JvmField
@RegisterExtension
val tempDirectory = TempDirectoryExtension()
@JvmField
@RegisterExtension
val testName = TestNameExtension()
@Test
fun testSourceRootPaths() {
doTest("ws-internals")
}
@Test
fun testAnotherSourceRootPaths() {
doTest("anotherPath")
}
private fun doTest(secondRootName: String) {
val testName = testName.methodName.removePrefix("test").decapitalize()
val testRoot = eclipseTestDataRoot.resolve("eml").resolve(testName)
val commonRoot = eclipseTestDataRoot.resolve("common").resolve("twoModulesWithClasspathStorage")
checkEmlFileGeneration(listOf(testRoot, commonRoot), tempDirectory, listOf(
"test" to "srcPath/sourceRootPaths/sourceRootPaths",
"ws-internals" to "srcPath/$secondRootName/ws-internals"
))
}
} | plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseEml2ModulesTest.kt | 1584340067 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Contract
@ApiStatus.Internal
abstract class SearchEverywhereMlService {
companion object {
val EP_NAME: ExtensionPointName<SearchEverywhereMlService> = ExtensionPointName.create("com.intellij.searchEverywhereMlService")
/**
* Returns an instance of the service if Machine Learning in Search Everywhere is enabled (see [isEnabled]), null otherwise.
*/
@JvmStatic
fun getInstance(): SearchEverywhereMlService? {
val extensions = EP_NAME.extensions
if (extensions.size > 1) {
val logger = Logger.getInstance(SearchEverywhereMlService::class.java)
logger.warn("Multiple implementations of ${SearchEverywhereMlService::class.java.name}. Using the first.")
}
return extensions.firstOrNull()?.takeIf { it.isEnabled() }
}
}
/**
* Indicates whether machine learning in Search Everywhere is enabled.
* This method can return false if ML-ranking is disabled and no experiments are allowed
* (see [com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlExperiment.isAllowed])
*/
abstract fun isEnabled(): Boolean
abstract fun onSessionStarted(project: Project?, mixedListInfo: SearchEverywhereMixedListInfo)
@Contract("_, _, _ -> new")
abstract fun createFoundElementInfo(contributor: SearchEverywhereContributor<*>,
element: Any,
priority: Int): SearchEverywhereFoundElementInfo
abstract fun onSearchRestart(project: Project?, tabId: String, reason: SearchRestartReason,
keysTyped: Int, backspacesTyped: Int, searchQuery: String,
previousElementsProvider: () -> List<SearchEverywhereFoundElementInfo>)
abstract fun onItemSelected(project: Project?, indexes: IntArray, selectedItems: List<Any>, closePopup: Boolean,
elementsProvider: () -> List<SearchEverywhereFoundElementInfo>)
abstract fun onSearchFinished(project: Project?, elementsProvider: () -> List<SearchEverywhereFoundElementInfo>)
abstract fun notifySearchResultsUpdated()
abstract fun onDialogClose()
} | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/SearchEverywhereMlService.kt | 3887847121 |
// PROBLEM: none
open class A {
val foo = "string"
}
class B {
companion object {
val foo = 2
fun <T : A> T.bar(): Int {
return <caret>Companion.foo
}
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/sameNameInImplicitReceiverClass3.kt | 3803549168 |
// 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.openapi.externalSystem.service.project.autoimport
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.externalSystem.ExternalSystemAutoImportAware
import com.intellij.openapi.externalSystem.autoimport.*
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.RESOLVE_PROJECT
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.util.concurrent.atomic.AtomicReference
class ProjectAware(
private val project: Project,
override val projectId: ExternalSystemProjectId,
private val autoImportAware: ExternalSystemAutoImportAware
) : ExternalSystemProjectAware {
private val systemId = projectId.systemId
private val projectPath = projectId.externalProjectPath
override val settingsFiles: Set<String>
get() {
val pathMacroManager = PathMacroManager.getInstance(project)
return externalProjectFiles.map {
val path = FileUtil.toCanonicalPath(it.path)
// The path string can be changed after serialization and deserialization inside persistent component state.
// To avoid that we resolve the path using IDE path macros configuration.
val collapsedPath = pathMacroManager.collapsePath(path)
val expandedPath = pathMacroManager.expandPath(collapsedPath)
expandedPath
}.toSet()
}
private val externalProjectFiles: List<File>
get() = autoImportAware.getAffectedExternalProjectFiles(projectPath, project)
override fun subscribe(listener: ExternalSystemProjectListener, parentDisposable: Disposable) {
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(TaskNotificationListener(listener), parentDisposable)
}
override fun reloadProject(context: ExternalSystemProjectReloadContext) {
val importSpec = ImportSpecBuilder(project, systemId)
if (!context.isExplicitReload) {
importSpec.dontReportRefreshErrors()
importSpec.dontNavigateToError()
}
if (!project.isTrusted()) {
importSpec.usePreviewMode()
}
ExternalSystemUtil.refreshProject(projectPath, importSpec)
}
private inner class TaskNotificationListener(
val delegate: ExternalSystemProjectListener
) : ExternalSystemTaskNotificationListenerAdapter() {
var externalSystemTaskId = AtomicReference<ExternalSystemTaskId?>(null)
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (id.type != RESOLVE_PROJECT) return
if (!FileUtil.pathsEqual(workingDir, projectPath)) return
val task = ApplicationManager.getApplication().getService(ExternalSystemProcessingManager::class.java).findTask(id)
if (task is ExternalSystemResolveProjectTask) {
if (!autoImportAware.isApplicable(task.resolverPolicy)) {
return
}
}
externalSystemTaskId.set(id)
delegate.onProjectReloadStart()
}
private fun afterProjectRefresh(id: ExternalSystemTaskId, status: ExternalSystemRefreshStatus) {
if (id.type != RESOLVE_PROJECT) return
if (!externalSystemTaskId.compareAndSet(id, null)) return
delegate.onProjectReloadFinish(status)
}
override fun onSuccess(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.SUCCESS)
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.FAILURE)
}
override fun onCancel(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.CANCEL)
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ProjectAware.kt | 1021933954 |
// "Convert property initializer to getter" "true"
fun String.foo() = "bar"
fun nop() {
}
interface A {
var name = <caret>"The quick brown fox jumps over the lazy dog".foo()
set(value) = nop()
} | plugins/kotlin/idea/tests/testData/quickfix/convertPropertyInitializerToGetter/varWithSetter.kt | 220258012 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.formatter.trailingComma
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.psi.KtElement
class TrailingCommaContext private constructor(val element: PsiElement, val state: TrailingCommaState) {
/**
* Return [KtElement] if [state] != [TrailingCommaState.NOT_APPLICABLE]
*/
val ktElement: KtElement get() = element as? KtElement ?: error("State is NOT_APPLICABLE")
companion object {
fun create(element: PsiElement): TrailingCommaContext = TrailingCommaContext(
element,
TrailingCommaState.stateForElement(element),
)
}
}
fun TrailingCommaContext.commaExistsOrMayExist(settings: KotlinCodeStyleSettings): Boolean = when (state) {
TrailingCommaState.EXISTS -> true
TrailingCommaState.MISSING -> settings.addTrailingCommaIsAllowedFor(element)
else -> false
}
| plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaContext.kt | 1060899746 |
fun returnFun(): Int = 10
fun usage(a: Int): Int {
when (a) {
10 -> {
re<caret>
}
}
return 10
}
// ORDER: return
// ORDER: returnFun
| plugins/kotlin/completion/tests/testData/weighers/basic/contextualReturn/withReturnType/InWhenWithBody.kt | 954838481 |
// "Replace with 'newFun(*p, x = null)'" "true"
// WITH_STDLIB
@Deprecated("", ReplaceWith("newFun(*p, x = null)"))
fun oldFun(vararg p: Int){
newFun(*p, x = null)
}
fun newFun(vararg p: Int, x: String? = ""){}
fun foo() {
<caret>oldFun(1, 2, 3)
}
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/vararg/addedNamedArgumentAfterRuntime.kt | 1004819630 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vic Lau
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.swordess.common.lang.io
import org.junit.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.fail
class ResourcesTest {
@Test
fun testResourceNameAsStreamCanFindFilesystemFile() {
val stream = "src/test/resources/message.properties".resourceNameAsStream()
assertNotNull(stream)
}
@Test
fun testResourceNameAsStreamCanFindClasspathFile() {
val stream = "message.properties".resourceNameAsStream()
assertNotNull(stream)
}
@Test
fun testResourceNameAsSteamShouldThrowExceptionIfNotFound() {
try {
"not_exist.properties".resourceNameAsStream()
fail("RuntimeException is expected")
} catch (e: RuntimeException) {
assertEquals("resource not found: not_exist.properties", e.message)
}
}
@Test
fun testResourceNameAsURLCanFindFilesystemFile() {
val url = "src/test/resources/message.properties".resourceNameAsURL()
assertNotNull(url)
}
@Test
fun testResourceNameAsURLCanFindClasspathFile() {
val url = "message.properties".resourceNameAsURL()
assertNotNull(url)
}
@Test
fun testResourceNameAsURLShouldThrowExceptionIfNotFound() {
try {
"not_exist.properties".resourceNameAsURL()
fail("RuntimeException is expected")
} catch (e: RuntimeException) {
assertEquals("resource not found: not_exist.properties", e.message)
}
}
@Test
fun testResourceNameAsFileAbsolutePath() {
val expected = File("src/test/resources/message.properties").absolutePath
val actual = "src/test/resources/message.properties".resourceNameAsFileAbsolutePath()
assertEquals(expected, actual)
}
} | src/test/kotlin/org/swordess/common/lang/io/ResourcesTest.kt | 3087268522 |
fun foo(bar: Int) {
0 < bar && 10 > bar<caret>
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/ltgt.kt | 138888100 |
// AFTER-WARNING: Parameter 's' is never used
class C {
companion object {
fun foo(s: String) = 1
}
val f = {<caret> s: String -> foo(s) }
} | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/companion2.kt | 3233433756 |
package zielu.intellij.util
internal interface ZProperty<T> {
var value: T
}
| src/main/kotlin/zielu/intellij/util/ZProperty.kt | 1478646338 |
// 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.vfilefinder
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.caches.project.ScriptModuleInfo
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory
class IDEVirtualFileFinderFactory : VirtualFileFinderFactory {
override fun create(scope: GlobalSearchScope): VirtualFileFinder = IDEVirtualFileFinder(scope)
override fun create(project: Project, module: ModuleDescriptor): VirtualFileFinder {
val ideaModuleInfo = (module.getCapability(ModuleInfo.Capability) as? IdeaModuleInfo)
val scope = when (ideaModuleInfo) {
is ScriptModuleInfo -> GlobalSearchScope.union(
ideaModuleInfo.dependencies().map { it.contentScope() }.toTypedArray()
)
else -> GlobalSearchScope.allScope(project)
}
return IDEVirtualFileFinder(scope)
}
}
| plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinderFactory.kt | 2276125779 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.shelf
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.vcs.VcsTestUtil
import com.intellij.openapi.vcs.changes.patch.CreatePatchCommitExecutor.ShelfPatchBuilder
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.util.io.createDirectories
import junit.framework.TestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.*
import java.nio.file.Paths
@RunsInEdt
class ShelveChangesManagerTest {
companion object {
@ClassRule
@JvmField
val appRule = ApplicationRule()
@ClassRule
@JvmField
val edtRule = EdtRule()
}
private lateinit var shelvedChangesManager: ShelveChangesManager
private lateinit var project: Project
@Rule
@JvmField
val tempDir = TemporaryDirectory()
@Before
fun setUp() {
// test data expects not directory-based project
val baseDir = tempDir.newPath()
val projectFile = baseDir.resolve("p.ipr")
val shelfDir = baseDir.resolve(".shelf")
shelfDir.createDirectories()
val testDataFile = Paths.get("${VcsTestUtil.getTestDataPath()}/shelf/shelvedChangeLists")
testDataFile.toFile().copyRecursively(shelfDir.toFile())
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(projectFile.parent)!!
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
project = ProjectManagerEx.getInstanceEx().openProject(projectFile, createTestOpenProjectOptions())!!
shelvedChangesManager = ShelveChangesManager.getInstance(project)
}
@After
fun closeProject() {
if (project.isInitialized) {
PlatformTestUtil.forceCloseProjectWithoutSaving(project)
}
}
@Test
fun `unshelve list`() {
doTestUnshelve(0, 0, 2, 1)
}
@Test
fun `unshelve files`() {
doTestUnshelve(changeCount = 1, binariesNum = 1, expectedListNum = 3, expectedRecycledNum = 1)
}
@Test
fun `unshelve all files`() {
doTestUnshelve(2, 2, 2, 1)
}
@Test
fun `do not remove files when unshelve`() {
doTestUnshelve(0, 0, 3, 0, false)
}
@Test
fun `delete list`() {
doTestDelete(shelvedChangesManager.shelvedChangeLists[0], 0, 0, 2, 1)
}
@Test
fun `delete files`() {
doTestDelete(shelvedChangesManager.shelvedChangeLists[0], 1, 1, 3, 1)
}
@Test
fun `delete all files`() {
doTestDelete(shelvedChangesManager.shelvedChangeLists[0], 2, 2, 2, 1)
}
@Test
fun `delete deleted list`() {
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangesManager.markChangeListAsDeleted(shelvedChangeList)
doTestDelete(shelvedChangeList, 0, 0, 2, 0)
}
@Test
fun `delete deleted files`() {
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangesManager.markChangeListAsDeleted(shelvedChangeList)
doTestDelete(shelvedChangeList, 1, 1, 2, 1)
}
@Test
fun `delete all deleted files`() {
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangesManager.markChangeListAsDeleted(shelvedChangeList)
doTestDelete(shelvedChangeList, 2, 2, 2, 0)
}
@Test
fun `undo list deletion`() {
doTestDelete(shelvedChangesManager.shelvedChangeLists[0], 0, 0, 2, 1, true)
}
@Test
fun `undo file deletion`() {
//correct undo depends on ability to merge 2 shelved lists with separated changes inside
doTestDelete(shelvedChangesManager.shelvedChangeLists[0], 1, 1, 3, 1, true)
}
@Test
fun `create patch from shelf`() {
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangeList.loadChangesIfNeeded(project)
val patchBuilder = ShelfPatchBuilder(project, shelvedChangeList, emptyList())
val patches = patchBuilder.buildPatches(project.stateStore.projectBasePath, emptyList(), false, false)
val changeSize = shelvedChangeList.changes?.size ?: 0
TestCase.assertTrue(patches.size == (changeSize + shelvedChangeList.binaryFiles.size))
}
@Test
fun `create patch from shelved changes`() {
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangeList.loadChangesIfNeeded(project)
val selectedPaths = listOf(ShelvedWrapper(shelvedChangeList.changes!!.first(), shelvedChangeList).path,
ShelvedWrapper(shelvedChangeList.binaryFiles!!.first(), shelvedChangeList).path)
val patchBuilder = ShelfPatchBuilder(project, shelvedChangeList, selectedPaths)
val patches = patchBuilder.buildPatches(project.stateStore.projectBasePath, emptyList(), false, false)
TestCase.assertTrue(patches.size == selectedPaths.size)
}
private fun doTestUnshelve(changeCount: Int,
binariesNum: Int,
expectedListNum: Int,
expectedRecycledNum: Int,
removeFilesFromShelf: Boolean = true) {
shelvedChangesManager.isRemoveFilesFromShelf = removeFilesFromShelf
val shelvedChangeList = shelvedChangesManager.shelvedChangeLists[0]
shelvedChangeList.loadChangesIfNeeded(project)
val originalDate = shelvedChangeList.DATE
val changes = if (changeCount == 0) null else shelvedChangeList.changes!!.subList(0, changeCount)
val binaries = if (changeCount == 0) null else shelvedChangeList.binaryFiles.subList(0, binariesNum)
shelvedChangesManager.unshelveChangeList(shelvedChangeList, changes, binaries, null, false)
// unshelveChangeList uses GuiUtils.invokeLaterIfNeeded
runInEdtAndWait { PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() }
val recycledShelvedChangeLists = shelvedChangesManager.recycledShelvedChangeLists
assertThat(shelvedChangesManager.shelvedChangeLists.size).isEqualTo(expectedListNum)
assertThat(recycledShelvedChangeLists.size).isEqualTo(expectedRecycledNum)
if (recycledShelvedChangeLists.isNotEmpty()) {
assertThat(originalDate.before(recycledShelvedChangeLists[0].DATE)).isTrue()
}
}
private fun doTestDelete(shelvedChangeList: ShelvedChangeList,
changesNum: Int,
binariesNum: Int,
expectedListNum: Int,
expectedDeletedNum: Int,
undoDeletion: Boolean = false) {
val originalDate = shelvedChangeList.DATE
shelvedChangeList.loadChangesIfNeeded(project)
val changes = if (changesNum == 0) emptyList<ShelvedChange>() else shelvedChangeList.changes!!.subList(0, changesNum)
val binaries = if (changesNum == 0) emptyList<ShelvedBinaryFile>() else shelvedChangeList.binaryFiles.subList(0, binariesNum)
val shouldDeleteEntireList = changesNum == 0 && binariesNum == 0
val deleteShelvesWithDates = shelvedChangesManager.deleteShelves(
if (shouldDeleteEntireList) listOf(shelvedChangeList) else emptyList(),
if (!shouldDeleteEntireList) listOf(shelvedChangeList) else emptyList(),
changes, binaries)
val deletedLists = shelvedChangesManager.deletedLists
TestCase.assertEquals(expectedListNum, shelvedChangesManager.shelvedChangeLists.size)
TestCase.assertEquals(expectedDeletedNum, deletedLists.size)
if (deletedLists.isNotEmpty() && deleteShelvesWithDates.isNotEmpty())
assertThat(originalDate.before(deletedLists[0].DATE)).isTrue()
if (undoDeletion) {
for ((l, d) in deleteShelvesWithDates) {
shelvedChangesManager.restoreList(l, d)
}
TestCase.assertEquals(expectedListNum + expectedDeletedNum, shelvedChangesManager.shelvedChangeLists.size)
}
}
}
| platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/shelf/ShelveChangesManagerTest.kt | 1317550947 |
package zielu.gittoolbox.changes
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import git4idea.repo.GitRepository
import zielu.gittoolbox.cache.VirtualFileRepoCache
import zielu.gittoolbox.changes.ChangesTrackerService.Companion.CHANGES_TRACKER_TOPIC
import zielu.gittoolbox.util.PrjBaseFacade
import zielu.intellij.metrics.GtTimer
internal open class ChangesTrackerServiceFacade(
private val project: Project
) : PrjBaseFacade(project), Disposable {
fun fireChangeCountsUpdated() {
publishAsync(this) { it.syncPublisher(CHANGES_TRACKER_TOPIC).changeCountsUpdated() }
}
fun getRepoForPath(path: FilePath): GitRepository? {
return VirtualFileRepoCache.getInstance(project).getRepoForPath(path)
}
fun getNotEmptyChangeListTimer(): GtTimer = getMetrics().timer("change-list-not-empty")
fun getChangeListRemovedTimer(): GtTimer = getMetrics().timer("change-list-removed")
override fun dispose() {
// TODO: implement
}
}
| src/main/kotlin/zielu/gittoolbox/changes/ChangesTrackerServiceFacade.kt | 3297018130 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.reply.data
import com.example.reply.data.local.LocalAccountsDataProvider
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class AccountsRepositoryImpl : AccountsRepository {
override fun getDefaultUserAccount(): Flow<Account> = flow {
emit(LocalAccountsDataProvider.getDefaultUserAccount())
}
override fun getAllUserAccounts(): Flow<List<Account>> = flow {
emit(LocalAccountsDataProvider.allUserAccounts)
}
override fun getContactAccountByUid(uid: Long): Flow<Account> = flow {
emit(LocalAccountsDataProvider.getContactAccountByUid(uid))
}
}
| Reply/app/src/main/java/com/example/reply/data/AccountsRepositoryImpl.kt | 479006345 |
package org.jetbrains.android.anko.functional
import org.jetbrains.android.anko.config.*
import org.junit.Test
public class FunctionalTestsForSdk15 : AbstractFunctionalTest() {
val version = "sdk15"
@Test public fun testComplexListenerClassTest() {
runFunctionalTest("ComplexListenerClassTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.COMPLEX_LISTENER_CLASSES)
}
}
@Test public fun testComplexListenerSetterTest() {
runFunctionalTest("ComplexListenerSetterTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.COMPLEX_LISTENER_SETTERS)
}
}
@Test public fun testLayoutsTest() {
runFunctionalTest("LayoutsTest.kt", AnkoFile.LAYOUTS, version) {
files.add(AnkoFile.LAYOUTS)
}
}
@Test public fun testViewTest() {
runFunctionalTest("ViewTest.kt", AnkoFile.VIEWS, version) {
files.add(AnkoFile.VIEWS)
tunes.add(ConfigurationTune.TOP_LEVEL_DSL_ITEMS)
tunes.add(ConfigurationTune.HELPER_CONSTRUCTORS)
}
}
@Test public fun testPropertyTest() {
runFunctionalTest("PropertyTest.kt", AnkoFile.PROPERTIES, version) {
files.add(AnkoFile.PROPERTIES)
}
}
@Test public fun testServicesTest() {
runFunctionalTest("ServicesTest.kt", AnkoFile.SERVICES, version) {
files.add(AnkoFile.SERVICES)
}
}
@Test public fun testSimpleListenerTest() {
runFunctionalTest("SimpleListenerTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.SIMPLE_LISTENERS)
}
}
@Test public fun testInterfaceWorkaroundsTest() {
runFunctionalTest("InterfaceWorkaroundsTest.kt", AnkoFile.INTERFACE_WORKAROUNDS_JAVA, version) {
files.add(AnkoFile.INTERFACE_WORKAROUNDS_JAVA)
}
}
@Test public fun testSqlParserHelpersTest() {
runFunctionalTest("SqlParserHelpersTest.kt", AnkoFile.SQL_PARSER_HELPERS, version) {
files.add(AnkoFile.SQL_PARSER_HELPERS)
}
}
}
| dsl/test/org/jetbrains/android/anko/functional/FunctionalTestsForSdk15.kt | 4039064836 |
package fr.insapp.insapp.fragments
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import fr.insapp.insapp.R
import fr.insapp.insapp.activities.EventActivity
import fr.insapp.insapp.adapters.CommentRecyclerViewAdapter
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.Comment
import fr.insapp.insapp.models.Event
import fr.insapp.insapp.utility.Utils
import kotlinx.android.synthetic.main.activity_event.*
import kotlinx.android.synthetic.main.fragment_event_comments.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* Created by thomas on 25/02/2017.
*/
class CommentsEventFragment : Fragment() {
private lateinit var commentAdapter: CommentRecyclerViewAdapter
private var event: Event? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// arguments
val bundle = arguments
if (bundle != null) {
this.event = bundle.getParcelable("event")
}
// adapter
event.let {
commentAdapter = CommentRecyclerViewAdapter(event!!.comments, Glide.with(this))
commentAdapter.setOnCommentItemLongClickListener(EventCommentLongClickListener(context, event!!, commentAdapter))
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_event_comments, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// edit comment
comment_event_input.setupComponent()
comment_event_input.setOnEditorActionListener(TextView.OnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// hide keyboard
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(textView.windowToken, 0)
val content = comment_event_input.text.toString()
comment_event_input.text.clear()
if (content.isNotBlank()) {
val user = Utils.user
user?.let {
val comment = Comment(null, user.id, content, null, comment_event_input.tags)
ServiceGenerator.client.commentEvent(event!!.id, comment)
.enqueue(object : Callback<Event> {
override fun onResponse(call: Call<Event>, response: Response<Event>) {
if (response.isSuccessful) {
commentAdapter.addComment(comment)
comment_event_input.tags.clear()
Toast.makeText(activity, resources.getText(R.string.write_comment_success), Toast.LENGTH_LONG).show()
} else {
Toast.makeText(activity, "CommentEditText", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Event>, t: Throwable) {
Toast.makeText(activity, "CommentEditText", Toast.LENGTH_LONG).show()
}
})
}
}
return@OnEditorActionListener true
}
false
})
// recycler view
recyclerview_comments_event?.setHasFixedSize(true)
recyclerview_comments_event?.isNestedScrollingEnabled = false
val layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
recyclerview_comments_event?.layoutManager = layoutManager
recyclerview_comments_event?.adapter = commentAdapter
// retrieve the avatar of the user
val user = Utils.user
val id = resources.getIdentifier(Utils.drawableProfileName(user?.promotion, user?.gender), "drawable", context!!.packageName)
Glide
.with(context!!)
.load(id)
.apply(RequestOptions.circleCropTransform())
.transition(withCrossFade())
.into(comment_event_username_avatar)
// animation on focus
comment_event_input?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
(activity as EventActivity).appbar_event.setExpanded(false, true)
(activity as EventActivity).fab_participate_event.hideMenu(false)
} else {
val atm = Calendar.getInstance().time
if (event!!.dateEnd.time >= atm.time) {
val handler = Handler()
handler.postDelayed({
val eventActivity = activity as EventActivity?
eventActivity?.fab_participate_event?.showMenu(true)
}, 500)
}
}
}
}
class EventCommentLongClickListener(
private val context: Context?,
private val event: Event,
private val adapter: CommentRecyclerViewAdapter
): CommentRecyclerViewAdapter.OnCommentItemLongClickListener {
override fun onCommentItemLongClick(comment: Comment) {
if (context != null) {
val alertDialogBuilder = AlertDialog.Builder(context)
val user = Utils.user
// delete comment
if (user != null) {
if (user.id == comment.user) {
alertDialogBuilder
.setTitle(context.resources.getString(R.string.delete_comment_action))
.setMessage(R.string.delete_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.uncommentEvent(event.id, comment.id!!)
call.enqueue(object : Callback<Event> {
override fun onResponse(call: Call<Event>, response: Response<Event>) {
val event = response.body()
if (response.isSuccessful && event != null) {
adapter.setComments(event.comments)
} else {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Event>, t: Throwable) {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show()
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
// report comment
else {
alertDialogBuilder
.setTitle(context.getString(R.string.report_comment_action))
.setMessage(R.string.report_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.reportComment(event.id, comment.id!!)
call.enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
Toast.makeText(context, context.getString(R.string.report_comment_success), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show();
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Toast.makeText(context, "EventCommentLongClickListener", Toast.LENGTH_LONG).show();
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
}
}
}
}
}
| app/src/main/java/fr/insapp/insapp/fragments/CommentsEventFragment.kt | 1637818463 |
package stan.androiddemo.project.petal.Observable
import rx.Observable
import stan.androiddemo.project.petal.Model.ErrorBaseInfo
import stan.androiddemo.tool.Logger
/**
* Created by stanhu on 12/8/2017.
*/
object ErrorHelper {
fun <T : ErrorBaseInfo> getCheckNetError(bean: T?): Observable<T> {
return Observable.create { subscriber ->
if (bean != null) {
val msg = bean!!.msg
if (msg != null) {
Logger.d("onError=" + msg!!)
subscriber.onError(RuntimeException(bean.msg))
} else {
Logger.d("onNext")
subscriber.onNext(bean)
}
} else {
subscriber.onError(RuntimeException())
}
}
}
} | app/src/main/java/stan/androiddemo/project/petal/Observable/ErrorHelper.kt | 669573143 |
// GENERATED
package com.fkorotkov.kubernetes.authorization.v1
import io.fabric8.kubernetes.api.model.authorization.v1.ResourceAttributes as v1_ResourceAttributes
import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectAccessReviewSpec as v1_SelfSubjectAccessReviewSpec
import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReviewSpec as v1_SubjectAccessReviewSpec
fun v1_SelfSubjectAccessReviewSpec.`resourceAttributes`(block: v1_ResourceAttributes.() -> Unit = {}) {
if(this.`resourceAttributes` == null) {
this.`resourceAttributes` = v1_ResourceAttributes()
}
this.`resourceAttributes`.block()
}
fun v1_SubjectAccessReviewSpec.`resourceAttributes`(block: v1_ResourceAttributes.() -> Unit = {}) {
if(this.`resourceAttributes` == null) {
this.`resourceAttributes` = v1_ResourceAttributes()
}
this.`resourceAttributes`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/authorization/v1/resourceAttributes.kt | 3869083309 |
// GENERATED
package com.fkorotkov.openshift
import io.fabric8.kubernetes.api.model.LocalObjectReference as model_LocalObjectReference
import io.fabric8.openshift.api.model.BuildSource as model_BuildSource
fun model_BuildSource.`sourceSecret`(block: model_LocalObjectReference.() -> Unit = {}) {
if(this.`sourceSecret` == null) {
this.`sourceSecret` = model_LocalObjectReference()
}
this.`sourceSecret`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/sourceSecret.kt | 1381035002 |
package org.usfirst.frc.team4186.routines.util
fun nop() {}
| src/main/kotlin/org/usfirst/frc/team4186/routines/util/util.kt | 1311898871 |
/*
* Copyright 2018 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.instantapps.samples.instantenabledandroidappbundle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.button).setOnClickListener {
// On button click, update the counter and refresh the UI
if (count == 0) {
findViewById<TextView>(R.id.statictext).text = "Kittens fed:"
}
findViewById<TextView>(R.id.text).text = (++count).toString()
}
}
}
| aab-simple/app/src/main/java/com/google/android/instantapps/samples/instantenabledandroidappbundle/MainActivity.kt | 2993930028 |
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
import java.util.HashSet
import java.util.LinkedList
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class DijkstraAlgorithm(graph: Graph) {
private val nodes: List<Vertex>
private val edges: List<Edge>
private var settledNodes: MutableSet<Vertex>? = null
private var unSettledNodes: MutableSet<Vertex>? = null
private var predecessors: MutableMap<Vertex, Vertex>? = null
private var distance: MutableMap<Vertex, Int>? = null
init {
// create a copy of the array so that we can operate on this array
this.nodes = ArrayList<Vertex>(graph.vertexes)
this.edges = ArrayList<Edge>(graph.edges)
}
fun execute(source: Vertex) {
settledNodes = HashSet()
unSettledNodes = HashSet()
distance = HashMap()
predecessors = HashMap()
distance!![source] = 0
unSettledNodes!!.add(source)
while (unSettledNodes!!.size > 0) {
val node = getMinimum(unSettledNodes!!)
settledNodes!!.add(node!!)
unSettledNodes!!.remove(node)
findMinimalDistances(node)
}
}
private fun findMinimalDistances(node: Vertex?) {
val adjacentNodes = getNeighbors(node)
for (target in adjacentNodes) {
if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) {
distance!![target] = getShortestDistance(node) + getDistance(node, target)
predecessors!![target] = node!!
unSettledNodes!!.add(target)
}
}
}
private fun getDistance(node: Vertex?, target: Vertex): Int {
for (edge in edges) {
if (edge.source == node && edge.destination == target) {
return edge.weight
}
}
throw RuntimeException("Should not happen")
}
private fun getNeighbors(node: Vertex?): List<Vertex> {
val neighbors = ArrayList<Vertex>()
for (edge in edges) {
if (edge.source == node && !isSettled(edge.destination)) {
neighbors.add(edge.destination)
}
}
return neighbors
}
private fun getMinimum(vertexes: Set<Vertex>): Vertex? {
var minimum: Vertex? = null
for (vertex in vertexes) {
if (minimum == null) {
minimum = vertex
} else {
if (getShortestDistance(vertex) < getShortestDistance(minimum)) {
minimum = vertex
}
}
}
return minimum
}
private fun isSettled(vertex: Vertex): Boolean {
return settledNodes!!.contains(vertex)
}
private fun getShortestDistance(destination: Vertex?): Int {
val d = distance!![destination]
return d ?: Integer.MAX_VALUE
}
/*
* This method returns the path from the source to the selected target and
* NULL if no path exists
*/
fun getPath(target: Vertex): LinkedList<Vertex>? {
val path = LinkedList<Vertex>()
var step = target
// check if a path exists
if (predecessors!![step] == null) {
return null
}
path.add(step)
while (predecessors!![step] != null) {
step = predecessors!![step]!!
path.add(step)
}
// Put it into the correct order
Collections.reverse(path)
return path
}
}
class Edge(val id: String, val source: Vertex, val destination: Vertex, val weight: Int) {
override fun toString(): String {
return source.toString() + " " + destination.toString()
}
}
class Graph(val vertexes: List<Vertex>, val edges: List<Edge>)
class Vertex(val id: String?, val name: String) {
override fun hashCode(): Int {
val prime = 31
var result = 1
result = prime * result + (id?.hashCode() ?: 0)
return result
}
override fun equals(obj: Any?): Boolean {
if (this === obj)
return true
if (obj == null)
return false
if (javaClass != obj.javaClass)
return false
val other = obj as Vertex?
if (id == null) {
if (other!!.id != null)
return false
} else if (id != other!!.id)
return false
return true
}
override fun toString(): String {
return name
}
}
class TestDijkstraAlgorithm {
companion object {
private lateinit var nodes: MutableList<Vertex>
private lateinit var edges: MutableList<Edge>
@JvmStatic
fun main(args : Array<String>) {
nodes = ArrayList()
edges = ArrayList()
for (i in 0..10) {
val location = Vertex("Node_$i", "Node_$i")
nodes.add(location)
}
addLane("Edge_0", 0, 1, 85)
addLane("Edge_1", 0, 2, 217)
addLane("Edge_2", 0, 4, 173)
addLane("Edge_3", 2, 6, 186)
addLane("Edge_4", 2, 7, 103)
addLane("Edge_5", 3, 7, 183)
addLane("Edge_6", 5, 8, 250)
addLane("Edge_7", 8, 9, 84)
addLane("Edge_8", 7, 9, 167)
addLane("Edge_9", 4, 9, 502)
addLane("Edge_10", 9, 10, 40)
addLane("Edge_11", 1, 10, 600)
// Lets check from location Loc_1 to Loc_10
val graph = Graph(nodes, edges)
val dijkstra = DijkstraAlgorithm(graph)
dijkstra.execute(nodes[0])
val path = dijkstra.getPath(nodes[10])
assertNotNull(path)
assertTrue(path!!.size > 0)
for (vertex in path) {
System.out.println(vertex)
}
}
private fun addLane(laneId: String, sourceLocNo: Int, destLocNo: Int,
duration: Int) {
val lane = Edge(laneId, nodes[sourceLocNo], nodes[destLocNo], duration)
edges.add(lane)
}
}
} | data_structures/Graphs/graph/Kotlin/DjikstraAlgorithm.kt | 325839807 |
package nullSafe
fun main(args: Array<String>) {
val str: String? = null
println(str?.length)
} | Curso Dev Kotlin/src/nullSafe/nullSafe.kt | 1634298954 |
package com.quran.labs.androidquran.pageselect
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.quran.labs.androidquran.R
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.lang.ref.WeakReference
class PageSelectAdapter(val inflater: LayoutInflater,
val width: Int,
private val selectionHandler: (String) -> Unit) : PagerAdapter() {
private val items : MutableList<PageTypeItem> = mutableListOf()
private val compositeDisposable = CompositeDisposable()
private val listener = View.OnClickListener { v ->
val tag = (v.parent as View).tag
if (tag != null) {
selectionHandler(tag.toString())
}
}
fun replaceItems(updates: List<PageTypeItem>, pager: ViewPager) {
items.clear()
items.addAll(updates)
items.forEach {
val view : View? = pager.findViewWithTag(it.pageType)
if (view != null) {
updateView(view, it)
}
}
notifyDataSetChanged()
}
override fun getCount() = items.size
override fun isViewFromObject(view: View, obj: Any): Boolean {
return obj === view
}
private fun updateView(view: View, data: PageTypeItem) {
view.findViewById<TextView>(R.id.title).setText(data.title)
view.findViewById<TextView>(R.id.description).setText(data.description)
view.findViewById<FloatingActionButton>(R.id.fab).setOnClickListener(listener)
val image = view.findViewById<ImageView>(R.id.preview)
val progressBar = view.findViewById<ProgressBar>(R.id.progress_bar)
if (data.previewImage != null) {
progressBar.visibility = View.GONE
readImage(data.previewImage.path, WeakReference(image))
} else {
progressBar.visibility = View.VISIBLE
image.setImageBitmap(null)
}
}
private fun readImage(path: String, imageRef: WeakReference<ImageView>) {
compositeDisposable.add(
Maybe.fromCallable {
val options = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.ALPHA_8 }
BitmapFactory.decodeFile(path, options)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { imageRef.get()?.setImageBitmap(it) }
)
}
fun cleanUp() {
compositeDisposable.clear()
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = inflater.inflate(R.layout.page_select_page, container, false)
val item = items[position]
updateView(view, item)
view.tag = item.pageType
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, o: Any) {
container.removeView(o as View)
}
}
| app/src/main/java/com/quran/labs/androidquran/pageselect/PageSelectAdapter.kt | 2121117290 |
package com.quran.recitation.common
import com.quran.data.model.SuraAyah
interface RecitationSession {
fun id(): String
fun startAyah(): SuraAyah
fun currentAyah(): SuraAyah
fun startedAt(): Long
fun recitation(): Recitation
}
| common/recitation/src/main/java/com/quran/recitation/common/RecitationSession.kt | 1930195209 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.