repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adrcotfas/Goodtime | app/src/google/java/com/apps/adrcotfas/goodtime/ui/upgrade_dialog/ExtraFeaturesAdapter.kt | 1 | 2326 | /*
* Copyright (C) 2020-2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apps.adrcotfas.goodtime.ui.upgrade_dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.apps.adrcotfas.goodtime.R
import com.apps.adrcotfas.goodtime.util.ThemeHelper
class ExtraFeaturesAdapter(
private val context: Context,
private val data : List<Pair<String, Int>>)
: RecyclerView.Adapter<ExtraFeaturesAdapter.ViewHolder>() {
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(context, data[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(itemView: View)
: RecyclerView.ViewHolder(itemView) {
private val text: TextView = itemView.findViewById(R.id.text)
private val icon: ImageView = itemView.findViewById(R.id.icon)
fun bind(context : Context, item: Pair<String, Int>) {
text.text = item.first
icon.setImageDrawable(context.resources.getDrawable(item.second))
icon.setColorFilter(ThemeHelper.getColor(context, ThemeHelper.COLOR_INDEX_UNLABELED))
}
companion object {
fun from(parent: ViewGroup) : ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.dialog_upgrade_row, parent, false)
return ViewHolder(view)
}
}
}
} | apache-2.0 | 192a78798e6b7d9274a3fc412e8955eb | 36.532258 | 97 | 0.708512 | 4.473077 | false | false | false | false |
aglne/mycollab | mycollab-esb/src/main/java/com/mycollab/module/project/esb/DeleteProjectTaskCommand.kt | 3 | 3718 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.esb
import com.google.common.eventbus.AllowConcurrentEvents
import com.google.common.eventbus.Subscribe
import com.mycollab.common.dao.CommentMapper
import com.mycollab.common.domain.CommentExample
import com.mycollab.common.domain.TagExample
import com.mycollab.common.service.TagService
import com.mycollab.module.ecm.service.ResourceService
import com.mycollab.module.esb.GenericCommand
import com.mycollab.module.file.AttachmentUtils
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.dao.TicketKeyMapper
import com.mycollab.module.project.dao.TicketRelationMapper
import com.mycollab.module.project.domain.TicketKeyExample
import com.mycollab.module.project.domain.TicketRelationExample
import org.springframework.stereotype.Component
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class DeleteProjectTaskCommand(private val resourceService: ResourceService,
private val commentMapper: CommentMapper,
private val tagService: TagService,
private val ticketKeyMapper: TicketKeyMapper,
private val ticketRelationMapper: TicketRelationMapper) : GenericCommand() {
@AllowConcurrentEvents
@Subscribe
fun removedTask(event: DeleteProjectTaskEvent) {
val taskIds = event.tasks.map { it.id }.toCollection(mutableListOf())
event.tasks.forEach {
removeRelatedFiles(event.accountId, it.projectid, it.id)
removeRelatedTags(it.id)
}
removeRelatedComments(taskIds)
removeTicketKeys(taskIds)
removeTicketRelations(taskIds)
}
private fun removeRelatedFiles(accountId: Int, projectId: Int, taskId: Int) {
val attachmentPath = AttachmentUtils.getProjectEntityAttachmentPath(accountId, projectId,
ProjectTypeConstants.TASK, "$taskId")
resourceService.removeResource(attachmentPath, "", true, accountId)
}
private fun removeRelatedComments(taskIds: MutableList<Int>) {
val ex = CommentExample()
ex.createCriteria().andTypeEqualTo(ProjectTypeConstants.TASK).andExtratypeidIn(taskIds)
commentMapper.deleteByExample(ex)
}
private fun removeTicketKeys(taskIds: MutableList<Int>) {
val ex = TicketKeyExample()
ex.createCriteria().andTicketidIn(taskIds).andTickettypeEqualTo(ProjectTypeConstants.TASK)
ticketKeyMapper.deleteByExample(ex)
}
private fun removeTicketRelations(taskIds: MutableList<Int>) {
val ex = TicketRelationExample()
ex.createCriteria().andTicketidIn(taskIds).andTickettypeEqualTo(ProjectTypeConstants.TASK)
ticketRelationMapper.deleteByExample(ex)
}
private fun removeRelatedTags(taskId: Int) {
val ex = TagExample()
ex.createCriteria().andTypeEqualTo(ProjectTypeConstants.TASK).andTypeidEqualTo("$taskId")
tagService.deleteByExample(ex)
}
} | agpl-3.0 | 6dbc39fdb5f4b9d180b54727529b1f03 | 41.25 | 107 | 0.734732 | 4.594561 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/server/MulticastEventReceiver.kt | 1 | 3885 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import net.mm2d.upnp.Http
import net.mm2d.upnp.HttpRequest
import net.mm2d.upnp.internal.parser.parseEventXml
import net.mm2d.upnp.internal.parser.parseUsn
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.internal.thread.ThreadCondition
import net.mm2d.upnp.internal.util.closeQuietly
import net.mm2d.upnp.util.findInet4Address
import net.mm2d.upnp.util.findInet6Address
import net.mm2d.upnp.util.toSimpleString
import java.io.ByteArrayInputStream
import java.io.IOException
import java.net.DatagramPacket
import java.net.InterfaceAddress
import java.net.MulticastSocket
import java.net.NetworkInterface
import java.net.SocketTimeoutException
internal class MulticastEventReceiver(
taskExecutors: TaskExecutors,
val address: Address,
private val networkInterface: NetworkInterface,
private val listener: (uuid: String, svcid: String, lvl: String, seq: Long, properties: List<Pair<String, String>>) -> Unit
) : Runnable {
private val interfaceAddress: InterfaceAddress =
if (address == Address.IP_V4)
networkInterface.findInet4Address()
else
networkInterface.findInet6Address()
private var socket: MulticastSocket? = null
private val threadCondition = ThreadCondition(taskExecutors.server)
// VisibleForTesting
@Throws(IOException::class)
internal fun createMulticastSocket(port: Int): MulticastSocket {
return MulticastSocket(port).also {
it.networkInterface = networkInterface
}
}
fun start() {
threadCondition.start(this)
}
fun stop() {
threadCondition.stop()
socket.closeQuietly()
}
override fun run() {
val suffix = "-multicast-event-" + networkInterface.name + "-" + interfaceAddress.address.toSimpleString()
Thread.currentThread().let { it.name = it.name + suffix }
if (threadCondition.isCanceled()) return
try {
val socket = createMulticastSocket(ServerConst.EVENT_PORT)
this.socket = socket
socket.joinGroup(address.eventInetAddress)
threadCondition.notifyReady()
receiveLoop(socket)
} catch (ignored: IOException) {
} finally {
socket?.leaveGroup(address.eventInetAddress)
socket.closeQuietly()
socket = null
}
}
// VisibleForTesting
@Throws(IOException::class)
internal fun receiveLoop(socket: MulticastSocket) {
val buf = ByteArray(1500)
while (!threadCondition.isCanceled()) {
try {
val dp = DatagramPacket(buf, buf.size)
socket.receive(dp)
if (threadCondition.isCanceled()) break
onReceive(dp.data, dp.length)
} catch (ignored: SocketTimeoutException) {
}
}
}
// VisibleForTesting
internal fun onReceive(data: ByteArray, length: Int) {
val request = HttpRequest.create().apply {
readData(ByteArrayInputStream(data, 0, length))
}
if (request.getHeader(Http.NT) != Http.UPNP_EVENT) return
if (request.getHeader(Http.NTS) != Http.UPNP_PROPCHANGE) return
val lvl = request.getHeader(Http.LVL)
if (lvl.isNullOrEmpty()) return
val seq = request.getHeader(Http.SEQ)?.toLongOrNull() ?: return
val svcid = request.getHeader(Http.SVCID)
if (svcid.isNullOrEmpty()) return
val (uuid, _) = request.parseUsn()
if (uuid.isEmpty()) return
val properties = request.getBody().parseEventXml()
if (properties.isEmpty()) return
listener.invoke(uuid, svcid, lvl, seq, properties)
}
}
| mit | 794bce510ac0ac833e9c1a8f940abba1 | 33.927928 | 127 | 0.666753 | 4.390713 | false | false | false | false |
agrosner/KBinding | app/src/main/java/com/andrewgrosner/kbinding/sample/widget/BaseViewHolder.kt | 1 | 1569 | package com.andrewgrosner.kbinding.sample.widget
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.andrewgrosner.kbinding.BindingHolder
import com.andrewgrosner.kbinding.BindingRegister
import com.andrewgrosner.kbinding.anko.BindingComponent
import org.jetbrains.anko.AnkoContext
/**
* Description: ViewHolder that holds a required binding.
*/
abstract class BaseViewHolder<Data> : RecyclerView.ViewHolder {
val component: BindingRegister<Data>
constructor(view: View) : super(view) {
component = BindingHolder<Data>()
component.bindAll()
}
constructor(parent: ViewGroup, component: BindingComponent<ViewGroup, Data>)
: super(component.createView(AnkoContext.create(parent.context, parent))) {
this.component = component
component.bindAll()
}
val context
get() = itemView.context
fun bind(data: Data) {
applyBindings(data, component)
if (!component.isBound) {
component.bindAll()
}
}
abstract fun applyBindings(data: Data, holder: BindingRegister<Data>)
}
class AnkoViewHolder<Data>(parent: ViewGroup, component: BindingComponent<ViewGroup, Data>)
: BaseViewHolder<Data>(parent, component) {
override fun applyBindings(data: Data, holder: BindingRegister<Data>) {
holder.viewModel = data
}
}
class NoBindingViewHolder<Any>(view: View)
: BaseViewHolder<Any>(view) {
override fun applyBindings(data: Any, holder: BindingRegister<Any>) = Unit
}
| mit | 601fc644c6197610abf4481e946faefb | 28.603774 | 91 | 0.715743 | 4.358333 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/span/ReplySpan.kt | 1 | 1075 | package com.emogoth.android.phone.mimi.span
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import com.emogoth.android.phone.mimi.activity.MimiActivity
import com.emogoth.android.phone.mimi.interfaces.ReplyClickListener
import com.emogoth.android.phone.mimi.util.MimiUtil
class ReplySpan(private val boardName: String, private val threadId: Long, private val replies: List<String>, private val textColor: Int) : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = true
ds.color = textColor
}
override fun onClick(widget: View) {
Log.i(LOG_TAG, "Caught click on reply: view=" + widget.javaClass.simpleName)
val activity = MimiUtil.scanForActivity(widget.context)
if (activity is ReplyClickListener) {
activity.onReplyClicked(boardName, threadId, -1, replies)
}
}
companion object {
private val LOG_TAG = ReplySpan::class.java.simpleName
}
} | apache-2.0 | 56d5686d001443c2f7cf12b51072706f | 33.709677 | 157 | 0.727442 | 4.150579 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/model/ModelPicture.kt | 1 | 758 | package com.tamsiree.rxui.model
/**
* 图片实体类
* @author Tamsiree
* @date : 2017/6/12 ${time}
*/
class ModelPicture {
var id: String? = null
var longitude: String? = null
var latitude: String? = null
var date: String? = null
var pictureName: String? = null
var picturePath: String? = null
var parentId: String? = null
constructor()
constructor(id: String?, longitude: String?, latitude: String?, date: String?, pictureName: String?, picturePath: String?, parentId: String?) {
this.id = id
this.longitude = longitude
this.latitude = latitude
this.date = date
this.pictureName = pictureName
this.picturePath = picturePath
this.parentId = parentId
}
} | apache-2.0 | b5f6ce0958a2fbc2e1b98cda83e97621 | 25.75 | 147 | 0.632353 | 4.021505 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/inputreadings/InputReadingsViewModel.kt | 1 | 6325 | /*
* 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.healthconnectsample.presentation.screen.inputreadings
import android.os.RemoteException
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.WeightRecord
import androidx.health.connect.client.units.Mass
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.healthconnectsample.data.HealthConnectManager
import com.example.healthconnectsample.data.WeightData
import com.example.healthconnectsample.data.dateTimeWithOffsetOrDefault
import kotlinx.coroutines.launch
import java.io.IOException
import java.time.Instant
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import java.util.UUID
class InputReadingsViewModel(private val healthConnectManager: HealthConnectManager) :
ViewModel() {
private val healthConnectCompatibleApps = healthConnectManager.healthConnectCompatibleApps
val permissions = setOf(
HealthPermission.createReadPermission(WeightRecord::class),
HealthPermission.createWritePermission(WeightRecord::class),
)
var weeklyAvg: MutableState<Mass?> = mutableStateOf(Mass.kilograms(0.0))
private set
var permissionsGranted = mutableStateOf(false)
private set
var readingsList: MutableState<List<WeightData>> = mutableStateOf(listOf())
private set
var uiState: UiState by mutableStateOf(UiState.Uninitialized)
private set
val permissionsLauncher = healthConnectManager.requestPermissionsActivityContract()
fun initialLoad() {
viewModelScope.launch {
tryWithPermissionsCheck {
readWeightInputs()
}
}
}
fun inputReadings(inputValue: Double) {
viewModelScope.launch {
tryWithPermissionsCheck {
val time = ZonedDateTime.now().withNano(0)
val weight = WeightRecord(
weight = Mass.kilograms(inputValue),
time = time.toInstant(),
zoneOffset = time.offset
)
healthConnectManager.writeWeightInput(weight)
readWeightInputs()
}
}
}
fun deleteWeightInput(uid: String) {
viewModelScope.launch {
tryWithPermissionsCheck {
healthConnectManager.deleteWeightInput(uid)
readWeightInputs()
}
}
}
private suspend fun readWeightInputs() {
val startOfDay = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS)
val now = Instant.now()
val endofWeek = startOfDay.toInstant().plus(7, ChronoUnit.DAYS)
readingsList.value = healthConnectManager
.readWeightInputs(startOfDay.toInstant(), now)
.map { record ->
val packageName = record.metadata.dataOrigin.packageName
WeightData(
weight = record.weight,
id = record.metadata.id,
time = dateTimeWithOffsetOrDefault(record.time, record.zoneOffset),
sourceAppInfo = healthConnectCompatibleApps[packageName]
)
}
weeklyAvg.value =
healthConnectManager.computeWeeklyAverage(startOfDay.toInstant(), endofWeek)
}
/**
* Provides permission check and error handling for Health Connect suspend function calls.
*
* Permissions are checked prior to execution of [block], and if all permissions aren't granted
* the [block] won't be executed, and [permissionsGranted] will be set to false, which will
* result in the UI showing the permissions button.
*
* Where an error is caught, of the type Health Connect is known to throw, [uiState] is set to
* [UiState.Error], which results in the snackbar being used to show the error message.
*/
private suspend fun tryWithPermissionsCheck(block: suspend () -> Unit) {
permissionsGranted.value = healthConnectManager.hasAllPermissions(permissions)
uiState = try {
if (permissionsGranted.value) {
block()
}
UiState.Done
} catch (remoteException: RemoteException) {
UiState.Error(remoteException)
} catch (securityException: SecurityException) {
UiState.Error(securityException)
} catch (ioException: IOException) {
UiState.Error(ioException)
} catch (illegalStateException: IllegalStateException) {
UiState.Error(illegalStateException)
}
}
sealed class UiState {
object Uninitialized : UiState()
object Done : UiState()
// A random UUID is used in each Error object to allow errors to be uniquely identified,
// and recomposition won't result in multiple snackbars.
data class Error(val exception: Throwable, val uuid: UUID = UUID.randomUUID()) : UiState()
}
}
class InputReadingsViewModelFactory(
private val healthConnectManager: HealthConnectManager
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(InputReadingsViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return InputReadingsViewModel(
healthConnectManager = healthConnectManager
) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| apache-2.0 | 56d54b82a55542cfa8d01fcbc2aed261 | 38.04321 | 99 | 0.683004 | 5.29732 | false | false | false | false |
AndroidX/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/Text.kt | 3 | 15505 | /*
* 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.material
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Paragraph
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
/**
* High level element that displays text and provides semantics / accessibility information.
*
* The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If
* you are setting your own style, you may want to consider first retrieving [LocalTextStyle],
* and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific
* attributes you want to override.
*
* For ease of use, commonly used parameters from [TextStyle] are also present here. The order of
* precedence is as follows:
* - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]),
* then this parameter will always be used.
* - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value
* from [style] will be used instead.
*
* Additionally, for [color], if [color] is not set, and [style] does not have a color, then
* [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this
* [Text] or element containing this [Text] to adapt to different background colors and still
* maintain contrast and accessibility.
*
* @param text The text to be displayed.
* @param modifier [Modifier] to apply to this layout node.
* @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set,
* this will be [LocalContentColor].
* @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize].
* @param fontStyle The typeface variant to use when drawing the letters (e.g., italic).
* See [TextStyle.fontStyle].
* @param fontWeight The typeface thickness to use when painting the text (e.g., [FontWeight.Bold]).
* @param fontFamily The font family to be used when rendering the text. See [TextStyle.fontFamily].
* @param letterSpacing The amount of space to add between each letter.
* See [TextStyle.letterSpacing].
* @param textDecoration The decorations to paint on the text (e.g., an underline).
* See [TextStyle.textDecoration].
* @param textAlign The alignment of the text within the lines of the paragraph.
* See [TextStyle.textAlign].
* @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM.
* See [TextStyle.lineHeight].
* @param overflow How visual overflow should be handled.
* @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in the
* text will be positioned as if there was unlimited horizontal space. If [softWrap] is false,
* [overflow] and TextAlign may have unexpected effects.
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated according to
* [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines].
* @param minLines The minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines].
* @param onTextLayout Callback that is executed when a new text layout is calculated. A
* [TextLayoutResult] object that callback provides contains paragraph information, size of the
* text, baselines and other details. The callback can be used to add additional decoration or
* functionality to the text. For example, to draw selection around the text.
* @param style Style configuration for the text such as color, font, line height etc.
*/
@Composable
fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
val textColor = color.takeOrElse {
style.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
// NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that
// will avoid reallocating if all of the options here are the defaults
val mergedStyle = style.merge(
TextStyle(
color = textColor,
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing
)
)
BasicText(
text = text,
modifier = modifier,
style = mergedStyle,
onTextLayout = onTextLayout,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
minLines = minLines
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
Text(
text,
modifier,
color,
fontSize,
fontStyle,
fontWeight,
fontFamily,
letterSpacing,
textDecoration,
textAlign,
lineHeight,
overflow,
softWrap,
maxLines,
1,
onTextLayout,
style
)
}
/**
* High level element that displays text and provides semantics / accessibility information.
*
* The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If
* you are setting your own style, you may want to consider first retrieving [LocalTextStyle],
* and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific
* attributes you want to override.
*
* For ease of use, commonly used parameters from [TextStyle] are also present here. The order of
* precedence is as follows:
* - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]),
* then this parameter will always be used.
* - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value
* from [style] will be used instead.
*
* Additionally, for [color], if [color] is not set, and [style] does not have a color, then
* [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this
* [Text] or element containing this [Text] to adapt to different background colors and still
* maintain contrast and accessibility.
*
* @param text The text to be displayed.
* @param modifier [Modifier] to apply to this layout node.
* @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set,
* this will be [LocalContentColor].
* @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize].
* @param fontStyle The typeface variant to use when drawing the letters (e.g., italic).
* See [TextStyle.fontStyle].
* @param fontWeight The typeface thickness to use when painting the text (e.g., [FontWeight.Bold]).
* @param fontFamily The font family to be used when rendering the text. See [TextStyle.fontFamily].
* @param letterSpacing The amount of space to add between each letter.
* See [TextStyle.letterSpacing].
* @param textDecoration The decorations to paint on the text (e.g., an underline).
* See [TextStyle.textDecoration].
* @param textAlign The alignment of the text within the lines of the paragraph.
* See [TextStyle.textAlign].
* @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM.
* See [TextStyle.lineHeight].
* @param overflow How visual overflow should be handled.
* @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in the
* text will be positioned as if there was unlimited horizontal space. If [softWrap] is false,
* [overflow] and TextAlign may have unexpected effects.
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated according to
* [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines].
* @param minLines The minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines].
* @param inlineContent A map store composables that replaces certain ranges of the text. It's
* used to insert composables into text layout. Check [InlineTextContent] for more information.
* @param onTextLayout Callback that is executed when a new text layout is calculated. A
* [TextLayoutResult] object that callback provides contains paragraph information, size of the
* text, baselines and other details. The callback can be used to add additional decoration or
* functionality to the text. For example, to draw selection around the text.
* @param style Style configuration for the text such as color, font, line height etc.
*/
@Composable
fun Text(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
val textColor = color.takeOrElse {
style.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
// NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that
// will avoid reallocating if all of the options here are the defaults
val mergedStyle = style.merge(
TextStyle(
color = textColor,
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing
)
)
BasicText(
text = text,
modifier = modifier,
style = mergedStyle,
onTextLayout = onTextLayout,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
minLines = minLines,
inlineContent = inlineContent
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun Text(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
Text(
text,
modifier,
color,
fontSize,
fontStyle,
fontWeight,
fontFamily,
letterSpacing,
textDecoration,
textAlign,
lineHeight,
overflow,
softWrap,
maxLines,
1,
inlineContent,
onTextLayout,
style
)
}
/**
* CompositionLocal containing the preferred [TextStyle] that will be used by [Text] components by
* default. To set the value for this CompositionLocal, see [ProvideTextStyle] which will merge any
* missing [TextStyle] properties with the existing [TextStyle] set in this CompositionLocal.
*
* @see ProvideTextStyle
*/
val LocalTextStyle = compositionLocalOf(structuralEqualityPolicy()) { TextStyle.Default }
// TODO: b/156598010 remove this and replace with fold definition on the backing CompositionLocal
/**
* This function is used to set the current value of [LocalTextStyle], merging the given style
* with the current style values for any missing attributes. Any [Text] components included in
* this component's [content] will be styled with this style unless styled explicitly.
*
* @see LocalTextStyle
*/
@Composable
fun ProvideTextStyle(value: TextStyle, content: @Composable () -> Unit) {
val mergedStyle = LocalTextStyle.current.merge(value)
CompositionLocalProvider(LocalTextStyle provides mergedStyle, content = content)
}
| apache-2.0 | 6862e467b48dd2abc1be5784f509889f | 41.596154 | 100 | 0.713512 | 4.615957 | false | false | false | false |
AndroidX/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/ResolverExt.kt | 3 | 4565 | /*
* 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.room.compiler.processing.ksp
import androidx.room.compiler.processing.XExecutableElement
import androidx.room.compiler.processing.XMethodElement
import androidx.room.compiler.processing.ksp.synthetic.KspSyntheticPropertyMethodElement
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.google.devtools.ksp.symbol.KSTypeParameter
import com.google.devtools.ksp.symbol.Nullability
internal fun Resolver.findClass(qName: String) = getClassDeclarationByName(
getKSNameFromString(qName)
)
internal fun Resolver.requireClass(qName: String) = checkNotNull(findClass(qName)) {
"cannot find class $qName"
}
internal fun Resolver.requireType(qName: String) = requireClass(qName).asType(emptyList())
internal fun Resolver.requireContinuationClass() = requireClass("kotlin.coroutines.Continuation")
private fun XExecutableElement.getDeclarationForOverride(): KSDeclaration = when (this) {
is KspExecutableElement -> this.declaration
is KspSyntheticPropertyMethodElement -> this.field.declaration
else -> throw IllegalStateException("unexpected XExecutableElement type. $this")
}
internal fun Resolver.overrides(
overriderElement: XMethodElement,
overrideeElement: XMethodElement
): Boolean {
// in addition to functions declared in kotlin, we also synthesize getter/setter functions for
// properties which means we cannot simply send the declaration to KSP for override check
// (otherwise, it won't give us a definitive answer when java methods override property
// getters /setters or even we won't be able to distinguish between our own Getter/Setter
// synthetics).
// By cheaply checking parameter counts, we avoid all those cases and if KSP returns true, it
// won't include false positives.
if (overriderElement.parameters.size != overrideeElement.parameters.size) {
return false
}
val ksOverrider = overriderElement.getDeclarationForOverride()
val ksOverridee = overrideeElement.getDeclarationForOverride()
if (overrides(ksOverrider, ksOverridee)) {
// Make sure it also overrides in JVM descriptors as well.
// This happens in cases where parent class has `<T>` type argument and child class
// declares it has `Int` (a type that might map to a primitive). In those cases,
// KAPT generates two methods, 1 w/ primitive and 1 boxed so we replicate that behavior
// here. This code would change when we generate kotlin code.
if (ksOverridee is KSFunctionDeclaration && ksOverrider is KSFunctionDeclaration) {
return ksOverrider.overridesInJvm(ksOverridee)
}
return true
}
return false
}
/**
* If the overrider specifies a primitive value for a type argument, ignore the override as
* kotlin will generate two class methods for them.
*
* see: b/160258066 for details
*/
private fun KSFunctionDeclaration.overridesInJvm(
other: KSFunctionDeclaration
): Boolean {
parameters.forEachIndexed { index, myParam ->
val myParamType = myParam.type.resolve()
if (myParamType.nullability == Nullability.NOT_NULL) {
val myParamDecl = myParamType.declaration
val paramQName = myParamDecl.qualifiedName?.asString()
if (paramQName != null &&
KspTypeMapper.getPrimitiveJavaTypeName(paramQName) != null
) {
// parameter is a primitive. Check if the parent declared it as a type argument,
// in which case, we should ignore the override.
val otherParamDeclaration = other.parameters
.getOrNull(index)?.type?.resolve()?.declaration
if (otherParamDeclaration is KSTypeParameter) {
return false
}
}
}
}
return true
}
| apache-2.0 | bca2ce9fac374ff4fd353409ec9f9bab | 42.47619 | 98 | 0.723768 | 4.770115 | false | false | false | false |
pyamsoft/padlock | padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoDialog.kt | 1 | 6066 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.list.info
import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.CheckResult
import androidx.fragment.app.DialogFragment
import com.pyamsoft.padlock.Injector
import com.pyamsoft.padlock.PadLockComponent
import com.pyamsoft.padlock.R
import com.pyamsoft.padlock.loader.AppIconLoader
import com.pyamsoft.padlock.model.list.ActivityEntry
import com.pyamsoft.padlock.model.list.AppEntry
import com.pyamsoft.padlock.model.list.ListDiffProvider
import com.pyamsoft.pydroid.core.singleDisposable
import com.pyamsoft.pydroid.core.tryDispose
import com.pyamsoft.pydroid.ui.app.noTitle
import com.pyamsoft.pydroid.ui.app.requireArguments
import com.pyamsoft.pydroid.ui.util.show
import javax.inject.Inject
class LockInfoDialog : DialogFragment() {
@field:Inject internal lateinit var appIconLoader: AppIconLoader
@field:Inject internal lateinit var viewModel: LockInfoViewModel
@field:Inject internal lateinit var lockView: LockInfoView
private var databaseChangeDisposable by singleDisposable()
private var lockEventDisposable by singleDisposable()
private var populateDisposable by singleDisposable()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val appPackageName = requireArguments().getString(
ARG_APP_PACKAGE_NAME, "")
val appName = requireArguments().getString(
ARG_APP_NAME, "")
val appIcon = requireArguments().getInt(
ARG_APP_ICON, 0)
val appIsSystem = requireArguments().getBoolean(
ARG_APP_SYSTEM, false)
require(appPackageName.isNotBlank())
require(appName.isNotBlank())
val listStateTag = TAG + appPackageName
Injector.obtain<PadLockComponent>(requireContext().applicationContext)
.plusLockInfoComponent()
.activity(requireActivity())
.owner(viewLifecycleOwner)
.appName(appName)
.packageName(appPackageName)
.appIcon(appIcon)
.appSystem(appIsSystem)
.listStateTag(listStateTag)
.inflater(inflater)
.container(container)
.savedInstanceState(savedInstanceState)
.diffProvider(object : ListDiffProvider<ActivityEntry> {
override fun data(): List<ActivityEntry> = lockView.getListData()
})
.build()
.inject(this)
lockView.create()
return lockView.root()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState)
.noTitle()
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
lockView.onSwipeRefresh { populateList(true) }
lockView.onToolbarNavigationClicked { dismiss() }
lockView.onToolbarMenuItemClicked {
if (it == R.id.menu_explain_lock_type) {
LockInfoExplanationDialog()
.show(requireActivity(), "lock_info_explain")
}
}
databaseChangeDisposable = viewModel.onDatabaseChangeEvent(
onChange = { lockView.onDatabaseChangeReceived(it.index, it.entry) },
onError = { lockView.onDatabaseChangeError { populateList(true) } }
)
lockEventDisposable = viewModel.onLockEvent(
onWhitelist = { populateList(true) },
onError = { lockView.onModifyEntryError { populateList(true) } }
)
}
private fun populateList(forced: Boolean) {
populateDisposable = viewModel.populateList(forced,
onPopulateBegin = { lockView.onListPopulateBegin() },
onPopulateSuccess = { lockView.onListLoaded(it) },
onPopulateError = { lockView.onListPopulateError { populateList(true) } },
onPopulateComplete = { lockView.onListPopulated() }
)
}
override fun onDestroyView() {
super.onDestroyView()
databaseChangeDisposable.tryDispose()
lockEventDisposable.tryDispose()
populateDisposable.tryDispose()
}
override fun onStart() {
super.onStart()
populateList(false)
}
override fun onPause() {
super.onPause()
lockView.commitListState(null)
}
override fun onSaveInstanceState(outState: Bundle) {
lockView.commitListState(outState)
super.onSaveInstanceState(outState)
}
override fun onResume() {
super.onResume()
// The dialog is super small for some reason. We have to set the size manually, in onResume
dialog.window?.apply {
setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
setGravity(Gravity.CENTER)
}
}
companion object {
internal const val TAG = "LockInfoDialog"
private const val ARG_APP_PACKAGE_NAME = "app_packagename"
private const val ARG_APP_ICON = "app_icon"
private const val ARG_APP_NAME = "app_name"
private const val ARG_APP_SYSTEM = "app_system"
@CheckResult
@JvmStatic
fun newInstance(appEntry: AppEntry): LockInfoDialog {
return LockInfoDialog()
.apply {
arguments = Bundle().apply {
putString(ARG_APP_PACKAGE_NAME, appEntry.packageName)
putString(ARG_APP_NAME, appEntry.name)
putInt(ARG_APP_ICON, appEntry.icon)
putBoolean(ARG_APP_SYSTEM, appEntry.system)
}
}
}
}
}
| apache-2.0 | ab0888f7d926669706d18cfe7e647141 | 30.759162 | 95 | 0.713815 | 4.506686 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/ui/FailureErrorMessageFormatter.kt | 1 | 9640 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui
import batect.cli.CommandLineOptionsParser
import batect.config.Container
import batect.docker.DockerContainer
import batect.execution.CleanupOption
import batect.execution.RunOptions
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerCreationFailedEvent
import batect.execution.model.events.ContainerDidNotBecomeHealthyEvent
import batect.execution.model.events.ContainerRemovalFailedEvent
import batect.execution.model.events.ContainerRunFailedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.ContainerStopFailedEvent
import batect.execution.model.events.ExecutionFailedEvent
import batect.execution.model.events.ImageBuildFailedEvent
import batect.execution.model.events.ImagePullFailedEvent
import batect.execution.model.events.RunningContainerExitedEvent
import batect.execution.model.events.SetupCommandExecutionErrorEvent
import batect.execution.model.events.SetupCommandFailedEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskFailedEvent
import batect.execution.model.events.TaskNetworkCreationFailedEvent
import batect.execution.model.events.TaskNetworkDeletionFailedEvent
import batect.execution.model.events.TemporaryDirectoryDeletionFailedEvent
import batect.execution.model.events.TemporaryFileDeletionFailedEvent
import batect.execution.model.events.UserInterruptedExecutionEvent
import batect.os.SystemInfo
import batect.ui.text.Text
import batect.ui.text.TextRun
import batect.ui.text.join
class FailureErrorMessageFormatter(systemInfo: SystemInfo) {
private val newLine = systemInfo.lineSeparator
fun formatErrorMessage(event: TaskFailedEvent, runOptions: RunOptions): TextRun = when (event) {
is TaskNetworkCreationFailedEvent -> formatErrorMessage("Could not create network for task", event.message)
is ImageBuildFailedEvent -> formatErrorMessage("Could not build image from directory '${event.source.buildDirectory}'", event.message)
is ImagePullFailedEvent -> formatErrorMessage(Text("Could not pull image ") + Text.bold(event.source.imageName), event.message)
is ContainerCreationFailedEvent -> formatErrorMessage(Text("Could not create container ") + Text.bold(event.container.name), event.message)
is ContainerDidNotBecomeHealthyEvent -> formatErrorMessage(Text("Container ") + Text.bold(event.container.name) + Text(" did not become healthy"), event.message) + hintToReRunWithCleanupDisabled(runOptions)
is ContainerRunFailedEvent -> formatErrorMessage(Text("Could not run container ") + Text.bold(event.container.name), event.message)
is ContainerStopFailedEvent -> formatErrorMessage(Text("Could not stop container ") + Text.bold(event.container.name), event.message)
is ContainerRemovalFailedEvent -> formatErrorMessage(Text("Could not remove container ") + Text.bold(event.container.name), event.message)
is TaskNetworkDeletionFailedEvent -> formatErrorMessage("Could not delete the task network", event.message)
is TemporaryFileDeletionFailedEvent -> formatErrorMessage("Could not delete temporary file '${event.filePath}'", event.message)
is TemporaryDirectoryDeletionFailedEvent -> formatErrorMessage("Could not delete temporary directory '${event.directoryPath}'", event.message)
is SetupCommandExecutionErrorEvent -> formatErrorMessage(Text("Could not run setup command ") + Text.bold(event.command.command.originalCommand) + Text(" in container ") + Text.bold(event.container.name), event.message) + hintToReRunWithCleanupDisabled(runOptions)
is SetupCommandFailedEvent -> formatErrorMessage(Text("Setup command ") + Text.bold(event.command.command.originalCommand) + Text(" in container ") + Text.bold(event.container.name) + Text(" failed"), setupCommandFailedBodyText(event.exitCode, event.output)) + hintToReRunWithCleanupDisabled(runOptions)
is ExecutionFailedEvent -> formatErrorMessage("An unexpected exception occurred during execution", event.message)
is UserInterruptedExecutionEvent -> formatMessage("Task cancelled", TextRun("Interrupt received during execution"), "Waiting for outstanding operations to stop or finish before cleaning up...")
}
private fun formatErrorMessage(headline: String, body: String) = formatErrorMessage(TextRun(headline), body)
private fun formatErrorMessage(headline: TextRun, body: String) = formatMessage("Error", headline, body)
private fun formatMessage(type: String, headline: TextRun, body: String) = Text.red(Text.bold("$type: ") + headline + Text(".$newLine")) + Text(body)
private fun hintToReRunWithCleanupDisabled(runOptions: RunOptions): TextRun = when (runOptions.behaviourAfterFailure) {
CleanupOption.Cleanup -> Text("$newLine${newLine}You can re-run the task with ") + Text.bold("--${CommandLineOptionsParser.disableCleanupAfterFailureFlagName}") + Text(" to leave the created containers running to diagnose the issue.")
CleanupOption.DontCleanup -> TextRun("")
}
private fun setupCommandFailedBodyText(exitCode: Int, output: String): String = if (output.isEmpty()) {
"The command exited with code $exitCode and did not produce any output."
} else {
"The command exited with code $exitCode and output:$newLine$output"
}
fun formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>): TextRun {
return formatManualCleanupMessageWhenCleanupDisabled(events, cleanupCommands, CommandLineOptionsParser.disableCleanupAfterFailureFlagName, "Once you have finished investigating the issue")
}
fun formatManualCleanupMessageAfterTaskSuccessWithCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>): TextRun {
return formatManualCleanupMessageWhenCleanupDisabled(events, cleanupCommands, CommandLineOptionsParser.disableCleanupAfterSuccessFlagName, "Once you have finished using the containers")
}
private fun formatManualCleanupMessageWhenCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>, argumentName: String, cleanupPhrase: String): TextRun {
val containerCreationEvents = events.filterIsInstance<ContainerCreatedEvent>()
if (containerCreationEvents.isEmpty()) {
throw IllegalArgumentException("No containers were created and so this method should not be called.")
}
if (cleanupCommands.isEmpty()) {
throw IllegalArgumentException("No cleanup commands were provided.")
}
val containerMessages = containerCreationEvents
.sortedBy { it.container.name }
.map { event -> containerOutputAndExecInstructions(event.container, event.dockerContainer, events) }
.join()
val formattedCommands = cleanupCommands.joinToString(newLine)
return Text.red(Text("As the task was run with ") + Text.bold("--$argumentName") + Text(" or ") + Text.bold("--${CommandLineOptionsParser.disableCleanupFlagName}") + Text(", the created containers will not be cleaned up.$newLine")) +
containerMessages +
Text(newLine) +
Text("$cleanupPhrase, clean up all temporary resources created by batect by running:$newLine") +
Text.bold(formattedCommands)
}
private fun containerOutputAndExecInstructions(container: Container, dockerContainer: DockerContainer, events: Set<TaskEvent>): TextRun {
val neverStarted = events.none { it is ContainerStartedEvent && it.container == container }
val alreadyExited = events.any { it is RunningContainerExitedEvent && it.container == container }
val execCommand = if (neverStarted || alreadyExited) {
"docker start ${dockerContainer.id}; docker exec -it ${dockerContainer.id} <command>"
} else {
"docker exec -it ${dockerContainer.id} <command>"
}
return Text("For container ") + Text.bold(container.name) + Text(", view its output by running '") + Text.bold("docker logs ${dockerContainer.id}") + Text("', or run a command in the container with '") + Text.bold(execCommand) + Text("'.$newLine")
}
fun formatManualCleanupMessageAfterCleanupFailure(cleanupCommands: List<String>): TextRun {
if (cleanupCommands.isEmpty()) {
return TextRun()
}
val instruction = if (cleanupCommands.size == 1) {
"You may need to run the following command to clean up any remaining resources:"
} else {
"You may need to run some or all of the following commands to clean up any remaining resources:"
}
val formattedCommands = cleanupCommands.joinToString(newLine)
return Text.red("Clean up has failed, and batect cannot guarantee that all temporary resources created have been completely cleaned up.$newLine") +
Text(instruction) + Text(newLine) +
Text.bold(formattedCommands)
}
}
| apache-2.0 | 4c96238e9795cbc3dd99afb3eb456019 | 64.135135 | 311 | 0.758299 | 5.108638 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/graphics/vector/ImageVector.kt | 3 | 26203 | /*
* Copyright 2019 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.graphics.vector
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.unit.Dp
/**
* Vector graphics object that is generated as a result of [ImageVector.Builder]
* It can be composed and rendered by passing it as an argument to [rememberVectorPainter]
*/
@Immutable
class ImageVector internal constructor(
/**
* Name of the Vector asset
*/
val name: String,
/**
* Intrinsic width of the vector asset in [Dp]
*/
val defaultWidth: Dp,
/**
* Intrinsic height of the vector asset in [Dp]
*/
val defaultHeight: Dp,
/**
* Used to define the width of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*/
val viewportWidth: Float,
/**
* Used to define the height of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*/
val viewportHeight: Float,
/**
* Root group of the vector asset that contains all the child groups and paths
*/
val root: VectorGroup,
/**
* Optional tint color to be applied to the vector graphic
*/
val tintColor: Color,
/**
* Blend mode used to apply [tintColor]
*/
val tintBlendMode: BlendMode,
/**
* Determines if the vector asset should automatically be mirrored for right to left locales
*/
val autoMirror: Boolean
) {
/**
* Builder used to construct a Vector graphic tree.
* This is useful for caching the result of expensive operations used to construct
* a vector graphic for compose.
* For example, the vector graphic could be serialized and downloaded from a server and represented
* internally in a ImageVector before it is composed through [rememberVectorPainter]
* The generated ImageVector is recommended to be memoized across composition calls to avoid
* doing redundant work
*/
@Suppress("MissingGetterMatchingBuilder")
class Builder(
/**
* Name of the vector asset
*/
private val name: String = DefaultGroupName,
/**
* Intrinsic width of the Vector in [Dp]
*/
private val defaultWidth: Dp,
/**
* Intrinsic height of the Vector in [Dp]
*/
private val defaultHeight: Dp,
/**
* Used to define the width of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*/
private val viewportWidth: Float,
/**
* Used to define the height of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*/
private val viewportHeight: Float,
/**
* Optional color used to tint the entire vector image
*/
private val tintColor: Color = Color.Unspecified,
/**
* Blend mode used to apply the tint color
*/
private val tintBlendMode: BlendMode = BlendMode.SrcIn,
/**
* Determines if the vector asset should automatically be mirrored for right to left locales
*/
private val autoMirror: Boolean = false
) {
// Secondary constructor to maintain API compatibility that defaults autoMirror to false
@Deprecated(
"Replace with ImageVector.Builder that consumes an optional auto " +
"mirror parameter",
replaceWith = ReplaceWith(
"Builder(name, defaultWidth, defaultHeight, viewportWidth, " +
"viewportHeight, tintColor, tintBlendMode, false)",
"androidx.compose.ui.graphics.vector"
),
DeprecationLevel.HIDDEN
)
constructor(
/**
* Name of the vector asset
*/
name: String = DefaultGroupName,
/**
* Intrinsic width of the Vector in [Dp]
*/
defaultWidth: Dp,
/**
* Intrinsic height of the Vector in [Dp]
*/
defaultHeight: Dp,
/**
* Used to define the width of the viewport space. Viewport is basically the virtual
* canvas where the paths are drawn on.
*/
viewportWidth: Float,
/**
* Used to define the height of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*/
viewportHeight: Float,
/**
* Optional color used to tint the entire vector image
*/
tintColor: Color = Color.Unspecified,
/**
* Blend mode used to apply the tint color
*/
tintBlendMode: BlendMode = BlendMode.SrcIn
) : this(
name,
defaultWidth,
defaultHeight,
viewportWidth,
viewportHeight,
tintColor,
tintBlendMode,
false
)
private val nodes = ArrayList<GroupParams>()
private var root = GroupParams()
private var isConsumed = false
private val currentGroup: GroupParams
get() = nodes.peek()
init {
nodes.push(root)
}
/**
* Create a new group and push it to the front of the stack of ImageVector nodes
*
* @param name the name of the group
* @param rotate the rotation of the group in degrees
* @param pivotX the x coordinate of the pivot point to rotate or scale the group
* @param pivotY the y coordinate of the pivot point to rotate or scale the group
* @param scaleX the scale factor in the X-axis to apply to the group
* @param scaleY the scale factor in the Y-axis to apply to the group
* @param translationX the translation in virtual pixels to apply along the x-axis
* @param translationY the translation in virtual pixels to apply along the y-axis
* @param clipPathData the path information used to clip the content within the group
*
* @return This ImageVector.Builder instance as a convenience for chaining calls
*/
@Suppress("MissingGetterMatchingBuilder")
fun addGroup(
name: String = DefaultGroupName,
rotate: Float = DefaultRotation,
pivotX: Float = DefaultPivotX,
pivotY: Float = DefaultPivotY,
scaleX: Float = DefaultScaleX,
scaleY: Float = DefaultScaleY,
translationX: Float = DefaultTranslationX,
translationY: Float = DefaultTranslationY,
clipPathData: List<PathNode> = EmptyPath
): Builder {
ensureNotConsumed()
val group = GroupParams(
name,
rotate,
pivotX,
pivotY,
scaleX,
scaleY,
translationX,
translationY,
clipPathData
)
nodes.push(group)
return this
}
/**
* Pops the topmost VectorGroup from this ImageVector.Builder. This is used to indicate
* that no additional ImageVector nodes will be added to the current VectorGroup
* @return This ImageVector.Builder instance as a convenience for chaining calls
*/
fun clearGroup(): Builder {
ensureNotConsumed()
val popped = nodes.pop()
currentGroup.children.add(popped.asVectorGroup())
return this
}
/**
* Add a path to the ImageVector graphic. This represents a leaf node in the ImageVector graphics
* tree structure
*
* @param pathData path information to render the shape of the path
* @param pathFillType rule to determine how the interior of the path is to be calculated
* @param name the name of the path
* @param fill specifies the [Brush] used to fill the path
* @param fillAlpha the alpha to fill the path
* @param stroke specifies the [Brush] used to fill the stroke
* @param strokeAlpha the alpha to stroke the path
* @param strokeLineWidth the width of the line to stroke the path
* @param strokeLineCap specifies the linecap for a stroked path
* @param strokeLineJoin specifies the linejoin for a stroked path
* @param strokeLineMiter specifies the miter limit for a stroked path
* @param trimPathStart specifies the fraction of the path to trim from the start in the
* range from 0 to 1. Values outside the range will wrap around the length of the path.
* Default is 0.
* @param trimPathStart specifies the fraction of the path to trim from the end in the
* range from 0 to 1. Values outside the range will wrap around the length of the path.
* Default is 1.
* @param trimPathOffset specifies the fraction to shift the path trim region in the range
* from 0 to 1. Values outside the range will wrap around the length of the path. Default is 0.
*
* @return This ImageVector.Builder instance as a convenience for chaining calls
*/
@Suppress("MissingGetterMatchingBuilder")
fun addPath(
pathData: List<PathNode>,
pathFillType: PathFillType = DefaultFillType,
name: String = DefaultPathName,
fill: Brush? = null,
fillAlpha: Float = 1.0f,
stroke: Brush? = null,
strokeAlpha: Float = 1.0f,
strokeLineWidth: Float = DefaultStrokeLineWidth,
strokeLineCap: StrokeCap = DefaultStrokeLineCap,
strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin,
strokeLineMiter: Float = DefaultStrokeLineMiter,
trimPathStart: Float = DefaultTrimPathStart,
trimPathEnd: Float = DefaultTrimPathEnd,
trimPathOffset: Float = DefaultTrimPathOffset
): Builder {
ensureNotConsumed()
currentGroup.children.add(
VectorPath(
name,
pathData,
pathFillType,
fill,
fillAlpha,
stroke,
strokeAlpha,
strokeLineWidth,
strokeLineCap,
strokeLineJoin,
strokeLineMiter,
trimPathStart,
trimPathEnd,
trimPathOffset
)
)
return this
}
/**
* Construct a ImageVector. This concludes the creation process of a ImageVector graphic
* This builder cannot be re-used to create additional ImageVector instances
* @return The newly created ImageVector instance
*/
fun build(): ImageVector {
ensureNotConsumed()
// pop all groups except for the root
while (nodes.size > 1) {
clearGroup()
}
val vectorImage = ImageVector(
name,
defaultWidth,
defaultHeight,
viewportWidth,
viewportHeight,
root.asVectorGroup(),
tintColor,
tintBlendMode,
autoMirror
)
isConsumed = true
return vectorImage
}
/**
* Throws IllegalStateException if the ImageVector.Builder has already been consumed
*/
private fun ensureNotConsumed() {
check(!isConsumed) {
"ImageVector.Builder is single use, create a new instance " +
"to create a new ImageVector"
}
}
/**
* Helper method to create an immutable VectorGroup object
* from an set of GroupParams which represent a group
* that is in the middle of being constructed
*/
private fun GroupParams.asVectorGroup(): VectorGroup =
VectorGroup(
name,
rotate,
pivotX,
pivotY,
scaleX,
scaleY,
translationX,
translationY,
clipPathData,
children
)
/**
* Internal helper class to help assist with in progress creation of
* a vector group before creating the immutable result
*/
private class GroupParams(
var name: String = DefaultGroupName,
var rotate: Float = DefaultRotation,
var pivotX: Float = DefaultPivotX,
var pivotY: Float = DefaultPivotY,
var scaleX: Float = DefaultScaleX,
var scaleY: Float = DefaultScaleY,
var translationX: Float = DefaultTranslationX,
var translationY: Float = DefaultTranslationY,
var clipPathData: List<PathNode> = EmptyPath,
var children: MutableList<VectorNode> = mutableListOf()
)
}
/**
* Provide an empty companion object to hang platform-specific companion extensions onto.
*/
companion object { } // ktlint-disable no-empty-class-body
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ImageVector) return false
if (name != other.name) return false
if (defaultWidth != other.defaultWidth) return false
if (defaultHeight != other.defaultHeight) return false
if (viewportWidth != other.viewportWidth) return false
if (viewportHeight != other.viewportHeight) return false
if (root != other.root) return false
if (tintColor != other.tintColor) return false
if (tintBlendMode != other.tintBlendMode) return false
if (autoMirror != other.autoMirror) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + defaultWidth.hashCode()
result = 31 * result + defaultHeight.hashCode()
result = 31 * result + viewportWidth.hashCode()
result = 31 * result + viewportHeight.hashCode()
result = 31 * result + root.hashCode()
result = 31 * result + tintColor.hashCode()
result = 31 * result + tintBlendMode.hashCode()
result = 31 * result + autoMirror.hashCode()
return result
}
}
sealed class VectorNode
/**
* Defines a group of paths or subgroups, plus transformation information.
* The transformations are defined in the same coordinates as the viewport.
* The transformations are applied in the order of scale, rotate then translate.
*
* This is constructed as part of the result of [ImageVector.Builder] construction
*/
@Immutable
class VectorGroup internal constructor(
/**
* Name of the corresponding group
*/
val name: String = DefaultGroupName,
/**
* Rotation of the group in degrees
*/
val rotation: Float = DefaultRotation,
/**
* X coordinate of the pivot point to rotate or scale the group
*/
val pivotX: Float = DefaultPivotX,
/**
* Y coordinate of the pivot point to rotate or scale the group
*/
val pivotY: Float = DefaultPivotY,
/**
* Scale factor in the X-axis to apply to the group
*/
val scaleX: Float = DefaultScaleX,
/**
* Scale factor in the Y-axis to apply to the group
*/
val scaleY: Float = DefaultScaleY,
/**
* Translation in virtual pixels to apply along the x-axis
*/
val translationX: Float = DefaultTranslationX,
/**
* Translation in virtual pixels to apply along the y-axis
*/
val translationY: Float = DefaultTranslationY,
/**
* Path information used to clip the content within the group
*/
val clipPathData: List<PathNode> = EmptyPath,
/**
* Child Vector nodes that are part of this group, this can contain
* paths or other groups
*/
private val children: List<VectorNode> = emptyList()
) : VectorNode(), Iterable<VectorNode> {
val size: Int
get() = children.size
operator fun get(index: Int): VectorNode {
return children[index]
}
override fun iterator(): Iterator<VectorNode> {
return object : Iterator<VectorNode> {
val it = children.iterator()
override fun hasNext(): Boolean = it.hasNext()
override fun next(): VectorNode = it.next()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is VectorGroup) return false
if (name != other.name) return false
if (rotation != other.rotation) return false
if (pivotX != other.pivotX) return false
if (pivotY != other.pivotY) return false
if (scaleX != other.scaleX) return false
if (scaleY != other.scaleY) return false
if (translationX != other.translationX) return false
if (translationY != other.translationY) return false
if (clipPathData != other.clipPathData) return false
if (children != other.children) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + rotation.hashCode()
result = 31 * result + pivotX.hashCode()
result = 31 * result + pivotY.hashCode()
result = 31 * result + scaleX.hashCode()
result = 31 * result + scaleY.hashCode()
result = 31 * result + translationX.hashCode()
result = 31 * result + translationY.hashCode()
result = 31 * result + clipPathData.hashCode()
result = 31 * result + children.hashCode()
return result
}
}
/**
* Leaf node of a Vector graphics tree. This specifies a path shape and parameters
* to color and style the shape itself
*
* This is constructed as part of the result of [ImageVector.Builder] construction
*/
@Immutable
class VectorPath internal constructor(
/**
* Name of the corresponding path
*/
val name: String = DefaultPathName,
/**
* Path information to render the shape of the path
*/
val pathData: List<PathNode>,
/**
* Rule to determine how the interior of the path is to be calculated
*/
val pathFillType: PathFillType,
/**
* Specifies the color or gradient used to fill the path
*/
val fill: Brush? = null,
/**
* Opacity to fill the path
*/
val fillAlpha: Float = 1.0f,
/**
* Specifies the color or gradient used to fill the stroke
*/
val stroke: Brush? = null,
/**
* Opacity to stroke the path
*/
val strokeAlpha: Float = 1.0f,
/**
* Width of the line to stroke the path
*/
val strokeLineWidth: Float = DefaultStrokeLineWidth,
/**
* Specifies the linecap for a stroked path, either butt, round, or square. The default is butt.
*/
val strokeLineCap: StrokeCap = DefaultStrokeLineCap,
/**
* Specifies the linejoin for a stroked path, either miter, round or bevel. The default is miter
*/
val strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin,
/**
* Specifies the miter limit for a stroked path, the default is 4
*/
val strokeLineMiter: Float = DefaultStrokeLineMiter,
/**
* Specifies the fraction of the path to trim from the start, in the range from 0 to 1.
* The default is 0.
*/
val trimPathStart: Float = DefaultTrimPathStart,
/**
* Specifies the fraction of the path to trim from the end, in the range from 0 to 1.
* The default is 1.
*/
val trimPathEnd: Float = DefaultTrimPathEnd,
/**
* Specifies the offset of the trim region (allows showed region to include the start and end),
* in the range from 0 to 1. The default is 0.
*/
val trimPathOffset: Float = DefaultTrimPathOffset
) : VectorNode() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as VectorPath
if (name != other.name) return false
if (fill != other.fill) return false
if (fillAlpha != other.fillAlpha) return false
if (stroke != other.stroke) return false
if (strokeAlpha != other.strokeAlpha) return false
if (strokeLineWidth != other.strokeLineWidth) return false
if (strokeLineCap != other.strokeLineCap) return false
if (strokeLineJoin != other.strokeLineJoin) return false
if (strokeLineMiter != other.strokeLineMiter) return false
if (trimPathStart != other.trimPathStart) return false
if (trimPathEnd != other.trimPathEnd) return false
if (trimPathOffset != other.trimPathOffset) return false
if (pathFillType != other.pathFillType) return false
if (pathData != other.pathData) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + pathData.hashCode()
result = 31 * result + (fill?.hashCode() ?: 0)
result = 31 * result + fillAlpha.hashCode()
result = 31 * result + (stroke?.hashCode() ?: 0)
result = 31 * result + strokeAlpha.hashCode()
result = 31 * result + strokeLineWidth.hashCode()
result = 31 * result + strokeLineCap.hashCode()
result = 31 * result + strokeLineJoin.hashCode()
result = 31 * result + strokeLineMiter.hashCode()
result = 31 * result + trimPathStart.hashCode()
result = 31 * result + trimPathEnd.hashCode()
result = 31 * result + trimPathOffset.hashCode()
result = 31 * result + pathFillType.hashCode()
return result
}
}
/**
* DSL extension for adding a [VectorPath] to [this].
*
* See [ImageVector.Builder.addPath] for the corresponding builder function.
*
* @param name the name for this path
* @param fill specifies the [Brush] used to fill the path
* @param fillAlpha the alpha to fill the path
* @param stroke specifies the [Brush] used to fill the stroke
* @param strokeAlpha the alpha to stroke the path
* @param strokeLineWidth the width of the line to stroke the path
* @param strokeLineCap specifies the linecap for a stroked path
* @param strokeLineJoin specifies the linejoin for a stroked path
* @param strokeLineMiter specifies the miter limit for a stroked path
* @param pathBuilder [PathBuilder] lambda for adding [PathNode]s to this path.
*/
inline fun ImageVector.Builder.path(
name: String = DefaultPathName,
fill: Brush? = null,
fillAlpha: Float = 1.0f,
stroke: Brush? = null,
strokeAlpha: Float = 1.0f,
strokeLineWidth: Float = DefaultStrokeLineWidth,
strokeLineCap: StrokeCap = DefaultStrokeLineCap,
strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin,
strokeLineMiter: Float = DefaultStrokeLineMiter,
pathFillType: PathFillType = DefaultFillType,
pathBuilder: PathBuilder.() -> Unit
) = addPath(
PathData(pathBuilder),
pathFillType,
name,
fill,
fillAlpha,
stroke,
strokeAlpha,
strokeLineWidth,
strokeLineCap,
strokeLineJoin,
strokeLineMiter
)
/**
* DSL extension for adding a [VectorGroup] to [this].
*
* See [ImageVector.Builder.pushGroup] for the corresponding builder function.
*
* @param name the name of the group
* @param rotate the rotation of the group in degrees
* @param pivotX the x coordinate of the pivot point to rotate or scale the group
* @param pivotY the y coordinate of the pivot point to rotate or scale the group
* @param scaleX the scale factor in the X-axis to apply to the group
* @param scaleY the scale factor in the Y-axis to apply to the group
* @param translationX the translation in virtual pixels to apply along the x-axis
* @param translationY the translation in virtual pixels to apply along the y-axis
* @param clipPathData the path information used to clip the content within the group
* @param block builder lambda to add children to this group
*/
inline fun ImageVector.Builder.group(
name: String = DefaultGroupName,
rotate: Float = DefaultRotation,
pivotX: Float = DefaultPivotX,
pivotY: Float = DefaultPivotY,
scaleX: Float = DefaultScaleX,
scaleY: Float = DefaultScaleY,
translationX: Float = DefaultTranslationX,
translationY: Float = DefaultTranslationY,
clipPathData: List<PathNode> = EmptyPath,
block: ImageVector.Builder.() -> Unit
) = apply {
addGroup(
name,
rotate,
pivotX,
pivotY,
scaleX,
scaleY,
translationX,
translationY,
clipPathData
)
block()
clearGroup()
}
private fun <T> ArrayList<T>.push(value: T): Boolean = add(value)
private fun <T> ArrayList<T>.pop(): T = this.removeAt(size - 1)
private fun <T> ArrayList<T>.peek(): T = this[size - 1]
| apache-2.0 | 1f787b2f0942e4976ad2fbe8c6a1739f | 33.162973 | 105 | 0.614624 | 5.111783 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/search/SearchFormFragment.kt | 1 | 6007 | package com.sedsoftware.yaptalker.presentation.feature.search
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxAdapterView
import com.jakewharton.rxbinding2.widget.RxRadioGroup
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.common.annotation.LayoutResource
import com.sedsoftware.yaptalker.presentation.base.BaseFragment
import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.FragmentLifecycle
import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationSection
import com.sedsoftware.yaptalker.presentation.extensions.string
import com.sedsoftware.yaptalker.presentation.feature.search.options.SearchConditions
import com.sedsoftware.yaptalker.presentation.feature.search.options.SortingMode
import com.sedsoftware.yaptalker.presentation.feature.search.options.TargetPeriod
import com.uber.autodispose.kotlin.autoDisposable
import kotlinx.android.synthetic.main.fragment_site_search.search_box_chaos
import kotlinx.android.synthetic.main.fragment_site_search.search_box_communication
import kotlinx.android.synthetic.main.fragment_site_search.search_box_feed
import kotlinx.android.synthetic.main.fragment_site_search.search_button
import kotlinx.android.synthetic.main.fragment_site_search.search_group_conditions
import kotlinx.android.synthetic.main.fragment_site_search.search_group_sorting
import kotlinx.android.synthetic.main.fragment_site_search.search_period_spinner
import kotlinx.android.synthetic.main.fragment_site_search.search_target_text
import java.util.ArrayList
import javax.inject.Inject
@LayoutResource(value = R.layout.fragment_site_search)
class SearchFormFragment : BaseFragment(), SearchFormView {
companion object {
fun getNewInstance() = SearchFormFragment()
private const val SEARCH_IN = "titles"
private const val CATEGORY_ALL = "all"
private const val ALL_CATEGORIES_SIZE = 3
private const val CATEGORY_FEED = "c_2"
private const val CATEGORY_COMMUNICATION = "c_5"
private const val CATEGORY_CHAOS = "c_3"
}
private var currentSearchPeriod = TargetPeriod.ALL_TIME
private var currentSearchConditions = SearchConditions.ANY_WORD
private var currentSortingMode = SortingMode.DATE
@Inject
@InjectPresenter
lateinit var presenter: SearchFormPresenter
@ProvidePresenter
fun provideSearchFormPresenter() = presenter
@Suppress("MagicNumber")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
RxAdapterView
.itemSelections(search_period_spinner)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe { itemId: Int? ->
currentSearchPeriod = when (itemId) {
1 -> TargetPeriod.TODAY
2 -> TargetPeriod.DAYS_7
3 -> TargetPeriod.DAYS_30
4 -> TargetPeriod.DAYS_60
5 -> TargetPeriod.DAYS_90
6 -> TargetPeriod.DAYS_180
7 -> TargetPeriod.DAYS_365
else -> TargetPeriod.ALL_TIME
}
}
RxRadioGroup
.checkedChanges(search_group_conditions)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe { itemId: Int? ->
currentSearchConditions = when (itemId) {
R.id.search_rb_words_all -> SearchConditions.ALL_WORDS
R.id.search_rb_words_phrase -> SearchConditions.EXACT_PHRASE
else -> SearchConditions.ANY_WORD
}
}
RxRadioGroup
.checkedChanges(search_group_sorting)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe { itemId: Int? ->
currentSortingMode = when (itemId) {
R.id.search_rb_relevant -> SortingMode.DATE
else -> SortingMode.RELEVANT
}
}
RxView
.clicks(search_button)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe { prepareSearchRequest() }
}
override fun updateCurrentUiState() {
setCurrentAppbarTitle(string(R.string.nav_drawer_search))
setCurrentNavDrawerItem(NavigationSection.SITE_SEARCH)
}
override fun hideKeyboard() {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view?.windowToken, 0)
}
private fun getCheckedCategories(): List<String> {
val categories: MutableList<String> = ArrayList()
if (search_box_feed.isChecked) {
categories.add(CATEGORY_FEED)
}
if (search_box_communication.isChecked) {
categories.add(CATEGORY_COMMUNICATION)
}
if (search_box_chaos.isChecked) {
categories.add(CATEGORY_CHAOS)
}
if (categories.isEmpty() || categories.size == ALL_CATEGORIES_SIZE) {
return listOf(CATEGORY_ALL)
}
return categories
}
private fun prepareSearchRequest() {
val searchText = search_target_text.text.toString()
if (searchText.isEmpty()) {
return
}
val request = SearchRequest(
searchFor = searchText,
targetForums = getCheckedCategories(),
searchIn = SEARCH_IN,
searchHow = currentSearchConditions,
searchInTags = false,
sortBy = currentSortingMode,
periodInDays = currentSearchPeriod
)
presenter.performSearchRequest(request)
}
}
| apache-2.0 | 7ac1848dc10b3a38a76da115a87da031 | 37.018987 | 96 | 0.681039 | 4.899674 | false | false | false | false |
google/android-auto-companion-android | trustagent/src/com/google/android/libraries/car/trustagent/blemessagestream/MessageStream.kt | 1 | 9332 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent.blemessagestream
import android.bluetooth.BluetoothDevice
import androidx.annotation.IntRange
import com.google.android.companionprotos.OperationProto.OperationType
import com.google.android.encryptionrunner.Key
import com.google.android.libraries.car.trustagent.blemessagestream.version2.BluetoothMessageStreamV2
import com.google.android.libraries.car.trustagent.util.loge
import com.google.android.libraries.car.trustagent.util.logi
import com.google.android.libraries.car.trustagent.util.logwtf
import java.util.Objects
import java.util.UUID
import java.util.zip.DataFormatException
import java.util.zip.Deflater
import java.util.zip.Inflater
/**
* Handles the streaming of messages to a specific [BluetoothDevice].
*
* This stream will handle if messages to a particular remote device need to be split into multiple
* messages or if the messages can be sent all at once. Internally, it will have its own protocol
* for how the split messages are structured.
*/
interface MessageStream {
/** Encryption key used to encrypt/decrypt data over this stream. */
var encryptionKey: Key?
/**
* Sends the given [streamMessage] to remote device and returns a message id generated for
* [streamMessage].
*
* The given message will adhere to the size limit of delivery channel. If the wrapped message is
* greater than the limit, then this stream should take the appropriate actions necessary to chunk
* the message to the device so that no parts of the message is dropped. The message id that will
* be return is an [Int] internally assigned to [streamMessage]. When [streamMessage] is sent out,
* callback [Callback.onMessageSent] will be invoked with this message id. If the sending fails,
* remote device will be disconnected. Message id will never be negative.
*/
@IntRange(from = 0) fun sendMessage(streamMessage: StreamMessage): Int
fun registerMessageEventCallback(callback: Callback)
fun unregisterMessageEventCallback(callback: Callback)
/** Encrypts the payload; throws exception if encrypted is not requested. */
fun StreamMessage.toEncrypted(): StreamMessage {
check(isPayloadEncrypted) { "StreamMessage should not be encrypted: $this" }
val key = checkNotNull(encryptionKey) { "Could not encrypt $this; encryption key is null." }
val encrypted = key.encryptData(payload)
return copy(payload = encrypted)
}
/** Decrypts the payload; throws exception if it is not marked as encrypted. */
fun StreamMessage.toDecrypted(): StreamMessage {
check(isPayloadEncrypted) { "StreamMessage is not encrypted: $this" }
val key = checkNotNull(encryptionKey) { "Could not decrypt $this; encryption key is null." }
val decrypted = key.decryptData(payload)
return copy(payload = decrypted, isPayloadEncrypted = false)
}
/**
* Compresses the payload.
*
* Data should be compressed before it's encrypted.
*/
fun StreamMessage.toCompressed(): StreamMessage {
if (isCompressed) {
loge(TAG, "StreamMessage compression: message is already compressed. Returning as is.")
return this
}
val compressed = compressData(payload)
if (compressed == null) {
logi(TAG, "Compression did not result in positive net savings. Returning as is.")
return this
}
var originalSize = payload.size
val saving = Math.round(100L * (originalSize - compressed.size) / originalSize.toDouble())
logi(TAG, "Compressed from $originalSize to ${compressed.size} bytes saved $saving%.")
return copy(payload = compressed, originalMessageSize = originalSize)
}
/**
* Decompresses the payload.
*
* Data should be decrypted before they are decompressed.
*/
fun StreamMessage.toDecompressed(): StreamMessage {
if (!isCompressed) {
return this
}
val decompressed = decompressData(payload, originalMessageSize)
if (decompressed == null) {
logwtf(TAG, "Could not decompress $this. Returning as is.")
return this
}
return copy(payload = decompressed, originalMessageSize = 0)
}
/** Callbacks that will be invoked for message events. */
interface Callback {
/** Invoked when the specified [streamMessage] has been received. */
fun onMessageReceived(streamMessage: StreamMessage)
/** Invoked when the specified [streamMessage] has been sent successfully. */
fun onMessageSent(messageId: Int)
}
companion object {
private const val TAG = "MessageStream"
private val inflater = Inflater()
private val deflater = Deflater(Deflater.BEST_COMPRESSION)
/**
* Compresses input and return the resulting [ByteArray].
*
* Returns `null` if compressed result is larger than the original input.
*/
internal fun compressData(byteArray: ByteArray): ByteArray? {
val buffer = ByteArray(byteArray.size)
val compressedSize =
deflater.run {
reset()
setInput(byteArray)
finish()
deflate(buffer)
}
// Unfinished deflater means compression generated data larger than the original input.
// Return null to indicate it should not be compressed.
if (!deflater.finished()) {
return null
}
return buffer.take(compressedSize).toByteArray()
}
/**
* Decompresses input and returns the resulting [ByteArray].
*
* @param originalSize The size of [byteArray] before compression.
*
* Returns `null` if [byteArray] could not be decompressed.
*/
internal fun decompressData(
byteArray: ByteArray,
@IntRange(from = 0) originalSize: Int
): ByteArray? {
if (originalSize == 0) {
logi(TAG, "Decompression: input is not compressed because original size is 0.")
return byteArray
}
val decompressedData = ByteArray(originalSize)
try {
inflater.run {
reset()
setInput(byteArray)
inflate(decompressedData)
}
} catch (exception: DataFormatException) {
loge(TAG, "An error occurred while decompressing the message.", exception)
return null
}
if (!inflater.finished()) {
loge(TAG, "Inflater is not finished after decompression.")
return null
}
logi(TAG, "Decompressed message from ${byteArray.size} to $originalSize bytes.")
return decompressedData
}
/**
* Creates an implementation of [MessageStream] with [bluetoothManager], based on
* [messageVersion].
*
* [messageVersion] must be no less than ConnectionResolver.MIN_MESSAGING_VERSION.
*/
fun create(
@IntRange(from = 2) messageVersion: Int,
bluetoothManager: BluetoothConnectionManager
): MessageStream? {
return when (messageVersion) {
2 -> {
logi(TAG, "Creating MessageStreamV2 without compression support")
BluetoothMessageStreamV2(bluetoothManager, isCompressionEnabled = false)
}
3 -> {
logi(TAG, "Creating MessageStreamV2 with compression support")
BluetoothMessageStreamV2(bluetoothManager, isCompressionEnabled = true)
}
else -> {
loge(TAG, "Unrecognized message version $messageVersion. No stream created.")
return null
}
}
}
}
}
/**
* The [payload] to be sent and its metadata.
*
* @property payload Bytes to be sent.
* @property operation The [OperationType] of this message.
* @property isPayloadEncrypted For a outgoing message, `true` if the payload should be encrypted;
* For an incoming message, `true` is the payload is encrypted.
* @property originalMessageSize If payload is compressed, its original size.
* 0 if payload is not compressed.
* @property recipient Identifies the intended receiver of payload.
*/
data class StreamMessage(
val payload: ByteArray,
val operation: OperationType,
val isPayloadEncrypted: Boolean,
val originalMessageSize: Int,
val recipient: UUID?
) {
val isCompressed: Boolean = originalMessageSize > 0
// Kotlin cannot properly generate these common functions for array property [payload].
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is StreamMessage) return false
return payload.contentEquals(other.payload) &&
operation == other.operation &&
isPayloadEncrypted == other.isPayloadEncrypted &&
recipient == other.recipient &&
originalMessageSize == other.originalMessageSize
}
override fun hashCode() =
Objects.hash(
payload.contentHashCode(),
recipient,
operation,
isPayloadEncrypted,
originalMessageSize
)
}
| apache-2.0 | e7b2c5caeda070580d8b3f3b7792da3d | 34.754789 | 101 | 0.700064 | 4.744281 | false | false | false | false |
jankotek/MapDB | src/test/java/org/mapdb/store/StoreTest.kt | 2 | 21342 | package org.mapdb.store
import io.kotlintest.shouldBe
import org.eclipse.collections.impl.list.mutable.primitive.LongArrayList
import org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap
import org.junit.Assert.*
import org.junit.Test
import org.mapdb.DBException
import org.mapdb.TT
import org.mapdb.io.DataIO
import org.mapdb.io.DataInput2
import org.mapdb.io.DataOutput2
import org.mapdb.ser.Serializer
import org.mapdb.ser.Serializers
import org.mapdb.ser.Serializers.LONG
import org.mapdb.store.li.LiStore
import java.util.*
import java.util.concurrent.atomic.AtomicLong
class HeapBufStoreTest : StoreTest() {
override fun openStore() = HeapBufStore()
}
class HeapBufStoreRWLockTest : StoreTest() {
override fun openStore() = HeapBufStoreRWLock()
}
class ConcMapStoreTest : StoreTest() {
override fun openStore() = ConcMapStore()
override fun recid_getAll_sorted(){
//TODO support multiform store
}
}
class LiStoreTest : StoreTest() {
override fun openStore() = LiStore()
}
/**
* Tests contract on `Store` interface
*/
abstract class StoreTest {
abstract fun openStore(): Store
@Test fun put_get() {
val e = openStore()
val l = 11231203099090L
val recid = e.put(l, LONG)
assertEquals(l, e.get(recid, LONG))
e.verify()
e.close()
}
@Test fun put_get_large() {
val e = openStore()
if(e.maxRecordSize()<1e6)
return
val b = TT.randomByteArray(1000000)
Random().nextBytes(b)
val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
e.verify()
e.close()
}
@Test fun testSetGet() {
val e = openStore()
val recid = e.put(10000.toLong(), LONG)
val s2 = e.get(recid, LONG)
assertEquals(s2, java.lang.Long.valueOf(10000))
e.verify()
e.close()
}
@Test fun reserved_recids(){
val e = openStore()
for(expectedRecid in 1 .. Recids.RECID_MAX_RESERVED){
val allocRecid = e.preallocate()
assertEquals(expectedRecid, allocRecid)
}
e.verify()
e.close()
}
@Test
fun large_record() {
val e = openStore()
if(e.maxRecordSize()<1e6)
return
val b = TT.randomByteArray(100000)
val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE)
val b2 = e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(b, b2))
e.verify()
e.close()
}
@Test fun large_record_delete() {
val e = openStore()
if(e.maxRecordSize()<1e6)
return
val b = TT.randomByteArray(100000)
val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE)
e.verify()
e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE)
e.verify()
e.close()
}
@Test fun large_record_delete2(){
val s = openStore()
if(s.maxRecordSize()<1e6)
return
val b = TT.randomByteArray(200000)
val recid1 = s.put(b, Serializers.BYTE_ARRAY_NOSIZE)
s.verify()
val b2 = TT.randomByteArray(220000)
val recid2 = s.put(b2, Serializers.BYTE_ARRAY_NOSIZE)
s.verify()
assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE)))
assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE)))
s.delete(recid1, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE)))
s.verify()
s.delete(recid2, Serializers.BYTE_ARRAY_NOSIZE)
s.verify()
s.verify()
s.close()
}
@Test fun large_record_update(){
val s = openStore()
if(s.maxRecordSize()<1e6)
return
var b = TT.randomByteArray(200000)
val recid1 = s.put(b, Serializers.BYTE_ARRAY_NOSIZE)
s.verify()
val b2 = TT.randomByteArray(220000)
val recid2 = s.put(b2, Serializers.BYTE_ARRAY_NOSIZE)
s.verify()
assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE)))
assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE)))
b = TT.randomByteArray(210000)
s.update(recid1, Serializers.BYTE_ARRAY_NOSIZE, b);
assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE)))
assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE)))
s.verify()
b = TT.randomByteArray(28001)
s.update(recid1, Serializers.BYTE_ARRAY_NOSIZE, b);
assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE)))
assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE)))
s.verify()
s.close()
}
@Test
fun get_non_existent() {
val e = openStore()
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(1, TT.Serializer_ILLEGAL_ACCESS)
}
e.verify()
e.close()
}
@Test fun preallocate_cas() {
val e = openStore()
val recid = e.preallocate()
e.verify()
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.compareAndUpdate(recid, LONG, 1L, 2L)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.compareAndUpdate(recid, LONG, 2L, 2L)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.get(recid, LONG)
}
e.preallocatePut(recid, LONG, 2L)
assertFalse(e.compareAndUpdate(recid, LONG, 1L, 3L))
assertTrue(e.compareAndUpdate(recid, LONG, 2L, 2L))
assertTrue(e.compareAndUpdate(recid, LONG, 2L, 3L))
assertEquals(3L, e.get(recid, LONG))
e.verify()
e.close()
}
@Test fun preallocate_get_update_delete_update_get() {
val e = openStore()
val recid = e.preallocate()
e.verify()
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.get(recid, TT.Serializer_ILLEGAL_ACCESS)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.update(recid, LONG, 1L)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
assertEquals(1L.toLong(), e.get(recid, LONG))
}
e.preallocatePut(recid, LONG, 1L)
assertEquals(1L.toLong(), e.get(recid, LONG))
e.delete(recid, LONG)
TT.assertFailsWith(DBException.RecordNotFound::class) {
assertNull(e.get(recid, TT.Serializer_ILLEGAL_ACCESS))
}
e.verify()
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.update(recid, LONG, 1L)
}
e.verify()
e.close()
}
@Test fun cas_delete() {
val e = openStore()
val recid = e.put(1L, LONG)
e.verify()
assertTrue(e.compareAndDelete(recid, LONG, 1L))
TT.assertFailsWith(DBException.RecordNotFound::class) {
assertNull(e.get(recid, TT.Serializer_ILLEGAL_ACCESS))
}
e.verify()
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.update(recid, LONG, 1L)
}
e.verify()
e.close()
}
@Test fun cas_prealloc() {
val e = openStore()
val recid = e.preallocate()
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.compareAndUpdate(recid, LONG, 2L, 1L)
}
e.preallocatePut(recid, LONG, 2L)
assertTrue(e.compareAndUpdate(recid, LONG, 2L, 1L))
e.verify()
assertEquals(1L, e.get(recid, LONG))
assertTrue(e.compareAndUpdate(recid, LONG, 1L, 3L))
e.verify()
assertEquals(3L, e.get(recid, LONG))
e.verify()
e.close()
}
@Test fun cas_prealloc_delete() {
val e = openStore()
val recid = e.preallocate()
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.delete(recid, LONG)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
e.get(recid, LONG)
}
e.preallocatePut(recid, LONG, 1L)
e.delete(recid, LONG)
TT.assertFailsWith(DBException.RecordNotFound::class) {
assertTrue(e.compareAndUpdate(recid, LONG, 3L, 1L))
}
e.verify()
e.close()
}
@Test fun putGetUpdateDelete() {
val e = openStore()
var s = "aaaad9009"
val recid = e.put(s, Serializers.STRING)
assertEquals(s, e.get(recid, Serializers.STRING))
s = "da8898fe89w98fw98f9"
e.update(recid, Serializers.STRING, s)
assertEquals(s, e.get(recid, Serializers.STRING))
e.verify()
e.delete(recid, Serializers.STRING)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(recid, Serializers.STRING)
}
e.verify()
e.close()
}
@Test fun not_preallocated() {
val e = openStore()
TT.assertFailsWith(DBException.RecordNotPreallocated::class) {
e.preallocatePut(222, LONG, 1L)
}
val recid = e.put(1L, LONG)
TT.assertFailsWith(DBException.RecordNotPreallocated::class) {
e.preallocatePut(recid, LONG, 1L)
}
}
@Test fun nosize_array() {
val e = openStore()
var b = ByteArray(0)
val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
b = byteArrayOf(1, 2, 3)
e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
e.verify()
b = byteArrayOf()
e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
e.verify()
e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)
}
e.verify()
e.close()
}
@Test fun nosize_array_prealloc() {
val e = openStore()
var b = ByteArray(0)
val recid = e.preallocate();
e.preallocatePut(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
b = byteArrayOf(1, 2, 3)
e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
e.verify()
b = byteArrayOf()
e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)))
e.verify()
e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(recid, Serializers.BYTE_ARRAY_NOSIZE)
}
e.verify()
e.close()
}
@Test fun get_deleted() {
val e = openStore()
val recid = e.put(1L, LONG)
e.verify()
e.delete(recid, LONG)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(recid, LONG)
}
e.verify()
e.close()
}
@Test fun update_deleted() {
val e = openStore()
val recid = e.put(1L, LONG)
e.delete(recid, LONG)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.update(recid, LONG, 2L)
}
e.verify()
e.close()
}
@Test fun double_delete() {
val e = openStore()
val recid = e.put(1L, LONG)
e.delete(recid, LONG)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.delete(recid, LONG)
}
e.verify()
e.close()
}
@Test fun empty_update_commit() {
if (TT.shortTest())
return
var e = openStore()
val recid = e.put("", Serializers.STRING)
assertEquals("", e.get(recid, Serializers.STRING))
for (i in 0..9999) {
val s = TT.randomString(80000)
e.update(recid, Serializers.STRING, s)
assertEquals(s, e.get(recid, Serializers.STRING))
e.commit()
assertEquals(s, e.get(recid, Serializers.STRING))
}
e.verify()
e.close()
}
@Test fun delete_reuse() {
for(size in 1 .. 20){
val e = openStore()
val recid = e.put(TT.randomString(size), Serializers.STRING)
e.delete(recid, Serializers.STRING)
TT.assertFailsWith(DBException.RecordNotFound::class) {
e.get(recid, TT.Serializer_ILLEGAL_ACCESS)
}
val recid2 = e.put(TT.randomString(size), Serializers.STRING)
assertEquals(recid, recid2)
e.verify()
e.close()
}
}
//TODO test
// @Test fun empty_rollback(){
// val e = openStore()
// if(e is StoreTx)
// e.rollback()
// e.verify()
// e.close()
// }
@Test fun empty_commit(){
val e = openStore()
e.commit()
e.verify()
e.close()
}
@Test fun randomUpdates() {
if(TT.shortTest())
return;
val s = openStore()
val random = Random(1);
val endTime = TT.nowPlusMinutes(10.0)
val ref = LongObjectHashMap<ByteArray>()
//TODO params could cause OOEM if too big. Make another case of tests with extremely large memory, or disk space
val maxRecSize = 1000
val maxSize = 66000 * 3
//fill up
for (i in 0 until maxSize){
val size = random.nextInt(maxRecSize)
val b = TT.randomByteArray(size, random.nextInt())
val recid = s.put(b, Serializers.BYTE_ARRAY_NOSIZE)
ref.put(recid, b)
}
s.verify()
while(endTime>System.currentTimeMillis()){
ref.forEachKeyValue { recid, record ->
val old = s.get(recid, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(record, old))
val size = random.nextInt(maxRecSize)
val b = TT.randomByteArray(size, random.nextInt())
ref.put(recid,b.clone())
s.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b)
assertTrue(Arrays.equals(b, s.get(recid, Serializers.BYTE_ARRAY_NOSIZE)));
}
s.verify()
//TODO TX test
// if(s is StoreWAL) {
// s.commit()
// s.verify()
// }
}
}
@Test fun concurrent_CAS(){
if(TT.shortTest())
return;
val s = openStore();
if(s.isThreadSafe().not())
return;
val ntime = TT.nowPlusMinutes(1.0)
var counter = AtomicLong(0);
val recid = s.put(0L, LONG)
TT.fork(10){
val random = Random();
while(ntime>System.currentTimeMillis()){
val plus = random.nextInt(1000).toLong()
val v:Long = s.get(recid, LONG)!!
if(s.compareAndUpdate(recid, LONG, v, v+plus)){
counter.addAndGet(plus);
}
}
}
assertTrue(counter.get()>0)
assertEquals(counter.get(), s.get(recid, LONG))
}
@Test fun varRecordSizeCompact(){
if(TT.shortTest())
return
val maxStoreSize = 10*1024*1024
var size = 1
while(size<maxStoreSize) {
val store = openStore()
val maxCount = 1 + maxStoreSize / size;
//insert recids
val recids = LongArrayList()
for (i in 0..maxCount) {
val r = TT.randomByteArray(size, seed = i)
val recid = store.put(r, Serializers.BYTE_ARRAY_NOSIZE)
recids.add(recid)
}
fun verify() {
//verify recids
recids.forEachWithIndex { recid, i ->
val r = store.get(recid, Serializers.BYTE_ARRAY_NOSIZE)
assertTrue(Arrays.equals(r, TT.randomByteArray(size, seed=i)))
}
}
verify()
store.compact()
verify()
size += 1 + size/113
}
}
// @Test
//TODO reentry test with preprocessor in paranoid mode
fun reentry(){
val store = openStore()
val recid = store.put("aa", Serializers.STRING)
val reentrySer1 = object: Serializer<String> {
override fun serializedType() = String::class.java
override fun serialize(out: DataOutput2, k: String) {
out.writeUTF(k)
// that should fail
store.update(recid, Serializers.STRING, k)
}
override fun deserialize(input: DataInput2): String {
return input.readUTF()
}
}
val reentrySer2 = object: Serializer<String> {
override fun serializedType() = String::class.java
override fun serialize(out: DataOutput2, k: String) {
out.writeUTF(k)
}
override fun deserialize(input: DataInput2): String {
val s = input.readUTF()
// that should fail
store.update(recid, Serializers.STRING, s)
return s
}
}
TT.assertFailsWith(DBException.StoreReentry::class){
store.put("aa", reentrySer1)
store.commit()
}
val recid2 = store.put("aa", Serializers.STRING)
TT.assertFailsWith(DBException.StoreReentry::class){
store.get(recid2, reentrySer2)
}
TT.assertFailsWith(DBException.StoreReentry::class){
store.update(recid2, reentrySer1, "bb")
store.commit()
}
TT.assertFailsWith(DBException.StoreReentry::class){
store.compareAndUpdate(recid2, reentrySer1, "aa", "bb")
store.commit()
}
TT.assertFailsWith(DBException.StoreReentry::class){
store.compareAndUpdate(recid2, reentrySer2, "aa", "bb")
store.commit()
}
TT.assertFailsWith(DBException.StoreReentry::class){
store.compareAndDelete(recid2, reentrySer2, "aa")
store.commit()
}
}
open @Test fun recid_getAll_sorted(){
val store = openStore()
val max = 1000
val records = (0 until max).map{ n->
val recid = store.put(n, Serializers.INTEGER)
Pair(recid, n)
}
val records2 = ArrayList<Pair<Long, Int>>()
store.getAll{recid, data:ByteArray? ->
data!!.size shouldBe 4
val n = DataIO.getInt(data!!, 0)
records2+=Pair(recid, n)
}
//TODO check preallocated records are excluded
//TODO check deleted records are excluded
records2.size shouldBe max
for(i in 0 until max){
val (recid, n) = records2[i]
n shouldBe i
store.get(recid, Serializers.INTEGER) shouldBe i
records[i].first shouldBe recid
records[i].second shouldBe n
}
}
//
// @Test fun export_to_archive(){
// val store = openStore()
//
// val max = 1000
//
// val records = (0 until max).map{ n->
// val recid = store.put(n*1000, Serializers.INTEGER)
// Pair(recid, n*1000)
// }
//
// val out = ByteArrayOutputStream()
// StoreArchive.importFromStore(store, out)
//
// val archive = StoreArchive(ByteBuffer.wrap(out.toByteArray()))
//
// for((recid,n) in records){
// archive.get(recid, Serializers.INTEGER) shouldBe n
// }
// }
@Test fun empty(){
val store = openStore()
store.isEmpty() shouldBe true
val recid = store.put(1, Serializers.INTEGER)
store.isEmpty() shouldBe false
store.delete(recid, Serializers.INTEGER)
//TODO restore empty state when no data in store? perhaps not possible, so replace is 'isFresh()` (no data inserted yet)
// store.isEmpty() shouldBe true
}
@Test fun null_prealloc_update_delete(){
val store = openStore()
val recid = store.preallocate()
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
store.update(recid, LONG, 1L)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
store.get(recid, TT.Serializer_ILLEGAL_ACCESS)
}
TT.assertFailsWith(DBException.PreallocRecordAccess::class) {
store.delete(recid, TT.Serializer_ILLEGAL_ACCESS)
}
store.preallocatePut(recid, LONG, 1L)
store.delete(recid, LONG);
TT.assertFailsWith(DBException.RecordNotFound::class) {
store.get(recid, TT.Serializer_ILLEGAL_ACCESS)
}
}
//TODO nullability tests outside of kotlin
}
| apache-2.0 | 3a2f6792cb317b8f8fc2424c3c980c92 | 28.76569 | 128 | 0.569394 | 4.034405 | false | true | false | false |
Benestar/focus-android | app/src/main/java/org/mozilla/focus/session/ui/SessionViewHolder.kt | 2 | 3028 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.session.ui
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v7.content.res.AppCompatResources
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import org.mozilla.focus.R
import org.mozilla.focus.session.Session
import org.mozilla.focus.session.SessionManager
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.ext.beautifyUrl
import java.lang.ref.WeakReference
class SessionViewHolder internal constructor(private val fragment: SessionsSheetFragment, private val textView: TextView) : RecyclerView.ViewHolder(textView), View.OnClickListener {
companion object {
@JvmField
internal val LAYOUT_ID = R.layout.item_session
}
private var sessionReference: WeakReference<Session> = WeakReference<Session>(null)
init {
textView.setOnClickListener(this)
}
fun bind(session: Session) {
this.sessionReference = WeakReference(session)
updateUrl(session)
val isCurrentSession = SessionManager.getInstance().isCurrentSession(session)
val actionColor = ContextCompat.getColor(textView.context, R.color.colorAction)
val darkColor = ContextCompat.getColor(textView.context, R.color.colorSession)
updateTextColor(isCurrentSession, actionColor, darkColor)
updateDrawable(isCurrentSession, actionColor, darkColor)
}
private fun updateTextColor(isCurrentSession: Boolean, actionColor: Int, darkColor: Int) {
textView.setTextColor(if (isCurrentSession) actionColor else darkColor)
}
private fun updateDrawable(isCurrentSession: Boolean, actionColor: Int, darkColor: Int) {
val drawable = AppCompatResources.getDrawable(itemView.context, R.drawable.ic_link) ?: return
val wrapDrawable = DrawableCompat.wrap(drawable.mutate())
DrawableCompat.setTint(wrapDrawable, if (isCurrentSession) actionColor else darkColor)
textView.setCompoundDrawablesWithIntrinsicBounds(wrapDrawable, null, null, null)
}
private fun updateUrl(session: Session) {
textView.text = session.url.value.beautifyUrl()
}
override fun onClick(view: View) {
val session = sessionReference.get() ?: return
selectSession(session)
}
private fun selectSession(session: Session) {
fragment.animateAndDismiss().addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
SessionManager.getInstance().selectSession(session)
TelemetryWrapper.switchTabInTabsTrayEvent()
}
})
}
}
| mpl-2.0 | df815ceccd7ba7497d569614033d763d | 37.820513 | 181 | 0.742734 | 4.829346 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/UserStatComputer.kt | 1 | 5048 | package com.habitrpg.android.habitica.helpers
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.inventory.Equipment
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.shared.habitica.models.Avatar
class UserStatComputer {
interface StatsRow
inner class AttributeRow : StatsRow {
var labelId: Int = 0
var strVal: Float = 0.toFloat()
var intVal: Float = 0.toFloat()
var conVal: Float = 0.toFloat()
var perVal: Float = 0.toFloat()
var roundDown: Boolean = false
var summary: Boolean = false
}
inner class EquipmentRow : StatsRow {
var gearKey: String? = null
var text: String? = null
var stats: String? = null
}
fun computeClassBonus(equipmentList: List<Equipment>, user: Avatar): List<StatsRow> {
val skillRows = ArrayList<StatsRow>()
var strAttributes = 0f
var intAttributes = 0f
var conAttributes = 0f
var perAttributes = 0f
var strClassBonus = 0f
var intClassBonus = 0f
var conClassBonus = 0f
var perClassBonus = 0f
// Summarize stats and fill equipment table
for (i in equipmentList) {
val strength = i.str
val intelligence = i._int
val constitution = i.con
val perception = i.per
strAttributes += strength.toFloat()
intAttributes += intelligence.toFloat()
conAttributes += constitution.toFloat()
perAttributes += perception.toFloat()
val sb = StringBuilder()
if (strength != 0) {
sb.append("STR ").append(strength).append(", ")
}
if (intelligence != 0) {
sb.append("INT ").append(intelligence).append(", ")
}
if (constitution != 0) {
sb.append("CON ").append(constitution).append(", ")
}
if (perception != 0) {
sb.append("PER ").append(perception).append(", ")
}
// remove the last comma
if (sb.length > 2) {
sb.delete(sb.length - 2, sb.length)
}
val equipmentRow = EquipmentRow()
equipmentRow.gearKey = i.key
equipmentRow.text = i.text
equipmentRow.stats = sb.toString()
skillRows.add(equipmentRow)
// Calculate class bonus
var itemClass: String? = i.klass
val itemSpecialClass = i.specialClass
val classDoesNotExist = itemClass == null || itemClass.isEmpty()
val specialClassDoesNotExist = itemSpecialClass.isEmpty()
if (classDoesNotExist && specialClassDoesNotExist) {
continue
}
var classBonus = 0.5f
val userClassMatchesGearClass = !classDoesNotExist && itemClass == user.stats?.habitClass
val userClassMatchesGearSpecialClass = !specialClassDoesNotExist && itemSpecialClass == user.stats?.habitClass
if (!userClassMatchesGearClass && !userClassMatchesGearSpecialClass) classBonus = 0f
if (itemClass == null || itemClass.isEmpty() || itemClass == "special") {
itemClass = itemSpecialClass
}
when (itemClass) {
Stats.ROGUE -> {
strClassBonus += strength * classBonus
perClassBonus += perception * classBonus
}
Stats.HEALER -> {
conClassBonus += constitution * classBonus
intClassBonus += intelligence * classBonus
}
Stats.WARRIOR -> {
strClassBonus += strength * classBonus
conClassBonus += constitution * classBonus
}
Stats.MAGE -> {
intClassBonus += intelligence * classBonus
perClassBonus += perception * classBonus
}
}
}
val attributeRow = AttributeRow()
attributeRow.labelId = R.string.battle_gear
attributeRow.strVal = strAttributes
attributeRow.intVal = intAttributes
attributeRow.conVal = conAttributes
attributeRow.perVal = perAttributes
attributeRow.roundDown = true
attributeRow.summary = false
skillRows.add(attributeRow)
val attributeRow2 = AttributeRow()
attributeRow2.labelId = R.string.profile_class_bonus
attributeRow2.strVal = strClassBonus
attributeRow2.intVal = intClassBonus
attributeRow2.conVal = conClassBonus
attributeRow2.perVal = perClassBonus
attributeRow2.roundDown = false
attributeRow2.summary = false
skillRows.add(attributeRow2)
return skillRows
}
}
| gpl-3.0 | 17455b4797522f5f0503b2a72bff697d | 33.549296 | 122 | 0.557647 | 5.296957 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/XdmValue.kt | 1 | 1944 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.type.Type
open class XdmValue(val saxonObject: Any, private val `class`: Class<*>) {
fun iterator(): XdmSequenceIterator {
val xdmSequenceIteratorClass = `class`.classLoader.loadClass("net.sf.saxon.s9api.XdmSequenceIterator")
return XdmSequenceIterator(`class`.getMethod("iterator").invoke(saxonObject), xdmSequenceIteratorClass)
}
private fun getUnderlyingValue(): Any = `class`.getMethod("getUnderlyingValue").invoke(saxonObject)
fun getItemType(typeHierarchy: Any?): Any {
val value = getUnderlyingValue()
return Type.getItemType(value, typeHierarchy, `class`.classLoader)
}
override fun toString(): String = saxonObject.toString()
override fun hashCode(): Int = saxonObject.hashCode()
override fun equals(other: Any?): Boolean {
if (other !is XdmItem) return false
return saxonObject == other.saxonObject
}
companion object {
fun newInstance(value: Any?, type: String, processor: Processor): XdmValue = when {
type == "empty-sequence()" || value == null -> XdmEmptySequence.getInstance(processor.classLoader)
else -> XdmItem.newInstance(value, type, processor)
}
}
}
| apache-2.0 | 0a12bfa9ab22c1a2dde955ee1452f770 | 39.5 | 111 | 0.710905 | 4.263158 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/achievement/ui/adapter/delegate/AchievementAdapterDelegate.kt | 2 | 1885 | package org.stepik.android.view.achievement.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.android.synthetic.main.view_achievement_item.view.*
import org.stepic.droid.R
import org.stepik.android.view.achievement.ui.resolver.AchievementResourceResolver
import org.stepik.android.domain.achievement.model.AchievementItem
import org.stepik.android.view.achievement.ui.delegate.AchievementTileDelegate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class AchievementAdapterDelegate(
private val achievementResourceResolver: AchievementResourceResolver,
private val onItemClicked: (AchievementItem) -> Unit
) : AdapterDelegate<AchievementItem, DelegateViewHolder<AchievementItem>>() {
override fun isForViewType(position: Int, data: AchievementItem): Boolean =
true
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<AchievementItem> =
ViewHolder(createView(parent, R.layout.view_achievement_item))
private inner class ViewHolder(root: View) : DelegateViewHolder<AchievementItem>(root) {
private val achievementTitle: TextView = root.achievementTitle
private val achievementDescription: TextView = root.achievementDescription
private val achievementTileDelegate = AchievementTileDelegate(root.achievementTile, achievementResourceResolver)
init {
root.setOnClickListener { itemData?.let(onItemClicked) }
}
override fun onBind(data: AchievementItem) {
achievementTileDelegate.setAchievement(data)
achievementTitle.text = achievementResourceResolver.resolveTitleForKind(data.kind)
achievementDescription.text = achievementResourceResolver.resolveDescription(data)
}
}
} | apache-2.0 | 1001cf21ff28604dd7df1f9a69e5011e | 45 | 120 | 0.787268 | 5.150273 | false | false | false | false |
k-kagurazaka/rx-property-android | sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoRepository.kt | 1 | 1234 | package jp.keita.kagurazaka.rxproperty.sample.todo
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject
import jp.keita.kagurazaka.rxproperty.NoParameter
object TodoRepository {
val onChanged: Observable<NoParameter>
get() = changeEmitter.observeOn(AndroidSchedulers.mainThread())
val all: List<TodoItem>
get() = list
val active: List<TodoItem>
get() = list.filter { !it.isDone }
val done: List<TodoItem>
get() = list.filter { it.isDone }
private val list = arrayListOf<TodoItem>()
private val changeEmitter = PublishSubject.create<NoParameter>().toSerialized()
fun store(item: TodoItem) {
list.add(item)
changeEmitter.onNext(NoParameter.INSTANCE)
}
fun update(item: TodoItem) {
val index = list.indexOf(item)
if (index >= 0) {
list[index] = item
changeEmitter.onNext(NoParameter.INSTANCE)
}
}
fun deleteDone() {
list.removeAll { it.isDone }
changeEmitter.onNext(NoParameter.INSTANCE)
}
fun clear() {
list.clear()
changeEmitter.onNext(NoParameter.INSTANCE)
}
}
| mit | cc94faa2bd1a0cb7bd11ed85ca461307 | 25.826087 | 83 | 0.660454 | 4.471014 | false | false | false | false |
exponentjs/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/adapters/react/apploader/RNHeadlessAppLoader.kt | 2 | 2725 | package expo.modules.adapters.react.apploader
import android.content.Context
import com.facebook.react.ReactApplication
import com.facebook.react.ReactInstanceManager
import com.facebook.react.common.LifecycleState
import expo.modules.apploader.HeadlessAppLoader
import expo.modules.core.interfaces.Consumer
import expo.modules.core.interfaces.DoNotStrip
private val appRecords: MutableMap<String, ReactInstanceManager> = mutableMapOf()
class RNHeadlessAppLoader @DoNotStrip constructor(private val context: Context) : HeadlessAppLoader {
//region HeadlessAppLoader
override fun loadApp(context: Context, params: HeadlessAppLoader.Params?, alreadyRunning: Runnable?, callback: Consumer<Boolean>?) {
if (params == null || params.appScopeKey == null) {
throw IllegalArgumentException("Params must be set with appScopeKey!")
}
if (context.applicationContext is ReactApplication) {
val reactInstanceManager = (context.applicationContext as ReactApplication).reactNativeHost.reactInstanceManager
if (!appRecords.containsKey(params.appScopeKey)) {
reactInstanceManager.addReactInstanceEventListener {
HeadlessAppLoaderNotifier.notifyAppLoaded(params.appScopeKey)
callback?.apply(true)
}
appRecords[params.appScopeKey] = reactInstanceManager
if (reactInstanceManager.hasStartedCreatingInitialContext()) {
reactInstanceManager.recreateReactContextInBackground()
} else {
reactInstanceManager.createReactContextInBackground()
}
} else {
alreadyRunning?.run()
}
} else {
throw IllegalStateException("Your application must implement ReactApplication")
}
}
override fun invalidateApp(appScopeKey: String?): Boolean {
return if (appRecords.containsKey(appScopeKey) && appRecords[appScopeKey] != null) {
val appRecord: ReactInstanceManager = appRecords[appScopeKey]!!
android.os.Handler(context.mainLooper).post {
// Only destroy the `ReactInstanceManager` if it does not bind with an Activity.
// And The Activity would take over the ownership of `ReactInstanceManager`.
// This case happens when a user clicks a background task triggered notification immediately.
if (appRecord.lifecycleState == LifecycleState.BEFORE_CREATE) {
appRecord.destroy()
}
HeadlessAppLoaderNotifier.notifyAppDestroyed(appScopeKey)
appRecords.remove(appScopeKey)
}
true
} else {
false
}
}
override fun isRunning(appScopeKey: String?): Boolean =
appRecords.contains(appScopeKey) && appRecords[appScopeKey]!!.hasStartedCreatingInitialContext()
//endregion HeadlessAppLoader
}
| bsd-3-clause | 72bd27bea47e6e6c6b2fe1a6514f6383 | 40.287879 | 134 | 0.73945 | 5.353635 | false | false | false | false |
paslavsky/music-sync-manager | msm-server/src/main/kotlin/net/paslavsky/msm/Logging.kt | 1 | 2739 | package net.paslavsky.msm
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.util.measureTimeMillis
/**
* Functions that helps to write logs
* @author Andrey Paslavsky
* @version 1.0
*/
private val Any.logger: Logger
get() = LoggerFactory.getLogger(this.javaClass)!!
private fun Any.logError(t: Throwable, message: String = t.getMessage() ?: "System error") = logger.error(message, t)
private fun Any.logError(message: String, t: Throwable) = logger.error(message, t)
//private fun Any.logError(format: String, vararg params: Any?) = logger.error(format, params)
private fun Any.logWarning(message: String, t: Throwable? = null) = logger.warn(message, t)
//private fun Any.logWarning(format: String, vararg params: Any?) = logger.warn(format, params)
private fun Any.logInfo(message: String, t: Throwable? = null) = logger.info(message, t)
//private fun Any.logInfo(format: String, vararg params: Any?) = logger.info(format, params)
private fun Any.logDebug(message: String, t: Throwable? = null) = logger.debug(message, t)
//private fun Any.logDebug(format: String, vararg params: Any?) = logger.debug(format, params)
//private fun Any.logTrace(message: String, t: Throwable? = null) = logger.trace(message, t)
//private fun Any.logTrace(format: String, vararg params: Any?) = logger.trace(format, params)
private fun Any.isErrorEnabled() = logger.isErrorEnabled()
private fun Any.isWarnEnabled() = logger.isWarnEnabled()
private fun Any.isInfoEnabled() = logger.isInfoEnabled()
private fun Any.isDebugEnabled() = logger.isDebugEnabled()
private fun Any.isTraceEnabled() = logger.isTraceEnabled()
interface IndexGetter {fun index(): String}
val static = object: IndexGetter {
private var index = 0L
public override fun index(): String = java.lang.Long.toString(++index, 16)
}
private fun <T> Any.logProcess(name: String, block: () -> T): T {
var result: T = null
val index = static.index()
logInfo("Starting the process (#$index) \"$name\"...")
try {
val millis = measureTimeMillis({
result = block()
})
logInfo("...\"$name\" process (#$index) is completed (took $millis ms${getCount(result)})")
return result
} catch (t: Throwable) {
logError("...\"$name\" process (#$index) is completed with an error!", t)
throw t
}
}
private fun getCount(value: Any) = when (value) {
is Array<*> -> ", processed ${value.size()} element(s)"
is Collection<*> -> ", processed ${value.size()} element(s)"
is Map<*, *> -> ", processed ${value.size()} element(s)"
is Iterator<*> -> ", processed ${value.size()} element(s)"
is Iterable<*> -> ", processed ${value.iterator().size()} element(s)"
else -> ""
}
| apache-2.0 | 9ce69b75b4e4f471d037b45b64bf53a6 | 41.796875 | 117 | 0.680905 | 3.777931 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/ConfirmDeleteDialogFragment.kt | 1 | 8395 | package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment
import android.content.DialogInterface
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.data.Todo
import com.rolandvitezhu.todocloud.databinding.DialogConfirmdeleteBinding
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.CategoriesViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.TodosViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.viewmodelfactory.ListsViewModelFactory
import kotlinx.android.synthetic.main.dialog_confirmdelete.view.*
import java.util.*
class ConfirmDeleteDialogFragment : AppCompatDialogFragment() {
private var itemType: String? = null
private var itemsToDelete: ArrayList<*>? = null
private var isMultipleItems = false
private val todosViewModel by lazy {
ViewModelProvider(requireActivity()).get(TodosViewModel::class.java)
}
private val categoriesViewModel by lazy {
ViewModelProvider(requireActivity()).get(CategoriesViewModel::class.java)
}
private val listsViewModel by lazy {
ViewModelProvider(requireActivity(), ListsViewModelFactory(categoriesViewModel)).
get(ListsViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme)
prepareItemVariables()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val dialogConfirmdeleteBinding: DialogConfirmdeleteBinding =
DialogConfirmdeleteBinding.inflate(inflater, container, false)
val view: View = dialogConfirmdeleteBinding.root
dialogConfirmdeleteBinding.confirmDeleteDialogFragment = this
dialogConfirmdeleteBinding.executePendingBindings()
prepareDialogTexts(view)
return view
}
private fun prepareItemVariables() {
itemType = requireArguments().getString("itemType")
itemsToDelete = requireArguments().getParcelableArrayList<Parcelable>("itemsToDelete")
prepareIsMultipleItems()
}
private fun prepareIsMultipleItems() {
isMultipleItems = !itemsToDelete.isNullOrEmpty()
}
/**
* Prepare and set the dialog title and the action text by the item type.
*/
private fun prepareDialogTexts(view: View) {
val itemTitle = requireArguments().getString("itemTitle")
when (itemType) {
"todo" -> if (isMultipleItems) {
prepareConfirmDeleteTodosDialogTexts(view)
} else {
prepareConfirmDeleteTodoDialogTexts(view)
}
"list" -> if (isMultipleItems) {
prepareConfirmDeleteListsDialogTexts(view)
} else {
prepareConfirmDeleteListDialogTexts(itemTitle, view)
}
"listInCategory" -> if (isMultipleItems) {
prepareConfirmDeleteListsDialogTexts(view)
} else {
prepareConfirmDeleteListDialogTexts(itemTitle, view)
}
"category" -> if (isMultipleItems) {
prepareConfirmDeleteCategoriesDialogTexts(view)
} else {
prepareConfirmDeleteCategoryDialogTexts(itemTitle, view)
}
}
}
private fun prepareConfirmDeleteCategoryDialogTexts(itemTitle: String?, view: View) {
val dialogTitle = getString(R.string.confirmdelete_deletecategorytitle)
val actionTextPrefix = getString(R.string.confirmdelete_deletecategoryactiontext)
val actionText = prepareActionText(actionTextPrefix, itemTitle)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareConfirmDeleteCategoriesDialogTexts(view: View) {
val dialogTitle = getString(R.string.confirmdelete_categoriestitle)
val actionText = getString(R.string.confirmdelete_categoriesactiontext)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareConfirmDeleteListDialogTexts(itemTitle: String?, view: View) {
val dialogTitle = getString(R.string.confirmdelete_deletelisttitle)
val actionTextPrefix = getString(R.string.confirmdelete_deletelistactiontext)
val actionText = prepareActionText(actionTextPrefix, itemTitle)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareConfirmDeleteListsDialogTexts(view: View) {
val dialogTitle = getString(R.string.confirmdelete_liststitle)
val actionText = getString(R.string.confirmdelete_listsactiontext)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareConfirmDeleteTodoDialogTexts(view: View) {
val dialogTitle = getString(R.string.confirmdelete_deletetodotitle)
val itemTitle = prepareTodoItemTitle()
val actionTextPrefix = getString(R.string.confirmdelete_deletetodoactiontext)
val actionText = prepareActionText(actionTextPrefix, itemTitle)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareConfirmDeleteTodosDialogTexts(view: View) {
val dialogTitle = getString(R.string.confirmdelete_todostitle)
val actionText = getString(R.string.confirmdelete_todosactiontext)
setDialogTitle(dialogTitle)
setActionText(actionText, view)
}
private fun prepareTodoItemTitle(): String? {
val todos: ArrayList<Todo>? = itemsToDelete as ArrayList<Todo>?
return todos!![0].title
}
private fun prepareActionText(actionTextPrefix: String, itemTitle: String?): String {
return "$actionTextPrefix\"$itemTitle\"?"
}
private fun setDialogTitle(dialogTitle: String) {
requireDialog().setTitle(dialogTitle)
}
private fun setActionText(actionText: String, view: View) {
view.textview_confirmdelete_actiontext.text = actionText
}
/**
* Mark categories as deleted, update them in the local database and update the categories.
*/
private fun softDeleteCategories(onlineId: String?) {
if (isMultipleItems)
categoriesViewModel.onSoftDelete(itemsToDelete, targetFragment)
else
categoriesViewModel.onSoftDelete(onlineId, targetFragment)
}
/**
* Mark lists as deleted, update them in the local database and update the lists.
*/
private fun softDeleteLists(onlineId: String?) {
if (isMultipleItems)
listsViewModel.onSoftDelete(itemsToDelete, targetFragment)
else
listsViewModel.onSoftDelete(onlineId, targetFragment)
}
/**
* Mark todos as deleted, update them in the local database and update the todos.
*/
private fun softDeleteTodos(onlineId: String?) {
if (isMultipleItems)
todosViewModel.onSoftDelete(itemsToDelete, targetFragment)
else
todosViewModel.onSoftDelete(onlineId, targetFragment)
}
fun onButtonOkClick(view: View) {
val onlineId = requireArguments().getString("onlineId")
when (itemType) {
"todo" -> {
softDeleteTodos(onlineId)
}
"list" -> {
softDeleteLists(onlineId)
}
"listInCategory" -> {
softDeleteLists(onlineId)
}
"category" -> {
softDeleteCategories(onlineId)
}
}
dismiss()
}
fun onButtonCancelClick(view: View) {
dismiss()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
if (targetFragment is DialogInterface.OnDismissListener?) {
(targetFragment as DialogInterface.OnDismissListener?)?.onDismiss(dialog)
}
}
} | mit | 87db0e9084f748bd3dbbfa7e2af15215 | 36.650224 | 100 | 0.689815 | 5.541254 | false | false | false | false |
realm/realm-java | examples/coroutinesExample/src/main/java/io/realm/examples/coroutinesexample/ui/main/MainAdapter.kt | 1 | 2563 | /*
* Copyright 2020 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.examples.coroutinesexample.ui.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.realm.examples.coroutinesexample.R
import io.realm.examples.coroutinesexample.data.newsreader.local.RealmNYTimesArticle
class MainAdapter(
private val onClick: (String) -> Unit
) : ListAdapter<RealmNYTimesArticle, MainAdapter.ArticleViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_article, parent, false)
.let { view -> ArticleViewHolder(view) }
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
with(holder.title) {
val article = getItem(position)
text = article.title
isEnabled = !article.read
}
}
inner class ArticleViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val title: TextView = view.findViewById(R.id.title)
init {
view.setOnClickListener {
onClick.invoke(getItem(adapterPosition).url)
}
}
}
companion object {
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<RealmNYTimesArticle>() {
override fun areItemsTheSame(oldItem: RealmNYTimesArticle, newItem: RealmNYTimesArticle): Boolean =
oldItem == newItem
override fun areContentsTheSame(oldItem: RealmNYTimesArticle, newItem: RealmNYTimesArticle): Boolean =
oldItem.read == newItem.read
&& oldItem.title == newItem.title
&& oldItem.abstractText == newItem.abstractText
}
}
}
| apache-2.0 | 2edfb1498f007206ae6ad0198d0322e5 | 36.144928 | 114 | 0.685525 | 4.854167 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt | 1 | 4946 | // 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.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.types.TypeUtils
class NullChecksToSafeCallInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
binaryExpressionVisitor { expression ->
if (isNullChecksToSafeCallFixAvailable(expression)) {
holder.registerProblem(
expression,
KotlinBundle.message("null.checks.replaceable.with.safe.calls"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
NullChecksToSafeCallCheckFix()
)
}
}
private class NullChecksToSafeCallCheckFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("null.checks.to.safe.call.check.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
applyFix(descriptor.psiElement as? KtBinaryExpression ?: return)
}
private fun applyFix(expression: KtBinaryExpression) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return
val (lte, rte, isAnd) = collectNullCheckExpressions(expression) ?: return
val parent = expression.parent
expression.replaced(KtPsiFactory(lte).buildExpression {
appendExpression(lte)
appendFixedText("?.")
appendExpression(rte.selectorExpression)
appendFixedText(if (isAnd) "!= null" else "== null")
})
if (isNullChecksToSafeCallFixAvailable(parent as? KtBinaryExpression ?: return)) {
applyFix(parent)
}
}
}
companion object {
private fun isNullChecksToSafeCallFixAvailable(expression: KtBinaryExpression): Boolean {
fun String.afterIgnoreCalls() = replace("?.", ".")
val (lte, rte) = collectNullCheckExpressions(expression) ?: return false
val context = expression.analyze()
if (!lte.isChainStable(context)) return false
val resolvedCall = rte.getResolvedCall(context) ?: return false
val extensionReceiver = resolvedCall.extensionReceiver
if (extensionReceiver != null && TypeUtils.isNullableType(extensionReceiver.type)) return false
return rte.receiverExpression.text.afterIgnoreCalls() == lte.text.afterIgnoreCalls()
}
private fun collectNullCheckExpressions(expression: KtBinaryExpression): Triple<KtExpression, KtQualifiedExpression, Boolean>? {
val isAnd = when (expression.operationToken) {
KtTokens.ANDAND -> true
KtTokens.OROR -> false
else -> return null
}
val lhs = expression.left as? KtBinaryExpression ?: return null
val rhs = expression.right as? KtBinaryExpression ?: return null
val expectedOperation = if (isAnd) KtTokens.EXCLEQ else KtTokens.EQEQ
val lte = lhs.getNullTestableExpression(expectedOperation) ?: return null
val rte = rhs.getNullTestableExpression(expectedOperation) as? KtQualifiedExpression ?: return null
return Triple(lte, rte, isAnd)
}
private fun KtBinaryExpression.getNullTestableExpression(expectedOperation: KtToken): KtExpression? {
if (operationToken != expectedOperation) return null
val lhs = left ?: return null
val rhs = right ?: return null
if (KtPsiUtil.isNullConstant(lhs)) return rhs
if (KtPsiUtil.isNullConstant(rhs)) return lhs
return null
}
private fun KtExpression.isChainStable(context: BindingContext): Boolean = when (this) {
is KtReferenceExpression -> isStableSimpleExpression(context)
is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable(
context
)
else -> false
}
}
}
| apache-2.0 | 44a4b862df187e413acf8b97921ef68b | 47.490196 | 158 | 0.676506 | 5.791569 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/notification/SummaryNotificationCreator.kt | 1 | 9380 | package com.fsck.k9.notification
import android.app.PendingIntent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.WearableExtender
import androidx.core.app.NotificationManagerCompat
import com.fsck.k9.Account
import com.fsck.k9.notification.NotificationChannelManager.ChannelType
import com.fsck.k9.notification.NotificationIds.getNewMailSummaryNotificationId
import timber.log.Timber
import androidx.core.app.NotificationCompat.Builder as NotificationBuilder
internal class SummaryNotificationCreator(
private val notificationHelper: NotificationHelper,
private val actionCreator: NotificationActionCreator,
private val lockScreenNotificationCreator: LockScreenNotificationCreator,
private val singleMessageNotificationCreator: SingleMessageNotificationCreator,
private val resourceProvider: NotificationResourceProvider,
private val notificationManager: NotificationManagerCompat
) {
fun createSummaryNotification(
baseNotificationData: BaseNotificationData,
summaryNotificationData: SummaryNotificationData
) {
when (summaryNotificationData) {
is SummarySingleNotificationData -> {
createSingleMessageNotification(baseNotificationData, summaryNotificationData.singleNotificationData)
}
is SummaryInboxNotificationData -> {
createInboxStyleSummaryNotification(baseNotificationData, summaryNotificationData)
}
}
}
private fun createSingleMessageNotification(
baseNotificationData: BaseNotificationData,
singleNotificationData: SingleNotificationData
) {
singleMessageNotificationCreator.createSingleNotification(
baseNotificationData,
singleNotificationData,
isGroupSummary = true
)
}
private fun createInboxStyleSummaryNotification(
baseNotificationData: BaseNotificationData,
notificationData: SummaryInboxNotificationData
) {
val account = baseNotificationData.account
val accountName = baseNotificationData.accountName
val newMessagesCount = baseNotificationData.newMessagesCount
val title = resourceProvider.newMessagesTitle(newMessagesCount)
val summary = buildInboxSummaryText(accountName, notificationData)
val notification = notificationHelper.createNotificationBuilder(account, ChannelType.MESSAGES)
.setCategory(NotificationCompat.CATEGORY_EMAIL)
.setAutoCancel(true)
.setGroup(baseNotificationData.groupKey)
.setGroupSummary(true)
.setSmallIcon(resourceProvider.iconNewMail)
.setColor(baseNotificationData.color)
.setWhen(notificationData.timestamp)
.setNumber(notificationData.additionalMessagesCount)
.setTicker(notificationData.content.firstOrNull())
.setContentTitle(title)
.setSubText(accountName)
.setInboxStyle(title, summary, notificationData.content)
.setContentIntent(createViewIntent(account, notificationData))
.setDeleteIntent(createDismissIntent(account, notificationData.notificationId))
.setDeviceActions(account, notificationData)
.setWearActions(account, notificationData)
.setAppearance(notificationData.isSilent, baseNotificationData.appearance)
.setLockScreenNotification(baseNotificationData)
.build()
Timber.v("Creating inbox-style summary notification (silent=%b): %s", notificationData.isSilent, notification)
notificationManager.notify(notificationData.notificationId, notification)
}
private fun buildInboxSummaryText(accountName: String, notificationData: SummaryInboxNotificationData): String {
return if (notificationData.additionalMessagesCount > 0) {
resourceProvider.additionalMessages(notificationData.additionalMessagesCount, accountName)
} else {
accountName
}
}
private fun NotificationBuilder.setInboxStyle(
title: String,
summary: String,
contentLines: List<CharSequence>
) = apply {
val style = NotificationCompat.InboxStyle()
.setBigContentTitle(title)
.setSummaryText(summary)
for (line in contentLines) {
style.addLine(line)
}
setStyle(style)
}
private fun createViewIntent(account: Account, notificationData: SummaryInboxNotificationData): PendingIntent {
return actionCreator.createViewMessagesPendingIntent(
account = account,
messageReferences = notificationData.messageReferences,
notificationId = notificationData.notificationId
)
}
private fun createDismissIntent(account: Account, notificationId: Int): PendingIntent {
return actionCreator.createDismissAllMessagesPendingIntent(account, notificationId)
}
private fun NotificationBuilder.setDeviceActions(
account: Account,
notificationData: SummaryInboxNotificationData
) = apply {
for (action in notificationData.actions) {
when (action) {
SummaryNotificationAction.MarkAsRead -> addMarkAllAsReadAction(account, notificationData)
SummaryNotificationAction.Delete -> addDeleteAllAction(account, notificationData)
}
}
}
private fun NotificationBuilder.addMarkAllAsReadAction(
account: Account,
notificationData: SummaryInboxNotificationData
) {
val icon = resourceProvider.iconMarkAsRead
val title = resourceProvider.actionMarkAsRead()
val messageReferences = notificationData.messageReferences
val notificationId = notificationData.notificationId
val markAllAsReadPendingIntent =
actionCreator.createMarkAllAsReadPendingIntent(account, messageReferences, notificationId)
addAction(icon, title, markAllAsReadPendingIntent)
}
private fun NotificationBuilder.addDeleteAllAction(
account: Account,
notificationData: SummaryInboxNotificationData
) {
val icon = resourceProvider.iconDelete
val title = resourceProvider.actionDelete()
val notificationId = getNewMailSummaryNotificationId(account)
val messageReferences = notificationData.messageReferences
val action = actionCreator.createDeleteAllPendingIntent(account, messageReferences, notificationId)
addAction(icon, title, action)
}
private fun NotificationBuilder.setWearActions(
account: Account,
notificationData: SummaryInboxNotificationData
) = apply {
val wearableExtender = WearableExtender().apply {
for (action in notificationData.wearActions) {
when (action) {
SummaryWearNotificationAction.MarkAsRead -> addMarkAllAsReadAction(account, notificationData)
SummaryWearNotificationAction.Delete -> addDeleteAllAction(account, notificationData)
SummaryWearNotificationAction.Archive -> addArchiveAllAction(account, notificationData)
}
}
}
extend(wearableExtender)
}
private fun WearableExtender.addMarkAllAsReadAction(
account: Account,
notificationData: SummaryInboxNotificationData
) {
val icon = resourceProvider.wearIconMarkAsRead
val title = resourceProvider.actionMarkAllAsRead()
val messageReferences = notificationData.messageReferences
val notificationId = getNewMailSummaryNotificationId(account)
val action = actionCreator.createMarkAllAsReadPendingIntent(account, messageReferences, notificationId)
val markAsReadAction = NotificationCompat.Action.Builder(icon, title, action).build()
addAction(markAsReadAction)
}
private fun WearableExtender.addDeleteAllAction(account: Account, notificationData: SummaryInboxNotificationData) {
val icon = resourceProvider.wearIconDelete
val title = resourceProvider.actionDeleteAll()
val messageReferences = notificationData.messageReferences
val notificationId = getNewMailSummaryNotificationId(account)
val action = actionCreator.createDeleteAllPendingIntent(account, messageReferences, notificationId)
val deleteAction = NotificationCompat.Action.Builder(icon, title, action).build()
addAction(deleteAction)
}
private fun WearableExtender.addArchiveAllAction(account: Account, notificationData: SummaryInboxNotificationData) {
val icon = resourceProvider.wearIconArchive
val title = resourceProvider.actionArchiveAll()
val messageReferences = notificationData.messageReferences
val notificationId = getNewMailSummaryNotificationId(account)
val action = actionCreator.createArchiveAllPendingIntent(account, messageReferences, notificationId)
val archiveAction = NotificationCompat.Action.Builder(icon, title, action).build()
addAction(archiveAction)
}
private fun NotificationBuilder.setLockScreenNotification(notificationData: BaseNotificationData) = apply {
lockScreenNotificationCreator.configureLockScreenNotification(this, notificationData)
}
}
| apache-2.0 | 29b80fe56fa1a47bd4985938d6856dc0 | 43.245283 | 120 | 0.729318 | 6.518416 | false | false | false | false |
Maccimo/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/model/HeaderAnchorSymbolResolveTest.kt | 2 | 3424 | package org.intellij.plugins.markdown.model
import com.intellij.model.psi.PsiSymbolReferenceService
import com.intellij.openapi.components.service
import com.intellij.psi.PsiFile
import com.intellij.psi.util.parents
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import org.assertj.core.api.Assertions.assertThat
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDestination
import org.intellij.plugins.markdown.model.psi.headers.HeaderAnchorLinkDestinationReference
import org.intellij.plugins.markdown.model.psi.headers.HeaderSymbol
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class HeaderAnchorSymbolResolveTest: BasePlatformTestCase() {
override fun setUp() {
super.setUp()
myFixture.copyDirectoryToProject("", "")
}
private fun findLinkDestination(file: PsiFile, offset: Int): MarkdownLinkDestination? {
val elementUnderCaret = file.findElementAt(offset)
checkNotNull(elementUnderCaret)
return elementUnderCaret.parents(withSelf = true).filterIsInstance<MarkdownLinkDestination>().firstOrNull()
}
@Test
fun `reference to own header is resolved`() = doTest("own-header")
@Test
fun `reference to header in other file is resolved`() = doTest("header-near-main")
@Test
fun `reference to header in subdirectory is resolved`() = doTest("header-in-subdirectory")
@Test
fun `reference to header in deep subdirectory is resolved`() = doTest("some-deep-header")
@Test
fun `reference to header in list is resolved`() = doTest("header-inside-list-item")
@Test
fun `reference to header in other file without extension is resolved`() = doTest("header-near-main")
@Test
fun `special gfm case`() = doTest("get-method")
@Test
fun `weird date case`() = doTest("100-april-8-2018")
private fun doTest(expectedAnchor: String) {
val testName = getTestName(true)
val file = myFixture.configureFromTempProjectFile("$testName.md")
val caretModel = myFixture.editor.caretModel
val caret = caretModel.primaryCaret
val offset = caret.offset
val linkDestination = findLinkDestination(file, offset)
checkNotNull(linkDestination)
val references = service<PsiSymbolReferenceService>().getReferences(linkDestination)
val targetReferences = references.filterIsInstance<HeaderAnchorLinkDestinationReference>()
assertThat(targetReferences)
.withFailMessage { "Failed to collect symbol references for ${linkDestination.text}" }
.isNotEmpty
val resolved = targetReferences.flatMap { it.resolveReference().filterIsInstance<HeaderSymbol>() }
assertThat(resolved)
.withFailMessage { "Failed to resolve symbol reference for ${linkDestination.text}" }
.isNotEmpty
val header = resolved.find { it.anchorText == expectedAnchor }
assertThat(header)
.withFailMessage {
"Anchor reference resolved to something else: ${resolved.map { "${it.anchorText} - ${it.text}" }}\n" +
"Expected resolution result: $expectedAnchor"
}.isNotNull
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
override fun getTestDataPath(): String {
return "${MarkdownTestingUtil.TEST_DATA_PATH}/model/headers/resolve"
}
}
| apache-2.0 | 6801e2ef7bbf1a1af56806d8dd1c0c04 | 38.356322 | 111 | 0.754965 | 4.602151 | false | true | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/handler/VisualOperatorActionHandler.kt | 1 | 10199 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.handler
import com.maddyhome.idea.vim.action.change.VimRepeater
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimMotionGroupBase
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.diagnostic.debug
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.group.visual.VimBlockSelection
import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.group.visual.VimSimpleSelection
import com.maddyhome.idea.vim.group.visual.VisualChange
import com.maddyhome.idea.vim.group.visual.VisualOperation
import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.inBlockSubMode
import com.maddyhome.idea.vim.helper.inRepeatMode
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.vimStateMachine
/**
* @author Alex Plate
*
* Base class for visual operation handlers.
*
* Use subclasses of this handler:
* - [VisualOperatorActionHandler.SingleExecution]
* - [VisualOperatorActionHandler.ForEachCaret]
*/
sealed class VisualOperatorActionHandler : EditorActionHandlerBase(false) {
/**
* Base class for visual operation handlers.
* This handler executes an action for each caret. That means that if you have 5 carets,
* [executeAction] will be called 5 times.
* @see [VisualOperatorActionHandler.SingleExecution] for only one execution.
*/
abstract class ForEachCaret : VisualOperatorActionHandler() {
/**
* Execute an action for current [caret].
* The selection offsets and type should be takes from [range] because this [caret] doesn't have this selection
* anymore in time of action execution (and editor is in normal mode, not visual).
*
* This method is executed once for each caret except case with block selection. If there is block selection,
* the method will be executed only once with [Caret#primaryCaret].
*/
abstract fun executeAction(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
range: VimSelection,
operatorArguments: OperatorArguments,
): Boolean
/**
* This method executes before [executeAction] and only once for all carets.
* [caretsAndSelections] contains a map of all current carets and corresponding selections.
* If there is block selection, only one caret is in [caretsAndSelections].
*/
open fun beforeExecution(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
caretsAndSelections: Map<VimCaret, VimSelection>,
) = true
/**
* This method executes after [executeAction] and only once for all carets.
* [res] has true if ALL executions of [executeAction] returned true.
*/
open fun afterExecution(editor: VimEditor, context: ExecutionContext, cmd: Command, res: Boolean) {}
}
/**
* Base class for visual operation handlers.
* This handler executes an action only once for all carets. That means that if you have 5 carets,
* [executeForAllCarets] will be called 1 time.
* @see [VisualOperatorActionHandler.ForEachCaret] for per-caret execution
*/
abstract class SingleExecution : VisualOperatorActionHandler() {
/**
* Execute an action
* [caretsAndSelections] contains a map of all current carets and corresponding selections.
* If there is block selection, only one caret is in [caretsAndSelections].
*
* This method is executed once for all carets.
*/
abstract fun executeForAllCarets(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
caretsAndSelections: Map<VimCaret, VimSelection>,
operatorArguments: OperatorArguments,
): Boolean
}
final override fun baseExecute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments
): Boolean {
logger.info("Execute visual command $cmd")
editor.vimChangeActionSwitchMode = null
val selections = editor.collectSelections() ?: return false
logger.debug { "Count of selection segments: ${selections.size}" }
logger.debug { selections.values.joinToString("\n") { vimSelection -> "Caret: $vimSelection" } }
val commandWrapper = VisualStartFinishWrapper(editor, cmd, this)
commandWrapper.start()
val res = arrayOf(true)
when (this) {
is SingleExecution -> {
res[0] = executeForAllCarets(editor, context, cmd, selections, operatorArguments)
}
is ForEachCaret -> {
logger.debug("Calling 'before execution'")
if (!beforeExecution(editor, context, cmd, selections)) {
logger.debug("Before execution block returned false. Stop further processing")
return false
}
when {
selections.keys.isEmpty() -> return false
selections.keys.size == 1 -> res[0] =
executeAction(
editor,
selections.keys.first(),
context,
cmd,
selections.values.first(),
operatorArguments
)
else -> editor.forEachNativeCaret(
{ currentCaret ->
val range = selections.getValue(currentCaret)
val loopRes = executeAction(editor, currentCaret, context, cmd, range, operatorArguments)
res[0] = loopRes and res[0]
},
true
)
}
logger.debug("Calling 'after execution'")
afterExecution(editor, context, cmd, res[0])
}
}
commandWrapper.finish(res[0])
editor.vimChangeActionSwitchMode?.let {
injector.changeGroup.processPostChangeModeSwitch(editor, context, it)
}
return res[0]
}
private fun VimEditor.collectSelections(): Map<VimCaret, VimSelection>? {
return when {
!this.inVisualMode && this.inRepeatMode -> {
if (this.vimLastSelectionType == SelectionType.BLOCK_WISE) {
val primaryCaret = primaryCaret()
val range = primaryCaret.vimLastVisualOperatorRange ?: return null
val end = VisualOperation.calculateRange(this, range, 1, primaryCaret)
mapOf(
primaryCaret to VimBlockSelection(
primaryCaret.offset.point,
end,
this, range.columns >= VimMotionGroupBase.LAST_COLUMN
)
)
} else {
val carets = mutableMapOf<VimCaret, VimSelection>()
this.nativeCarets().forEach { caret ->
val range = caret.vimLastVisualOperatorRange ?: return@forEach
val end = VisualOperation.calculateRange(this, range, 1, caret)
carets += caret to VimSelection.create(caret.offset.point, end, range.type, this)
}
carets.toMap()
}
}
this.inBlockSubMode -> {
val primaryCaret = primaryCaret()
mapOf(
primaryCaret to VimBlockSelection(
primaryCaret.vimSelectionStart,
primaryCaret.offset.point,
this, primaryCaret.vimLastColumn >= VimMotionGroupBase.LAST_COLUMN
)
)
}
else -> this.nativeCarets().associateWith { caret ->
val subMode = this.vimStateMachine.subMode
VimSimpleSelection.createWithNative(
caret.vimSelectionStart,
caret.offset.point,
caret.selectionStart,
caret.selectionEnd,
SelectionType.fromSubMode(subMode),
this
)
}
}
}
private class VisualStartFinishWrapper(
private val editor: VimEditor,
private val cmd: Command,
private val visualOperatorActionHandler: VisualOperatorActionHandler
) {
private val visualChanges = mutableMapOf<VimCaret, VisualChange?>()
fun start() {
logger.debug("Preparing visual command")
editor.vimKeepingVisualOperatorAction = CommandFlags.FLAG_EXIT_VISUAL !in cmd.flags
editor.forEachCaret {
val change =
if ([email protected] && [email protected]) {
VisualOperation.getRange([email protected], it, [email protected])
} else null
[email protected][it] = change
}
logger.debug { visualChanges.values.joinToString("\n") { "Caret: $visualChanges" } }
// If this is a mutli key change then exit visual now
if (CommandFlags.FLAG_MULTIKEY_UNDO in cmd.flags || CommandFlags.FLAG_EXIT_VISUAL in cmd.flags) {
logger.debug("Exit visual before command executing")
editor.exitVisualMode()
}
}
fun finish(res: Boolean) {
logger.debug("Finish visual command. Result: $res")
if (visualOperatorActionHandler.id != "VimVisualOperatorAction" ||
injector.keyGroup.operatorFunction?.postProcessSelection() != false
) {
if (CommandFlags.FLAG_MULTIKEY_UNDO !in cmd.flags && CommandFlags.FLAG_EXPECT_MORE !in cmd.flags) {
logger.debug("Not multikey undo - exit visual")
editor.exitVisualMode()
}
}
if (res) {
VimRepeater.saveLastChange(cmd)
VimRepeater.repeatHandler = false
editor.forEachCaret { caret ->
val visualChange = visualChanges[caret]
if (visualChange != null) {
caret.vimLastVisualOperatorRange = visualChange
}
}
}
editor.vimKeepingVisualOperatorAction = false
}
}
private companion object {
val logger = vimLogger<VisualOperatorActionHandler>()
}
}
| mit | 3bdbc75976b9c0c9a718f95a47164a50 | 35.295374 | 120 | 0.675949 | 4.777049 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/FullscreenBarcodeActivity.kt | 1 | 2732 | package org.ligi.passandroid.ui
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import kotlinx.android.synthetic.main.fullscreen_image.*
import org.ligi.kaxt.lockOrientation
import org.ligi.passandroid.R
import timber.log.Timber
class FullscreenBarcodeActivity : PassViewActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fullscreen_image)
if (Build.VERSION.SDK_INT >= 27) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
this.window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
}
}
override fun onResume() {
super.onResume()
if (currentPass.barCode == null) {
Timber.w("FullscreenBarcodeActivity in bad state")
finish() // this should never happen, but better safe than sorry
return
}
setBestFittingOrientationForBarCode()
fullscreen_barcode.setImageDrawable(currentPass.barCode!!.getBitmap(resources))
if (currentPass.barCode!!.alternativeText != null) {
alternativeBarcodeText.visibility = View.VISIBLE
alternativeBarcodeText.text = currentPass.barCode!!.alternativeText
} else {
alternativeBarcodeText.visibility = View.GONE
}
}
/**
* QR and AZTEC are best fit in Portrait
* PDF417 is best viewed in Landscape
*
*
* main work is to avoid changing if we are already optimal
* ( reverse orientation / sensor is the problem here ..)
*/
private fun setBestFittingOrientationForBarCode() {
if (currentPass.barCode!!.format!!.isQuadratic()) {
when (requestedOrientation) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT -> return // do nothing
else -> lockOrientation(Configuration.ORIENTATION_PORTRAIT)
}
} else {
when (requestedOrientation) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE -> return // do nothing
else -> lockOrientation(Configuration.ORIENTATION_LANDSCAPE)
}
}
}
}
| gpl-3.0 | ecdc8fe2aedb8cd7a2908fa7d69d7170 | 32.317073 | 87 | 0.655198 | 5.022059 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/image/getters/WPRemoteResourceViewTarget.kt | 1 | 5067 | @file:Suppress("DEPRECATION")
package org.wordpress.android.util.image.getters
import android.annotation.SuppressLint
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.widget.TextView
import com.bumptech.glide.request.Request
import com.bumptech.glide.request.target.SizeReadyCallback
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.target.ViewTarget
import com.bumptech.glide.request.transition.Transition
import org.wordpress.android.ui.WPTextViewDrawableCallback
import org.wordpress.android.util.ImageUtils
/**
* A class that we can load a remote resource into. Automatically displays placeholder while the remote img is
* loading and displays an error image if the loading fails.
*
* We could probably subclass BaseTarget instead of ViewTarget, since we basically override most of its functionality.
* However, we might want to use ViewTarget.clearOnDetach(..) when it becomes stable (it's experimental now).
* It clears the View's Request when the View is detached from its Window and restarts the Request when the View is
* re-attached from its Window.
*/
@Suppress("DEPRECATION")
internal class WPRemoteResourceViewTarget(
view: TextView,
private val maxSize: Int
) : ViewTarget<TextView, Drawable>(view) {
private val drawableWrapper = RemoteDrawableWrapper()
private var request: Request? = null
val drawable: Drawable get() = drawableWrapper
override fun onResourceReady(res: Drawable, transition: Transition<in Drawable>?) {
if (res is Animatable) {
// Bind a Callback object to this Drawable. Required for clients that want to support
// animated drawables.
res.callback = WPTextViewDrawableCallback(getView())
(res as Animatable).start()
}
replaceDrawable(res, ImageUtils.getScaledBounds(res.intrinsicWidth, res.intrinsicHeight, maxSize))
}
override fun onLoadFailed(errorDrawable: Drawable?) {
errorDrawable?.let {
replaceDrawable(it, Rect(0, 0, it.intrinsicWidth, it.intrinsicHeight))
}
}
override fun onLoadStarted(res: Drawable?) {
super.onLoadStarted(res)
res?.let {
replaceDrawable(it, Rect(0, 0, it.intrinsicWidth, it.intrinsicHeight))
}
}
private fun replaceDrawable(drawable: Drawable, bounds: Rect) {
drawableWrapper.setDrawable(drawable)
drawableWrapper.bounds = bounds
// force textView to resize correctly by resetting the content to itself
getView().text = getView().text
}
/**
* Since this target can be used for loading multiple images into a single TextView, we can't use the default
* implementation which supports only one request per view. On the other hand, by using field to store the request
* we lose the ability to clear previous requests if the client creates new instance of the
* WPRemoteResourceViewTarget for the new request on the same view. Canceling any previous requests for the same
* View must be handled by the client (see WPCustomImageGetter.clear(..) methods for reference).
*/
override fun getRequest(): Request? {
return request
}
override fun setRequest(request: Request?) {
this.request = request
}
/**
* We don't want to call super, since it determines the size from the size of the View. But this target may be used
* for loading multiple images into a single View.
*/
@SuppressLint("MissingSuperCall")
override fun getSize(cb: SizeReadyCallback) {
cb.onSizeReady(maxSize, Target.SIZE_ORIGINAL)
}
/**
* Drawable wrapper so we can replace placeholder with remote/error resource, after the requests finishes.
*
* We need to synchronously return drawable in WPCustomImageGetter.getDrawable(...).
* If we return regular drawable - let's say a placeholder, we won't be able to replace it with the actual image
* ==> This wrapper just adds us ability to change the content of the drawable after the asynchronous call finishes.
*/
private class RemoteDrawableWrapper : Drawable() {
internal var drawable: Drawable? = null
fun setDrawable(drawable: Drawable) {
this.drawable = drawable
}
override fun draw(canvas: Canvas) {
drawable?.draw(canvas)
}
override fun setAlpha(alpha: Int) {
drawable?.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
drawable?.colorFilter = colorFilter
}
@Suppress("DEPRECATION")
override fun getOpacity(): Int {
return drawable?.opacity ?: PixelFormat.UNKNOWN
}
override fun setBounds(bounds: Rect) {
super.setBounds(bounds)
drawable?.bounds = bounds
}
}
}
| gpl-2.0 | fb0c2ea464ebd65be1d9d4321c823464 | 37.976923 | 120 | 0.701007 | 4.834924 | false | false | false | false |
ingokegel/intellij-community | plugins/toml/core/src/main/kotlin/org/toml/lang/parse/TomlParserUtil.kt | 9 | 1964 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.lang.parse
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
object TomlParserUtil : GeneratedParserUtilBase() {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun remap(b: PsiBuilder, level: Int, from: IElementType, to: IElementType): Boolean {
if (b.tokenType == from) {
b.remapCurrentToken(to)
b.advanceLexer()
return true
}
return false
}
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun any(b: PsiBuilder, level: Int): Boolean = true
@JvmStatic
fun atSameLine(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val marker = enter_section_(b)
b.eof() // skip whitespace
val isSameLine = !isNextAfterNewLine(b)
if (!isSameLine) addVariant(b, "VALUE")
val result = isSameLine && parser.parse(b, level)
exit_section_(b, marker, null, result)
return result
}
@JvmStatic
fun atNewLine(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val marker = enter_section_(b)
b.eof() // skip whitespace
val result = isNextAfterNewLine(b) && parser.parse(b, level)
exit_section_(b, marker, null, result)
return result
}
}
private fun isNextAfterNewLine(b: PsiBuilder): Boolean {
val prevToken = b.rawLookup(-1)
return prevToken == null || prevToken == TokenType.WHITE_SPACE && b.rawLookupText(-1).contains("\n")
}
/** Similar to [com.intellij.lang.PsiBuilderUtil.rawTokenText] */
private fun PsiBuilder.rawLookupText(steps: Int): CharSequence {
val start = rawTokenTypeStart(steps)
val end = rawTokenTypeStart(steps + 1)
return if (start == -1 || end == -1) "" else originalText.subSequence(start, end)
}
| apache-2.0 | 6ddbf5fe1393393b9e1b0af6185fa7b2 | 30.677419 | 104 | 0.659369 | 4.008163 | false | false | false | false |
anitaa1990/DeviceInfo-Sample | deviceinfo/src/main/java/com/an/deviceinfo/ads/AdInfo.kt | 1 | 928 | package com.an.deviceinfo.ads
import android.content.Context
import java.io.IOException
class AdInfo(private val context: Context) {
//Send Data to callback
val ad: Ad
@Throws(Exception::class)
get() {
val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)
val advertisingId = adInfo.id
val adDoNotTrack = adInfo.isLimitAdTrackingEnabled
val ad = Ad()
ad.isAdDoNotTrack = adDoNotTrack
ad.advertisingId = advertisingId
return ad
}
fun getAndroidAdId(callback: AdIdCallback) {
Thread(Runnable {
try {
val ad = ad
callback.onResponse(context, ad)
} catch (e: Exception) {
e.printStackTrace()
}
}).start()
}
interface AdIdCallback {
fun onResponse(context: Context, ad: Ad)
}
}
| apache-2.0 | 650bc5056954cef37a88b0b40a96fcc4 | 24.777778 | 74 | 0.570043 | 4.504854 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/AbstractEntitiesTest.kt | 2 | 8946 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.workspaceModel.storage.entities.test.api.*
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.assertConsistency
import junit.framework.TestCase
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class AbstractEntitiesTest {
@Test
fun `simple adding`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
builder.addLeftEntity(sequenceOf(middleEntity))
val storage = builder.toSnapshot()
val leftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
assertOneElement(leftEntity.children.toList())
}
@Test
fun `modifying left entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity("first")
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity("second")
builder.modifyEntity(leftEntity) {
}
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `modifying abstract entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity()
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `children replace in addDiff`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherBuilder = MutableEntityStorage.from(builder)
val anotherMiddleEntity = anotherBuilder.addMiddleEntity("Another")
anotherBuilder.modifyEntity(leftEntity.from(anotherBuilder)) {
this.children = listOf(middleEntity, anotherMiddleEntity)
}
val initialMiddleEntity = builder.addMiddleEntity("Initial")
builder.modifyEntity(leftEntity) {
this.children = listOf(middleEntity, initialMiddleEntity)
}
builder.addDiff(anotherBuilder)
val actualLeftEntity = assertOneElement(builder.entities(LeftEntity::class.java).toList())
val children = actualLeftEntity.children.toList() as List<MiddleEntity>
assertEquals(2, children.size)
assertTrue(children.any { it.property == "Another" })
assertTrue(children.none { it.property == "Initial" })
}
@Test
fun `keep children ordering when making storage`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).single().children.toList()
assertEquals(middleEntity1, children[0])
assertEquals(middleEntity2, children[1])
}
@Test
fun `keep children ordering when making storage 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("Two")
val middleEntity2 = builder.addMiddleEntity("One")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val anotherBuilder = makeBuilder(builder) {
addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
}
builder.addDiff(anotherBuilder)
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2, children[0])
assertEquals(middleEntity1, children[1])
}
@Test
fun `keep children ordering after rbs 1`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity1.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity2.property, (children[1] as MiddleEntity).property)
}
@Test
fun `keep children ordering after rbs 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity1.property, (children[1] as MiddleEntity).property)
}
@Test
fun `modifying one to one child switch`() {
val builder = MutableEntityStorage.create()
val headAbstractionEntity = HeadAbstractionEntity("info", MySource)
builder.addEntity(headAbstractionEntity)
builder.addEntity(LeftEntity(AnotherSource) {
this.parent = headAbstractionEntity
})
builder.addEntity(LeftEntity(MySource) {
this.parent = headAbstractionEntity
})
builder.assertConsistency()
assertNull(builder.entities(LeftEntity::class.java).single { it.entitySource == AnotherSource }.parent)
assertNotNull(builder.entities(LeftEntity::class.java).single { it.entitySource == MySource }.parent)
}
@Test
fun `modifying one to one parent switch`() {
val builder = MutableEntityStorage.create()
val child = builder addEntity LeftEntity(AnotherSource)
builder addEntity HeadAbstractionEntity("Info", MySource) {
this.child = child
}
builder addEntity HeadAbstractionEntity("Info2", MySource) {
this.child = child
}
builder.assertConsistency()
assertNull(builder.entities(HeadAbstractionEntity::class.java).single { it.data == "Info" }.child)
assertNotNull(builder.entities(HeadAbstractionEntity::class.java).single { it.data == "Info2" }.child)
}
@Test
fun `entity changes visible in mutable storage`() {
var builder = MutableEntityStorage.create()
val entity = ParentNullableEntity("ParentData", MySource)
builder.addEntity(entity)
builder = MutableEntityStorage.from(builder.toSnapshot())
val resultEntity = builder.entities(ParentNullableEntity::class.java).single()
resultEntity.parentData
var firstEntityData = (entity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
var secondEntityData = (resultEntity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
TestCase.assertSame(firstEntityData, secondEntityData)
val originalEntityData = firstEntityData
builder.modifyEntity(resultEntity) {
this.parentData = "NewParentData"
}
val anotherResult = builder.entities(ParentNullableEntity::class.java).single()
TestCase.assertEquals(resultEntity.parentData, anotherResult.parentData)
firstEntityData = (resultEntity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
secondEntityData = (anotherResult as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
TestCase.assertSame(firstEntityData, secondEntityData)
TestCase.assertNotSame(firstEntityData, originalEntityData)
builder.modifyEntity(anotherResult) {
this.parentData = "AnotherParentData"
}
val oneMoreResult = builder.entities(ParentNullableEntity::class.java).single()
TestCase.assertEquals(resultEntity.parentData, anotherResult.parentData)
TestCase.assertEquals(oneMoreResult.parentData, anotherResult.parentData)
TestCase.assertEquals(oneMoreResult.parentData, resultEntity.parentData)
}
}
| apache-2.0 | 96fe33123fc4556a529e928f5fab089c | 37.068085 | 140 | 0.753409 | 4.986622 | false | true | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/projectlevelman/VcsDefaultMappingUtils.kt | 3 | 3832 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.impl.projectlevelman
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vcs.VcsRootChecker
import com.intellij.openapi.vfs.VirtualFile
internal object VcsDefaultMappingUtils {
/**
* Provides VCS roots where [projectRoots] are located using [rootChecker].
*
* [mappedDirs] are took into account during detection, so that direct mappings shouldn't be overwritten by <Project> mappings.
* E.g. if directory `/project` has direct mapping for Hg and there is `/project/.git` folder
* (that is going to be detected as <Project> mapping),
* `/project` shouldn't be returned as <Project> mapping. It should stay as Hg direct mapping.
* So, already mapped files and directories from [mappedDirs] are excluded from the result.
*
* NB: if [rootChecker]'s [com.intellij.openapi.vcs.VcsRootChecker.areChildrenValidMappings]
* is true then a result may contain directories under [project] but not "pure" VCS roots.
* Example: for `root/svn_root_dir/project_root_dir` if `svn_root_dir` is not under project
* `project_dir` will be returned as VCS root, not `svn_root_dir`.
* It is needed to detect changes only under `project_root_dir`, not under `svn_root_dir/unrelated_project`
*
* @param projectRoots files and directories that are a part of the [project]
* @param mappedDirs directories that were already mapped with VCS
*/
@JvmStatic
fun detectProjectMappings(
project: Project,
rootChecker: VcsRootChecker,
projectRoots: Collection<VirtualFile>,
mappedDirs: Set<VirtualFile>
): Set<VirtualFile> {
return VcsDefaultMappingDetector(project, rootChecker).detectProjectMappings(projectRoots, mappedDirs)
}
}
private class VcsDefaultMappingDetector(
private val project: Project,
private val rootChecker: VcsRootChecker
) {
private val fileIndex = ProjectFileIndex.getInstance(project)
private val checkedDirs = mutableMapOf<VirtualFile, Boolean>()
fun detectProjectMappings(
projectRoots: Collection<VirtualFile>,
mappedDirs: Set<VirtualFile>
): Set<VirtualFile> {
for (dir in mappedDirs) {
checkedDirs[dir] = true
}
val vcsRoots = mutableSetOf<VirtualFile>()
for (projectRoot in projectRoots) {
val root = detectVcsForProjectRoot(projectRoot)
if (root != null) {
vcsRoots.add(root)
}
}
vcsRoots.removeAll(mappedDirs) // do not report known mappings
return vcsRoots
}
private fun detectVcsForProjectRoot(projectRoot: VirtualFile): VirtualFile? {
for (file in generateSequence(projectRoot) { it.parent }) {
if (isVcsRoot(file)) {
return file
}
val parent = file.parent
if (parent != null && !isUnderProject(parent)) {
if (rootChecker.areChildrenValidMappings() &&
isUnderVcsRoot(parent)) {
return file
}
else {
return null
}
}
}
return null
}
private fun isUnderVcsRoot(file: VirtualFile): Boolean {
return generateSequence(file) { it.parent }.any { isVcsRoot(it) }
}
private fun isVcsRoot(file: VirtualFile): Boolean {
ProgressManager.checkCanceled()
return checkedDirs.computeIfAbsent(file) { key -> rootChecker.isRoot(key) }
}
private fun isUnderProject(f: VirtualFile): Boolean {
return runReadAction {
if (project.isDisposed) {
throw ProcessCanceledException()
}
fileIndex.isInContent(f)
}
}
} | apache-2.0 | 9b14ee005eaa77aaa597e254bfe2d528 | 34.165138 | 129 | 0.714509 | 4.32018 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/SettingValidator.kt | 8 | 4421 | // 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.tools.projectWizard.core.entity
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.Failure
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.UNIT_SUCCESS
import org.jetbrains.kotlin.tools.projectWizard.core.ValidationError
@JvmInline
value class SettingValidator<V>(val validate: Reader.(V) -> ValidationResult) {
infix fun and(other: SettingValidator<V>) = SettingValidator<V> { value ->
validate(value) and other.validate(this, value)
}
operator fun Reader.invoke(value: V) = validate(value)
}
fun <V> settingValidator(validator: Reader.(V) -> ValidationResult) =
SettingValidator(validator)
fun <V> inValidatorContext(validator: Reader.(V) -> SettingValidator<V>) =
SettingValidator<V> { value ->
validator(value).validate(this, value)
}
object StringValidators {
fun shouldNotBeBlank(name: String) = settingValidator { value: String ->
if (value.isBlank()) ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message("validation.should.not.be.blank", name.capitalize())
)
else ValidationResult.OK
}
fun shouldBeValidIdentifier(name: String, allowedExtraSymbols: Set<Char>) = settingValidator { value: String ->
if (value.any { char -> !char.isLetterOrDigit() && char !in allowedExtraSymbols }) {
val allowedExtraSymbolsStringified = allowedExtraSymbols
.takeIf { it.isNotEmpty() }
?.joinToString(separator = ", ") { char -> "'$char'" }
?.let { chars -> KotlinNewProjectWizardBundle.message("validation.identifier.additional.symbols", chars) }
.orEmpty()
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message("validation.identifier", name.capitalize(), allowedExtraSymbolsStringified)
)
} else ValidationResult.OK
}
}
fun List<ValidationResult>.fold() = fold(ValidationResult.OK, ValidationResult::and)
sealed class ValidationResult {
abstract val isOk: Boolean
object OK : ValidationResult() {
override val isOk = true
}
data class ValidationError(val messages: List<@Nls String>, val target: Any? = null) : ValidationResult() {
constructor(@Nls message: String, target: Any? = null) : this(listOf(message), target)
override val isOk = false
}
infix fun and(other: ValidationResult) = when {
this is OK -> other
this is ValidationError && other is ValidationError -> ValidationError(messages + other.messages, target ?: other.target)
else -> this
}
companion object {
fun create(condition: Boolean, @Nls message: String) =
if (condition) OK else ValidationError(message)
inline fun create(condition: Boolean, message: () -> @Nls String) =
if (condition) OK else ValidationError(message())
}
}
fun <V> SettingValidator<V>.withTarget(target: Any) = SettingValidator<V> { value ->
this.validate(value).withTarget(target)
}
infix fun ValidationResult.isSpecificError(error: ValidationResult.ValidationError) =
this is ValidationResult.ValidationError && messages.firstOrNull() == error.messages.firstOrNull()
fun ValidationResult.withTarget(target: Any) = when (this) {
ValidationResult.OK -> this
is ValidationResult.ValidationError -> copy(target = target)
}
fun ValidationResult.withTargetIfNull(target: Any) = when (this) {
ValidationResult.OK -> this
is ValidationResult.ValidationError -> if (this.target == null) copy(target = target) else this
}
fun ValidationResult.toResult() = when (this) {
ValidationResult.OK -> UNIT_SUCCESS
is ValidationResult.ValidationError -> Failure(messages.map { ValidationError(it) })
}
interface Validatable<out V> {
val validator: SettingValidator<@UnsafeVariance V>
}
fun <V, Q : Validatable<Q>> Reader.validateList(list: List<Q>) = settingValidator<V> {
list.fold(ValidationResult.OK as ValidationResult) { result, value ->
result and value.validator.validate(this, value).withTarget(value)
}
}
| apache-2.0 | 3ea5ab00ab96e78d49b206e3cbb7e76a | 37.443478 | 129 | 0.703913 | 4.5861 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/HideSideWindowsAction.kt | 7 | 1853 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.toolWindow.ToolWindowEventSource
internal class HideSideWindowsAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val toolWindowManager = ToolWindowManagerEx.getInstanceEx(project) as ToolWindowManagerImpl
val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId ?: return
val window = toolWindowManager.getToolWindow(id) ?: return
if (HideToolWindowAction.shouldBeHiddenByShortCut(window)) {
toolWindowManager.hideToolWindow(id = id, hideSide = true, source = ToolWindowEventSource.HideSideWindowsAction)
}
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
val project = event.project
if (project == null) {
presentation.isEnabled = false
return
}
val toolWindowManager = ToolWindowManager.getInstance(project)
if (toolWindowManager.activeToolWindowId == null) {
val window = toolWindowManager.getToolWindow(toolWindowManager.lastActiveToolWindowId ?: return)
presentation.isEnabled = window != null && HideToolWindowAction.shouldBeHiddenByShortCut(window)
}
else {
presentation.isEnabled = true
}
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
} | apache-2.0 | 9484d8fca0b40fd350ef0beb48e19d0c | 42.116279 | 120 | 0.782515 | 5.049046 | false | false | false | false |
jk1/intellij-community | plugins/settings-repository/src/actions/CommitToIcsAction.kt | 4 | 6263 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.actions
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.actions.CommonCheckinFilesAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.checkin.BeforeCheckinDialogHandler
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.util.SmartList
import org.jetbrains.settingsRepository.CommitToIcsDialog
import org.jetbrains.settingsRepository.ProjectId
import org.jetbrains.settingsRepository.icsManager
import org.jetbrains.settingsRepository.icsMessage
import java.util.*
class CommitToIcsAction : CommonCheckinFilesAction() {
class IcsBeforeCommitDialogHandler : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return CheckinHandler.DUMMY
}
override fun createSystemReadyHandler(project: Project): BeforeCheckinDialogHandler? {
return BEFORE_CHECKIN_DIALOG_HANDLER
}
companion object {
private val BEFORE_CHECKIN_DIALOG_HANDLER = object : BeforeCheckinDialogHandler() {
override fun beforeCommitDialogShown(project: Project, changes: List<Change>, executors: Iterable<CommitExecutor>, showVcsCommit: Boolean): Boolean {
val collectConsumer = ProjectChangeCollectConsumer(project)
collectProjectChanges(changes, collectConsumer)
showDialog(project, collectConsumer, null)
return true
}
}
}
}
override fun getActionName(dataContext: VcsContext): String = icsMessage("action.CommitToIcs.text")
override fun isApplicableRoot(file: VirtualFile, status: FileStatus, dataContext: VcsContext): Boolean {
val project = dataContext.project
return project is ProjectEx && project.stateStore.storageScheme == StorageScheme.DIRECTORY_BASED && super.isApplicableRoot(file, status, dataContext) && !file.isDirectory && isProjectConfigFile(file, dataContext.project!!)
}
override fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> = roots
override fun performCheckIn(context: VcsContext, project: Project, roots: Array<out FilePath>) {
val projectId = getProjectId(project) ?: return
val changes = context.selectedChanges
val collectConsumer = ProjectChangeCollectConsumer(project)
if (changes != null && changes.isNotEmpty()) {
for (change in changes) {
collectConsumer.consume(change)
}
}
else {
val manager = ChangeListManager.getInstance(project)
for (path in getRoots(context)) {
collectProjectChanges(manager.getChangesIn(path), collectConsumer)
}
}
showDialog(project, collectConsumer, projectId)
}
}
private class ProjectChangeCollectConsumer(private val project: Project) {
private var projectChanges: MutableList<Change>? = null
fun consume(change: Change) {
if (isProjectConfigFile(change.virtualFile, project)) {
if (projectChanges == null) {
projectChanges = SmartList<Change>()
}
projectChanges!!.add(change)
}
}
fun getResult() = if (projectChanges == null) listOf<Change>() else projectChanges!!
fun hasResult() = projectChanges != null
}
private fun getProjectId(project: Project): String? {
val projectId = ServiceManager.getService<ProjectId>(project, ProjectId::class.java)!!
if (projectId.uid == null) {
if (icsManager.settings.doNoAskMapProject ||
MessageDialogBuilder.yesNo("Settings Server Project Mapping", "Project is not mapped on Settings Server. Would you like to map?").project(project).doNotAsk(object : DialogWrapper.DoNotAskOption.Adapter() {
override fun isSelectedByDefault(): Boolean {
return true
}
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
icsManager.settings.doNoAskMapProject = isSelected
}
}).show() == Messages.YES) {
projectId.uid = UUID.randomUUID().toString()
}
}
return projectId.uid
}
private fun showDialog(project: Project, collectConsumer: ProjectChangeCollectConsumer, projectId: String?) {
if (!collectConsumer.hasResult()) {
return
}
var effectiveProjectId = projectId
if (effectiveProjectId == null) {
effectiveProjectId = getProjectId(project)
if (effectiveProjectId == null) {
return
}
}
CommitToIcsDialog(project, effectiveProjectId, collectConsumer.getResult()).show()
}
private fun collectProjectChanges(changes: Collection<Change>, collectConsumer: ProjectChangeCollectConsumer) {
for (change in changes) {
collectConsumer.consume(change)
}
}
private fun isProjectConfigFile(file: VirtualFile?, project: Project): Boolean {
if (file == null) {
return false
}
return FileUtil.isAncestor(project.basePath!!, file.path, true)
}
| apache-2.0 | 668651164494591a1b51dcf0b4a15d35 | 37.660494 | 226 | 0.758263 | 4.649592 | false | false | false | false |
carrotengineer/Warren | src/test/kotlin/engineer/carrot/warren/warren/handler/PrivMsgHandlerTests.kt | 2 | 3397 | package engineer.carrot.warren.warren.handler
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import engineer.carrot.warren.kale.irc.CharacterCodes
import engineer.carrot.warren.kale.irc.message.rfc1459.PrivMsgMessage
import engineer.carrot.warren.kale.irc.message.utility.CaseMapping
import engineer.carrot.warren.kale.irc.prefix.Prefix
import engineer.carrot.warren.warren.event.*
import engineer.carrot.warren.warren.state.*
import org.junit.Before
import org.junit.Test
class PrivMsgHandlerTests {
lateinit var handler: PrivMsgHandler
lateinit var channelTypesState: ChannelTypesState
lateinit var joinedChannelsState: JoinedChannelsState
lateinit var mockEventDispatcher: IWarrenEventDispatcher
@Before fun setUp() {
joinedChannelsState = JoinedChannelsState(mappingState = CaseMappingState(CaseMapping.RFC1459))
channelTypesState = ChannelTypesState(types = setOf('#', '&'))
mockEventDispatcher = mock()
handler = PrivMsgHandler(mockEventDispatcher, joinedChannelsState, channelTypesState)
}
@Test fun test_handle_ChannelMessage_FiresEvent() {
val channel = emptyChannel("&channel")
channel.users += generateUser("someone")
joinedChannelsState += channel
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "&channel", message = "a test message"), mapOf())
verify(mockEventDispatcher).fire(ChannelMessageEvent(user = generateUser("someone"), channel = channel, message = "a test message"))
}
@Test fun test_handle_ChannelMessage_NotInChannel_DoesNothing() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "¬InChannel", message = "a test message"), mapOf())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_PrivateMessage_FiresEvent() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "not-a-channel", message = "a test message"), mapOf())
verify(mockEventDispatcher).fire(PrivateMessageEvent(user = Prefix(nick = "someone"), message = "a test message"))
}
@Test fun test_handle_NoSource_DoesNothing() {
handler.handle(PrivMsgMessage(source = null, target = "not-a-channel", message = "a test message"), mapOf())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_ChannelMessage_Action_FiresEvent() {
val channel = emptyChannel("&channel")
channel.users += generateUser("someone")
joinedChannelsState += channel
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "&channel", message = "${CharacterCodes.CTCP}ACTION an action${CharacterCodes.CTCP}"), mapOf())
verify(mockEventDispatcher).fire(ChannelActionEvent(user = generateUser("someone"), channel = channel, message = "an action"))
}
@Test fun test_handle_PrivateMessage_Action_FiresEvent() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "not a channel", message = "${CharacterCodes.CTCP}ACTION an action${CharacterCodes.CTCP}"), mapOf())
verify(mockEventDispatcher).fire(PrivateActionEvent(user = Prefix(nick = "someone"), message = "an action"))
}
} | isc | 61878278c85bb7975a79b94705d39405 | 43.710526 | 182 | 0.722991 | 4.584345 | false | true | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/engine/opengl/GlWallpaperServiceImpl.kt | 1 | 6791 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.doctoror.particleswallpaper.engine.opengl
import android.annotation.TargetApi
import android.opengl.GLSurfaceView
import android.os.Build
import android.os.Handler
import android.view.SurfaceHolder
import com.doctoror.particlesdrawable.contract.SceneScheduler
import com.doctoror.particlesdrawable.opengl.chooser.FailsafeEGLConfigChooserFactory
import com.doctoror.particlesdrawable.opengl.renderer.GlSceneRenderer
import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker
import com.doctoror.particleswallpaper.engine.EngineController
import com.doctoror.particleswallpaper.engine.EnginePresenter
import com.doctoror.particleswallpaper.engine.EngineSceneRenderer
import com.doctoror.particleswallpaper.engine.makeInjectArgumentsForWallpaperServiceEngineImpl
import com.doctoror.particleswallpaper.framework.di.get
import com.doctoror.particleswallpaper.framework.execution.GlScheduler
import com.doctoror.particleswallpaper.framework.opengl.KnownOpenglIssuesHandler
import com.doctoror.particleswallpaper.userprefs.data.OpenGlSettings
import net.rbgrn.android.glwallpaperservice.GLWallpaperService
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class GlWallpaperServiceImpl : GLWallpaperService() {
override fun onCreateEngine(): Engine {
val renderer = GlEngineSceneRenderer()
val settingsOpenGL: OpenGlSettings = get(this)
val knownOpenglIssuesHandler: KnownOpenglIssuesHandler = get(this)
val engine = EngineImpl(knownOpenglIssuesHandler, renderer, settingsOpenGL.numSamples)
engine.presenter = get(
context = this,
parameters = {
makeInjectArgumentsForWallpaperServiceEngineImpl(
engine,
GlScheduler(engine),
renderer as EngineSceneRenderer,
engine as SceneScheduler
)
}
)
return engine
}
inner class EngineImpl(
private val knownOpenglIssuesHandler: KnownOpenglIssuesHandler,
private val renderer: GlSceneRenderer,
samples: Int
) : GLEngine(), EngineController, GLSurfaceView.Renderer, SceneScheduler {
private val handler = Handler()
lateinit var presenter: EnginePresenter
@Volatile
private var surfaceWidth = 0
@Volatile
private var surfaceHeight = 0
private var firstDraw = true
init {
GLErrorChecker.setShouldCheckGlError(true)
setEGLContextClientVersion(2)
setEGLConfigChooser(
FailsafeEGLConfigChooserFactory.newFailsafeEGLConfigChooser(samples, null)
)
setRenderer(this)
renderMode = RENDERMODE_WHEN_DIRTY
}
override fun onCreate(surfaceHolder: SurfaceHolder?) {
super.onCreate(surfaceHolder)
queueEvent { presenter.onCreate() }
}
override fun onDestroy() {
super.onDestroy()
queueEvent { presenter.onDestroy() }
}
override fun onSurfaceCreated(gl: GL10, config: EGLConfig?) {
renderer.setupGl()
presenter.onSurfaceCreated()
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
surfaceWidth = width
surfaceHeight = height
notifyDimensions(
width,
height,
desiredMinimumWidth
)
}
override fun onDesiredSizeChanged(desiredWidth: Int, desiredHeight: Int) {
super.onDesiredSizeChanged(desiredWidth, desiredHeight)
queueEvent {
notifyDimensions(
surfaceWidth,
surfaceHeight,
desiredWidth
)
}
}
private fun notifyDimensions(
surfaceWidth: Int,
surfaceHeight: Int,
desiredWidth: Int
) {
if (surfaceWidth != 0 && surfaceHeight != 0) {
presenter.setDimensions(
EnginePresenter.WallpaperDimensions(
width = surfaceWidth,
height = surfaceHeight,
desiredWidth = Math.max(surfaceWidth, desiredWidth)
)
)
}
}
override fun onOffsetsChanged(
xOffset: Float,
yOffset: Float,
xOffsetStep: Float,
yOffsetStep: Float,
xPixelOffset: Int,
yPixelOffset: Int
) {
queueEvent { presenter.setTranslationX(xPixelOffset.toFloat()) }
}
override fun onDrawFrame(gl: GL10) {
if (firstDraw) {
// Never check draw errors there. Disable on first call.
GLErrorChecker.setShouldCheckGlError(false)
}
presenter.onDrawFrame()
if (firstDraw) {
firstDraw = false
// Check draw error once here, where known issues expected.
knownOpenglIssuesHandler.handleGlError("GlWallpaperServiceImpl.onDrawFrame")
}
}
override fun onSurfaceDestroyed(holder: SurfaceHolder) {
super.onSurfaceDestroyed(holder)
presenter.visible = false
}
override fun onVisibilityChanged(visible: Boolean) {
super.onVisibilityChanged(visible)
queueEvent { presenter.visible = visible }
}
@TargetApi(Build.VERSION_CODES.O_MR1)
override fun onComputeColors() = presenter.onComputeColors()
override fun scheduleNextFrame(delay: Long) {
if (presenter.visible) {
if (delay == 0L) {
requestRender()
} else {
handler.postDelayed(renderRunnable, delay)
}
}
}
override fun unscheduleNextFrame() {
handler.removeCallbacksAndMessages(null)
}
private val renderRunnable = Runnable { requestRender() }
}
}
| apache-2.0 | a5fcb89bb2c9ad9e8d65d07fa2f51ae9 | 32.78607 | 94 | 0.629068 | 5.543673 | false | false | false | false |
ayatk/biblio | infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/Converters.kt | 1 | 2548 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.infrastructure.database
import androidx.room.TypeConverter
import com.ayatk.biblio.infrastructure.database.entity.enums.BigGenre
import com.ayatk.biblio.infrastructure.database.entity.enums.Genre
import com.ayatk.biblio.infrastructure.database.entity.enums.NovelState
import com.ayatk.biblio.infrastructure.database.entity.enums.Publisher
import com.ayatk.biblio.infrastructure.database.entity.enums.ReadingState
import java.util.Date
import java.util.UUID
@Suppress("TooManyFunctions")
object Converters {
@JvmStatic
@TypeConverter
fun serializeBigGenre(genre: BigGenre): String = genre.name
@JvmStatic
@TypeConverter
fun deserializeBigGenre(genre: String): BigGenre = BigGenre.valueOf(genre)
@JvmStatic
@TypeConverter
fun serializeGenre(genre: Genre): String = genre.name
@JvmStatic
@TypeConverter
fun deserializeGenre(genre: String): Genre = Genre.valueOf(genre)
@JvmStatic
@TypeConverter
fun serializeNovelType(state: NovelState): String = state.name
@JvmStatic
@TypeConverter
fun deserializeNovelType(state: String): NovelState = NovelState.valueOf(state)
@JvmStatic
@TypeConverter
fun serializePublisher(publisher: Publisher): String = publisher.name
@JvmStatic
@TypeConverter
fun deserializePublisher(publisher: String): Publisher = Publisher.valueOf(publisher)
@JvmStatic
@TypeConverter
fun serializeReadingState(readingState: ReadingState): String = readingState.name
@JvmStatic
@TypeConverter
fun deserializeReadingState(state: String): ReadingState = ReadingState.valueOf(state)
@JvmStatic
@TypeConverter
fun deserializeUUID(value: String): UUID = UUID.fromString(value)
@JvmStatic
@TypeConverter
fun serializeUUID(value: UUID): String = value.toString()
@JvmStatic
@TypeConverter
fun deserializeDate(value: Long): Date = Date(value)
@JvmStatic
@TypeConverter
fun serializeDate(value: Date): Long = value.time
}
| apache-2.0 | df32915a0798c8fb6438b3fb0cf9560e | 28.627907 | 88 | 0.774333 | 4.282353 | false | false | false | false |
bozaro/git-lfs-java | gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/internal/BatchWorker.kt | 1 | 10998 | package ru.bozaro.gitlfs.client.internal
import org.apache.http.HttpStatus
import org.slf4j.LoggerFactory
import ru.bozaro.gitlfs.client.AuthHelper
import ru.bozaro.gitlfs.client.BatchSettings
import ru.bozaro.gitlfs.client.Client
import ru.bozaro.gitlfs.client.Client.ConnectionClosePolicy
import ru.bozaro.gitlfs.client.exceptions.ForbiddenException
import ru.bozaro.gitlfs.client.exceptions.UnauthorizedException
import ru.bozaro.gitlfs.common.Constants.PATH_BATCH
import ru.bozaro.gitlfs.common.data.*
import java.io.FileNotFoundException
import java.io.IOException
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.stream.Collectors
/**
* Base batch client.
*
* @author Artem V. Navrotskiy
*/
abstract class BatchWorker<T, R>(
protected val client: Client,
protected val pool: ExecutorService,
private val settings: BatchSettings,
private val operation: Operation
) {
private val log = LoggerFactory.getLogger(BatchWorker::class.java)
private val batchSequence = AtomicInteger(0)
private val batchInProgress = AtomicInteger()
private val objectQueue: ConcurrentMap<String, State<T, R?>> = ConcurrentHashMap()
private val objectInProgress = AtomicInteger(0)
private val currentAuth = AtomicReference<Link?>(null)
/**
* This method start send object metadata to server.
*
* @param context Object worker context.
* @param meta Object metadata.
* @return Return future with result. For same objects can return same future.
*/
protected fun enqueue(meta: Meta, context: T): CompletableFuture<R?> {
var state = objectQueue[meta.oid]
if (state != null) {
if (state.future.isCancelled) {
objectQueue.remove(meta.oid, state)
state = null
}
}
if (state == null) {
val newState = State<T, R?>(meta, context)
state = objectQueue.putIfAbsent(meta.oid, newState)
if (state == null) {
state = newState
stateEnqueue(true)
}
}
return state.future
}
private fun stateEnqueue(pooled: Boolean) {
val batchId = batchSequence.incrementAndGet()
tryBatchRequest(batchId, pooled)
}
private fun tryBatchRequestPredicate(): Boolean {
return (objectInProgress.get() < settings.threshold
&& !objectQueue.isEmpty())
}
private fun tryBatchRequest(batchId: Int, pooled: Boolean): Boolean {
if (!tryBatchRequestPredicate()) {
return false
}
if (batchInProgress.compareAndSet(0, batchId)) {
executeInPool(
"batch request: " + objectQueue.size + " in queue",
{
var curBatchId = batchId
while (true) {
try {
submitBatchTask()
} finally {
batchInProgress.set(0)
}
val newBatchId = batchSequence.get()
if (newBatchId == curBatchId && !tryBatchRequestPredicate()) {
break
}
curBatchId = newBatchId
if (!batchInProgress.compareAndSet(0, curBatchId)) {
break
}
}
},
{ batchInProgress.compareAndSet(batchId, 0) },
pooled
)
return true
}
return false
}
private fun invalidateAuth(auth: Link) {
if (currentAuth.compareAndSet(auth, null)) {
client.authProvider.invalidateAuth(operation, auth)
}
}
private fun submitBatchTask() {
val batch = takeBatch()
var auth = currentAuth.get()
try {
if (batch.isNotEmpty()) {
if (auth == null) {
auth = client.authProvider.getAuth(operation)
currentAuth.set(auth)
}
val metas = batch.values.stream().map { s: State<T, R?> -> s.meta }.collect(Collectors.toList())
val result = client.doRequest(
auth,
JsonPost(BatchReq(operation, metas), BatchRes::class.java),
AuthHelper.join(auth.href, PATH_BATCH),
ConnectionClosePolicy.Close
)
for (item in result.objects) {
val state = batch.remove(item.oid)
if (state != null) {
val error = item.error
if (error != null) {
objectQueue.remove(item.oid, state)
state.future.completeExceptionally(createError(error))
} else {
submitTask(state, item, auth)
}
}
}
for (value in batch.values) {
value.future.completeExceptionally(IOException("Requested object not found in server response: " + value.meta.oid))
}
}
} catch (e: UnauthorizedException) {
auth?.let { invalidateAuth(it) }
} catch (e: IOException) {
for (state in batch.values) {
state.onException(e, state.retry)
}
}
}
protected fun createError(error: Error): Throwable {
return if (error.code == HttpStatus.SC_NOT_FOUND) {
FileNotFoundException(error.message)
} else IOException("Can't process object (code " + error.code + "): " + error.message)
}
protected abstract fun objectTask(state: State<T, R?>, item: BatchItem): Work<R>?
/**
* Submit object processing task.
*
* @param state Current object state
* @param item Metadata information with upload/download urls.
* @param auth Urls authentication state.
*/
private fun submitTask(state: State<T, R?>, item: BatchItem, auth: Link) {
// Submit task
val holder = StateHolder(state)
try {
state.auth = auth
val worker = objectTask(state, item)
if (state.future.isDone) {
holder.close()
return
}
checkNotNull(worker) { "Uncompleted task worker is null: $item" }
executeInPool(
"task: " + state.meta.oid,
{ processObject(state, auth, worker) }, { holder.close() },
true
)
} catch (e: Throwable) {
holder.close()
throw e
}
}
private fun takeBatch(): MutableMap<String, State<T, R?>> {
val batch: MutableMap<String, State<T, R?>> = HashMap()
val completed: MutableList<State<T, R?>> = ArrayList()
for (state in objectQueue.values) {
if (state.future.isDone) {
completed.add(state)
continue
}
if (state.auth == null) {
batch[state.meta.oid] = state
if (batch.size >= settings.limit) {
break
}
}
}
for (state in completed) {
objectQueue.remove(state.meta.oid, state)
}
return batch
}
private fun processObject(state: State<T, R?>, auth: Link, worker: Work<R>) {
if (currentAuth.get() != auth) {
state.auth = null
return
}
try {
state.auth = auth
val result = worker.exec(auth)
objectQueue.remove(state.meta.oid, state)
state.future.complete(result)
} catch (e: UnauthorizedException) {
invalidateAuth(auth)
} catch (e: ForbiddenException) {
state.onException(e, 0)
} catch (e: Throwable) {
state.onException(e, settings.retryCount)
} finally {
state.auth = null
}
}
/**
* Schedule task in thread pool.
*
*
* If pool reject task - task will execute immediately in current thread.
*
*
* If pool is shutdown - task will not run, but finalizer will executed.
*
* @param name Task name for debug
* @param task Task runnable
* @param finalizer Finalizer to execute like 'try-final' block
*/
private fun executeInPool(name: String, task: Runnable, finalizer: Runnable?, pooled: Boolean) {
if (pool.isShutdown) {
log.warn("Thread pool is shutdown")
finalizer?.run()
return
}
if (!pooled) {
log.debug("Begin: $name")
try {
task.run()
} catch (e: Throwable) {
log.error("Execute exception: $e")
finalizer?.run()
throw e
} finally {
finalizer?.run()
log.debug("End: $name")
}
return
}
try {
pool.execute(object : Runnable {
override fun run() {
executeInPool(name, task, finalizer, false)
}
override fun toString(): String {
return name
}
})
} catch (e: RejectedExecutionException) {
if (pool.isShutdown) {
log.warn("Thread pool is shutdown")
} else {
executeInPool(name, task, finalizer, false)
}
} catch (e: Throwable) {
log.error("Execute in pool exception: $e")
finalizer?.run()
throw e
}
}
class State<T, R>(
val meta: Meta,
val context: T
) {
val future = CompletableFuture<R>()
@Volatile
var auth: Link? = null
var retry = 0
fun onException(e: Throwable, maxRetryCount: Int) {
retry++
if (retry >= maxRetryCount) {
future.completeExceptionally(e)
}
auth = null
}
}
private inner class StateHolder(state: State<T, R?>) : AutoCloseable {
private val stateRef: AtomicReference<State<T, R?>> = AtomicReference(state)
override fun close() {
val state = stateRef.getAndSet(null) ?: return
if (state.future.isDone) {
objectInProgress.decrementAndGet()
objectQueue.remove(state.meta.oid, state)
} else {
state.auth = null
objectInProgress.decrementAndGet()
}
stateEnqueue(false)
}
init {
objectInProgress.incrementAndGet()
}
}
}
| lgpl-3.0 | e7dcc9b3663299b5f893b9eac2a08a37 | 32.126506 | 135 | 0.523641 | 4.877162 | false | false | false | false |
mdanielwork/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/upsource.kt | 1 | 4168 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync
import org.apache.http.HttpEntityEnclosingRequest
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.entity.ContentType
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
private val UPSOURCE = System.getProperty("upsource.url")
private fun upsourceGet(method: String, args: String): String {
val params = if (args.isEmpty()) "" else "?params=${URLEncoder.encode(args, Charsets.UTF_8.name())}"
return get("$UPSOURCE/~rpc/$method$params") {
upsourceAuthAndLog()
}
}
private fun upsourcePost(method: String, args: String) = post("$UPSOURCE/~rpc/$method", args) {
upsourceAuthAndLog()
addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString())
}
private fun HttpRequestBase.upsourceAuthAndLog() {
log("Calling $uri${if (this is HttpEntityEnclosingRequest && entity != null) " with ${entity.asString()}" else ""}")
basicAuth(System.getProperty("upsource.user.name"), System.getProperty("upsource.user.password"))
}
internal class Review(val id: String, val url: String)
@Suppress("ReplaceSingleLineLet")
internal fun createReview(projectId: String, branch: String, commits: Collection<String>): Review {
var revisions = emptyList<String>()
loop@ for (i in 1..20) {
revisions = getBranchRevisions(projectId, branch, commits.size)
when {
revisions.isNotEmpty() -> break@loop
i == 20 -> error("$commits are not found")
else -> {
log("Upsource hasn't updated branch list yet. Retrying in 30s..")
TimeUnit.SECONDS.sleep(30)
}
}
}
val reviewId = upsourcePost("createReview", """{
"projectId" : "$projectId",
"revisions" : [
${revisions.joinToString { "\"$it\"" }}
]}""")
.let { extract(it, Regex(""""reviewId":\{([^}]+)""")) }
.let { extract(it, Regex(""""reviewId":"([^,"]+)"""")) }
val review = Review(reviewId, "$UPSOURCE/$projectId/review/$reviewId")
removeReviewer(projectId, review, System.getProperty("upsource.user.email"))
return review
}
private fun getBranchRevisions(projectId: String, branch: String, limit: Int) =
extractAll(upsourceGet("getRevisionsListFiltered", """{
"projectId" : "$projectId",
"limit" : $limit,
"query" : "branch: $branch"
}"""), Regex(""""revisionId":"([^,"]+)""""))
internal fun addReviewer(projectId: String, review: Review, email: String) {
try {
actionOnReviewer("addParticipantToReview", projectId, review, email)
}
catch (e: Exception) {
e.printStackTrace()
if (email != DEFAULT_INVESTIGATOR) addReviewer(projectId, review, DEFAULT_INVESTIGATOR)
}
}
private fun removeReviewer(projectId: String, review: Review, email: String) {
callSafely {
actionOnReviewer("removeParticipantFromReview", projectId, review, email)
}
}
private fun actionOnReviewer(action: String, projectId: String, review: Review, email: String) {
val userId = userId(email, projectId)
upsourcePost(action, """{
"reviewId" : {
"projectId" : "$projectId",
"reviewId" : "${review.id}"
},
"participant" : {
"userId" : "$userId",
"role" : 2
}
}""")
}
private fun userId(email: String, projectId: String): String {
val invitation = upsourceGet("inviteUser", """{"projectId":"$projectId","email":"$email"}""")
return extract(invitation, Regex(""""userId":"([^,"]+)""""))
}
private fun extract(json: String, regex: Regex) = extractAll(json, regex).last()
private fun extractAll(json: String, regex: Regex) = json
.replace(" ", "")
.replace(System.lineSeparator(), "").let { str ->
regex.findAll(str).map { it.groupValues.last() }.toList()
}
internal fun postComment(projectId: String, review: Review, comment: String) {
upsourcePost("createDiscussion", """{
"projectId" : "$projectId",
"reviewId": {
"projectId" : "$projectId",
"reviewId": "${review.id}"
},
"text" : "$comment",
"anchor" : {}
}""")
} | apache-2.0 | dc1263771cb64d363df4ea1fa1d8f368 | 34.330508 | 140 | 0.667466 | 3.920978 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplacePutWithAssignmentInspection.kt | 1 | 5219 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplacePutWithAssignmentInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
), CleanupLocalInspectionTool {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression is KtSuperExpression) return false
val callExpression = element.callExpression
if (callExpression?.valueArguments?.size != 2) return false
val calleeExpression = callExpression.calleeExpression as? KtNameReferenceExpression ?: return false
if (calleeExpression.getReferencedName() !in compatibleNames) return false
val context = element.analyze()
if (element.isUsedAsExpression(context)) return false
// This fragment had to be added because of incorrect behaviour of isUsesAsExpression
// TODO: remove it after fix of KT-25682
val binaryExpression = element.getStrictParentOfType<KtBinaryExpression>()
val right = binaryExpression?.right
if (binaryExpression?.operationToken == KtTokens.ELVIS &&
right != null && (right == element || KtPsiUtil.deparenthesize(right) == element)
) return false
val resolvedCall = element.getResolvedCall(context)
val receiverType = resolvedCall?.getExplicitReceiverValue()?.type ?: return false
val receiverClass = receiverType.constructor.declarationDescriptor as? ClassDescriptor ?: return false
if (!receiverClass.isSubclassOf(DefaultBuiltIns.Instance.mutableMap)) return false
val overriddenTree =
resolvedCall.resultingDescriptor.safeAs<CallableMemberDescriptor>()?.overriddenTreeAsSequence(true) ?: return false
if (overriddenTree.none { it.fqNameOrNull() == mutableMapPutFqName }) return false
val assignment = createAssignmentExpression(element) ?: return false
val newContext = assignment.analyzeAsReplacement(element, context)
return assignment.left.getResolvedCall(newContext)?.resultingDescriptor?.fqNameOrNull() == collectionsSetFqName
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val assignment = createAssignmentExpression(element) ?: return
element.replace(assignment)
}
private fun createAssignmentExpression(element: KtDotQualifiedExpression): KtBinaryExpression? {
val valueArguments = element.callExpression?.valueArguments ?: return null
val firstArg = valueArguments[0]?.getArgumentExpression() ?: return null
val secondArg = valueArguments[1]?.getArgumentExpression() ?: return null
val label = if (secondArg is KtLambdaExpression) {
val returnLabel = secondArg.findDescendantOfType<KtReturnExpression>()?.getLabelName()
compatibleNames.firstOrNull { it == returnLabel }?.plus("@") ?: ""
} else ""
return KtPsiFactory(element).createExpressionByPattern(
"$0[$1] = $label$2",
element.receiverExpression, firstArg, secondArg,
reformat = false
) as? KtBinaryExpression
}
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("map.put.should.be.converted.to.assignment")
override val defaultFixText get() = KotlinBundle.message("convert.put.to.assignment")
companion object {
private val compatibleNames = setOf("put")
private val collectionsSetFqName = FqName("kotlin.collections.set")
private val mutableMapPutFqName = FqName("kotlin.collections.MutableMap.put")
}
} | apache-2.0 | 822464111468dc906916ac5b7b5124b8 | 51.727273 | 127 | 0.767005 | 5.546227 | false | false | false | false |
phylame/jem | commons/src/main/kotlin/jclp/ServiceSpi.kt | 1 | 2085 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jclp
import jclp.io.defaultClassLoader
import jclp.log.Log
import java.util.*
interface KeyedService {
val keys: Set<String>
val name: String get() = ""
}
open class ServiceManager<S : KeyedService>(type: Class<S>, loader: ClassLoader? = null) {
private val serviceLoader = ServiceLoader.load(type, loader ?: defaultClassLoader())
private val localRegistry = hashMapOf<String, S>()
private val serviceProviders = hashSetOf<S>()
init {
initServices()
}
fun reload() {
localRegistry.clear()
serviceProviders.clear()
serviceLoader.reload()
initServices()
}
val services get() = serviceProviders + localRegistry.values
operator fun get(key: String) = localRegistry.getOrSet(key) {
serviceProviders.firstOrNull { key in it.keys }
}
operator fun set(name: String, factory: S) {
localRegistry[name] = factory
}
private fun initServices() {
val it = serviceLoader.iterator()
try {
while (it.hasNext()) {
try {
serviceProviders += it.next()
} catch (e: ServiceConfigurationError) {
Log.e(javaClass.simpleName, e) { "in providers.next()" }
}
}
} catch (e: ServiceConfigurationError) {
Log.e(javaClass.simpleName, e) { "in providers.hasNext()" }
}
}
}
| apache-2.0 | 3439ca0efcf8f45753f7940f75a5a2fe | 27.561644 | 90 | 0.635012 | 4.371069 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/model/ShowStat.kt | 1 | 841 | package com.mgaetan89.showsrage.model
import com.google.gson.annotations.SerializedName
data class ShowStat(
val archived: Int = 0,
val downloaded: Map<String, Int>? = null,
val failed: Int = 0,
val ignored: Int = 0,
val skipped: Int = 0,
val snatched: Map<String, Int>? = null,
@SerializedName("snatched_best") val snatchedBest: Int = 0,
val subtitled: Int = 0,
val total: Int = 0,
val unaired: Int = 0,
val wanted: Int = 0
) {
fun getTotalDone(): Int {
if (this.downloaded == null) {
return this.archived
}
val total = this.downloaded["total"] ?: return this.archived
return this.archived + total
}
fun getTotalPending(): Int {
if (this.snatched == null) {
return this.snatchedBest
}
val total = this.snatched["total"] ?: return this.snatchedBest
return this.snatchedBest + total
}
}
| apache-2.0 | a1f38a626e78793aa66616679a2a5935 | 21.72973 | 64 | 0.671819 | 3.161654 | false | false | false | false |
paplorinc/intellij-community | platform/projectModel-api/src/com/intellij/util/RecursionPreventingSafePublicationLazy.kt | 1 | 2224 | // 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.util
import com.intellij.openapi.util.RecursionManager
import java.util.concurrent.atomic.AtomicReference
/**
* Same as [SafePublicationLazyImpl], but returns `null` in case of computation recursion occurred.
*/
class RecursionPreventingSafePublicationLazy<T>(recursionKey: Any?, initializer: () -> T) : Lazy<T?> {
@Volatile
private var initializer: (() -> T)? = { ourNotNullizer.notNullize(initializer()) }
private val valueRef: AtomicReference<T> = AtomicReference()
private val recursionKey: Any = recursionKey ?: this
override val value: T?
get() {
val computedValue = valueRef.get()
if (computedValue !== null) {
return ourNotNullizer.nullize(computedValue)
}
val initializerValue = initializer
if (initializerValue === null) {
// Some thread managed to clear the initializer => it managed to set the value.
return ourNotNullizer.nullize(valueRef.get())
}
val stamp = ourRecursionGuard.markStack()
val newValue = ourRecursionGuard.doPreventingRecursion(recursionKey, false, initializerValue)
// In case of recursion don't update [valueRef] and don't clear [initializer].
if (newValue === null) {
// Recursion occurred for this lazy.
return null
}
if (!stamp.mayCacheNow()) {
// Recursion occurred somewhere deep.
return ourNotNullizer.nullize(newValue)
}
if (!valueRef.compareAndSet(null, newValue)) {
// Some thread managed to set the value.
return ourNotNullizer.nullize(valueRef.get())
}
initializer = null
return ourNotNullizer.nullize(newValue)
}
override fun isInitialized(): Boolean = valueRef.get() !== null
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
companion object {
private val ourRecursionGuard = RecursionManager.createGuard("RecursionPreventingSafePublicationLazy")
private val ourNotNullizer = NotNullizer("RecursionPreventingSafePublicationLazy")
}
}
| apache-2.0 | def5b6482592ecdd2f7c9ff26e4dbfcc | 36.694915 | 140 | 0.69964 | 4.986547 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKSymbolRenderer.kt | 2 | 4324 | // 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.nj2k.printing
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.nj2k.JKImportStorage
import org.jetbrains.kotlin.nj2k.conversions.TOP_LEVEL_FUNCTIONS_THAT_MAY_BE_SHADOWED_BY_EXISTING_METHODS
import org.jetbrains.kotlin.nj2k.escaped
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.JKClassAccessExpression
import org.jetbrains.kotlin.nj2k.tree.JKQualifiedExpression
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class JKSymbolRenderer(private val importStorage: JKImportStorage, project: Project) {
private val canBeShortenedClassNameCache = CanBeShortenedCache(project)
private fun JKSymbol.isFqNameExpected(owner: JKTreeElement?): Boolean {
if (owner?.isSelectorOfQualifiedExpression() == true) return false
return fqName in TOP_LEVEL_FUNCTIONS_THAT_MAY_BE_SHADOWED_BY_EXISTING_METHODS ||
this is JKClassSymbol || isStaticMember || isEnumConstant
}
private fun JKSymbol.isFromJavaLangPackage() =
fqName.startsWith(JAVA_LANG_FQ_PREFIX)
fun renderSymbol(symbol: JKSymbol, owner: JKTreeElement?): String {
val name = symbol.name.escaped()
if (!symbol.isFqNameExpected(owner)) return name
val fqName = symbol.getDisplayFqName().escapedAsQualifiedName()
if (owner is JKClassAccessExpression && symbol.isFromJavaLangPackage()) return fqName
return when {
symbol is JKClassSymbol && canBeShortenedClassNameCache.canBeShortened(symbol) -> {
importStorage.addImport(fqName)
name
}
symbol.isStaticMember && symbol.containingClass?.isUnnamedCompanion == true -> {
val containingClass = symbol.containingClass ?: return fqName
val classContainingCompanion = containingClass.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(classContainingCompanion)) return fqName
importStorage.addImport(classContainingCompanion.getDisplayFqName())
"${classContainingCompanion.name.escaped()}.${SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT}.$name"
}
symbol.isEnumConstant || symbol.isStaticMember -> {
val containingClass = symbol.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(containingClass)) return fqName
importStorage.addImport(containingClass.getDisplayFqName())
"${containingClass.name.escaped()}.$name"
}
else -> fqName
}
}
private fun JKTreeElement.isSelectorOfQualifiedExpression() =
parent?.safeAs<JKQualifiedExpression>()?.selector == this
companion object {
private const val JAVA_LANG_FQ_PREFIX = "java.lang"
}
}
private class CanBeShortenedCache(project: Project) {
private val shortNameCache = PsiShortNamesCache.getInstance(project)
private val searchScope = GlobalSearchScope.allScope(project)
private val canBeShortenedCache = mutableMapOf<String, Boolean>().apply {
CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA.forEach { name ->
this[name] = false
}
}
fun canBeShortened(symbol: JKClassSymbol): Boolean = canBeShortenedCache.getOrPut(symbol.name) {
var symbolsWithSuchNameCount = 0
val processSymbol = { _: PsiClass ->
symbolsWithSuchNameCount++
symbolsWithSuchNameCount <= 1 //stop if met more than one symbol with such name
}
shortNameCache.processClassesWithName(symbol.name, processSymbol, searchScope, null)
symbolsWithSuchNameCount == 1
}
companion object {
private val CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA = setOf(
"Function",
"Serializable"
)
}
} | apache-2.0 | 604044c3455a014d554ef5f1803a1992 | 45.010638 | 158 | 0.709991 | 5.069168 | false | false | false | false |
apollographql/apollo-android | apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/ApolloCall.kt | 1 | 3760 | package com.apollographql.apollo3
import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.ExecutionContext
import com.apollographql.apollo3.api.ExecutionOptions
import com.apollographql.apollo3.api.MutableExecutionOptions
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.http.HttpHeader
import com.apollographql.apollo3.api.http.HttpMethod
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.single
class ApolloCall<D : Operation.Data> internal constructor(
internal val apolloClient: ApolloClient,
val operation: Operation<D>,
) : MutableExecutionOptions<ApolloCall<D>> {
override var executionContext: ExecutionContext = ExecutionContext.Empty
override var httpMethod: HttpMethod? = null
override var httpHeaders: List<HttpHeader>? = null
override var sendApqExtensions: Boolean? = null
override var sendDocument: Boolean? = null
override var enableAutoPersistedQueries: Boolean? = null
override fun addExecutionContext(executionContext: ExecutionContext) = apply {
this.executionContext = this.executionContext + executionContext
}
override fun httpMethod(httpMethod: HttpMethod?) = apply {
this.httpMethod = httpMethod
}
override fun httpHeaders(httpHeaders: List<HttpHeader>?) = apply {
this.httpHeaders = httpHeaders
}
override fun addHttpHeader(name: String, value: String) = apply {
this.httpHeaders = (this.httpHeaders ?: emptyList()) + HttpHeader(name, value)
}
override fun sendApqExtensions(sendApqExtensions: Boolean?) = apply {
this.sendApqExtensions = sendApqExtensions
}
override fun sendDocument(sendDocument: Boolean?) = apply {
this.sendDocument = sendDocument
}
override fun enableAutoPersistedQueries(enableAutoPersistedQueries: Boolean?) = apply {
this.enableAutoPersistedQueries = enableAutoPersistedQueries
}
override var canBeBatched: Boolean? = null
override fun canBeBatched(canBeBatched: Boolean?) = apply {
this.canBeBatched = canBeBatched
if (canBeBatched != null) addHttpHeader(ExecutionOptions.CAN_BE_BATCHED, canBeBatched.toString())
}
fun copy(): ApolloCall<D> {
return ApolloCall(apolloClient, operation)
.addExecutionContext(executionContext)
.httpMethod(httpMethod)
.httpHeaders(httpHeaders)
.sendApqExtensions(sendApqExtensions)
.sendDocument(sendDocument)
.enableAutoPersistedQueries(enableAutoPersistedQueries)
}
/**
* Returns a cold Flow that produces [ApolloResponse]s for this [ApolloCall].
* Note that the execution happens when collecting the Flow.
* This method can be called several times to execute a call again.
*
* Example:
* ```
* apolloClient.subscription(NewOrders())
* .toFlow()
* .collect {
* println("order received: ${it.data?.order?.id"})
* }
* ```
*/
fun toFlow(): Flow<ApolloResponse<D>> {
val request = ApolloRequest.Builder(operation)
.executionContext(executionContext)
.httpMethod(httpMethod)
.httpHeaders(httpHeaders)
.sendApqExtensions(sendApqExtensions)
.sendDocument(sendDocument)
.enableAutoPersistedQueries(enableAutoPersistedQueries)
.build()
return apolloClient.executeAsFlow(request)
}
/**
* A shorthand for `toFlow().single()`.
* Use this for queries and mutation to get a single [ApolloResponse] from the network or the cache.
* For subscriptions, you usually want to use [toFlow] instead to listen to all values.
*/
suspend fun execute(): ApolloResponse<D> {
return toFlow().single()
}
}
| mit | 8e3d6ac5c918765af3c10ad934f3b68a | 34.809524 | 102 | 0.728191 | 4.902216 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/equals/EqOperator.kt | 1 | 1088 | internal interface I
internal class C
internal class O
internal class E {
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
}
internal open class B {
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
}
internal class BB : B()
internal enum class EE {
A,
B,
C
}
internal class X {
fun foo(
i1: I?,
i2: I?,
s1: String,
s2: String,
c1: C,
c2: C,
i: Int,
o1: O,
o2: O,
e1: E,
e2: E,
bb1: BB,
bb2: BB,
arr1: IntArray,
arr2: IntArray,
ee1: EE?,
ee2: EE
) {
if (i1 === i2) return
if (s1 === s2) return
if (c1 == c2) return
if (i1 == null) return
if (null == i2) return
if (i == 0) return
if (o1 === o2) return
if (e1 === e2) return
if (bb1 === bb2) return
if (arr1 == arr2) return
if (ee1 == ee2 || ee1 == null) return
if (s1 !== s2) return
if (c1 != c2) return
}
}
| apache-2.0 | 63971e8c0ae5988fcc60c14f8fae7fb9 | 18.087719 | 45 | 0.449449 | 3.181287 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_info/mapper/CourseInfoMapper.kt | 1 | 3545 | package org.stepik.android.view.course_info.mapper
import android.content.Context
import androidx.annotation.StringRes
import org.stepic.droid.R
import org.stepik.android.domain.course_info.model.CourseInfoData
import org.stepik.android.view.course_info.model.CourseInfoItem
import org.stepik.android.view.course_info.model.CourseInfoType
private const val NEW_LINE = "<br/>"
fun CourseInfoData.toSortedItems(context: Context): List<CourseInfoItem> {
val items = arrayListOf<CourseInfoItem>()
if (summary != null) {
items.add(CourseInfoItem.SummaryBlock(summary))
}
if (authors != null) {
items.add(CourseInfoItem.AuthorsBlock(authors))
}
if (videoMediaData != null) {
items.add(CourseInfoItem.VideoBlock(videoMediaData))
}
if (acquiredSkills != null && acquiredSkills.isNotEmpty()) {
items.add(CourseInfoItem.Skills(acquiredSkills))
}
if (about != null) {
items.add(CourseInfoItem.AboutBlock(about))
}
items.addTextItem(CourseInfoType.REQUIREMENTS, requirements)
items.addTextItem(CourseInfoType.TARGET_AUDIENCE, targetAudience)
if (timeToComplete > 0) {
val hours = (timeToComplete / 3600).toInt()
items.addTextItem(CourseInfoType.TIME_TO_COMPLETE, context.resources.getQuantityString(R.plurals.hours, hours, hours))
}
if (instructors != null) {
items.add(CourseInfoItem.WithTitle.InstructorsBlock(instructors))
}
items.addTextItem(CourseInfoType.LANGUAGE, mapCourseLanguage(language)?.let(context::getString))
if (certificate != null) {
items.addTextItem(CourseInfoType.CERTIFICATE, certificate.title.ifEmpty { context.getString(R.string.certificate_issuing) })
val certificateConditions = mutableListOf<String>()
if (certificate.regularThreshold > 0) {
val regularPoints = context.resources.getQuantityString(R.plurals.points, certificate.regularThreshold.toInt(), certificate.regularThreshold)
val regularCondition = context.getString(R.string.course_info_certificate_regular, regularPoints)
certificateConditions.add(regularCondition)
}
if (certificate.distinctionThreshold > 0) {
val distinctionPoints = context.resources.getQuantityString(R.plurals.points, certificate.distinctionThreshold.toInt(), certificate.distinctionThreshold)
val distinctionCondition = context.getString(R.string.course_info_certificate_distinction, distinctionPoints)
certificateConditions.add(distinctionCondition)
}
items.addTextItem(CourseInfoType.CERTIFICATE_DETAILS, certificateConditions.joinToString(NEW_LINE))
} else {
items.addTextItem(CourseInfoType.CERTIFICATE, context.getString(R.string.certificate_not_issuing))
}
if (learnersCount > 0) {
items.addTextItem(CourseInfoType.LEARNERS_COUNT, learnersCount.toString())
}
return items
}
private fun MutableList<CourseInfoItem>.addTextItem(type: CourseInfoType, text: String?) {
if (text != null) {
add(CourseInfoItem.WithTitle.TextBlock(type, text))
}
}
@StringRes
private fun mapCourseLanguage(language: String?): Int? =
when (language) {
"ru" -> R.string.course_info_language_ru
"en" -> R.string.course_info_language_en
"de" -> R.string.course_info_language_de
"es" -> R.string.course_info_language_es
"ua" -> R.string.course_info_language_ua
"ch" -> R.string.course_info_language_ch
else -> null
} | apache-2.0 | e7ac0b35bf18f88928c9e08da73246e5 | 37.129032 | 165 | 0.711989 | 4.344363 | false | false | false | false |
allotria/intellij-community | xml/impl/src/com/intellij/ide/browsers/WebBrowserXmlServiceImpl.kt | 3 | 1659 | // 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.ide.browsers
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.lang.Language
import com.intellij.lang.html.HTMLLanguage
import com.intellij.lang.xhtml.XHTMLLanguage
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.xml.util.HtmlUtil
class WebBrowserXmlServiceImpl : WebBrowserXmlService() {
override fun isHtmlFile(element: PsiElement): Boolean {
return HtmlUtil.isHtmlFile(element)
}
override fun isHtmlFile(file: VirtualFile): Boolean {
return HtmlUtil.isHtmlFile(file)
}
override fun isHtmlOrXmlFile(psiFile: PsiFile): Boolean {
if (!isHtmlFile(psiFile.virtualFile) && psiFile.virtualFile.fileType != XmlFileType.INSTANCE) {
return false
}
val baseLanguage: Language = psiFile.viewProvider.baseLanguage
if (isHtmlOrXmlLanguage(baseLanguage)) {
return true
}
return if (psiFile.fileType is LanguageFileType) {
isHtmlOrXmlLanguage((psiFile.fileType as LanguageFileType).language)
}
else false
}
override fun isXmlLanguage(language: Language): Boolean {
return language == XMLLanguage.INSTANCE
}
override fun isHtmlOrXmlLanguage(language: Language): Boolean {
return language.isKindOf(HTMLLanguage.INSTANCE)
|| language === XHTMLLanguage.INSTANCE
|| language === XMLLanguage.INSTANCE
}
} | apache-2.0 | a2e46c91e1d09d96beadce9185bca2e2 | 33.583333 | 140 | 0.760699 | 4.435829 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/sdk/add/PyAddSdkPanel.kt | 1 | 6371 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.text.StringUtil
import com.jetbrains.python.PySdkBundle
import com.jetbrains.python.newProject.steps.PyAddNewEnvironmentPanel
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.OK
import com.jetbrains.python.sdk.configuration.PyProjectVirtualEnvConfiguration
import icons.PythonIcons
import java.awt.Component
import java.io.File
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author vlan
*/
abstract class PyAddSdkPanel : JPanel(), PyAddSdkView {
override val actions: Map<PyAddSdkDialogFlowAction, Boolean>
get() = mapOf(OK.enabled())
override val component: Component
get() = this
/**
* [component] is permanent. [PyAddSdkStateListener.onComponentChanged] won't
* be called anyway.
*/
override fun addStateListener(stateListener: PyAddSdkStateListener): Unit = Unit
override fun previous(): Nothing = throw UnsupportedOperationException()
override fun next(): Nothing = throw UnsupportedOperationException()
override fun complete(): Unit = Unit
abstract override val panelName: String
override val icon: Icon = PythonIcons.Python.Python
open val sdk: Sdk? = null
open val nameExtensionComponent: JComponent? = null
open var newProjectPath: String? = null
override fun getOrCreateSdk(): Sdk? = sdk
override fun onSelected(): Unit = Unit
override fun validateAll(): List<ValidationInfo> = emptyList()
open fun addChangeListener(listener: Runnable) {}
companion object {
@JvmStatic
fun validateEnvironmentDirectoryLocation(field: TextFieldWithBrowseButton): ValidationInfo? {
val text = field.text
val file = File(text)
val message = when {
StringUtil.isEmptyOrSpaces(text) -> PySdkBundle.message("python.venv.location.field.empty")
file.exists() && !file.isDirectory -> PySdkBundle.message("python.venv.location.field.not.directory")
file.isNotEmptyDirectory -> PySdkBundle.message("python.venv.location.directory.not.empty")
else -> return null
}
return ValidationInfo(message, field)
}
@JvmStatic
protected fun validateSdkComboBox(field: PySdkPathChoosingComboBox, view: PyAddSdkView): ValidationInfo? {
return validateSdkComboBox(field, getDefaultButtonName(view))
}
@JvmStatic
fun validateSdkComboBox(field: PySdkPathChoosingComboBox, @NlsContexts.Button defaultButtonName: String): ValidationInfo? {
return when (val sdk = field.selectedSdk) {
null -> ValidationInfo(PySdkBundle.message("python.sdk.field.is.empty"), field)
is PySdkToInstall -> {
val message = sdk.getInstallationWarning(defaultButtonName)
ValidationInfo(message).asWarning().withOKEnabled()
}
else -> null
}
}
@NlsContexts.Button
private fun getDefaultButtonName(view: PyAddSdkView): String {
return if (view.component.parent?.parent is PyAddNewEnvironmentPanel) {
IdeBundle.message("new.dir.project.create") // ProjectSettingsStepBase.createActionButton
}
else {
CommonBundle.getOkButtonText() // DialogWrapper.createDefaultActions
}
}
}
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, sdkObtainer: () -> List<Sdk>) {
addInterpretersAsync(sdkComboBox, sdkObtainer, {})
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] and calls [onAdded] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
sdkObtainer: () -> List<Sdk>,
onAdded: () -> Unit) {
ApplicationManager.getApplication().executeOnPooledThread {
val executor = AppUIExecutor.onUiThread(ModalityState.any())
executor.execute { sdkComboBox.setBusy(true) }
var sdks = emptyList<Sdk>()
try {
sdks = sdkObtainer()
}
finally {
executor.execute {
sdkComboBox.setBusy(false)
sdks.forEach(sdkComboBox.childComponent::addItem)
onAdded()
}
}
}
}
/**
* Obtains a list of sdk to be used as a base for a virtual environment on a pool,
* then fills the [sdkComboBox] on the EDT and chooses [PySdkSettings.preferredVirtualEnvBaseSdk] or prepends it.
*/
fun addBaseInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
existingSdks: List<Sdk>,
module: Module?,
context: UserDataHolder,
callback: () -> Unit = {}) {
addInterpretersAsync(
sdkComboBox,
{ findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: getSdksToInstall() },
{
sdkComboBox.apply {
val preferredSdk = PyProjectVirtualEnvConfiguration.findPreferredVirtualEnvBaseSdk(items)
if (preferredSdk != null) {
if (items.find { it.homePath == preferredSdk.homePath } == null) {
childComponent.insertItemAt(preferredSdk, 0)
}
selectedSdk = preferredSdk
}
}
callback()
}
)
}
| apache-2.0 | 75683f0484896e92ba5a24c5171c587e | 35.198864 | 127 | 0.712133 | 4.750932 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/component/grid/QueryDslAcrariumGrid.kt | 1 | 3608 | /*
* (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component.grid
import com.faendir.acra.dataprovider.QueryDslDataProvider
import com.faendir.acra.dataprovider.QueryDslFilter
import com.faendir.acra.i18n.Messages
import com.faendir.acra.settings.GridSettings
import com.querydsl.jpa.impl.JPAQuery
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.grid.ItemClickEvent
import com.vaadin.flow.component.icon.VaadinIcon
import com.vaadin.flow.data.renderer.Renderer
import com.vaadin.flow.router.RouteParameters
/**
* @author lukas
* @since 13.07.18
*/
class QueryDslAcrariumGrid<T>(val dataProvider: QueryDslDataProvider<T>, var gridSettings: GridSettings? = null) :
AbstractAcrariumGrid<T, QueryDslAcrariumColumn<T>>() {
override val columnFactory: (Renderer<T>, String) -> QueryDslAcrariumColumn<T> = { renderer, id -> QueryDslAcrariumColumn(this, renderer, id) }
val acrariumColumns: List<QueryDslAcrariumColumn<T>>
get() = super.getColumns().filterIsInstance<QueryDslAcrariumColumn<T>>()
init {
dataCommunicator.setDataProvider(dataProvider, object : QueryDslFilter {
override fun <T> apply(query: JPAQuery<T>): JPAQuery<T> = acrariumColumns.mapNotNull { it.filter }.fold(query) { q, f -> f.apply(q) }
})
setSizeFull()
isMultiSort = true
isColumnReorderingAllowed = true
}
/**
* call when all columns were added
*/
fun loadLayout() {
gridSettings?.apply {
val orderedColumns = columnOrder.mapNotNull { key -> acrariumColumns.find { it.key == key } }
val unorderedColumns = acrariumColumns - orderedColumns
setColumnOrder(orderedColumns + unorderedColumns)
hiddenColumns.forEach { key -> acrariumColumns.find { it.key == key }?.isVisible = false }
}
}
fun addOnLayoutChangedListener(listener: (gridSettings: GridSettings) -> Unit) {
addColumnReorderListener { event ->
val settings = GridSettings(event.columns.mapNotNull { it.key }, gridSettings?.hiddenColumns ?: emptyList())
gridSettings = settings
listener(settings)
}
acrariumColumns.forEach { column ->
column.addVisibilityChangeListener {
val settings = GridSettings(gridSettings?.columnOrder ?: columns.mapNotNull { it.key }, columns.filter { !it.isVisible }.mapNotNull { it.key })
gridSettings = settings
listener(settings)
}
}
}
fun addOnClickNavigation(target: Class<out Component>, getParameters: (T) -> Map<String, String>) {
addItemClickListener { e: ItemClickEvent<T> ->
ui.ifPresent { it.navigate(target, RouteParameters(getParameters(e.item))) }
}
column(RouteButtonRenderer(VaadinIcon.EXTERNAL_LINK, target, getParameters)) {
setCaption(Messages.OPEN)
isAutoWidth = false
width = "100px"
}
}
} | apache-2.0 | 6f1dc7f960899ef36d471e4c6d8ef05a | 41.458824 | 159 | 0.685421 | 4.44335 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/js/src/Exceptions.kt | 1 | 1551 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
/**
* Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled while it is suspending.
* It indicates _normal_ cancellation of a coroutine.
* **It is not printed to console/log by default uncaught exception handler**.
* (see [CoroutineExceptionHandler]).
*/
public actual typealias CancellationException = kotlin.coroutines.cancellation.CancellationException
/**
* Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled or completed
* without cause, or with a cause or exception that is not [CancellationException]
* (see [Job.getCancellationException]).
*/
internal actual class JobCancellationException public actual constructor(
message: String,
cause: Throwable?,
internal actual val job: Job
) : CancellationException(message, cause) {
override fun toString(): String = "${super.toString()}; job=$job"
override fun equals(other: Any?): Boolean =
other === this ||
other is JobCancellationException && other.message == message && other.job == job && other.cause == cause
override fun hashCode(): Int =
(message!!.hashCode() * 31 + job.hashCode()) * 31 + (cause?.hashCode() ?: 0)
}
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun Throwable.addSuppressedThrowable(other: Throwable) { /* empty */ }
// For use in tests
internal actual val RECOVER_STACK_TRACES: Boolean = false
| apache-2.0 | 6baf27f14d5a0230e6599c12ec146030 | 40.918919 | 117 | 0.722115 | 4.535088 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt | 1 | 7402 | // 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.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.openapi.util.text.StringUtil
import java.io.File
import java.util.function.Consumer
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private const val COMPILER_MESSAGES_GROUP = "Kotlin compiler"
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity)
if (colonIndex2 < 0) return false
val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2)
val file = File(path)
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) {
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity.amendNextLinesIfNeeded(reader), line),
consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2)
var lineWoPositionIndex = -1
var matcher: Matcher? = null
if (lineWoPath.startsWith('(')) {
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
lineWoPositionIndex = colonIndex3
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex)
matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
else {
val colonIndex4 = lineWoPath.colon(1)
if (colonIndex4 >= 0) {
lineWoPositionIndex = colonIndex4
}
else {
lineWoPositionIndex = lineWoPath.colon()
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex4)
matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
if (lineWoPositionIndex >= 0) {
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines
val details = line + relatedNextLines
if (matcher != null && matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.parentEventId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer)
}
else {
val text = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), text, text), consumer)
}
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate
|| StringUtil.startsWith(this, "> Task :") // Next gradle message candidate
|| StringUtil.containsIgnoreCase(this, "FAILURE")
|| StringUtil.containsIgnoreCase(this, "FAILED")
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
private fun getMessageKind(kind: String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun String.colon(skip: Int): Int {
var index = -1
repeat(skip + 1) {
index = indexOf(COLON, index + 1)
if (index < 0) return index
}
return index
}
private fun Int.skipDriveOnWin(line: String): Int {
return if (this == 1) line.indexOf(COLON, this + 1) else this
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + "Error while annotation processing"
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(parentId: Any, messageKind: MessageEvent.Kind, text: String, detail: String): MessageEvent {
return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail)
}
private fun createMessageWithLocation(
parentId: Any,
messageKind: MessageEvent.Kind,
text: String,
file: String,
lineNumber: Int,
columnIndex: Int,
detail: String
): FileMessageEventImpl {
return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail,
FilePosition(File(file), lineNumber - 1, columnIndex - 1))
}
} | apache-2.0 | c0d404b4f607635774487399403a05c2 | 38.37766 | 140 | 0.69819 | 4.646579 | false | false | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/query/Set.kt | 1 | 1678 | package com.dbflow5.query
import android.content.ContentValues
import com.dbflow5.addContentValues
import com.dbflow5.sql.Query
import com.dbflow5.structure.ChangeAction
/**
* Description: Used to specify the SET part of an [com.dbflow5.query.Update] query.
*/
class Set<T : Any> internal constructor(
override val queryBuilderBase: Query, table: Class<T>)
: BaseTransformable<T>(table), WhereBase<T> {
private val operatorGroup: OperatorGroup = OperatorGroup.nonGroupingClause().setAllCommaSeparated(true)
override val query: String
get() = " ${queryBuilderBase.query}SET ${operatorGroup.query} "
override val primaryAction: ChangeAction
get() = ChangeAction.UPDATE
/**
* Specifies a varg of conditions to append to this SET
*
* @param conditions The varg of conditions
* @return This instance.
*/
fun conditions(vararg conditions: SQLOperator) = apply {
operatorGroup.andAll(*conditions)
}
/**
* Specifies a varg of conditions to append to this SET
*
* @param condition The varg of conditions
* @return This instance.
*/
infix fun and(condition: SQLOperator) = apply {
operatorGroup.and(condition)
}
fun conditionValues(contentValues: ContentValues) = apply {
addContentValues(contentValues, operatorGroup)
}
override fun cloneSelf(): Set<T> {
val set = Set(
when (queryBuilderBase) {
is Update<*> -> queryBuilderBase.cloneSelf()
else -> queryBuilderBase
}, table)
set.operatorGroup.andAll(operatorGroup.conditions)
return set
}
}
| mit | e1bf56ad52bb197fa48a9ea236e27c82 | 28.964286 | 107 | 0.66329 | 4.39267 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/display/Banner.kt | 1 | 2942 | package slatekit.utils.display
import slatekit.utils.writer.ConsoleWriter
import slatekit.common.envs.Envs
import slatekit.common.info.Info
import slatekit.common.log.LogSupport
import slatekit.common.log.Logger
open class Banner(val info: Info,
val envs: Envs,
override val logger: Logger?) : LogSupport {
/**
* Shows the welcome header
*/
open fun welcome() {
// Basic welcome
val writer = ConsoleWriter()
writer.text("************************************")
writer.title("Welcome to ${info.about.name}")
writer.text("************************************")
writer.line()
writer.text("starting in environment: " + this.envs.key)
}
/**
* Displays diagnostic info about the app and process
*/
open fun display() {
val maxLen = Math.max(0, "lang.versionNum ".length)
info("app.area ".padEnd(maxLen) + info.about.area)
info("app.name ".padEnd(maxLen) + info.about.name)
info("app.desc ".padEnd(maxLen) + info.about.desc)
info("app.tags ".padEnd(maxLen) + info.about.tags)
info("app.region ".padEnd(maxLen) + info.about.region)
info("app.contact ".padEnd(maxLen) + info.about.contact)
info("app.url ".padEnd(maxLen) + info.about.url)
info("build.version ".padEnd(maxLen) + info.build.version)
info("build.commit ".padEnd(maxLen) + info.build.commit)
info("build.date ".padEnd(maxLen) + info.build.date)
info("host.name ".padEnd(maxLen) + info.host.name)
info("host.ip ".padEnd(maxLen) + info.host.ip)
info("host.origin ".padEnd(maxLen) + info.host.origin)
info("host.version ".padEnd(maxLen) + info.host.version)
info("lang.name ".padEnd(maxLen) + info.lang.name)
info("lang.version ".padEnd(maxLen) + info.lang.version)
info("lang.versionNum ".padEnd(maxLen) + info.lang.vendor)
info("lang.java ".padEnd(maxLen) + info.lang.origin)
info("lang.home ".padEnd(maxLen) + info.lang.home)
}
/**
* prints the summary at the end of the application run
*/
open fun summary() {
info("===============================================================")
info("SUMMARY : ")
info("===============================================================")
// Standardized info
// e.g. name, desc, env, log, start-time etc.
extra().forEach { info(it.first + " = " + it.second) }
info("===============================================================")
}
/**
* Collection of results executing this application which can be used to display
* at the end of the application
*/
open fun extra(): List<Pair<String, String>> {
return listOf()
}
}
| apache-2.0 | 2769564c59dc00fe38c910e43bd97afc | 39.30137 | 84 | 0.523453 | 4.196862 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/observable/operations/AnonymousParallelOperationTrace.kt | 1 | 872 | // 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.observable.operations
class AnonymousParallelOperationTrace(debugName: String? = null) {
private val delegate = CompoundParallelOperationTrace<Nothing?>(debugName)
fun isOperationCompleted() = delegate.isOperationCompleted()
fun startTask() = delegate.startTask(null)
fun finishTask() = delegate.finishTask(null)
fun beforeOperation(listener: CompoundParallelOperationTrace.Listener) = delegate.beforeOperation(listener)
fun beforeOperation(listener: () -> Unit) = delegate.beforeOperation(listener)
fun afterOperation(listener: CompoundParallelOperationTrace.Listener) = delegate.afterOperation(listener)
fun afterOperation(listener: () -> Unit) = delegate.afterOperation(listener)
} | apache-2.0 | 2f2dad11371bf42e70e525e184a08287 | 61.357143 | 140 | 0.801606 | 4.926554 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/arrayPlusAssign.kt | 5 | 125 | fun box(): String {
val s = IntArray(1)
s[0] = 5
s[0] += 7
return if (s[0] == 12) "OK" else "Fail ${s[0]}"
}
| apache-2.0 | 0edf1a0692f44ebbe5e821928676e4eb | 19.833333 | 51 | 0.44 | 2.403846 | false | false | false | false |
Triple-T/gradle-play-publisher | play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/PublishProducts.kt | 1 | 3102 | package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.tasks.internal.PublishTaskBase
import com.github.triplet.gradle.play.tasks.internal.workers.PlayWorkerBase
import com.github.triplet.gradle.play.tasks.internal.workers.paramsForBase
import com.google.api.client.json.gson.GsonFactory
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileType
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.submit
import org.gradle.work.ChangeType
import org.gradle.work.DisableCachingByDefault
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import org.gradle.workers.WorkerExecutor
import javax.inject.Inject
@DisableCachingByDefault
internal abstract class PublishProducts @Inject constructor(
extension: PlayPublisherExtension,
private val executor: WorkerExecutor,
) : PublishTaskBase(extension) {
@get:Incremental
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
abstract val productsDir: ConfigurableFileCollection
// Used by Gradle to skip the task if all inputs are empty
@Suppress("MemberVisibilityCanBePrivate", "unused")
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:SkipWhenEmpty
@get:InputFiles
protected val targetFiles: FileCollection by lazy { productsDir.asFileTree }
// This directory isn't used, but it's needed for up-to-date checks to work
@Suppress("MemberVisibilityCanBePrivate", "unused")
@get:Optional
@get:OutputDirectory
protected val outputDir = null
@TaskAction
fun publishProducts(changes: InputChanges) {
changes.getFileChanges(productsDir)
.filterNot { it.changeType == ChangeType.REMOVED }
.filter { it.fileType == FileType.FILE }
.forEach {
executor.noIsolation().submit(Uploader::class) {
paramsForBase(this)
target.set(it.file)
}
}
}
abstract class Uploader : PlayWorkerBase<Uploader.Params>() {
override fun execute() {
val productFile = parameters.target.get().asFile
val product = productFile.inputStream().use {
GsonFactory.getDefaultInstance().createJsonParser(it).parse(Map::class.java)
}
println("Uploading ${product["sku"]}")
val response = apiService.publisher.updateInAppProduct(productFile)
if (response.needsCreating) apiService.publisher.insertInAppProduct(productFile)
}
interface Params : PlayPublishingParams {
val target: RegularFileProperty
}
}
}
| mit | ec288620ccea68163683f4d0fd0b3f8b | 38.265823 | 92 | 0.722115 | 4.671687 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ReferenceSearcher.kt | 6 | 3241 | // 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.j2k
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
interface ReferenceSearcher {
fun findLocalUsages(element: PsiElement, scope: PsiElement): Collection<PsiReference>
fun hasInheritors(`class`: PsiClass): Boolean
fun hasOverrides(method: PsiMethod): Boolean
fun findUsagesForExternalCodeProcessing(element: PsiElement, searchJava: Boolean, searchKotlin: Boolean): Collection<PsiReference>
}
fun ReferenceSearcher.findVariableUsages(variable: PsiVariable, scope: PsiElement): Collection<PsiReferenceExpression>
= findLocalUsages(variable, scope).filterIsInstance<PsiReferenceExpression>()
fun ReferenceSearcher.findMethodCalls(method: PsiMethod, scope: PsiElement): Collection<PsiMethodCallExpression> {
return findLocalUsages(method, scope).mapNotNull {
if (it is PsiReferenceExpression) {
val methodCall = it.parent as? PsiMethodCallExpression
if (methodCall?.methodExpression == it) methodCall else null
}
else {
null
}
}
}
fun PsiField.isVar(searcher: ReferenceSearcher): Boolean {
if (hasModifierProperty(PsiModifier.FINAL)) return false
if (!hasModifierProperty(PsiModifier.PRIVATE)) return true
val containingClass = containingClass ?: return true
val writes = searcher.findVariableUsages(this, containingClass).filter { PsiUtil.isAccessedForWriting(it) }
if (writes.size == 0) return false
if (writes.size > 1) return true
val write = writes.single()
val parent = write.parent
if (parent is PsiAssignmentExpression
&& parent.operationSign.tokenType == JavaTokenType.EQ
&& write.isQualifierEmptyOrThis()
) {
val constructor = write.getContainingConstructor()
return constructor == null
|| constructor.containingClass != containingClass
|| !(parent.parent is PsiExpressionStatement)
|| parent.parent?.parent != constructor.body
}
return true
}
fun PsiVariable.hasWriteAccesses(searcher: ReferenceSearcher, scope: PsiElement?): Boolean
= if (scope != null) searcher.findVariableUsages(this, scope).any { PsiUtil.isAccessedForWriting(it) } else false
fun PsiVariable.isInVariableInitializer(searcher: ReferenceSearcher, scope: PsiElement?): Boolean {
return if (scope != null) searcher.findVariableUsages(this, scope).any {
val parent = PsiTreeUtil.skipParentsOfType(it, PsiParenthesizedExpression::class.java)
parent is PsiVariable && parent.initializer == it
} else false
}
object EmptyReferenceSearcher: ReferenceSearcher {
override fun findLocalUsages(element: PsiElement, scope: PsiElement): Collection<PsiReference> = emptyList()
override fun hasInheritors(`class`: PsiClass) = false
override fun hasOverrides(method: PsiMethod) = false
override fun findUsagesForExternalCodeProcessing(element: PsiElement, searchJava: Boolean, searchKotlin: Boolean): Collection<PsiReference>
= emptyList()
} | apache-2.0 | 29c8c383463707ddd9b1312fd5b5d2a6 | 45.314286 | 158 | 0.735884 | 5.048287 | false | false | false | false |
android/compose-samples | JetNews/app/src/main/java/com/example/jetnews/ui/home/HomeScreens.kt | 1 | 29249 | /*
* 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
*
* 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.jetnews.ui.home
import android.content.Context
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.widget.Toast
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.TopAppBarState
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.Result
import com.example.jetnews.data.posts.impl.BlockingFakePostsRepository
import com.example.jetnews.model.Post
import com.example.jetnews.model.PostsFeed
import com.example.jetnews.ui.article.postContentItems
import com.example.jetnews.ui.article.sharePost
import com.example.jetnews.ui.components.JetnewsSnackbarHost
import com.example.jetnews.ui.modifiers.interceptKey
import com.example.jetnews.ui.rememberContentPaddingForScreen
import com.example.jetnews.ui.theme.JetnewsTheme
import com.example.jetnews.ui.utils.BookmarkButton
import com.example.jetnews.ui.utils.FavoriteButton
import com.example.jetnews.ui.utils.ShareButton
import com.example.jetnews.ui.utils.TextSettingsButton
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.runBlocking
/**
* The home screen displaying the feed along with an article details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeFeedWithArticleDetailsScreen(
uiState: HomeUiState,
showTopAppBar: Boolean,
onToggleFavorite: (String) -> Unit,
onSelectPost: (String) -> Unit,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
onInteractWithList: () -> Unit,
onInteractWithDetail: (String) -> Unit,
openDrawer: () -> Unit,
homeListLazyListState: LazyListState,
articleDetailLazyListStates: Map<String, LazyListState>,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
onSearchInputChanged: (String) -> Unit,
) {
HomeScreenWithList(
uiState = uiState,
showTopAppBar = showTopAppBar,
onRefreshPosts = onRefreshPosts,
onErrorDismiss = onErrorDismiss,
openDrawer = openDrawer,
snackbarHostState = snackbarHostState,
modifier = modifier,
) { hasPostsUiState, contentModifier ->
val contentPadding = rememberContentPaddingForScreen(
additionalTop = if (showTopAppBar) 0.dp else 8.dp,
excludeTop = showTopAppBar
)
Row(contentModifier) {
PostList(
postsFeed = hasPostsUiState.postsFeed,
favorites = hasPostsUiState.favorites,
showExpandedSearch = !showTopAppBar,
onArticleTapped = onSelectPost,
onToggleFavorite = onToggleFavorite,
contentPadding = contentPadding,
modifier = Modifier
.width(334.dp)
.notifyInput(onInteractWithList),
state = homeListLazyListState,
searchInput = hasPostsUiState.searchInput,
onSearchInputChanged = onSearchInputChanged,
)
// Crossfade between different detail posts
Crossfade(targetState = hasPostsUiState.selectedPost) { detailPost ->
// Get the lazy list state for this detail view
val detailLazyListState by remember {
derivedStateOf {
articleDetailLazyListStates.getValue(detailPost.id)
}
}
// Key against the post id to avoid sharing any state between different posts
key(detailPost.id) {
LazyColumn(
state = detailLazyListState,
contentPadding = contentPadding,
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxSize()
.notifyInput {
onInteractWithDetail(detailPost.id)
}
) {
stickyHeader {
val context = LocalContext.current
PostTopBar(
isFavorite = hasPostsUiState.favorites.contains(detailPost.id),
onToggleFavorite = { onToggleFavorite(detailPost.id) },
onSharePost = { sharePost(detailPost, context) },
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.End)
)
}
postContentItems(detailPost)
}
}
}
}
}
}
/**
* A [Modifier] that tracks all input, and calls [block] every time input is received.
*/
private fun Modifier.notifyInput(block: () -> Unit): Modifier =
composed {
val blockState = rememberUpdatedState(block)
pointerInput(Unit) {
while (currentCoroutineContext().isActive) {
awaitPointerEventScope {
awaitPointerEvent(PointerEventPass.Initial)
blockState.value()
}
}
}
}
/**
* The home screen displaying just the article feed.
*/
@Composable
fun HomeFeedScreen(
uiState: HomeUiState,
showTopAppBar: Boolean,
onToggleFavorite: (String) -> Unit,
onSelectPost: (String) -> Unit,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
openDrawer: () -> Unit,
homeListLazyListState: LazyListState,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
HomeScreenWithList(
uiState = uiState,
showTopAppBar = showTopAppBar,
onRefreshPosts = onRefreshPosts,
onErrorDismiss = onErrorDismiss,
openDrawer = openDrawer,
snackbarHostState = snackbarHostState,
modifier = modifier
) { hasPostsUiState, contentModifier ->
PostList(
postsFeed = hasPostsUiState.postsFeed,
favorites = hasPostsUiState.favorites,
showExpandedSearch = !showTopAppBar,
onArticleTapped = onSelectPost,
onToggleFavorite = onToggleFavorite,
contentPadding = rememberContentPaddingForScreen(
additionalTop = if (showTopAppBar) 0.dp else 8.dp,
excludeTop = showTopAppBar
),
modifier = contentModifier,
state = homeListLazyListState,
searchInput = searchInput,
onSearchInputChanged = onSearchInputChanged
)
}
}
/**
* A display of the home screen that has the list.
*
* This sets up the scaffold with the top app bar, and surrounds the [hasPostsContent] with refresh,
* loading and error handling.
*
* This helper functions exists because [HomeFeedWithArticleDetailsScreen] and [HomeFeedScreen] are
* extremely similar, except for the rendered content when there are posts to display.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeScreenWithList(
uiState: HomeUiState,
showTopAppBar: Boolean,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
openDrawer: () -> Unit,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
hasPostsContent: @Composable (
uiState: HomeUiState.HasPosts,
modifier: Modifier
) -> Unit
) {
val topAppBarState = rememberTopAppBarState()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(topAppBarState)
Scaffold(
snackbarHost = { JetnewsSnackbarHost(hostState = snackbarHostState) },
topBar = {
if (showTopAppBar) {
HomeTopAppBar(
openDrawer = openDrawer,
topAppBarState = topAppBarState
)
}
},
modifier = modifier
) { innerPadding ->
val contentModifier = Modifier
.padding(innerPadding)
.nestedScroll(scrollBehavior.nestedScrollConnection)
LoadingContent(
empty = when (uiState) {
is HomeUiState.HasPosts -> false
is HomeUiState.NoPosts -> uiState.isLoading
},
emptyContent = { FullScreenLoading() },
loading = uiState.isLoading,
onRefresh = onRefreshPosts,
content = {
when (uiState) {
is HomeUiState.HasPosts -> hasPostsContent(uiState, contentModifier)
is HomeUiState.NoPosts -> {
if (uiState.errorMessages.isEmpty()) {
// if there are no posts, and no error, let the user refresh manually
TextButton(
onClick = onRefreshPosts,
modifier.fillMaxSize()
) {
Text(
stringResource(id = R.string.home_tap_to_load_content),
textAlign = TextAlign.Center
)
}
} else {
// there's currently an error showing, don't show any content
Box(contentModifier.fillMaxSize()) { /* empty screen */ }
}
}
}
}
)
}
// Process one error message at a time and show them as Snackbars in the UI
if (uiState.errorMessages.isNotEmpty()) {
// Remember the errorMessage to display on the screen
val errorMessage = remember(uiState) { uiState.errorMessages[0] }
// Get the text to show on the message from resources
val errorMessageText: String = stringResource(errorMessage.messageId)
val retryMessageText = stringResource(id = R.string.retry)
// If onRefreshPosts or onErrorDismiss change while the LaunchedEffect is running,
// don't restart the effect and use the latest lambda values.
val onRefreshPostsState by rememberUpdatedState(onRefreshPosts)
val onErrorDismissState by rememberUpdatedState(onErrorDismiss)
// Effect running in a coroutine that displays the Snackbar on the screen
// If there's a change to errorMessageText, retryMessageText or snackbarHostState,
// the previous effect will be cancelled and a new one will start with the new values
LaunchedEffect(errorMessageText, retryMessageText, snackbarHostState) {
val snackbarResult = snackbarHostState.showSnackbar(
message = errorMessageText,
actionLabel = retryMessageText
)
if (snackbarResult == SnackbarResult.ActionPerformed) {
onRefreshPostsState()
}
// Once the message is displayed and dismissed, notify the ViewModel
onErrorDismissState(errorMessage.id)
}
}
}
/**
* Display an initial empty state or swipe to refresh content.
*
* @param empty (state) when true, display [emptyContent]
* @param emptyContent (slot) the content to display for the empty state
* @param loading (state) when true, display a loading spinner over [content]
* @param onRefresh (event) event to request refresh
* @param content (slot) the main content to show
*/
@Composable
private fun LoadingContent(
empty: Boolean,
emptyContent: @Composable () -> Unit,
loading: Boolean,
onRefresh: () -> Unit,
content: @Composable () -> Unit
) {
if (empty) {
emptyContent()
} else {
SwipeRefresh(
state = rememberSwipeRefreshState(loading),
onRefresh = onRefresh,
content = content,
)
}
}
/**
* Display a feed of posts.
*
* When a post is clicked on, [onArticleTapped] will be called.
*
* @param postsFeed (state) the feed to display
* @param onArticleTapped (event) request navigation to Article screen
* @param modifier modifier for the root element
*/
@Composable
private fun PostList(
postsFeed: PostsFeed,
favorites: Set<String>,
showExpandedSearch: Boolean,
onArticleTapped: (postId: String) -> Unit,
onToggleFavorite: (String) -> Unit,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
state: LazyListState = rememberLazyListState(),
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
LazyColumn(
modifier = modifier,
contentPadding = contentPadding,
state = state
) {
if (showExpandedSearch) {
item {
HomeSearch(
Modifier.padding(horizontal = 16.dp),
searchInput = searchInput,
onSearchInputChanged = onSearchInputChanged,
)
}
}
item { PostListTopSection(postsFeed.highlightedPost, onArticleTapped) }
if (postsFeed.recommendedPosts.isNotEmpty()) {
item {
PostListSimpleSection(
postsFeed.recommendedPosts,
onArticleTapped,
favorites,
onToggleFavorite
)
}
}
if (postsFeed.popularPosts.isNotEmpty() && !showExpandedSearch) {
item {
PostListPopularSection(
postsFeed.popularPosts, onArticleTapped
)
}
}
if (postsFeed.recentPosts.isNotEmpty()) {
item { PostListHistorySection(postsFeed.recentPosts, onArticleTapped) }
}
}
}
/**
* Full screen circular progress indicator
*/
@Composable
private fun FullScreenLoading() {
Box(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center)
) {
CircularProgressIndicator()
}
}
/**
* Top section of [PostList]
*
* @param post (state) highlighted post to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListTopSection(post: Post, navigateToArticle: (String) -> Unit) {
Text(
modifier = Modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp),
text = stringResource(id = R.string.home_top_section_title),
style = MaterialTheme.typography.titleMedium
)
PostCardTop(
post = post,
modifier = Modifier.clickable(onClick = { navigateToArticle(post.id) })
)
PostListDivider()
}
/**
* Full-width list items for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListSimpleSection(
posts: List<Post>,
navigateToArticle: (String) -> Unit,
favorites: Set<String>,
onToggleFavorite: (String) -> Unit
) {
Column {
posts.forEach { post ->
PostCardSimple(
post = post,
navigateToArticle = navigateToArticle,
isFavorite = favorites.contains(post.id),
onToggleFavorite = { onToggleFavorite(post.id) }
)
PostListDivider()
}
}
}
/**
* Horizontal scrolling cards for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListPopularSection(
posts: List<Post>,
navigateToArticle: (String) -> Unit
) {
Column {
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(id = R.string.home_popular_section_title),
style = MaterialTheme.typography.titleLarge
)
LazyRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
items(posts) { post ->
PostCardPopular(
post,
navigateToArticle
)
}
}
Spacer(Modifier.height(16.dp))
PostListDivider()
}
}
/**
* Full-width list items that display "based on your history" for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListHistorySection(
posts: List<Post>,
navigateToArticle: (String) -> Unit
) {
Column {
posts.forEach { post ->
PostCardHistory(post, navigateToArticle)
PostListDivider()
}
}
}
/**
* Full-width divider with padding for [PostList]
*/
@Composable
private fun PostListDivider() {
Divider(
modifier = Modifier.padding(horizontal = 14.dp),
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f)
)
}
/**
* Expanded search UI - includes support for enter-to-send on the search field
*/
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
private fun HomeSearch(
modifier: Modifier = Modifier,
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
val context = LocalContext.current
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
OutlinedTextField(
value = searchInput,
onValueChange = onSearchInputChanged,
placeholder = { Text(stringResource(R.string.home_search)) },
leadingIcon = { Icon(Icons.Filled.Search, null) },
modifier = modifier
.fillMaxWidth()
.interceptKey(Key.Enter) {
// submit a search query when Enter is pressed
submitSearch(onSearchInputChanged, context)
keyboardController?.hide()
focusManager.clearFocus(force = true)
},
singleLine = true,
// keyboardOptions change the newline key to a search key on the soft keyboard
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
// keyboardActions submits the search query when the search key is pressed
keyboardActions = KeyboardActions(
onSearch = {
submitSearch(onSearchInputChanged, context)
keyboardController?.hide()
}
)
)
}
/**
* Stub helper function to submit a user's search query
*/
private fun submitSearch(
onSearchInputChanged: (String) -> Unit,
context: Context
) {
onSearchInputChanged("")
Toast.makeText(
context,
"Search is not yet implemented",
Toast.LENGTH_SHORT
).show()
}
/**
* Top bar for a Post when displayed next to the Home feed
*/
@Composable
private fun PostTopBar(
isFavorite: Boolean,
onToggleFavorite: () -> Unit,
onSharePost: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(8.dp),
border = BorderStroke(Dp.Hairline, MaterialTheme.colorScheme.onSurface.copy(alpha = .6f)),
modifier = modifier.padding(end = 16.dp)
) {
Row(Modifier.padding(horizontal = 8.dp)) {
FavoriteButton(onClick = { /* Functionality not available */ })
BookmarkButton(isBookmarked = isFavorite, onClick = onToggleFavorite)
ShareButton(onClick = onSharePost)
TextSettingsButton(onClick = { /* Functionality not available */ })
}
}
}
/**
* TopAppBar for the Home screen
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeTopAppBar(
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
topAppBarState: TopAppBarState = rememberTopAppBarState(),
scrollBehavior: TopAppBarScrollBehavior? =
TopAppBarDefaults.enterAlwaysScrollBehavior(topAppBarState)
) {
val title = stringResource(id = R.string.app_name)
CenterAlignedTopAppBar(
title = {
Image(
painter = painterResource(R.drawable.ic_jetnews_wordmark),
contentDescription = title,
contentScale = ContentScale.Inside,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onBackground),
modifier = Modifier.fillMaxWidth()
)
},
navigationIcon = {
IconButton(onClick = openDrawer) {
Icon(
painter = painterResource(R.drawable.ic_jetnews_logo),
contentDescription = stringResource(R.string.cd_open_navigation_drawer),
tint = MaterialTheme.colorScheme.primary
)
}
},
actions = {
IconButton(onClick = { /* TODO: Open search */ }) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.cd_search)
)
}
},
scrollBehavior = scrollBehavior,
modifier = modifier
)
}
@Preview("Home list drawer screen")
@Preview("Home list drawer screen (dark)", uiMode = UI_MODE_NIGHT_YES)
@Preview("Home list drawer screen (big font)", fontScale = 1.5f)
@Composable
fun PreviewHomeListDrawerScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = false,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
@Preview("Home list navrail screen", device = Devices.NEXUS_7_2013)
@Preview(
"Home list navrail screen (dark)",
uiMode = UI_MODE_NIGHT_YES,
device = Devices.NEXUS_7_2013
)
@Preview("Home list navrail screen (big font)", fontScale = 1.5f, device = Devices.NEXUS_7_2013)
@Composable
fun PreviewHomeListNavRailScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = true,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
@Preview("Home list detail screen", device = Devices.PIXEL_C)
@Preview("Home list detail screen (dark)", uiMode = UI_MODE_NIGHT_YES, device = Devices.PIXEL_C)
@Preview("Home list detail screen (big font)", fontScale = 1.5f, device = Devices.PIXEL_C)
@Composable
fun PreviewHomeListDetailScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedWithArticleDetailsScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = true,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
onInteractWithList = {},
onInteractWithDetail = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
articleDetailLazyListStates = postsFeed.allPosts.associate { post ->
key(post.id) {
post.id to rememberLazyListState()
}
},
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
| apache-2.0 | 77325c8e48a7e5b2d0f770ff6f83dbe7 | 35.020936 | 100 | 0.635509 | 5.286282 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerNewEditorListener.kt | 1 | 1146 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.formatting.visualLayer
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.project.Project
class VisualFormattingLayerNewEditorListener(val project: Project) : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
val editor: Editor = event.editor
if (project == editor.project) {
editor.addVisualLayer()
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor: Editor = event.editor
if (project == editor.project) {
editor.removeVisualLayer()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as VisualFormattingLayerNewEditorListener
return project == that.project
}
override fun hashCode(): Int {
return project.hashCode()
}
}
| apache-2.0 | ccd47414a1e87048d1dfd679a7c3d2d7 | 29.972973 | 120 | 0.739092 | 4.44186 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt | 1 | 1860 | package info.nightscout.androidaps.plugins.general.maintenance.activities
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.databinding.ActivityLogsettingBinding
import info.nightscout.androidaps.logging.L
import javax.inject.Inject
class LogSettingActivity : NoSplashAppCompatActivity() {
@Inject lateinit var l: L
private lateinit var binding: ActivityLogsettingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLogsettingBinding.inflate(layoutInflater)
setContentView(binding.root)
createViewsForSettings()
binding.reset.setOnClickListener {
l.resetToDefaults()
createViewsForSettings()
}
binding.ok.setOnClickListener { finish() }
}
private fun createViewsForSettings() {
binding.placeholder.removeAllViews()
for (element in l.getLogElements()) {
val logViewHolder = LogViewHolder(element)
binding.placeholder.addView(logViewHolder.baseView)
}
}
internal inner class LogViewHolder(element: L.LogElement) {
@Suppress("InflateParams")
var baseView = layoutInflater.inflate(R.layout.logsettings_item, null) as LinearLayout
init {
(baseView.findViewById<View>(R.id.logsettings_description) as TextView).text = element.name
val enabled = baseView.findViewById<CheckBox>(R.id.logsettings_visibility)
enabled.isChecked = element.enabled
enabled.setOnClickListener { element.enable(enabled.isChecked) }
}
}
}
| agpl-3.0 | 5f9cfecba29cdeb5d4bc550e02d8f0c8 | 32.214286 | 103 | 0.724194 | 5.013477 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/psi/src/org/jetbrains/kotlin/idea/base/psi/KotlinPsiHeuristics.kt | 1 | 9535 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.psi
import com.google.common.collect.HashMultimap
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.JvmNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_OVERLOADS_FQ_NAME
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object KotlinPsiHeuristics {
@JvmStatic
fun unwrapImportAlias(file: KtFile, aliasName: String): Collection<String> {
return file.aliasImportMap[aliasName]
}
@JvmStatic
fun unwrapImportAlias(type: KtUserType, aliasName: String): Collection<String> {
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return emptyList()
return unwrapImportAlias(file, aliasName)
}
@JvmStatic
fun getImportAliases(file: KtFile, names: Set<String>): Set<String> {
val result = LinkedHashSet<String>()
for ((aliasName, name) in file.aliasImportMap.entries()) {
if (name in names) {
result += aliasName
}
}
return result
}
private val KtFile.aliasImportMap by userDataCached("ALIAS_IMPORT_MAP_KEY") { file ->
HashMultimap.create<String, String>().apply {
for (import in file.importList?.imports.orEmpty()) {
val aliasName = import.aliasName ?: continue
val name = import.importPath?.fqName?.shortName()?.asString() ?: continue
put(aliasName, name)
}
}
}
@JvmStatic
fun isProbablyNothing(typeReference: KtTypeReference): Boolean {
val userType = typeReference.typeElement as? KtUserType ?: return false
return isProbablyNothing(userType)
}
@JvmStatic
fun isProbablyNothing(type: KtUserType): Boolean {
val referencedName = type.referencedName
if (referencedName == "Nothing") {
return true
}
// TODO: why don't use PSI-less stub for calculating aliases?
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return false
// TODO: support type aliases
return file.aliasImportMap[referencedName].contains("Nothing")
}
@JvmStatic
fun getJvmName(fqName: FqName): String {
val asString = fqName.asString()
var startIndex = 0
while (startIndex != -1) { // always true
val dotIndex = asString.indexOf('.', startIndex)
if (dotIndex == -1) return asString
startIndex = dotIndex + 1
val charAfterDot = asString.getOrNull(startIndex) ?: return asString
if (!charAfterDot.isLetter()) return asString
if (charAfterDot.isUpperCase()) return buildString {
append(asString.subSequence(0, startIndex))
append(asString.substring(startIndex).replace('.', '$'))
}
}
return asString
}
@JvmStatic
fun getPackageName(file: KtFile): FqName? {
val entry = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve(file, JvmNames.JVM_PACKAGE_NAME_SHORT) ?: return null
val customPackageName = JvmFileClassUtil.getLiteralStringFromAnnotation(entry)
if (customPackageName != null) {
return FqName(customPackageName)
}
return file.packageFqName
}
@JvmStatic
fun getJvmName(declaration: KtClassOrObject): String? {
val classId = declaration.classIdIfNonLocal ?: return null
val jvmClassName = JvmClassName.byClassId(classId)
return jvmClassName.fqNameForTopLevelClassMaybeWithDollars.asString()
}
private fun checkAnnotationUseSiteTarget(annotationEntry: KtAnnotationEntry, useSiteTarget: AnnotationUseSiteTarget?): Boolean {
return useSiteTarget == null || annotationEntry.useSiteTarget?.getAnnotationUseSiteTarget() == useSiteTarget
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
return declaration.annotationEntries
.firstOrNull { checkAnnotationUseSiteTarget(it, useSiteTarget) && it.shortName?.asString() == shortName }
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
val targetShortName = fqName.shortName().asString()
val targetAliasName = declaration.containingKtFile.findAliasByFqName(fqName)?.name
for (annotationEntry in declaration.annotationEntries) {
if (!checkAnnotationUseSiteTarget(annotationEntry, useSiteTarget)) {
continue
}
val annotationShortName = annotationEntry.shortName?.asString() ?: continue
if (annotationShortName == targetShortName || annotationShortName == targetAliasName) {
return annotationEntry
}
}
return null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName, useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: Name, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName.asString(), useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, fqName, useSiteTarget) != null
}
@JvmStatic
fun findJvmName(declaration: KtAnnotated, useSiteTarget: AnnotationUseSiteTarget? = null): String? {
val annotation = findAnnotation(declaration, JvmFileClassUtil.JVM_NAME, useSiteTarget) ?: return null
return JvmFileClassUtil.getLiteralStringFromAnnotation(annotation)
}
@JvmStatic
fun findJvmGetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.getter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
else -> null
}
}
@JvmStatic
fun findJvmSetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.setter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
else -> null
}
}
@JvmStatic
fun findSuppressAnnotation(declaration: KtAnnotated): KtAnnotationEntry? {
return findAnnotation(declaration, StandardNames.FqNames.suppress)
}
@JvmStatic
fun hasSuppressAnnotation(declaration: KtAnnotated): Boolean {
return findSuppressAnnotation(declaration) != null
}
@JvmStatic
fun hasNonSuppressAnnotations(declaration: KtAnnotated): Boolean {
val annotationEntries = declaration.annotationEntries
return annotationEntries.size > 1 || annotationEntries.size == 1 && !hasSuppressAnnotation(declaration)
}
@JvmStatic
fun hasJvmFieldAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME)
}
@JvmStatic
fun hasJvmOverloadsAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_OVERLOADS_FQ_NAME)
}
@JvmStatic
fun hasJvmStaticAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_STATIC_ANNOTATION_FQ_NAME)
}
@JvmStatic
fun getStringValue(argument: ValueArgument): String? {
return argument.getArgumentExpression()
?.safeAs<KtStringTemplateExpression>()
?.entries
?.singleOrNull()
?.safeAs<KtLiteralStringTemplateEntry>()
?.text
}
@JvmStatic
fun findSuppressedEntities(declaration: KtAnnotated): List<String>? {
val entry = findSuppressAnnotation(declaration) ?: return null
return entry.valueArguments.mapNotNull(::getStringValue)
}
@JvmStatic
fun isPossibleOperator(declaration: KtNamedFunction): Boolean {
if (declaration.hasModifier(KtTokens.OPERATOR_KEYWORD)) {
return true
} else if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
// Operator modifier could be omitted only for overridden function
return false
}
val name = declaration.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) {
return false
}
return true
}
} | apache-2.0 | d20688189c7e98de510f9e61dc3b92ec | 38.242798 | 137 | 0.690614 | 5.387006 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/trackers/PureKotlinCodeBlockModificationListener.kt | 2 | 18553 | // 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.caches.trackers
import com.intellij.lang.ASTNode
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.PomManager
import com.intellij.pom.PomModelAspect
import com.intellij.pom.event.PomModelEvent
import com.intellij.pom.event.PomModelListener
import com.intellij.pom.tree.TreeAspect
import com.intellij.pom.tree.events.TreeChangeEvent
import com.intellij.pom.tree.events.impl.ChangeInfoImpl
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.findTopmostParentInFile
import com.intellij.psi.util.findTopmostParentOfType
import com.intellij.psi.util.parentOfTypes
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
interface PureKotlinOutOfCodeBlockModificationListener {
fun kotlinFileOutOfCodeBlockChanged(file: KtFile, physical: Boolean)
}
class PureKotlinCodeBlockModificationListener(project: Project) : Disposable {
companion object {
fun getInstance(project: Project): PureKotlinCodeBlockModificationListener = project.service()
private fun isReplLine(file: VirtualFile): Boolean = file.getUserData(KOTLIN_CONSOLE_KEY) == true
private fun incFileModificationCount(file: KtFile) {
val tracker = file.getUserData(PER_FILE_MODIFICATION_TRACKER)
?: file.putUserDataIfAbsent(PER_FILE_MODIFICATION_TRACKER, SimpleModificationTracker())
tracker.incModificationCount()
}
private fun inBlockModifications(elements: Array<ASTNode>): List<KtElement> {
if (elements.any { !it.psi.isValid }) return emptyList()
// When a code fragment is reparsed, Intellij doesn't do an AST diff and considers the entire
// contents to be replaced, which is represented in a POM event as an empty list of changed elements
return elements.map { element ->
val modificationScope = getInsideCodeBlockModificationScope(element.psi) ?: return emptyList()
modificationScope.blockDeclaration
}
}
private fun isSpecificChange(changeSet: TreeChangeEvent, precondition: (ASTNode?) -> Boolean): Boolean =
changeSet.changedElements.all { changedElement ->
val changesByElement = changeSet.getChangesByElement(changedElement)
changesByElement.affectedChildren.all { affectedChild ->
precondition(affectedChild) && changesByElement.getChangeByChild(affectedChild).let { changeByChild ->
if (changeByChild is ChangeInfoImpl) {
val oldChild = changeByChild.oldChildNode
precondition(oldChild)
} else false
}
}
}
private inline fun isCommentChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) { it is PsiComment || it is KDoc }
private inline fun isFormattingChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) { it is PsiWhiteSpace }
private inline fun isStringLiteralChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) {
it?.elementType == KtTokens.REGULAR_STRING_PART &&
it?.psi?.parentOfTypes(KtAnnotationEntry::class, KtWhenCondition::class) == null
}
/**
* Has to be aligned with [getInsideCodeBlockModificationScope] :
*
* result of analysis has to be reflected in dirty scope,
* the only difference is whitespaces and comments
*/
fun getInsideCodeBlockModificationDirtyScope(element: PsiElement): PsiElement? {
if (!element.isPhysical) return null
// dirty scope for whitespaces and comments is the element itself
if (element is PsiWhiteSpace || element is PsiComment || element is KDoc) return element
return getInsideCodeBlockModificationScope(element)?.blockDeclaration
}
fun getInsideCodeBlockModificationScope(element: PsiElement): BlockModificationScopeElement? {
val lambda = element.findTopmostParentOfType<KtLambdaExpression>()
if (lambda is KtLambdaExpression) {
lambda.findTopmostParentOfType<KtSuperTypeCallEntry>()?.findTopmostParentOfType<KtClassOrObject>()?.let {
return BlockModificationScopeElement(it, it)
}
}
val blockDeclaration = element.findTopmostParentInFile { isBlockDeclaration(it) } as? KtDeclaration ?: return null
// KtPsiUtil.getTopmostParentOfType<KtClassOrObject>(element) as? KtDeclaration ?: return null
// should not be local declaration
if (KtPsiUtil.isLocal(blockDeclaration))
return null
val directParentClassOrObject = PsiTreeUtil.getParentOfType(blockDeclaration, KtClassOrObject::class.java)
val parentClassOrObject = directParentClassOrObject
?.takeIf { !it.isTopLevel() && it.hasModifier(KtTokens.INNER_KEYWORD) }?.let {
var e: KtClassOrObject? = it
while (e != null) {
e = PsiTreeUtil.getParentOfType(e, KtClassOrObject::class.java)
if (e?.hasModifier(KtTokens.INNER_KEYWORD) == false) {
break
}
}
e
} ?: directParentClassOrObject
when (blockDeclaration) {
is KtNamedFunction -> {
// if (blockDeclaration.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE) {
// topClassLikeDeclaration(blockDeclaration)?.let {
// return BlockModificationScopeElement(it, it)
// }
// }
if (blockDeclaration.hasBlockBody()) {
// case like `fun foo(): String {...<caret>...}`
return blockDeclaration.bodyExpression
?.takeIf { it.isAncestor(element) }
?.let {
if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(blockDeclaration, it)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, it)
} else null
}
} else if (blockDeclaration.hasDeclaredReturnType()) {
// case like `fun foo(): String = b<caret>labla`
return blockDeclaration.initializer
?.takeIf { it.isAncestor(element) }
?.let {
if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(blockDeclaration, it)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, it)
} else null
}
}
}
is KtProperty -> {
// if (blockDeclaration.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE) {
// topClassLikeDeclaration(blockDeclaration)?.let {
// return BlockModificationScopeElement(it, it)
// }
// }
if (blockDeclaration.typeReference != null &&
// TODO: it's a workaround for KTIJ-20240 :
// FE does not report CONSTANT_EXPECTED_TYPE_MISMATCH within a property within a class
(parentClassOrObject == null || element !is KtConstantExpression)
) {
// adding annotations to accessor is the same as change contract of property
if (element !is KtAnnotated || element.annotationEntries.isEmpty()) {
val properExpression = blockDeclaration.accessors
.firstOrNull { (it.initializer ?: it.bodyExpression).isAncestor(element) }
?: blockDeclaration.initializer?.takeIf {
// name references changes in property initializer are OCB, see KT-38443, KT-38762
it.isAncestor(element) && !it.anyDescendantOfType<KtNameReferenceExpression>()
}
if (properExpression != null) {
val declaration =
blockDeclaration.findTopmostParentOfType<KtClassOrObject>() as? KtElement
if (declaration != null) {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(declaration, properExpression)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, properExpression)
} else null
}
}
}
}
}
is KtScriptInitializer -> {
return (blockDeclaration.body as? KtCallExpression)
?.lambdaArguments
?.lastOrNull()
?.getLambdaExpression()
?.takeIf { it.isAncestor(element) }
?.let { BlockModificationScopeElement(blockDeclaration, it) }
}
is KtClassInitializer -> {
blockDeclaration
.takeIf { it.isAncestor(element) }
?.let { ktClassInitializer ->
parentClassOrObject?.let {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(it, ktClassInitializer)
} else {
BlockModificationScopeElement(parentClassOrObject, ktClassInitializer)
}
}
}
}
is KtSecondaryConstructor -> {
blockDeclaration.takeIf {
it.bodyExpression?.isAncestor(element) ?: false || it.getDelegationCallOrNull()?.isAncestor(element) ?: false
}?.let { ktConstructor ->
parentClassOrObject?.let {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(it, ktConstructor)
} else {
BlockModificationScopeElement(parentClassOrObject, ktConstructor)
}
}
}
}
// is KtClassOrObject -> {
// return when (element) {
// is KtProperty, is KtNamedFunction -> {
// if ((element as? KtModifierListOwner)?.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE)
// BlockModificationScopeElement(blockDeclaration, blockDeclaration) else null
// }
// else -> null
// }
// }
else -> throw IllegalStateException()
}
return null
}
data class BlockModificationScopeElement(val blockDeclaration: KtElement, val element: KtElement)
fun isBlockDeclaration(declaration: PsiElement): Boolean {
return declaration is KtProperty ||
declaration is KtNamedFunction ||
declaration is KtClassInitializer ||
declaration is KtSecondaryConstructor ||
declaration is KtScriptInitializer
}
}
private val listeners: MutableList<PureKotlinOutOfCodeBlockModificationListener> = ContainerUtil.createLockFreeCopyOnWriteList()
private val outOfCodeBlockModificationTrackerImpl = SimpleModificationTracker()
val outOfCodeBlockModificationTracker = ModificationTracker { outOfCodeBlockModificationTrackerImpl.modificationCount }
init {
val treeAspect: TreeAspect = TreeAspect.getInstance(project)
val model = PomManager.getModel(project)
model.addModelListener(
object : PomModelListener {
override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean = aspect == treeAspect
override fun modelChanged(event: PomModelEvent) {
val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return
val ktFile = changeSet.rootElement.psi.containingFile as? KtFile ?: return
incFileModificationCount(ktFile)
val changedElements = changeSet.changedElements
// skip change if it contains only virtual/fake change
if (changedElements.isNotEmpty()) {
// ignore formatting (whitespaces etc)
if (isFormattingChange(changeSet) ||
isCommentChange(changeSet) ||
isStringLiteralChange(changeSet)
) return
}
val inBlockElements = inBlockModifications(changedElements)
val physicalFile = ktFile.isPhysical
if (inBlockElements.isEmpty()) {
val physical = physicalFile && !isReplLine(ktFile.virtualFile)
if (physical) {
outOfCodeBlockModificationTrackerImpl.incModificationCount()
}
ktFile.incOutOfBlockModificationCount()
didChangeKotlinCode(ktFile, physical)
} else if (physicalFile) {
inBlockElements.forEach { it.containingKtFile.addInBlockModifiedItem(it) }
}
}
},
this,
)
}
fun addListener(listener: PureKotlinOutOfCodeBlockModificationListener, parentDisposable: Disposable) {
listeners.add(listener)
Disposer.register(parentDisposable) { removeModelListener(listener) }
}
fun removeModelListener(listener: PureKotlinOutOfCodeBlockModificationListener) {
listeners.remove(listener)
}
private fun didChangeKotlinCode(ktFile: KtFile, physical: Boolean) {
listeners.forEach {
it.kotlinFileOutOfCodeBlockChanged(ktFile, physical)
}
}
override fun dispose() = Unit
}
private val PER_FILE_MODIFICATION_TRACKER = Key<SimpleModificationTracker>("FILE_OUT_OF_BLOCK_MODIFICATION_COUNT")
val KtFile.perFileModificationTracker: ModificationTracker
get() = putUserDataIfAbsent(PER_FILE_MODIFICATION_TRACKER, SimpleModificationTracker())
private val FILE_OUT_OF_BLOCK_MODIFICATION_COUNT = Key<Long>("FILE_OUT_OF_BLOCK_MODIFICATION_COUNT")
val KtFile.outOfBlockModificationCount: Long by NotNullableUserDataProperty(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT, 0)
private fun KtFile.incOutOfBlockModificationCount() {
clearInBlockModifications()
val count = getUserData(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT) ?: 0
putUserData(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT, count + 1)
}
/**
* inBlockModifications is a collection of block elements those have in-block modifications
*/
private val IN_BLOCK_MODIFICATIONS = Key<MutableCollection<KtElement>>("IN_BLOCK_MODIFICATIONS")
private val FILE_IN_BLOCK_MODIFICATION_COUNT = Key<Long>("FILE_IN_BLOCK_MODIFICATION_COUNT")
val KtFile.inBlockModificationCount: Long by NotNullableUserDataProperty(FILE_IN_BLOCK_MODIFICATION_COUNT, 0)
val KtFile.inBlockModifications: Collection<KtElement>
get() {
val collection = getUserData(IN_BLOCK_MODIFICATIONS)
return collection ?: emptySet()
}
private fun KtFile.addInBlockModifiedItem(element: KtElement) {
val collection = putUserDataIfAbsent(IN_BLOCK_MODIFICATIONS, mutableSetOf())
synchronized(collection) {
val needToAddBlock = collection.none { it.isAncestor(element, strict = false) }
if (needToAddBlock) {
collection.removeIf { element.isAncestor(it, strict = false) }
collection.add(element)
}
}
val count = getUserData(FILE_IN_BLOCK_MODIFICATION_COUNT) ?: 0
putUserData(FILE_IN_BLOCK_MODIFICATION_COUNT, count + 1)
}
fun KtFile.clearInBlockModifications() {
val collection = getUserData(IN_BLOCK_MODIFICATIONS)
collection?.let {
synchronized(it) {
it.clear()
}
}
} | apache-2.0 | db95bdce3da88fc6895fa5096d84d845 | 47.443864 | 158 | 0.581523 | 6.347246 | false | false | false | false |
leafclick/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/gitUtils.kt | 1 | 13730 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync
import java.io.File
import java.io.IOException
import java.util.stream.Collectors
import java.util.stream.Stream
import kotlin.math.max
internal val GIT = (System.getenv("TEAMCITY_GIT_PATH") ?: System.getenv("GIT") ?: "git").also {
val noGitFound = "Git is not found, please specify path to git executable in TEAMCITY_GIT_PATH or GIT or add it to PATH"
try {
val gitVersion = execute(null, it, "--version")
if (gitVersion.isBlank()) error(noGitFound)
log(gitVersion)
}
catch (e: IOException) {
throw IllegalStateException(noGitFound, e)
}
}
internal fun gitPull(repo: File) = try {
execute(repo, GIT, "pull", "--rebase")
}
catch (e: Exception) {
callSafely(printStackTrace = false) {
execute(repo, GIT, "rebase", "--abort")
}
log("Unable to pull changes for $repo: ${e.message}")
}
/**
* @param dirToList optional dir in [repo] from which to list files
* @return map of file paths (relative to [dirToList]) to [GitObject]
*/
internal fun listGitObjects(
repo: File, dirToList: File?,
fileFilter: (File) -> Boolean = { true }
): Map<String, GitObject> = listGitTree(repo, dirToList, fileFilter)
.collect(Collectors.toMap({ it.first }, { it.second }))
private fun listGitTree(
repo: File, dirToList: File?,
fileFilter: (File) -> Boolean
): Stream<Pair<String, GitObject>> {
val relativeDirToList = dirToList?.relativeTo(repo)?.path ?: ""
log("Inspecting $repo/$relativeDirToList")
if (!isUnderTeamCity()) gitPull(repo)
return execute(repo, GIT, "ls-tree", "HEAD", "-r", relativeDirToList)
.trim().lines().stream()
.filter(String::isNotBlank).map { line ->
// format: <mode> SP <type> SP <object> TAB <file>
line.splitWithTab()
.also { if (it.size != 2) error(line) }
.let { it[0].splitWithSpace() + it[1] }
.also { if (it.size != 4) error(line) }
}
.filter { fileFilter(repo.resolve(it[3].removeSuffix("\"").removePrefix("\""))) }
// <file>, <object>, repo
.map { GitObject(it[3], it[2], repo) }
.map { it.path.removePrefix("$relativeDirToList/") to it }
}
/**
* @param repos multiple git repos from which to list files
* @param root root repo
* @return map of file paths (relative to [root]) to [GitObject]
*/
internal fun listGitObjects(
root: File, repos: List<File>,
fileFilter: (File) -> Boolean = { true }
): Map<String, GitObject> = repos.parallelStream().flatMap { repo ->
listGitTree(repo, null, fileFilter).map {
// root relative <file> path to git object
val rootRelativePath = repo.relativeTo(root).path
if (rootRelativePath.isEmpty()) {
it.first
}
else {
"$rootRelativePath/${it.first}"
} to it.second
}
}.collect(Collectors.toMap({ it.first }, { it.second }))
/**
* @param path path relative to [repo]
*/
internal data class GitObject(val path: String, val hash: String, val repo: File) {
val file = File(repo, path)
}
/**
* @param dir path in repo
* @return root of repo
*/
internal fun findGitRepoRoot(dir: File, silent: Boolean = false): File = when {
dir.isDirectory && dir.listFiles()?.find { file ->
file.isDirectory && file.name == ".git"
} != null -> {
if (!silent) log("Git repo found in $dir")
dir
}
dir.parentFile != null -> {
if (!silent) log("No git repo found in $dir")
findGitRepoRoot(dir.parentFile, silent)
}
else -> error("No git repo found in $dir")
}
internal fun cleanup(repo: File) {
execute(repo, GIT, "reset", "--hard")
execute(repo, GIT, "clean", "-xfd")
}
internal fun stageFiles(files: List<String>, repo: File) {
// OS has argument length limit
splitAndTry(1000, files, repo) {
execute(repo, GIT, "add", "--no-ignore-removal", "--ignore-errors", *it.toTypedArray())
}
}
private fun splitAndTry(factor: Int, files: List<String>, repo: File, block: (files: List<String>) -> Unit) {
files.split(factor).forEach {
try {
block(it)
}
catch (e: Exception) {
if (e.message?.contains("did not match any files") == true) return
val finerFactor: Int = factor / 2
if (finerFactor < 1) throw e
log("Git add command failed with ${e.message}")
splitAndTry(finerFactor, files, repo, block)
}
}
}
internal fun commit(repo: File, message: String, user: String, email: String) {
execute(
repo, GIT,
"-c", "user.name=$user",
"-c", "user.email=$email",
"commit", "-m", message,
"--author=$user <$email>"
)
}
internal fun commitAndPush(repo: File, branch: String, message: String, user: String, email: String, force: Boolean = false): CommitInfo {
commit(repo, message, user, email)
push(repo, branch, user, email, force)
return commitInfo(repo) ?: error("Unable to read last commit")
}
internal fun checkout(repo: File, branch: String) = execute(repo, GIT, "checkout", branch)
internal fun push(repo: File, spec: String, user: String? = null, email: String? = null, force: Boolean = false) =
retry(doRetry = { beforePushRetry(it, repo, spec, user, email) }) {
var args = arrayOf("origin", spec)
if (force) args += "--force"
execute(repo, GIT, "push", *args, withTimer = true)
}
private fun beforePushRetry(e: Throwable, repo: File, spec: String, user: String?, email: String?): Boolean {
if (!isGitServerUnavailable(e)) {
val specParts = spec.split(':')
val identity = if (user != null && email != null) arrayOf(
"-c", "user.name=$user",
"-c", "user.email=$email"
)
else emptyArray()
execute(repo, GIT, *identity, "pull", "--rebase=true", "origin", if (specParts.count() == 2) {
"${specParts[1]}:${specParts[0]}"
}
else spec, withTimer = true)
}
return true
}
private fun isGitServerUnavailable(e: Throwable) = with(e.message ?: "") {
contains("remote end hung up unexpectedly")
|| contains("Service is in readonly mode")
|| contains("failed to lock")
|| contains("Connection timed out")
}
@Volatile
private var origins = emptyMap<File, String>()
private val originsGuard = Any()
internal fun getOriginUrl(repo: File): String {
if (!origins.containsKey(repo)) {
synchronized(originsGuard) {
if (!origins.containsKey(repo)) {
origins += repo to execute(repo, GIT, "ls-remote", "--get-url", "origin")
.removeSuffix(System.lineSeparator())
.trim()
}
}
}
return origins.getValue(repo)
}
@Volatile
private var latestChangeCommits = emptyMap<String, CommitInfo>()
private val latestChangeCommitsGuard = Any()
/**
* @param path path relative to [repo]
*/
internal fun latestChangeCommit(path: String, repo: File): CommitInfo? {
val file = repo.resolve(path).canonicalPath
if (!latestChangeCommits.containsKey(file)) {
synchronized(file) {
if (!latestChangeCommits.containsKey(file)) {
val commitInfo = monoRepoMergeAwareCommitInfo(repo, path)
if (commitInfo != null) {
synchronized(latestChangeCommitsGuard) {
latestChangeCommits += file to commitInfo
}
}
else return null
}
}
}
return latestChangeCommits.getValue(file)
}
private fun monoRepoMergeAwareCommitInfo(repo: File, path: String) =
pathInfo(repo, "--", path)?.let { commitInfo ->
if (commitInfo.parents.size == 6 && commitInfo.subject.contains("Merge all repositories")) {
val strippedPath = path.stripMergedRepoPrefix()
commitInfo.parents.asSequence().mapNotNull {
pathInfo(repo, it, "--", strippedPath)
}.firstOrNull()
}
else commitInfo
}
private fun String.stripMergedRepoPrefix(): String = when {
startsWith("community/android/tools-base/") -> removePrefix("community/android/tools-base/")
startsWith("community/android/") -> removePrefix("community/android/")
startsWith("community/") -> removePrefix("community/")
startsWith("contrib/") -> removePrefix("contrib/")
startsWith("CIDR/") -> removePrefix("CIDR/")
else -> this
}
/**
* @return latest commit (or merge) time
*/
internal fun latestChangeTime(path: String, repo: File): Long {
// latest commit for file
val commit = latestChangeCommit(path, repo)
if (commit == null) return -1
val mergeCommit = findMergeCommit(repo, commit.hash)
return max(commit.timestamp, mergeCommit?.timestamp ?: -1)
}
/**
* see [https://stackoverflow.com/questions/8475448/find-merge-commit-which-include-a-specific-commit]
*/
private fun findMergeCommit(repo: File, commit: String, searchUntil: String = "HEAD"): CommitInfo? {
// list commits that are both descendants of commit hash and ancestors of HEAD
val ancestryPathList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--ancestry-path")
.lineSequence().filter { it.isNotBlank() }
// follow only the first parent commit upon seeing a merge commit
val firstParentList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--first-parent")
.lineSequence().filter { it.isNotBlank() }.toSet()
// last common commit may be the latest merge
return ancestryPathList
.lastOrNull(firstParentList::contains)
?.let { commitInfo(repo, it) }
?.takeIf {
// should be merge
it.parents.size > 1 &&
// but not some branch merge right after [commit]
it.parents.first() != commit
}?.let {
when {
// if it's a merge of master into master then all parents belong to master but the first one doesn't lead to [commit]
isMergeOfMasterIntoMaster(repo, it) -> findMergeCommit(repo, commit, it.parents[1])
it.parents.size > 2 -> {
log("WARNING: Merge commit ${it.hash} for $commit in $repo is found but it has more than two parents (one of them could be master), skipping")
null
}
// merge is found
else -> it
}
}
}
/**
* Inspecting commit subject which isn't reliable criteria, may need to be adjusted
*
* @param merge merge commit
*/
private fun isMergeOfMasterIntoMaster(repo: File, merge: CommitInfo) =
merge.parents.size == 2 && with(merge.subject) {
val head = head(repo)
(contains("Merge branch $head") ||
contains("Merge branch '$head'") ||
contains("origin/$head")) &&
(!contains(" into ") ||
endsWith("into $head") ||
endsWith("into '$head'"))
}
@Volatile
private var heads = emptyMap<File, String>()
private val headsGuard = Any()
internal fun head(repo: File): String {
if (!heads.containsKey(repo)) {
synchronized(headsGuard) {
if (!heads.containsKey(repo)) {
heads += repo to execute(repo, GIT, "rev-parse", "--abbrev-ref", "HEAD").removeSuffix(System.lineSeparator())
}
}
}
return heads.getValue(repo)
}
internal fun commitInfo(repo: File, vararg args: String) = gitLog(repo, *args).singleOrNull()
private fun pathInfo(repo: File, vararg args: String) = gitLog(repo, "--follow", *args).singleOrNull()
private fun gitLog(repo: File, vararg args: String): List<CommitInfo> =
execute(
repo, GIT, "log",
"--max-count", "1",
"--format=%H/%cd/%P/%cn/%ce/%s",
"--date=raw", *args
).lineSequence().mapNotNull {
val output = it.splitNotBlank("/")
// <hash>/<timestamp> <timezone>/<parent hashes>/committer email/<subject>
if (output.size >= 6) {
CommitInfo(
repo = repo,
hash = output[0],
timestamp = output[1].splitWithSpace()[0].toLong(),
parents = output[2].splitWithSpace(),
committer = Committer(name = output[3], email = output[4]),
subject = output.subList(5, output.size)
.joinToString(separator = "/")
.removeSuffix(System.lineSeparator())
)
}
else null
}.toList()
internal data class CommitInfo(
val hash: String,
val timestamp: Long,
val subject: String,
val committer: Committer,
val parents: List<String>,
val repo: File
)
internal data class Committer(val name: String, val email: String)
internal fun gitStatus(repo: File, includeUntracked: Boolean = false) = Changes().apply {
execute(repo, GIT, "status", "--short", "--untracked-files=${if (includeUntracked) "all" else "no"}", "--ignored=no")
.lineSequence()
.filter(String::isNotBlank)
.forEach {
val (status, path) = it.splitToSequence("->", " ")
.filter(String::isNotBlank)
.map(String::trim)
.toList()
val type = when(status) {
"A", "??" -> Changes.Type.ADDED
"M" -> Changes.Type.MODIFIED
"D" -> Changes.Type.DELETED
else -> error("Unknown change type: $status. Git status line: $it")
}
register(type, listOf(path))
}
}
internal fun gitStage(repo: File) = execute(repo, GIT, "diff", "--cached", "--name-status")
internal fun changesFromCommit(repo: File, hash: String) =
execute(repo, GIT, "show", "--pretty=format:none", "--name-status", "--no-renames", hash)
.lineSequence().map { it.trim() }
.filter { it.isNotEmpty() && it != "none" }
.map { it.splitWithTab() }
.onEach { if (it.size != 2) error(it.joinToString(" ")) }
.map {
val (type, path) = it
when (type) {
"A" -> Changes.Type.ADDED
"D" -> Changes.Type.DELETED
"M" -> Changes.Type.MODIFIED
"T" -> Changes.Type.MODIFIED
else -> return@map null
} to path
}.filterNotNull().groupBy({ it.first }, { it.second })
internal fun gitClone(uri: String, dir: File): File {
val filesBeforeClone = dir.listFiles()?.toList() ?: emptyList()
execute(dir, GIT, "clone", uri)
return ((dir.listFiles()?.toList() ?: emptyList()) - filesBeforeClone).first {
uri.contains(it.name)
}
}
| apache-2.0 | 65439823d4746d73c7a349e6b4e1cf16 | 32.985149 | 152 | 0.643409 | 3.712818 | false | false | false | false |
ncoe/rosetta | Rosetta_Code/Tasks_without_examples/Kotlin/TasksWithoutExamples/src/main/kotlin/main.kt | 1 | 1691 | import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.regex.Pattern
fun readPage(client: HttpClient, uri: URI): String {
val request = HttpRequest.newBuilder()
.GET()
.uri(uri)
.timeout(Duration.ofSeconds(5))
.setHeader("accept", "text/html")
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
return response.body()
}
fun main() {
var re = Pattern.compile("<li><a href=\"/wiki/(.*?)\"", Pattern.DOTALL + Pattern.MULTILINE)
val client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build()
val uri = URI("http", "rosettacode.org", "/wiki/Category:Programming_Tasks", "")
var body = readPage(client, uri)
var matcher = re.matcher(body)
val tasks = mutableListOf<String>()
while (matcher.find()) {
tasks.add(matcher.group(1))
}
val base = "http://rosettacode.org/wiki/"
val limit = 3L
re = Pattern.compile(".*using any language you may know.</div>(.*?)<div id=\"toc\".*", Pattern.DOTALL + Pattern.MULTILINE)
val re2 = Pattern.compile("</?[^>]*>")
for (task in tasks.stream().limit(limit)) {
val page = base + task
body = readPage(client, URI(page))
matcher = re.matcher(body)
if (matcher.matches()) {
val group = matcher.group(1)
val m2 = re2.matcher(group)
val text = m2.replaceAll("")
println(text)
}
}
}
| mit | b6a705922c4ffa6a0bda39ea10de0e65 | 30.314815 | 126 | 0.616795 | 3.774554 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/NonAdjustableCaches.kt | 1 | 1833 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.core.dataStructures
import jetbrains.exodus.core.execution.SharedTimer
class NonAdjustableConcurrentObjectCache<K, V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentObjectCache<K, V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
}
class NonAdjustableConcurrentLongObjectCache<V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentLongObjectCache<V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
}
class NonAdjustableConcurrentIntObjectCache<V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentIntObjectCache<V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
} | apache-2.0 | f0765c3174c1d8cbfa120de38eb51726 | 44.85 | 131 | 0.686307 | 4.980978 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/MonthFragment.kt | 1 | 5850 | package com.simplemobiletools.calendar.pro.fragments
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.activities.MainActivity
import com.simplemobiletools.calendar.pro.extensions.config
import com.simplemobiletools.calendar.pro.extensions.getViewBitmap
import com.simplemobiletools.calendar.pro.extensions.printBitmap
import com.simplemobiletools.calendar.pro.helpers.Config
import com.simplemobiletools.calendar.pro.helpers.DAY_CODE
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.helpers.MonthlyCalendarImpl
import com.simplemobiletools.calendar.pro.interfaces.MonthlyCalendar
import com.simplemobiletools.calendar.pro.interfaces.NavigationListener
import com.simplemobiletools.calendar.pro.models.DayMonthly
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.beGone
import com.simplemobiletools.commons.extensions.beVisible
import com.simplemobiletools.commons.extensions.getProperTextColor
import kotlinx.android.synthetic.main.fragment_month.view.*
import kotlinx.android.synthetic.main.top_navigation.view.*
import org.joda.time.DateTime
class MonthFragment : Fragment(), MonthlyCalendar {
private var mTextColor = 0
private var mSundayFirst = false
private var mShowWeekNumbers = false
private var mDayCode = ""
private var mPackageName = ""
private var mLastHash = 0L
private var mCalendar: MonthlyCalendarImpl? = null
var listener: NavigationListener? = null
lateinit var mRes: Resources
lateinit var mHolder: RelativeLayout
lateinit var mConfig: Config
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_month, container, false)
mRes = resources
mPackageName = requireActivity().packageName
mHolder = view.month_calendar_holder
mDayCode = requireArguments().getString(DAY_CODE)!!
mConfig = requireContext().config
storeStateVariables()
setupButtons()
mCalendar = MonthlyCalendarImpl(this, requireContext())
return view
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onResume() {
super.onResume()
if (mConfig.showWeekNumbers != mShowWeekNumbers) {
mLastHash = -1L
}
mCalendar!!.apply {
mTargetDate = Formatter.getDateTimeFromCode(mDayCode)
getDays(false) // prefill the screen asap, even if without events
}
storeStateVariables()
updateCalendar()
}
private fun storeStateVariables() {
mConfig.apply {
mSundayFirst = isSundayFirst
mShowWeekNumbers = showWeekNumbers
}
}
fun updateCalendar() {
mCalendar?.updateMonthlyCalendar(Formatter.getDateTimeFromCode(mDayCode))
}
override fun updateMonthlyCalendar(context: Context, month: String, days: ArrayList<DayMonthly>, checkedEvents: Boolean, currTargetDate: DateTime) {
val newHash = month.hashCode() + days.hashCode().toLong()
if ((mLastHash != 0L && !checkedEvents) || mLastHash == newHash) {
return
}
mLastHash = newHash
activity?.runOnUiThread {
mHolder.top_value.apply {
text = month
contentDescription = text
if (activity != null) {
setTextColor(requireActivity().getProperTextColor())
}
}
updateDays(days)
}
}
private fun setupButtons() {
mTextColor = requireContext().getProperTextColor()
mHolder.top_left_arrow.apply {
applyColorFilter(mTextColor)
background = null
setOnClickListener {
listener?.goLeft()
}
val pointerLeft = requireContext().getDrawable(R.drawable.ic_chevron_left_vector)
pointerLeft?.isAutoMirrored = true
setImageDrawable(pointerLeft)
}
mHolder.top_right_arrow.apply {
applyColorFilter(mTextColor)
background = null
setOnClickListener {
listener?.goRight()
}
val pointerRight = requireContext().getDrawable(R.drawable.ic_chevron_right_vector)
pointerRight?.isAutoMirrored = true
setImageDrawable(pointerRight)
}
mHolder.top_value.apply {
setTextColor(requireContext().getProperTextColor())
setOnClickListener {
(activity as MainActivity).showGoToDateDialog()
}
}
}
private fun updateDays(days: ArrayList<DayMonthly>) {
mHolder.month_view_wrapper.updateDays(days, true) {
(activity as MainActivity).openDayFromMonthly(Formatter.getDateTimeFromCode(it.code))
}
}
fun printCurrentView() {
mHolder.apply {
top_left_arrow.beGone()
top_right_arrow.beGone()
top_value.setTextColor(resources.getColor(R.color.theme_light_text_color))
month_view_wrapper.togglePrintMode()
requireContext().printBitmap(month_calendar_holder.getViewBitmap())
top_left_arrow.beVisible()
top_right_arrow.beVisible()
top_value.setTextColor(requireContext().getProperTextColor())
month_view_wrapper.togglePrintMode()
}
}
}
| gpl-3.0 | deccd5107e6a5e0c9e35c5ca3c6b73c1 | 33.615385 | 152 | 0.677094 | 5.11811 | false | false | false | false |
jwren/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereStatisticianService.kt | 1 | 1296 | package com.intellij.ide.actions.searcheverywhere.ml.features.statistician
import com.intellij.openapi.components.Service
import com.intellij.openapi.util.Key
import com.intellij.psi.statistics.StatisticsManager
@Service(Service.Level.APP)
internal class SearchEverywhereStatisticianService {
companion object {
val KEY: Key<SearchEverywhereStatistician<in Any>> = Key.create("searchEverywhere")
}
fun increaseUseCount(element: Any) = getSerializedInfo(element)?.let { StatisticsManager.getInstance().incUseCount(it) }
fun getCombinedStats(element: Any): SearchEverywhereStatisticianStats? {
val statisticsManager = StatisticsManager.getInstance()
val info = getSerializedInfo(element) ?: return null
val allValues = statisticsManager.getAllValues(info.context).associateWith { statisticsManager.getUseCount(it) }
val useCount = allValues.entries.firstOrNull { it.key.value == info.value }?.value ?: 0
val isMostPopular = useCount > 0 && useCount == allValues.maxOf { it.value }
val recency = statisticsManager.getLastUseRecency(info)
return SearchEverywhereStatisticianStats(useCount, isMostPopular, recency)
}
private fun getSerializedInfo(element: Any) = StatisticsManager.serialize(KEY, element, "") // location is obtained from element
}
| apache-2.0 | a92ec0b110d889ef4c71da71dc138326 | 43.689655 | 131 | 0.782407 | 4.468966 | false | false | false | false |
cy6erGn0m/github-release-plugin | github-release-shared/src/main/kotlin/util.kt | 1 | 750 | package cy.github
import org.json.simple.*
import org.json.simple.parser.*
import java.io.*
import java.net.*
fun String.encodeURLComponent() = URLEncoder.encode(this, "UTF-8")!!
internal fun <T> URLConnection.withReader(block: (Reader) -> T): T = inputStream.reader().use(block)
internal fun JSONObject.getAsLong(key: String) = (get(key) as? Number)?.toLong()
internal fun Reader.toJSONObject(): JSONObject? = JSONParser().parse(this) as? JSONObject
fun String.parseSCMUrl(): Repo? =
"^scm:git:([^@]+@)?(ssh://|https?://)?([^:]+)[:/]([^/]+)/([^/]+)\\.git".toRegex().matchEntire(this)?.let { match ->
Repo(endpointOf(match.groups[2]?.value, match.groups[3]!!.value), match.groups[4]!!.value, match.groups[5]!!.value)
}
| apache-2.0 | f150710baf96c47ed429eb201f711a4a | 45.875 | 127 | 0.653333 | 3.409091 | false | false | false | false |
androidx/androidx | paging/paging-common/src/main/kotlin/androidx/paging/WrapperPositionalDataSource.kt | 3 | 2203 | /*
* Copyright 2019 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.paging
import androidx.arch.core.util.Function
@Suppress("DEPRECATION")
internal class WrapperPositionalDataSource<A : Any, B : Any>(
private val source: PositionalDataSource<A>,
val listFunction: Function<List<A>, List<B>>
) : PositionalDataSource<B>() {
override val isInvalid
get() = source.isInvalid
override fun addInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) {
source.addInvalidatedCallback(onInvalidatedCallback)
}
override fun removeInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) {
source.removeInvalidatedCallback(onInvalidatedCallback)
}
override fun invalidate() = source.invalidate()
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<B>) {
source.loadInitial(
params,
object : LoadInitialCallback<A>() {
override fun onResult(data: List<A>, position: Int, totalCount: Int) =
callback.onResult(convert(listFunction, data), position, totalCount)
override fun onResult(data: List<A>, position: Int) =
callback.onResult(convert(listFunction, data), position)
}
)
}
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<B>) {
source.loadRange(
params,
object : LoadRangeCallback<A>() {
override fun onResult(data: List<A>) =
callback.onResult(convert(listFunction, data))
}
)
}
}
| apache-2.0 | 0e3e63aeadd4bdfdbf35994b15047fd0 | 35.114754 | 91 | 0.67635 | 4.895556 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverridenTraitDeclarations.kt | 5 | 912 | // TODO: Declarations have no implementation and should be considered as "overloaded"
interface <lineMarker descr="Is implemented by Second Click or press ... to navigate">First</lineMarker> {
val <lineMarker descr="<html><body>Is implemented in <br/> Second</body></html>">some</lineMarker>: Int
var <lineMarker descr="<html><body>Is implemented in <br/> Second</body></html>">other</lineMarker>: String
get
set
fun <lineMarker descr="<html><body>Is implemented in <br> Second</body></html>">foo</lineMarker>()
}
interface Second : First {
override val <lineMarker descr="Overrides property in 'First'">some</lineMarker>: Int
override var <lineMarker descr="Overrides property in 'First'">other</lineMarker>: String
override fun <lineMarker descr="Overrides function in 'First'">foo</lineMarker>()
} | apache-2.0 | 3ad836b8a042792d5b00f4d16d869757 | 59.866667 | 134 | 0.710526 | 4.301887 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/constraints/ConstrainedCoroutineDispatcher.kt | 14 | 2374 | // 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.application.constraints
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.cancel
import java.util.function.BooleanSupplier
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
internal fun createConstrainedCoroutineDispatcher(executionScheduler: ConstrainedExecutionScheduler,
cancellationCondition: BooleanSupplier? = null,
expiration: Expiration? = null): ContinuationInterceptor {
val dispatcher = ConstrainedCoroutineDispatcherImpl(executionScheduler, cancellationCondition)
return when (expiration) {
null -> dispatcher
else -> ExpirableContinuationInterceptor(dispatcher, expiration)
}
}
internal class ConstrainedCoroutineDispatcherImpl(private val executionScheduler: ConstrainedExecutionScheduler,
private val cancellationCondition: BooleanSupplier?) : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
val condition = cancellationCondition?.let {
BooleanSupplier {
true.also {
if (cancellationCondition.asBoolean) context.cancel()
}
}
}
executionScheduler.scheduleWithinConstraints(block, condition)
}
override fun toString(): String = executionScheduler.toString()
}
internal class ExpirableContinuationInterceptor(private val dispatcher: CoroutineDispatcher,
private val expiration: Expiration)
: AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
/** Invoked once on each newly launched coroutine when dispatching it for the first time. */
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
expiration.cancelJobOnExpiration(continuation.context[Job]!!)
return dispatcher.interceptContinuation(continuation)
}
override fun toString(): String = dispatcher.toString()
}
| apache-2.0 | 7805686313b1dca10357667fb3a30624 | 47.44898 | 140 | 0.741786 | 6.025381 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinFunctionCallUsage.kt | 1 | 27021 | // 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.changeSignature.usages
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.RemoveEmptyParenthesesFromLambdaCallApplicator
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBody
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.createNameCounterpartMap
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.kind
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.sure
class KotlinFunctionCallUsage(
element: KtCallElement,
private val callee: KotlinCallableDefinitionUsage<*>,
forcedResolvedCall: ResolvedCall<*>? = null
) : KotlinUsageInfo<KtCallElement>(element) {
private val context = element.analyze(BodyResolveMode.FULL)
private val resolvedCall = forcedResolvedCall ?: element.getResolvedCall(context)
private val skipUnmatchedArgumentsCheck = forcedResolvedCall != null
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>): Boolean {
processUsageAndGetResult(changeInfo, element, allUsages)
return true
}
fun processUsageAndGetResult(
changeInfo: KotlinChangeInfo,
element: KtCallElement,
allUsages: Array<out UsageInfo>,
skipRedundantArgumentList: Boolean = false,
): KtElement {
if (shouldSkipUsage(element)) return element
var result: KtElement = element
changeNameIfNeeded(changeInfo, element)
if (element.valueArgumentList == null && changeInfo.isParameterSetOrOrderChanged && element.lambdaArguments.isNotEmpty()) {
val anchor = element.typeArgumentList ?: element.calleeExpression
if (anchor != null) {
element.addAfter(KtPsiFactory(element).createCallArguments("()"), anchor)
}
}
if (element.valueArgumentList != null) {
if (changeInfo.isParameterSetOrOrderChanged) {
result = updateArgumentsAndReceiver(changeInfo, element, allUsages, skipRedundantArgumentList)
} else {
changeArgumentNames(changeInfo, element)
}
}
if (changeInfo.getNewParametersCount() == 0 && element is KtSuperTypeCallEntry) {
val enumEntry = element.getStrictParentOfType<KtEnumEntry>()
if (enumEntry != null && enumEntry.initializerList == element.parent) {
val initializerList = enumEntry.initializerList
enumEntry.deleteChildRange(enumEntry.getColon() ?: initializerList, initializerList)
}
}
return result
}
private fun shouldSkipUsage(element: KtCallElement): Boolean {
// TODO: We probable need more clever processing of invalid calls, but for now default to Java-like behaviour
if (resolvedCall == null && element !is KtSuperTypeCallEntry) return true
if (resolvedCall == null || resolvedCall.isReallySuccess()) return false
// TODO: investigate why arguments are not recorded for enum constructor call
if (element is KtSuperTypeCallEntry && element.parent.parent is KtEnumEntry && element.valueArguments.isEmpty()) return false
if (skipUnmatchedArgumentsCheck) return false
if (!resolvedCall.call.valueArguments.all { resolvedCall.getArgumentMapping(it) is ArgumentMatch }) return true
val arguments = resolvedCall.valueArguments
return !resolvedCall.resultingDescriptor.valueParameters.all { arguments.containsKey(it) }
}
private val isPropertyJavaUsage: Boolean
get() {
val calleeElement = this.callee.element
if (calleeElement !is KtProperty && calleeElement !is KtParameter) return false
return resolvedCall?.resultingDescriptor is JavaMethodDescriptor
}
private fun changeNameIfNeeded(changeInfo: KotlinChangeInfo, element: KtCallElement) {
if (!changeInfo.isNameChanged) return
val callee = element.calleeExpression as? KtSimpleNameExpression ?: return
var newName = changeInfo.newName
if (isPropertyJavaUsage) {
val currentName = callee.getReferencedName()
if (JvmAbi.isGetterName(currentName))
newName = JvmAbi.getterName(newName)
else if (JvmAbi.isSetterName(currentName)) newName = JvmAbi.setterName(newName)
}
callee.replace(KtPsiFactory(project).createSimpleName(newName))
}
private fun getReceiverExpressionIfMatched(
receiverValue: ReceiverValue?,
originalDescriptor: DeclarationDescriptor,
psiFactory: KtPsiFactory
): KtExpression? {
if (receiverValue == null) return null
// Replace descriptor of extension function/property with descriptor of its receiver
// to simplify checking against receiver value in the corresponding resolved call
val adjustedDescriptor = if (originalDescriptor is CallableDescriptor && originalDescriptor !is ReceiverParameterDescriptor) {
originalDescriptor.extensionReceiverParameter ?: return null
} else originalDescriptor
val currentIsExtension = resolvedCall!!.extensionReceiver == receiverValue
val originalIsExtension = adjustedDescriptor is ReceiverParameterDescriptor && adjustedDescriptor.value is ExtensionReceiver
if (currentIsExtension != originalIsExtension) return null
val originalType = when (adjustedDescriptor) {
is ReceiverParameterDescriptor -> adjustedDescriptor.type
is ClassDescriptor -> adjustedDescriptor.defaultType
else -> null
}
if (originalType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(receiverValue.type, originalType)) return null
return getReceiverExpression(receiverValue, psiFactory)
}
private fun needSeparateVariable(element: PsiElement): Boolean {
return when {
element is KtConstantExpression || element is KtThisExpression || element is KtSimpleNameExpression -> false
element is KtBinaryExpression && OperatorConventions.ASSIGNMENT_OPERATIONS.contains(element.operationToken) -> true
element is KtUnaryExpression && OperatorConventions.INCREMENT_OPERATIONS.contains(element.operationToken) -> true
element is KtCallExpression -> element.getResolvedCall(context)?.resultingDescriptor is ConstructorDescriptor
else -> element.children.any { needSeparateVariable(it) }
}
}
private fun substituteReferences(
expression: KtExpression,
referenceMap: Map<PsiReference, DeclarationDescriptor>,
psiFactory: KtPsiFactory
): KtExpression {
if (referenceMap.isEmpty() || resolvedCall == null) return expression
var newExpression = expression.copy() as KtExpression
val nameCounterpartMap = createNameCounterpartMap(expression, newExpression)
val valueArguments = resolvedCall.valueArguments
val replacements = ArrayList<Pair<KtExpression, KtExpression>>()
loop@ for ((ref, descriptor) in referenceMap.entries) {
var argumentExpression: KtExpression?
val addReceiver: Boolean
if (descriptor is ValueParameterDescriptor) {
// Ordinary parameter
// Find corresponding parameter in the current function (may differ from 'descriptor' if original function is part of override hierarchy)
val parameterDescriptor = resolvedCall.resultingDescriptor.valueParameters[descriptor.index]
val resolvedValueArgument = valueArguments[parameterDescriptor] as? ExpressionValueArgument ?: continue
val argument = resolvedValueArgument.valueArgument ?: continue
addReceiver = false
argumentExpression = argument.getArgumentExpression()
} else {
addReceiver = descriptor !is ReceiverParameterDescriptor
argumentExpression =
getReceiverExpressionIfMatched(resolvedCall.extensionReceiver, descriptor, psiFactory)
?: getReceiverExpressionIfMatched(resolvedCall.dispatchReceiver, descriptor, psiFactory)
}
if (argumentExpression == null) continue
if (needSeparateVariable(argumentExpression)
&& PsiTreeUtil.getNonStrictParentOfType(
element,
KtConstructorDelegationCall::class.java,
KtSuperTypeListEntry::class.java,
KtParameter::class.java
) == null
) {
KotlinIntroduceVariableHandler.doRefactoring(
project, null, argumentExpression,
isVar = false,
occurrencesToReplace = listOf(argumentExpression),
onNonInteractiveFinish = {
argumentExpression = psiFactory.createExpression(it.name!!)
})
}
var expressionToReplace: KtExpression = nameCounterpartMap[ref.element] ?: continue
val parent = expressionToReplace.parent
if (parent is KtThisExpression) {
expressionToReplace = parent
}
if (addReceiver) {
val callExpression = expressionToReplace.getParentOfTypeAndBranch<KtCallExpression>(true) { calleeExpression }
when {
callExpression != null -> expressionToReplace = callExpression
parent is KtOperationExpression && parent.operationReference == expressionToReplace -> continue@loop
}
val replacement = psiFactory.createExpression("${argumentExpression!!.text}.${expressionToReplace.text}")
replacements.add(expressionToReplace to replacement)
} else {
replacements.add(expressionToReplace to argumentExpression!!)
}
}
// Sort by descending offset so that call arguments are replaced before call itself
ContainerUtil.sort(replacements, REVERSED_TEXT_OFFSET_COMPARATOR)
for ((expressionToReplace, replacingExpression) in replacements) {
val replaced = expressionToReplace.replaced(replacingExpression)
if (expressionToReplace == newExpression) {
newExpression = replaced
}
}
return newExpression
}
class ArgumentInfo(
val parameter: KotlinParameterInfo,
val parameterIndex: Int,
val resolvedArgument: ResolvedValueArgument?,
val receiverValue: ReceiverValue?
) {
private val mainValueArgument: ValueArgument?
get() = resolvedArgument?.arguments?.firstOrNull()
val wasNamed: Boolean
get() = mainValueArgument?.isNamed() ?: false
var name: String? = null
private set
fun makeNamed(callee: KotlinCallableDefinitionUsage<*>) {
name = parameter.getInheritedName(callee)
}
fun shouldSkip() = parameter.defaultValue != null && mainValueArgument == null
}
private fun getResolvedValueArgument(oldIndex: Int): ResolvedValueArgument? {
if (oldIndex < 0) return null
val parameterDescriptor = resolvedCall!!.resultingDescriptor.valueParameters[oldIndex]
return resolvedCall.valueArguments[parameterDescriptor]
}
private fun ArgumentInfo.getArgumentByDefaultValue(
element: KtCallElement,
allUsages: Array<out UsageInfo>,
psiFactory: KtPsiFactory
): KtValueArgument {
val isInsideOfCallerBody = element.isInsideOfCallerBody(allUsages)
val defaultValueForCall = parameter.defaultValueForCall
val argValue = when {
isInsideOfCallerBody -> psiFactory.createExpression(parameter.name)
defaultValueForCall != null -> substituteReferences(
defaultValueForCall,
parameter.defaultValueParameterReferences,
psiFactory,
).asMarkedForShortening()
else -> null
}
val argName = (if (isInsideOfCallerBody) null else name)?.let { Name.identifier(it) }
return psiFactory.createArgument(argValue ?: psiFactory.createExpression("0"), argName).apply {
if (argValue == null) {
getArgumentExpression()?.delete()
}
}
}
private fun ExpressionReceiver.wrapInvalidated(element: KtCallElement): ExpressionReceiver = object : ExpressionReceiver by this {
override val expression = element.getQualifiedExpressionForSelector()!!.receiverExpression
}
private fun updateArgumentsAndReceiver(
changeInfo: KotlinChangeInfo,
element: KtCallElement,
allUsages: Array<out UsageInfo>,
skipRedundantArgumentList: Boolean,
): KtElement {
if (isPropertyJavaUsage) return updateJavaPropertyCall(changeInfo, element)
val fullCallElement = element.getQualifiedExpressionForSelector() ?: element
val oldArguments = element.valueArguments
val newParameters = changeInfo.getNonReceiverParameters()
val purelyNamedCall = element is KtCallExpression && oldArguments.isNotEmpty() && oldArguments.all { it.isNamed() }
val newReceiverInfo = changeInfo.receiverParameterInfo
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
val extensionReceiver = resolvedCall?.extensionReceiver
val dispatchReceiver = resolvedCall?.dispatchReceiver
// Do not add extension receiver to calls with explicit dispatch receiver except for objects
if (newReceiverInfo != null &&
fullCallElement is KtQualifiedExpression &&
dispatchReceiver is ExpressionReceiver
) {
if (isObjectReceiver(dispatchReceiver)) {
//It's safe to replace object reference with a new receiver, but we shall import the function
addDelayedImportRequest(changeInfo.method, element.containingKtFile)
} else {
return element
}
}
val newArgumentInfos = newParameters.asSequence().withIndex().map {
val (index, param) = it
val oldIndex = param.oldIndex
val resolvedArgument = if (oldIndex >= 0) getResolvedValueArgument(oldIndex) else null
var receiverValue = if (param == originalReceiverInfo) extensionReceiver else null
// Workaround for recursive calls where implicit extension receiver is transformed into ordinary value argument
// Receiver expression retained in the original resolved call is no longer valid at this point
if (receiverValue is ExpressionReceiver && !receiverValue.expression.isValid) {
receiverValue = receiverValue.wrapInvalidated(element)
}
ArgumentInfo(param, index, resolvedArgument, receiverValue)
}.toList()
val lastParameterIndex = newParameters.lastIndex
val canMixArguments = element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)
var firstNamedIndex = newArgumentInfos.firstOrNull {
!canMixArguments && it.wasNamed ||
it.parameter.isNewParameter && it.parameter.defaultValue != null ||
it.resolvedArgument is VarargValueArgument && it.parameterIndex < lastParameterIndex
}?.parameterIndex
if (firstNamedIndex == null) {
val lastNonDefaultArgIndex = (lastParameterIndex downTo 0).firstOrNull { !newArgumentInfos[it].shouldSkip() } ?: -1
firstNamedIndex = (0..lastNonDefaultArgIndex).firstOrNull { newArgumentInfos[it].shouldSkip() }
}
val lastPositionalIndex = if (firstNamedIndex != null) firstNamedIndex - 1 else lastParameterIndex
val namedRange = lastPositionalIndex + 1..lastParameterIndex
for ((index, argument) in newArgumentInfos.withIndex()) {
if (purelyNamedCall || argument.wasNamed || index in namedRange) {
argument.makeNamed(callee)
}
}
val psiFactory = KtPsiFactory(element.project)
val newArgumentList = psiFactory.createCallArguments("()").apply {
for (argInfo in newArgumentInfos) {
if (argInfo.shouldSkip()) continue
val name = argInfo.name?.let { Name.identifier(it) }
if (argInfo.receiverValue != null) {
val receiverExpression = getReceiverExpression(argInfo.receiverValue, psiFactory) ?: continue
addArgument(psiFactory.createArgument(receiverExpression, name))
continue
}
when (val resolvedArgument = argInfo.resolvedArgument) {
null, is DefaultValueArgument -> addArgument(argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory))
is ExpressionValueArgument -> {
val valueArgument = resolvedArgument.valueArgument
val newValueArgument: KtValueArgument = when {
valueArgument == null -> argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory)
valueArgument is KtLambdaArgument -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name)
valueArgument is KtValueArgument && valueArgument.getArgumentName()?.asName == name -> valueArgument
else -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name)
}
addArgument(newValueArgument)
}
// TODO: Support Kotlin varargs
is VarargValueArgument -> resolvedArgument.arguments.forEach {
if (it is KtValueArgument) addArgument(it)
}
else -> return element
}
}
}
newArgumentList.arguments.singleOrNull()?.let {
if (it.getArgumentExpression() == null) {
newArgumentList.removeArgument(it)
}
}
val lastOldArgument = oldArguments.lastOrNull()
val lastNewParameter = newParameters.lastOrNull()
val lastNewArgument = newArgumentList.arguments.lastOrNull()
val oldLastResolvedArgument = getResolvedValueArgument(lastNewParameter?.oldIndex ?: -1) as? ExpressionValueArgument
val lambdaArgumentNotTouched = lastOldArgument is KtLambdaArgument && oldLastResolvedArgument?.valueArgument == lastOldArgument
val newLambdaArgumentAddedLast = lastNewParameter != null
&& lastNewParameter.isNewParameter
&& lastNewParameter.defaultValueForCall is KtLambdaExpression
&& lastNewArgument?.getArgumentExpression() is KtLambdaExpression
&& !lastNewArgument.isNamed()
if (lambdaArgumentNotTouched) {
newArgumentList.removeArgument(newArgumentList.arguments.last())
} else {
val lambdaArguments = element.lambdaArguments
if (lambdaArguments.isNotEmpty()) {
element.deleteChildRange(lambdaArguments.first(), lambdaArguments.last())
}
}
val oldArgumentList = element.valueArgumentList.sure { "Argument list is expected: " + element.text }
for (argument in replaceListPsiAndKeepDelimiters(changeInfo, oldArgumentList, newArgumentList) { arguments }.arguments) {
if (argument.getArgumentExpression() == null) argument.delete()
}
var newElement: KtElement = element
if (newReceiverInfo != originalReceiverInfo) {
val replacingElement: PsiElement = if (newReceiverInfo != null) {
val receiverArgument = getResolvedValueArgument(newReceiverInfo.oldIndex)?.arguments?.singleOrNull()
val extensionReceiverExpression = receiverArgument?.getArgumentExpression()
val defaultValueForCall = newReceiverInfo.defaultValueForCall
val receiver = extensionReceiverExpression?.let { psiFactory.createExpression(it.text) }
?: defaultValueForCall?.asMarkedForShortening()
?: psiFactory.createExpression("_")
psiFactory.createExpressionByPattern("$0.$1", receiver, element)
} else {
element.copy()
}
newElement = fullCallElement.replace(replacingElement) as KtElement
}
val newCallExpression = newElement.safeAs<KtExpression>()?.getPossiblyQualifiedCallExpression()
if (!lambdaArgumentNotTouched && newLambdaArgumentAddedLast) {
newCallExpression?.moveFunctionLiteralOutsideParentheses()
}
if (!skipRedundantArgumentList) {
newCallExpression?.valueArgumentList?.let {
if (RemoveEmptyParenthesesFromLambdaCallApplicator.applicator.isApplicableByPsi(it, it.project)) {
RemoveEmptyParenthesesFromLambdaCallApplicator.applicator.applyTo(
it, KotlinApplicatorInput.Empty, it.project, editor = null
)
}
}
}
newElement.flushElementsForShorteningToWaitList()
return newElement
}
private fun isObjectReceiver(dispatchReceiver: ReceiverValue) = dispatchReceiver.safeAs<ClassValueReceiver>()?.classQualifier?.descriptor?.kind == ClassKind.OBJECT
private fun changeArgumentNames(changeInfo: KotlinChangeInfo, element: KtCallElement) {
for (argument in element.valueArguments) {
val argumentName = argument.getArgumentName()
val argumentNameExpression = argumentName?.referenceExpression ?: continue
val oldParameterIndex = changeInfo.getOldParameterIndex(argumentNameExpression.getReferencedName()) ?: continue
val newParameterIndex = if (changeInfo.receiverParameterInfo != null) oldParameterIndex + 1 else oldParameterIndex
val parameterInfo = changeInfo.newParameters[newParameterIndex]
changeArgumentName(argumentNameExpression, parameterInfo)
}
}
private fun changeArgumentName(argumentNameExpression: KtSimpleNameExpression?, parameterInfo: KotlinParameterInfo) {
val identifier = argumentNameExpression?.getIdentifier() ?: return
val newName = parameterInfo.getInheritedName(callee)
identifier.replace(KtPsiFactory(project).createIdentifier(newName))
}
companion object {
private val REVERSED_TEXT_OFFSET_COMPARATOR = Comparator<Pair<KtElement, KtElement>> { p1, p2 ->
val offset1 = p1.first.startOffset
val offset2 = p2.first.startOffset
when {
offset1 < offset2 -> 1
offset1 > offset2 -> -1
else -> 0
}
}
private fun updateJavaPropertyCall(changeInfo: KotlinChangeInfo, element: KtCallElement): KtElement {
val newReceiverInfo = changeInfo.receiverParameterInfo
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
if (newReceiverInfo == originalReceiverInfo) return element
val arguments = element.valueArgumentList.sure { "Argument list is expected: " + element.text }
val oldArguments = element.valueArguments
val psiFactory = KtPsiFactory(element.project)
val firstArgument = oldArguments.firstOrNull() as KtValueArgument?
when {
newReceiverInfo != null -> {
val defaultValueForCall = newReceiverInfo.defaultValueForCall ?: psiFactory.createExpression("_")
val newReceiverArgument = psiFactory.createArgument(defaultValueForCall, null, false)
if (originalReceiverInfo != null) {
firstArgument?.replace(newReceiverArgument)
} else {
arguments.addArgumentAfter(newReceiverArgument, null)
}
}
firstArgument != null -> arguments.removeArgument(firstArgument)
}
return element
}
private fun getReceiverExpression(receiver: ReceiverValue, psiFactory: KtPsiFactory): KtExpression? {
return when (receiver) {
is ExpressionReceiver -> receiver.expression
is ImplicitReceiver -> {
val descriptor = receiver.declarationDescriptor
val thisText = if (descriptor is ClassDescriptor && !DescriptorUtils.isAnonymousObject(descriptor)) {
"this@" + descriptor.name.asString()
} else {
"this"
}
psiFactory.createExpression(thisText)
}
else -> null
}
}
}
}
| apache-2.0 | 12764d96eff37cc0c489073c01ff05c0 | 47.080071 | 167 | 0.672218 | 6.611451 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt | 1 | 4711 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.surroundWith
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.openapi.application.Result
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerEvaluationBundle
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinRuntimeTypeEvaluator
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
class KotlinRuntimeTypeCastSurrounder : KotlinExpressionSurrounder() {
override fun isApplicable(expression: KtExpression): Boolean {
if (!super.isApplicable(expression)) return false
if (!expression.isPhysical) return false
val file = expression.containingFile
if (file !is KtCodeFragment) return false
val type = expression.analyze(BodyResolveMode.PARTIAL).getType(expression) ?: return false
return TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)
}
override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange? {
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if (debuggerSession != null) {
val progressWindow = ProgressWindow(true, expression.project)
val worker = SurroundWithCastWorker(editor, expression, debuggerContext, progressWindow)
progressWindow.title = JavaDebuggerBundle.message("title.evaluating")
debuggerContext.debugProcess?.managerThread?.startProgress(worker, progressWindow)
}
return null
}
override fun getTemplateDescription(): String {
return KotlinDebuggerEvaluationBundle.message("surround.with.runtime.type.cast.template")
}
private inner class SurroundWithCastWorker(
private val myEditor: Editor,
expression: KtExpression,
context: DebuggerContextImpl,
indicator: ProgressIndicator
) : KotlinRuntimeTypeEvaluator(myEditor, expression, context, indicator) {
override fun typeCalculationFinished(type: KotlinType?) {
if (type == null) return
hold()
val project = myEditor.project
DebuggerInvocationUtil.invokeLater(project, Runnable {
object : WriteCommandAction<Any>(project, JavaDebuggerBundle.message("command.name.surround.with.runtime.cast")) {
override fun run(result: Result<in Any>) {
try {
val factory = KtPsiFactory(myElement.project)
val fqName = DescriptorUtils.getFqName(type.constructor.declarationDescriptor!!)
val parentCast = factory.createExpression("(expr as " + fqName.asString() + ")") as KtParenthesizedExpression
val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS
cast.left.replace(myElement)
val expr = myElement.replace(parentCast) as KtExpression
ShortenReferences.DEFAULT.process(expr)
val range = expr.textRange
myEditor.selectionModel.setSelection(range.startOffset, range.endOffset)
myEditor.caretModel.moveToOffset(range.endOffset)
myEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE)
} finally {
release()
}
}
}.execute()
}, myProgressIndicator.modalityState)
}
}
}
| apache-2.0 | a4567f7a172d9febd522ce803dc19dc0 | 46.585859 | 158 | 0.699851 | 5.52286 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemovePsiElementSimpleFix.kt | 3 | 4774 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.isExplicitTypeReferenceNeededForTypeInference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
open class RemovePsiElementSimpleFix private constructor(element: PsiElement, @Nls private val text: String) :
KotlinPsiOnlyQuickFixAction<PsiElement>(element) {
override fun getFamilyName() = KotlinBundle.message("remove.element")
override fun getText() = text
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
object RemoveImportFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val directive = psiElement.getNonStrictParentOfType<KtImportDirective>() ?: return emptyList()
val refText = directive.importedReference?.let { KotlinBundle.message("for.0", it.text) } ?: ""
return listOf(RemovePsiElementSimpleFix(directive, KotlinBundle.message("remove.conflicting.import.0", refText)))
}
}
object RemoveSpreadFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement
if (element.node.elementType != KtTokens.MUL) return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.star")))
}
}
object RemoveTypeArgumentsFactory :
QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement.getNonStrictParentOfType<KtTypeArgumentList>() ?: return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.type.arguments")))
}
}
object RemoveTypeParametersFactory :
QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
// FIR passes the KtProperty while FE1.0 passes the type parameter list.
val element = if (psiElement is KtProperty) {
psiElement.typeParameterList
} else {
psiElement.getNonStrictParentOfType<KtTypeParameterList>()
} ?: return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.type.parameters")))
}
}
object RemoveVariableFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
if (psiElement is KtDestructuringDeclarationEntry) return emptyList()
val ktProperty = psiElement.getNonStrictParentOfType<KtProperty>() ?: return emptyList()
if (ktProperty.isExplicitTypeReferenceNeededForTypeInference()) return emptyList()
val removePropertyFix = object : RemovePsiElementSimpleFix(ktProperty, KotlinBundle.message("remove.variable.0", ktProperty.name.toString())) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
removeProperty(element as? KtProperty ?: return)
}
}
return listOf(removePropertyFix)
}
fun removeProperty(ktProperty: KtProperty) {
val initializer = ktProperty.initializer
if (initializer != null && initializer !is KtConstantExpression) {
val commentSaver = CommentSaver(ktProperty)
val replaced = ktProperty.replace(initializer)
commentSaver.restore(replaced)
} else {
ktProperty.delete()
}
}
}
}
| apache-2.0 | 2340153bbc55569e42d9c27e766f8aa0 | 50.333333 | 155 | 0.717009 | 5.690107 | false | false | false | false |
GunoH/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventMergeStrategy.kt | 9 | 1614 | // 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.internal.statistic.eventLog
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import com.jetbrains.fus.reporting.model.lion3.LogEventAction
interface StatisticsEventMergeStrategy {
fun shouldMerge(lastEvent: LogEvent, newEvent: LogEvent): Boolean
}
class FilteredEventMergeStrategy(private val ignoredFields: Set<String>) : StatisticsEventMergeStrategy {
override fun shouldMerge(lastEvent: LogEvent, newEvent: LogEvent): Boolean {
if (lastEvent.session != newEvent.session) return false
if (lastEvent.bucket != newEvent.bucket) return false
if (lastEvent.build != newEvent.build) return false
if (lastEvent.recorderVersion != newEvent.recorderVersion) return false
if (lastEvent.group.id != newEvent.group.id) return false
if (lastEvent.group.version != newEvent.group.version) return false
if (!shouldMergeEvents(lastEvent.event, newEvent.event)) return false
return true
}
private fun shouldMergeEvents(lastEvent: LogEventAction, newEvent: LogEventAction): Boolean {
if (lastEvent.state || newEvent.state) return false
if (lastEvent.id != newEvent.id) return false
if (lastEvent.data.size != newEvent.data.size) return false
for (datum in lastEvent.data) {
val key = datum.key
if (!ignoredFields.contains(key)) {
val value = newEvent.data[key]
if (value == null || value != datum.value) return false
}
}
return true
}
} | apache-2.0 | 7ab495966b957a1aebaa4d21db767546 | 41.5 | 158 | 0.740397 | 4.33871 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/SuggestingUtils.kt | 8 | 2781 | // 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 training.featuresSuggester
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parents
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import training.featuresSuggester.actions.Action
import training.featuresSuggester.settings.FeatureSuggesterSettings
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.IOException
data class TextFragment(val startOffset: Int, val endOffset: Int, val text: String)
internal object SuggestingUtils {
var forceShowSuggestions: Boolean
get() = Registry.`is`("feature.suggester.force.show.suggestions", false)
set(value) = Registry.get("feature.suggester.force.show.suggestions").setValue(value)
fun isActionsProcessingEnabled(project: Project): Boolean {
return !project.isDisposed && !DumbService.isDumb(project) && FeatureSuggesterSettings.instance().isAnySuggesterEnabled
}
fun handleAction(project: Project, action: Action) {
if (isActionsProcessingEnabled(project)) {
project.getService(FeatureSuggestersManager::class.java)?.actionPerformed(action)
}
}
fun findBreakpointOnPosition(project: Project, position: XSourcePosition): XBreakpoint<*>? {
val breakpointManager = XDebuggerManager.getInstance(project)?.breakpointManager ?: return null
return breakpointManager.allBreakpoints.find { b ->
b is XLineBreakpoint<*> && b.fileUrl == position.file.url && b.line == position.line
}
}
fun Transferable.asString(): String? {
return try {
getTransferData(DataFlavor.stringFlavor) as? String
}
catch (ex: IOException) {
null
}
catch (ex: UnsupportedFlavorException) {
null
}
}
fun Editor.getSelection(): TextFragment? {
with(selectionModel) {
return if (selectedText != null) {
TextFragment(selectionStart, selectionEnd, selectedText!!)
}
else {
null
}
}
}
}
inline fun <reified T : PsiElement> PsiElement.getParentOfType(): T? {
return PsiTreeUtil.getParentOfType(this, T::class.java)
}
fun PsiElement.getParentByPredicate(predicate: (PsiElement) -> Boolean): PsiElement? {
return parents(true).find(predicate)
}
| apache-2.0 | 09a923593c60bee666381bd10670341f | 35.116883 | 158 | 0.762316 | 4.51461 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/util/GHSecurityUtil.kt | 4 | 2886 | // 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 org.jetbrains.plugins.github.authentication.util
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.Url
import com.intellij.util.Urls.newUrl
import org.jetbrains.plugins.github.api.*
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
object GHSecurityUtil {
private const val REPO_SCOPE = "repo"
private const val GIST_SCOPE = "gist"
private const val READ_ORG_SCOPE = "read:org"
private const val WORKFLOW_SCOPE = "workflow"
val MASTER_SCOPES = listOf(REPO_SCOPE, GIST_SCOPE, READ_ORG_SCOPE, WORKFLOW_SCOPE)
const val DEFAULT_CLIENT_NAME = "Github Integration Plugin"
@JvmStatic
internal fun loadCurrentUserWithScopes(executor: GithubApiRequestExecutor,
progressIndicator: ProgressIndicator,
server: GithubServerPath): Pair<GithubAuthenticatedUser, String?> {
var scopes: String? = null
val details = executor.execute(progressIndicator,
object : GithubApiRequest.Get.Json<GithubAuthenticatedUser>(
GithubApiRequests.getUrl(server,
GithubApiRequests.CurrentUser.urlSuffix),
GithubAuthenticatedUser::class.java) {
override fun extractResult(response: GithubApiResponse): GithubAuthenticatedUser {
scopes = response.findHeader("X-OAuth-Scopes")
return super.extractResult(response)
}
}.withOperationName("get profile information"))
return details to scopes
}
@JvmStatic
internal fun isEnoughScopes(grantedScopes: String): Boolean {
val scopesArray = grantedScopes.split(", ")
if (scopesArray.isEmpty()) return false
if (!scopesArray.contains(REPO_SCOPE)) return false
if (!scopesArray.contains(GIST_SCOPE)) return false
if (scopesArray.none { it.endsWith(":org") }) return false
return true
}
internal fun buildNewTokenUrl(server: GithubServerPath): String {
val productName = ApplicationNamesInfo.getInstance().fullProductName
return server
.append("settings/tokens/new")
.addParameters(mapOf(
"description" to "$productName GitHub integration plugin",
"scopes" to MASTER_SCOPES.joinToString(",")
))
.toExternalForm()
}
private fun GithubServerPath.append(path: String): Url =
newUrl(schema, host + port?.let { ":$it" }.orEmpty(), suffix.orEmpty() + "/" + path)
} | apache-2.0 | 3ef18e88c788342b14d8e5ec070b76b2 | 44.825397 | 140 | 0.643451 | 5.285714 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/inspections/FormatViolationInspection.kt | 2 | 1251 | package com.intellij.aws.cloudformation.inspections
import com.intellij.aws.cloudformation.CloudFormationInspections
import com.intellij.aws.cloudformation.CloudFormationParser
import com.intellij.aws.cloudformation.CloudFormationPsiUtils
import com.intellij.codeInspection.*
import com.intellij.psi.PsiFile
abstract class FormatViolationInspection : LocalInspectionTool() {
override fun runForWholeFile(): Boolean = true
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (!CloudFormationPsiUtils.isCloudFormationFile(file)) {
return null
}
val parsed = CloudFormationParser.parse(file)
val inspected = CloudFormationInspections.inspectFile(parsed)
val problems = parsed.problems.plus(inspected.problems).map {
manager.createProblemDescriptor(
it.element,
it.description,
isOnTheFly,
LocalQuickFix.EMPTY_ARRAY,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
return problems.toTypedArray()
}
override fun getStaticDescription(): String? = ""
}
class JsonFormatViolationInspection: FormatViolationInspection()
class YamlFormatViolationInspection: FormatViolationInspection()
| apache-2.0 | 362dc6450c8e5f1956a901549a22e997 | 32.810811 | 117 | 0.772982 | 5.190871 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/player/NavigationView.kt | 1 | 2861 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.player
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.view.View
import com.gigamole.navigationtabstrip.NavigationTabStrip
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.TIMELINE_FAVORITES
import com.sinyuk.fanfou.domain.TIMELINE_USER
import com.sinyuk.fanfou.ui.photo.PhotoGridView
import com.sinyuk.fanfou.ui.timeline.TimelineView
import kotlinx.android.synthetic.main.navigation_view.*
/**
* Created by sinyuk on 2017/12/23.
*
*/
class NavigationView : AbstractFragment(), Injectable {
override fun layoutId() = R.layout.navigation_view
companion object {
fun newInstance(player: Player?) = NavigationView().apply {
arguments = Bundle().apply { putParcelable("player", player) }
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
assert(arguments != null)
val player = arguments!!.getParcelable<Player>("player")!!
fragmentList = arrayListOf(TimelineView.playerTimeline(TIMELINE_USER, player), PhotoGridView.newInstance(player), TimelineView.playerTimeline(TIMELINE_FAVORITES, player))
setupViewPager()
}
lateinit var fragmentList: MutableList<Fragment>
private fun setupViewPager() {
viewPager.offscreenPageLimit = fragmentList.size - 1
viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getItem(position: Int) = fragmentList[position]
override fun getCount() = fragmentList.size
}
tabStrip.setTabIndex(0, true)
tabStrip.onTabStripSelectedIndexListener = object : NavigationTabStrip.OnTabStripSelectedIndexListener {
override fun onStartTabSelected(title: String?, index: Int) {
}
override fun onEndTabSelected(title: String?, index: Int) {
viewPager.setCurrentItem(index, false)
}
}
}
} | mit | 96e5791566c9c3df27cb121fcf26cbc8 | 34.775 | 178 | 0.709542 | 4.341426 | false | false | false | false |
jeeb/mpv-android | app/src/main/java/is/xyz/mpv/MPVActivity.kt | 1 | 28798 | package `is`.xyz.mpv
import kotlinx.android.synthetic.main.player.*
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.AssetManager
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.preference.PreferenceManager.getDefaultSharedPreferences
import androidx.core.content.ContextCompat
import android.view.*
import android.widget.SeekBar
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import android.widget.Toast.makeText
import kotlinx.android.synthetic.main.player.view.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MPVActivity : Activity(), EventObserver, TouchGesturesObserver {
private lateinit var fadeHandler: Handler
private lateinit var fadeRunnable: FadeOutControlsRunnable
private var activityIsForeground = true
private var userIsOperatingSeekbar = false
private lateinit var toast: Toast
private lateinit var gestures: TouchGestures
private lateinit var audioManager: AudioManager
private val seekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (!fromUser)
return
player.timePos = progress
updatePlaybackPos(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
userIsOperatingSeekbar = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
userIsOperatingSeekbar = false
}
}
private var statsEnabled = false
private var statsOnlyFPS = false
private var statsLuaMode = 0 // ==0 disabled, >0 page number
private var gesturesEnabled = true
private var backgroundPlayMode = ""
private var shouldSavePosition = false
private var autoRotationMode = ""
private fun initListeners() {
controls.cycleAudioBtn.setOnClickListener { _ -> cycleAudio() }
controls.cycleAudioBtn.setOnLongClickListener { _ -> pickAudio(); true }
controls.cycleSubsBtn.setOnClickListener { _ ->cycleSub() }
controls.cycleSubsBtn.setOnLongClickListener { _ -> pickSub(); true }
}
private fun initMessageToast() {
toast = makeText(applicationContext, "This totally shouldn't be seen", LENGTH_SHORT)
toast.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 0)
}
private var playbackHasStarted = false
private var onload_commands = ArrayList<Array<String>>()
override fun onCreate(icicle: Bundle?) {
super.onCreate(icicle)
// Do copyAssets here and not in MainActivity because mpv can be launched from a file browser
copyAssets()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContentView(R.layout.player)
// Init controls to be hidden and view fullscreen
initControls()
// Initialize listeners for the player view
initListeners()
// Initialize toast used for short messages
initMessageToast()
// set up a callback handler and a runnable for fading the controls out
fadeHandler = Handler()
fadeRunnable = FadeOutControlsRunnable(this, controls)
syncSettings()
// set initial screen orientation (depending on settings)
updateOrientation(true)
val filepath: String?
if (intent.action == Intent.ACTION_VIEW) {
filepath = resolveUri(intent.data)
parseIntentExtras(intent.extras)
} else {
filepath = intent.getStringExtra("filepath")
}
if (filepath == null) {
Log.e(TAG, "No file given, exiting")
finish()
return
}
player.initialize(applicationContext.filesDir.path)
player.addObserver(this)
player.playFile(filepath)
playbackSeekbar.setOnSeekBarChangeListener(seekBarChangeListener)
if (this.gesturesEnabled) {
val dm = resources.displayMetrics
gestures = TouchGestures(dm.widthPixels.toFloat(), dm.heightPixels.toFloat(), this)
player.setOnTouchListener { _, e -> gestures.onTouchEvent(e) }
}
audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
volumeControlStream = AudioManager.STREAM_MUSIC
}
override fun onDestroy() {
// take the background service with us
val intent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.stopService(intent)
player.removeObserver(this)
player.destroy()
super.onDestroy()
}
private fun copyAssets() {
val assetManager = applicationContext.assets
val files = arrayOf("subfont.ttf", "cacert.pem")
val configDir = applicationContext.filesDir.path
for (filename in files) {
var ins: InputStream? = null
var out: OutputStream? = null
try {
ins = assetManager.open(filename, AssetManager.ACCESS_STREAMING)
val outFile = File("$configDir/$filename")
// Note that .available() officially returns an *estimated* number of bytes available
// this is only true for generic streams, asset streams return the full file size
if (outFile.length() == ins.available().toLong()) {
Log.w(TAG, "Skipping copy of asset file (exists same size): $filename")
continue
}
out = FileOutputStream(outFile)
ins.copyTo(out)
Log.w(TAG, "Copied asset file: $filename")
} catch (e: IOException) {
Log.e(TAG, "Failed to copy asset file: $filename", e)
} finally {
ins?.close()
out?.close()
}
}
}
private fun shouldBackground(): Boolean {
if (isFinishing) // about to exit?
return false
if (player.paused ?: true)
return false
when (backgroundPlayMode) {
"always" -> return true
"never" -> return false
}
// backgroundPlayMode == "audio-only"
val fmt = MPVLib.getPropertyString("video-format")
return fmt.isNullOrEmpty() || arrayOf("mjpeg", "png", "bmp").indexOf(fmt) != -1
}
override fun onPause() {
val multiWindowMode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) isInMultiWindowMode else false
if (multiWindowMode) {
Log.v(TAG, "Going into multi-window mode")
super.onPause()
return
}
val shouldBackground = shouldBackground()
if (shouldBackground && !MPVLib.getPropertyString("video-format").isNullOrEmpty())
BackgroundPlaybackService.thumbnail = MPVLib.grabThumbnail(THUMB_SIZE)
else
BackgroundPlaybackService.thumbnail = null
// player.onPause() modifies the playback state, so save stuff beforehand
if (isFinishing)
savePosition()
player.onPause()
super.onPause()
activityIsForeground = false
if (shouldBackground) {
Log.v(TAG, "Resuming playback in background")
// start background playback service
val serviceIntent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.startService(serviceIntent)
}
}
private fun syncSettings() {
// FIXME: settings should be in their own class completely
val prefs = getDefaultSharedPreferences(this.applicationContext)
val statsMode = prefs.getString("stats_mode", "")
if (statsMode.isNullOrBlank()) {
this.statsEnabled = false
this.statsLuaMode = 0
} else if (statsMode == "native" || statsMode == "native_fps") {
this.statsEnabled = true
this.statsLuaMode = 0
this.statsOnlyFPS = statsMode == "native_fps"
} else if (statsMode == "lua1" || statsMode == "lua2") {
this.statsEnabled = false
this.statsLuaMode = if (statsMode == "lua1") 1 else 2
}
this.gesturesEnabled = prefs.getBoolean("touch_gestures", true)
this.backgroundPlayMode = prefs.getString("background_play", "never")
this.shouldSavePosition = prefs.getBoolean("save_position", false)
this.autoRotationMode = prefs.getString("auto_rotation", "auto")
if (this.statsOnlyFPS)
statsTextView.setTextColor((0xFF00FF00).toInt()) // green
if (this.autoRotationMode != "auto")
orientationBtn.visibility = View.VISIBLE
}
override fun onResume() {
// If we weren't actually in the background (e.g. multi window mode), don't reinitialize stuff
if (activityIsForeground) {
super.onResume()
return
}
// Init controls to be hidden and view fullscreen
initControls()
syncSettings()
activityIsForeground = true
refreshUi()
// stop background playback if still running
val intent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.stopService(intent)
player.onResume()
super.onResume()
}
private fun savePosition() {
if (!shouldSavePosition)
return
if (MPVLib.getPropertyBoolean("eof-reached") ?: true) {
Log.d(TAG, "player indicates EOF, not saving watch-later config")
return
}
MPVLib.command(arrayOf("write-watch-later-config"))
}
private fun updateStats() {
if (this.statsOnlyFPS) {
statsTextView.text = "${player.estimatedVfFps} FPS"
return
}
val text = "File: ${player.filename}\n\n" +
"Video: ${player.videoCodec} hwdec: ${player.hwdecActive}\n" +
"\tA-V: ${player.avsync}\n" +
"\tDropped: decoder: ${player.decoderFrameDropCount}, VO: ${player.frameDropCount}\n" +
"\tFPS: ${player.fps} (specified) ${player.estimatedVfFps} (estimated)\n" +
"\tResolution: ${player.videoW}x${player.videoH}\n\n" +
"Audio: ${player.audioCodec}\n" +
"\tSample rate: ${player.audioSampleRate} Hz\n" +
"\tChannels: ${player.audioChannels}"
statsTextView.text = text
}
private fun showControls() {
// remove all callbacks that were to be run for fading
fadeHandler.removeCallbacks(fadeRunnable)
// set the main controls as 75%, actual seek bar|buttons as 100%
controls.alpha = 1f
// Open, Sesame!
controls.visibility = View.VISIBLE
top_controls.visibility = View.VISIBLE
if (this.statsEnabled) {
updateStats()
statsTextView.visibility = View.VISIBLE
}
window.decorView.systemUiVisibility = 0
// add a new callback to hide the controls once again
fadeHandler.postDelayed(fadeRunnable, CONTROLS_DISPLAY_TIMEOUT)
}
fun initControls() {
/* Init controls to be hidden */
// use GONE here instead of INVISIBLE (which makes more sense) because of Android bug with surface views
// see http://stackoverflow.com/a/12655713/2606891
controls.visibility = View.GONE
top_controls.visibility = View.GONE
statsTextView.visibility = View.GONE
val flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE
window.decorView.systemUiVisibility = flags
}
private fun hideControls() {
fadeHandler.removeCallbacks(fadeRunnable)
fadeHandler.post(fadeRunnable)
}
private fun toggleControls(): Boolean {
return if (controls.visibility == View.VISIBLE) {
hideControls()
false
} else {
showControls()
true
}
}
override fun dispatchKeyEvent(ev: KeyEvent): Boolean {
showControls()
// try built-in event handler first, forward all other events to libmpv
if (ev.action == KeyEvent.ACTION_DOWN && interceptKeyDown(ev)) {
return true
} else if (player.onKey(ev)) {
return true
}
return super.dispatchKeyEvent(ev)
}
private var mightWantToToggleControls = false
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (super.dispatchTouchEvent(ev)) {
// reset delay if the event has been handled
if (controls.visibility == View.VISIBLE)
showControls()
if (ev.action == MotionEvent.ACTION_UP)
return true
}
if (ev.action == MotionEvent.ACTION_DOWN)
mightWantToToggleControls = true
if (ev.action == MotionEvent.ACTION_UP && mightWantToToggleControls)
toggleControls()
return true
}
private fun interceptKeyDown(event: KeyEvent): Boolean {
// intercept some keys to provide functionality "native" to
// mpv-android even if libmpv already implements these
var unhandeled = 0
when (event.unicodeChar.toChar()) {
// overrides a default binding:
'j' -> cycleSub()
'#' -> cycleAudio()
else -> unhandeled++
}
when (event.keyCode) {
// no default binding:
KeyEvent.KEYCODE_CAPTIONS -> cycleSub()
KeyEvent.KEYCODE_HEADSETHOOK -> player.cyclePause()
KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK -> cycleAudio()
KeyEvent.KEYCODE_INFO -> toggleControls()
// overrides a default binding:
KeyEvent.KEYCODE_MEDIA_PAUSE -> player.paused = true
KeyEvent.KEYCODE_MEDIA_PLAY -> player.paused = false
else -> unhandeled++
}
return unhandeled < 2
}
@Suppress("UNUSED_PARAMETER")
fun playPause(view: View) = player.cyclePause()
@Suppress("UNUSED_PARAMETER")
fun playlistPrev(view: View) = MPVLib.command(arrayOf("playlist-prev"))
@Suppress("UNUSED_PARAMETER")
fun playlistNext(view: View) = MPVLib.command(arrayOf("playlist-next"))
private fun showToast(msg: String) {
toast.setText(msg)
toast.show()
}
private fun resolveUri(data: Uri): String? {
val filepath = when (data.scheme) {
"file" -> data.path
"content" -> openContentFd(data)
"http", "https", "rtmp", "rtmps", "rtp", "rtsp", "mms", "mmst", "mmsh", "udp"
-> data.toString()
else -> null
}
if (filepath == null)
Log.e(TAG, "unknown scheme: ${data.scheme}")
return filepath
}
private fun openContentFd(uri: Uri): String? {
val resolver = applicationContext.contentResolver
return try {
val fd = resolver.openFileDescriptor(uri, "r")
"fdclose://${fd.detachFd()}"
} catch(e: Exception) {
Log.e(TAG, "Failed to open content fd: $e")
null
}
}
private fun parseIntentExtras(extras: Bundle?) {
onload_commands.clear()
if (extras == null)
return
// API reference: http://mx.j2inter.com/api (partially implemented)
if (extras.getByte("decode_mode") == 2.toByte())
onload_commands.add(arrayOf("set", "file-local-options/hwdec", "no"))
if (extras.containsKey("subs")) {
val subList = extras.getParcelableArray("subs")?.mapNotNull { it as? Uri } ?: emptyList()
val subsToEnable = extras.getParcelableArray("subs.enable")?.mapNotNull { it as? Uri } ?: emptyList()
for (suburi in subList) {
val subfile = resolveUri(suburi) ?: continue
val flag = if (subsToEnable.filter({ it.compareTo(suburi) == 0 }).any()) "select" else "auto"
Log.v(TAG, "Adding subtitles from intent extras: $subfile")
onload_commands.add(arrayOf("sub-add", subfile, flag))
}
}
if (extras.getInt("position", 0) > 0) {
val pos = extras.getInt("position", 0) / 1000f
onload_commands.add(arrayOf("set", "start", pos.toString()))
}
}
data class TrackData(val track_id: Int, val track_type: String)
private fun trackSwitchNotification(f: () -> TrackData) {
val (track_id, track_type) = f()
val trackPrefix = when (track_type) {
"audio" -> "Audio"
"sub" -> "Subs"
"video" -> "Video"
else -> "Unknown"
}
if (track_id == -1) {
showToast("$trackPrefix Off")
return
}
val trackName = player.tracks[track_type]?.firstOrNull{ it.mpvId == track_id }?.name ?: "???"
showToast("$trackPrefix $trackName")
}
private fun cycleAudio() = trackSwitchNotification {
player.cycleAudio(); TrackData(player.aid, "audio")
}
private fun cycleSub() = trackSwitchNotification {
player.cycleSub(); TrackData(player.sid, "sub")
}
private fun selectTrack(type: String, get: () -> Int, set: (Int) -> Unit) {
val tracks = player.tracks[type]!!
val selectedMpvId = get()
val selectedIndex = tracks.indexOfFirst { it.mpvId == selectedMpvId }
val wasPlayerPaused = player.paused ?: true // default to not changing state after switch
player.paused = true
with (AlertDialog.Builder(this)) {
setSingleChoiceItems(tracks.map { it.name }.toTypedArray(), selectedIndex) { dialog, item ->
val trackId = tracks[item].mpvId
set(trackId)
dialog.dismiss()
trackSwitchNotification { TrackData(trackId, type) }
}
setOnDismissListener { if (!wasPlayerPaused) player.paused = false }
create().show()
}
}
private fun pickAudio() = selectTrack("audio", { player.aid }, { player.aid = it })
private fun pickSub() = selectTrack("sub", { player.sid }, { player.sid = it })
@Suppress("UNUSED_PARAMETER")
fun switchDecoder(view: View) {
player.cycleHwdec()
updateDecoderButton()
}
@Suppress("UNUSED_PARAMETER")
fun cycleSpeed(view: View) {
player.cycleSpeed()
updateSpeedButton()
}
@Suppress("UNUSED_PARAMETER")
fun cycleOrientation(view: View) {
requestedOrientation = if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
}
private fun prettyTime(d: Int): String {
val hours = d / 3600
val minutes = d % 3600 / 60
val seconds = d % 60
if (hours == 0)
return "%02d:%02d".format(minutes, seconds)
return "%d:%02d:%02d".format(hours, minutes, seconds)
}
private fun refreshUi() {
// forces update of entire UI, used when returning from background playback
if (player.timePos == null)
return
updatePlaybackStatus(player.paused!!)
updatePlaybackPos(player.timePos!!)
updatePlaybackDuration(player.duration!!)
updatePlaylistButtons()
}
fun updatePlaybackPos(position: Int) {
playbackPositionTxt.text = prettyTime(position)
if (!userIsOperatingSeekbar)
playbackSeekbar.progress = position
updateDecoderButton()
updateSpeedButton()
}
private fun updatePlaybackDuration(duration: Int) {
playbackDurationTxt.text = prettyTime(duration)
if (!userIsOperatingSeekbar)
playbackSeekbar.max = duration
}
private fun updatePlaybackStatus(paused: Boolean) {
val r = if (paused) R.drawable.ic_play_arrow_black_24dp else R.drawable.ic_pause_black_24dp
playBtn.setImageResource(r)
}
private fun updateDecoderButton() {
cycleDecoderBtn.text = if (player.hwdecActive!!) "HW" else "SW"
}
private fun updateSpeedButton() {
cycleSpeedBtn.text = "${player.playbackSpeed}x"
}
private fun updatePlaylistButtons() {
val plCount = MPVLib.getPropertyInt("playlist-count") ?: 1
val plPos = MPVLib.getPropertyInt("playlist-pos") ?: 0
if (plCount == 1) {
// use View.GONE so the buttons won't take up any space
prevBtn.visibility = View.GONE
nextBtn.visibility = View.GONE
return
}
prevBtn.visibility = View.VISIBLE
nextBtn.visibility = View.VISIBLE
val g = ContextCompat.getColor(applicationContext, R.color.tint_disabled)
val w = ContextCompat.getColor(applicationContext, R.color.tint_normal)
prevBtn.imageTintList = ColorStateList.valueOf(if (plPos == 0) g else w)
nextBtn.imageTintList = ColorStateList.valueOf(if (plPos == plCount-1) g else w)
}
private fun updateOrientation(initial: Boolean = false) {
if (autoRotationMode != "auto") {
if (!initial)
return // don't reset at runtime
requestedOrientation = if (autoRotationMode == "landscape")
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
if (initial)
return
val ratio = (player.videoW ?: 0) / (player.videoH ?: 1).toFloat()
Log.v(TAG, "auto rotation: aspect ratio = ${ratio}")
if (ratio == 0f || ratio in (1f / ASPECT_RATIO_MIN) .. ASPECT_RATIO_MIN) {
// video is square, let Android do what it wants
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
return
}
requestedOrientation = if (ratio > 1f)
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
private fun eventPropertyUi(property: String) {
when (property) {
"track-list" -> player.loadTracks()
"video-params" -> updateOrientation()
}
}
private fun eventPropertyUi(property: String, value: Boolean) {
when (property) {
"pause" -> updatePlaybackStatus(value)
}
}
private fun eventPropertyUi(property: String, value: Long) {
when (property) {
"time-pos" -> updatePlaybackPos(value.toInt())
"duration" -> updatePlaybackDuration(value.toInt())
}
}
@Suppress("UNUSED_PARAMETER")
private fun eventPropertyUi(property: String, value: String) {
}
private fun eventUi(eventId: Int) {
when (eventId) {
MPVLib.mpvEventId.MPV_EVENT_PLAYBACK_RESTART -> updatePlaybackStatus(player.paused!!)
MPVLib.mpvEventId.MPV_EVENT_START_FILE -> updatePlaylistButtons()
}
}
override fun eventProperty(property: String) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property) }
}
override fun eventProperty(property: String, value: Boolean) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun eventProperty(property: String, value: Long) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun eventProperty(property: String, value: String) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun event(eventId: Int) {
// exit properly even when in background
if (playbackHasStarted && eventId == MPVLib.mpvEventId.MPV_EVENT_IDLE)
finish()
else if(eventId == MPVLib.mpvEventId.MPV_EVENT_SHUTDOWN)
finish()
if (!activityIsForeground) return
// deliberately not on the UI thread
if (eventId == MPVLib.mpvEventId.MPV_EVENT_START_FILE) {
playbackHasStarted = true
for (c in onload_commands)
MPVLib.command(c)
if (this.statsLuaMode > 0) {
MPVLib.command(arrayOf("script-binding", "stats/display-stats-toggle"))
MPVLib.command(arrayOf("script-binding", "stats/${this.statsLuaMode}"))
}
}
runOnUiThread { eventUi(eventId) }
}
private fun getInitialBrightness(): Float {
// "local" brightness first
val lp = window.attributes
if (lp.screenBrightness >= 0f)
return lp.screenBrightness
// read system pref: https://stackoverflow.com/questions/4544967//#answer-8114307
// (doesn't work with auto-brightness mode)
val resolver = applicationContext.contentResolver
return try {
Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS) / 255f
} catch (e: Settings.SettingNotFoundException) {
0.5f
}
}
private var initialSeek = 0
private var initialBright = 0f
private var initialVolume = 0
private var maxVolume = 0
override fun onPropertyChange(p: PropertyChange, diff: Float) {
when (p) {
PropertyChange.Init -> {
mightWantToToggleControls = false
initialSeek = player.timePos ?: -1
initialBright = getInitialBrightness()
initialVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
gestureTextView.visibility = View.VISIBLE
gestureTextView.text = ""
}
PropertyChange.Seek -> {
// disable seeking on livestreams and when timePos is not available
if (player.duration ?: 0 == 0 || initialSeek < 0)
return
val newPos = Math.min(Math.max(0, initialSeek + diff.toInt()), player.duration!!)
val newDiff = newPos - initialSeek
// seek faster than assigning to timePos but less precise
MPVLib.command(arrayOf("seek", newPos.toString(), "absolute", "keyframes"))
updatePlaybackPos(newPos)
val diffText = (if (newDiff >= 0) "+" else "-") + prettyTime(Math.abs(newDiff.toInt()))
gestureTextView.text = "${prettyTime(newPos)}\n[$diffText]"
}
PropertyChange.Volume -> {
val newVolume = Math.min(Math.max(0, initialVolume + (diff * maxVolume).toInt()), maxVolume)
val newVolumePercent = 100 * newVolume / maxVolume
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0)
gestureTextView.text = "V: $newVolumePercent%"
}
PropertyChange.Bright -> {
val lp = window.attributes
val newBright = Math.min(Math.max(0f, initialBright + diff), 1f)
lp.screenBrightness = newBright
window.attributes = lp
gestureTextView.text = "B: ${Math.round(newBright * 100)}%"
}
PropertyChange.Finalize -> gestureTextView.visibility = View.GONE
}
}
companion object {
private val TAG = "mpv"
// how long should controls be displayed on screen (ms)
private val CONTROLS_DISPLAY_TIMEOUT = 2000L
// size (px) of the thumbnail displayed with background play notification
private val THUMB_SIZE = 192
// smallest aspect ratio that is considered non-square
private val ASPECT_RATIO_MIN = 1.2f // covers 5:4 and up
}
}
internal class FadeOutControlsRunnable(private val activity: MPVActivity, private val controls: View) : Runnable {
override fun run() {
controls.animate().alpha(0f).setDuration(500).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
activity.initControls()
}
})
}
}
| mit | 5ea601a100d8502f773794bcff86773c | 34.9975 | 122 | 0.612265 | 4.746662 | false | false | false | false |
xaethos/tracker-notifier | app/src/main/java/net/xaethos/trackernotifier/api/TrackerClient.kt | 1 | 2574 | package net.xaethos.trackernotifier.api
import com.squareup.okhttp.Interceptor
import com.squareup.okhttp.Response
import net.xaethos.trackernotifier.BuildConfig
import net.xaethos.trackernotifier.utils.Log
import net.xaethos.trackernotifier.utils.empty
import retrofit.MoshiConverterFactory
import retrofit.Retrofit
import retrofit.RxJavaCallAdapterFactory
import java.util.concurrent.TimeUnit
class TrackerClient internal constructor(retrofit: Retrofit) {
private val authInterceptor = AuthInterceptor()
val me = retrofit.create(MeApi::class.java)
val notifications = retrofit.create(NotificationsApi::class.java)
val stories = retrofit.create(StoriesApi::class.java)
val comments = retrofit.create(CommentsApi::class.java)
init {
retrofit.client().interceptors().add(0, authInterceptor)
}
fun hasToken() = !authInterceptor.trackerToken.empty
fun setToken(trackerToken: String?) {
authInterceptor.trackerToken = trackerToken
}
private class AuthInterceptor : Interceptor {
var trackerToken: String? = null
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val token = trackerToken
if (token.empty) return chain.proceed(request)
val authorizedRequest = request.newBuilder().header("X-TrackerToken", token).build()
return chain.proceed(authorizedRequest)
}
}
private class LoggingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val startTime = System.nanoTime()
Log.v { "Sending request ${request.method()} ${request.url()}\n${request.headers()}" }
val response = chain.proceed(request)
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)
Log.v { "Received response for ${request.url()} in ${elapsed}ms\n${response.headers()}" }
return response
}
}
companion object {
val instance: TrackerClient by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://www.pivotaltracker.com/services/v5/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.build()
if (BuildConfig.DEBUG) retrofit.client().interceptors().add(LoggingInterceptor())
TrackerClient(retrofit)
}
}
}
| mit | 3f3ad17438842a1deb35d526607a7c6d | 35.253521 | 101 | 0.671717 | 4.978723 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/geometry/QuadTree.kt | 1 | 3542 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* 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 io.uuddlrlrba.ktalgs.geometry
class QuadNode<V> private constructor(
private val NW: QuadTree<V>,
private val NE: QuadTree<V>,
private val SW: QuadTree<V>,
private val SE: QuadTree<V>) : QuadTree<V> {
override val frame: Rect = Rect(NW.frame.TL, SE.frame.BR)
constructor(frame: Rect) : this(
QuadNil<V>(Rect(frame.origin, frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(Point(frame.x1 + frame.width / 2 + 1, frame.y1), frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(Point(frame.x1, frame.y1 + frame.height / 2 + 1), frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(frame.center, frame.width / 2, frame.height / 2))
)
override fun get(rect: Rect): Iterable<V> =
(if (NW.frame.intersects(rect)) NW[rect] else emptyList()) +
(if (NE.frame.intersects(rect)) NE[rect] else emptyList()) +
(if (SW.frame.intersects(rect)) SW[rect] else emptyList()) +
(if (SE.frame.intersects(rect)) SE[rect] else emptyList())
override fun plus(pair: Pair<Point, V>): QuadTree<V> = QuadNode(
if (NW.frame.isInside(pair.first)) NW + pair else NW,
if (NE.frame.isInside(pair.first)) NE + pair else NE,
if (SW.frame.isInside(pair.first)) SW + pair else SW,
if (SE.frame.isInside(pair.first)) SE + pair else SE
)
}
class QuadLeaf<V>(override val frame: Rect, val value: Pair<Point, V>) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> =
if (rect.isInside(value.first)) listOf(value.second)
else emptyList()
override fun plus(pair: Pair<Point, V>): QuadTree<V> = QuadNode<V>(frame.cover(pair.first)) + value + pair
}
class QuadNil<V>(override val frame: Rect) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> = emptyList()
override fun plus(pair: Pair<Point, V>): QuadLeaf<V> = QuadLeaf(frame.cover(pair.first), value = pair)
}
interface QuadTree<V> {
val frame: Rect
operator fun get(rect: Rect): Iterable<V>
operator fun plus(pair: Pair<Point, V>): QuadTree<V>
}
fun<V> emptyQuadTree(frame: Rect): QuadTree<V> = QuadNil(frame)
fun<V> quadTreeOf(frame: Rect, vararg pairs: Pair<Point, V>): QuadTree<V> {
var empty = emptyQuadTree<V>(frame)
for (pair in pairs) {
empty += pair
}
return empty
}
| mit | b66bd904eb68283ae92b9d00c171c63a | 43.835443 | 114 | 0.661208 | 3.712788 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockEditDialog.kt | 1 | 3733 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.adblock.ui.original
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.InputType
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import androidx.fragment.app.DialogFragment
import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock
import jp.hazuki.yuzubrowser.core.utility.extensions.density
class AdBlockEditDialog : DialogFragment() {
private var listener: AdBlockEditDialogListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val params = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
val density = activity!!.density
val marginWidth = (4 * density + 0.5f).toInt()
val marginHeight = (16 * density + 0.5f).toInt()
params.setMargins(marginWidth, marginHeight, marginWidth, marginHeight)
val editText = EditText(activity).apply {
layoutParams = params
id = android.R.id.edit
inputType = InputType.TYPE_CLASS_TEXT
}
val arguments = arguments ?: throw NullPointerException()
val text = arguments.getString(ARG_TEXT)
if (!text.isNullOrEmpty())
editText.setText(text)
return AlertDialog.Builder(activity)
.setView(editText)
.setTitle(arguments.getString(ARG_TITLE))
.setPositiveButton(android.R.string.ok) { _, _ ->
listener!!.onEdited(
arguments.getInt(ARG_INDEX, -1),
arguments.getInt(ARG_ID, -1),
editText.text.toString())
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
override fun onAttach(context: Context) {
super.onAttach(context)
listener = if (parentFragment is AdBlockEditDialogListener) {
parentFragment as AdBlockEditDialogListener
} else {
activity as AdBlockEditDialogListener
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
internal interface AdBlockEditDialogListener {
fun onEdited(index: Int, id: Int, text: String)
}
companion object {
private const val ARG_TITLE = "title"
private const val ARG_INDEX = "index"
private const val ARG_ID = "id"
private const val ARG_TEXT = "text"
operator fun invoke(title: String, index: Int = -1, adBlock: AdBlock? = null): AdBlockEditDialog {
return AdBlockEditDialog().apply {
arguments = Bundle().apply {
putString(ARG_TITLE, title)
putInt(ARG_INDEX, index)
if (adBlock != null) {
putInt(ARG_ID, adBlock.id)
putString(ARG_TEXT, adBlock.match)
}
}
}
}
}
}
| apache-2.0 | b9381d664f4555727dd66469de658f5b | 34.552381 | 106 | 0.622288 | 4.873368 | false | false | false | false |
virvar/magnetic-ball-2 | MagneticBallLogic/src/main/kotlin/ru/virvar/apps/magneticBall2/blocksGenerators/OnLineBlocksGenerator.kt | 1 | 2822 | package ru.virvar.apps.magneticBall2.blocksGenerators
import ru.virvar.apps.magneticBall2.MagneticBallLevel
import ru.virvar.apps.magneticBall2.blocks.SquareBlock
import ru.virvar.apps.magneticBall2.blocks.TriangleBlock
import ru.virvar.apps.magneticBallCore.Block
import ru.virvar.apps.magneticBallCore.IBlocksGenerator
import ru.virvar.apps.magneticBallCore.Level
import ru.virvar.apps.magneticBallCore.Point2D
import java.util.*
class OnLineBlocksGenerator(val blocksCount: Int = 20) : IBlocksGenerator {
override fun generateInitialBlocks(level: Level) {
generateBlocks(level, blocksCount)
}
private fun generateBlocks(level: Level, count: Int) {
for (i in 0..count - 1) {
if (level.freeCells.size != 0) {
val block = createRandomBlock()
val positionIndex = random.nextInt(level.freeCells.size)
val position = level.freeCells[positionIndex]
block.x = position % level.fieldSize
block.y = Math.floor((position.toDouble() / level.fieldSize)).toInt()
level.addBlock(block)
}
}
}
override fun generateBlocks(level: Level) {
val onLineFreeCells = getOnLineFreeCells(level)
while (level.blocks.size <= blocksCount) {
if (onLineFreeCells.size == 0) {
generateBlocks(level, blocksCount - level.blocks.size + 1)
} else {
val block = createRandomBlock()
val positionIndex = random.nextInt(onLineFreeCells.size)
val position = onLineFreeCells[positionIndex]
onLineFreeCells.remove(position)
block.x = position.x
block.y = position.y
level.addBlock(block)
}
}
}
private fun getOnLineFreeCells(level: Level): LinkedList<Point2D> {
val player = (level as MagneticBallLevel).player
val onLineFreeCells = LinkedList<Point2D>()
for (i in 0..level.fieldSize - 1) {
if (level.getBlock(player.x, i) == null) {
onLineFreeCells.add(Point2D(player.x, i))
}
}
for (i in 0..level.fieldSize - 1) {
if (level.getBlock(i, player.y) == null) {
onLineFreeCells.add(Point2D(i, player.y))
}
}
return onLineFreeCells
}
private fun createRandomBlock(): Block {
var block: Block? = null
var blockType = random.nextInt(2)
when (blockType) {
0 ->
block = SquareBlock()
1 -> {
val direction = random.nextInt(4)
block = TriangleBlock(TriangleBlock.ReflectionDirection.values().get(direction))
}
}
return block!!
}
}
| gpl-2.0 | 729b8458bb02516dfe0634b803c91bd3 | 36.105263 | 96 | 0.597518 | 4.454976 | false | false | false | false |
wizardofos/Protozoo | extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt | 1 | 3381 | package org.jetbrains.exposed.sql.statements
import org.jetbrains.exposed.sql.*
import java.sql.PreparedStatement
import java.sql.ResultSet
/**
* isIgnore is supported for mysql only
*/
open class InsertStatement<Key:Any>(val table: Table, val isIgnore: Boolean = false) : UpdateBuilder<Int>(StatementType.INSERT, listOf(table)) {
open protected val flushCache = true
var generatedKey: Key? = null
infix operator fun <T:Key> get(column: Column<T>): T = generatedKey as? T ?: error("No key generated")
open protected fun generatedKeyFun(rs: ResultSet, inserted: Int) : Key? {
return table.columns.firstOrNull { it.columnType.isAutoInc }?.let { column ->
if (rs.next()) {
@Suppress("UNCHECKED_CAST")
column.columnType.valueFromDB(rs.getObject(1)) as? Key
} else null
}
}
protected fun valuesAndDefaults(): Map<Column<*>, Any?> {
val columnsWithNotNullDefault = targets.flatMap { it.columns }.filter {
(it.dbDefaultValue != null || it.defaultValueFun != null) && !it.columnType.nullable && it !in values.keys
}
return values + columnsWithNotNullDefault.map { it to (it.defaultValueFun?.invoke() ?: DefaultValueMarker) }
}
override fun prepareSQL(transaction: Transaction): String {
val builder = QueryBuilder(true)
val values = valuesAndDefaults()
val sql = if(values.isEmpty()) ""
else values.entries.joinToString(prefix = "VALUES (", postfix = ")") {
val (col, value) = it
when (value) {
is Expression<*> -> value.toSQL(builder)
DefaultValueMarker -> col.dbDefaultValue!!.toSQL(builder)
else -> builder.registerArgument(col.columnType, value)
}
}
return transaction.db.dialect.insert(isIgnore, table, values.map { it.key }, sql, transaction)
}
override fun PreparedStatement.executeInternal(transaction: Transaction): Int {
if (flushCache)
transaction.flushCache()
transaction.entityCache.removeTablesReferrers(listOf(table))
val inserted = if (arguments().count() > 1 || isAlwaysBatch) executeBatch().sum() else executeUpdate()
return inserted.apply {
generatedKeys?.let {
generatedKey = generatedKeyFun(it, this)
}
}
}
override fun prepared(transaction: Transaction, sql: String): PreparedStatement {
val autoincs = targets.flatMap { it.columns }.filter { it.columnType.isAutoInc }
return if (autoincs.isNotEmpty()) {
// http://viralpatel.net/blogs/oracle-java-jdbc-get-primary-key-insert-sql/
transaction.connection.prepareStatement(sql, autoincs.map { transaction.identity(it) }.toTypedArray())!!
} else {
transaction.connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)!!
}
}
override fun arguments() = QueryBuilder(true).run {
valuesAndDefaults().forEach {
val value = it.value
when (value) {
is Expression<*> -> value.toSQL(this)
DefaultValueMarker -> {}
else -> registerArgument(it.key.columnType, value)
}
}
if (args.isNotEmpty()) listOf(args.toList()) else emptyList()
}
}
| mit | db18494604ec956a78a20bde68090bd5 | 41.797468 | 144 | 0.624963 | 4.544355 | false | false | false | false |
SoulBeaver/Arena--7DRL- | src/main/java/com/sbg/arena/core/animation/ToggleWallAnimation.kt | 1 | 1560 | package com.sbg.arena.core.animation
import com.sbg.arena.core.input.ToggleWallRequest
import com.sbg.arena.core.level.Skin
import org.newdawn.slick.Graphics
import kotlin.properties.Delegates
import org.newdawn.slick.Image
import com.sbg.arena.core.level.FloorType
import org.newdawn.slick.Color
class ToggleWallAnimation(val request: ToggleWallRequest, val onAnimationFinished: () -> Unit): Animation {
private var floorSkin: Image by Delegates.notNull()
private var wallSkin: Image by Delegates.notNull()
private var current = 1F
override fun initialize(levelSkin: Skin) {
floorSkin = levelSkin.floorTile()
wallSkin = levelSkin.wallTile()
request.level.toggleFloor(request.target)
}
override fun update() {
current -= 0.02F
}
override fun render(graphics: Graphics) {
when (request.level[request.target]) {
FloorType.Floor -> wallSkin.draw(request.target.x.toFloat() * 20,
request.target.y.toFloat() * 20,
Color(1F, 1F, 1F, current))
FloorType.Wall -> floorSkin.draw(request.target.x.toFloat() * 20,
request.target.y.toFloat() * 20,
Color(1F, 1F, 1F, current))
}
}
override fun isFinished(): Boolean {
return current <= 0F
}
override fun finish() {
request.level.toggleFloor(request.target)
onAnimationFinished()
}
} | apache-2.0 | 72e0a30e132b5a8dad2900d242d4aa70 | 32.212766 | 107 | 0.60641 | 4.216216 | false | false | false | false |
AlmasB/FXGL | fxgl-samples/src/main/kotlin/sandbox/view/AASubdivision.kt | 1 | 3317 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.view
import com.almasb.fxgl.core.collection.Array
import com.almasb.fxgl.core.math.FXGLMath
import com.almasb.fxgl.core.math.FXGLMath.random
import com.almasb.fxgl.core.math.FXGLMath.randomBoolean
import javafx.geometry.Rectangle2D
/**
* Axis-aligned 2D space subdivision.
*
* @author Almas Baimagambetov ([email protected])
*/
object AASubdivision {
/**
* Subdivides given 2D space ([rect]) into maximum of n = [maxSubspaces] such that
* each subspace has width and height no less than [minSize].
*/
@JvmStatic fun divide(rect: Rectangle2D, maxSubspaces: Int, minSize: Int): Array<Rectangle2D> {
// keeps currently being processed subspaces
val grids = arrayListOf<Rectangle2D>(rect)
val result = Array<Rectangle2D>(maxSubspaces)
for (i in 1..maxSubspaces -1) {
var grid: Rectangle2D
var divisible: Pair<Boolean, Boolean>
do {
if (grids.isEmpty())
throw RuntimeException("Cannot subdivide")
grid = grids[random(0, grids.size-1)]
grids.remove(grid)
divisible = isDivisible(grid, minSize)
} while (!divisible.first && !divisible.second)
// grid is about to be subdivided, so remove from result list
result.removeValueByIdentity(grid)
var pair: Pair<Rectangle2D, Rectangle2D>
// we know at least 1 side is divisible
// if both are valid, then flip a coin
if (divisible.first && divisible.second) {
pair = if (randomBoolean()) subdivideHorizontal(grid, minSize) else subdivideVertical(grid, minSize)
} else if (divisible.first) {
// only horizontally divisible
pair = subdivideHorizontal(grid, minSize)
} else {
// only vertically divisible
pair = subdivideVertical(grid, minSize)
}
// push divided items to tmp and result list
grids.add(pair.first)
grids.add(pair.second)
result.addAll(pair.first, pair.second)
}
return result
}
private fun isDivisible(grid: Rectangle2D, minSize: Int): Pair<Boolean, Boolean> {
val horizontal = grid.width / 2 >= minSize
val vertical = grid.height / 2 >= minSize
return horizontal.to(vertical)
}
private fun subdivideVertical(grid: Rectangle2D, minSize: Int): Pair<Rectangle2D, Rectangle2D> {
val lineY = random(grid.minY.toInt() + minSize, grid.maxY.toInt() - minSize).toDouble()
return Rectangle2D(grid.minX, grid.minY, grid.width, lineY - grid.minY)
.to(Rectangle2D(grid.minX, lineY, grid.width, grid.maxY - lineY))
}
private fun subdivideHorizontal(grid: Rectangle2D, minSize: Int): Pair<Rectangle2D, Rectangle2D> {
val lineX = random(grid.minX.toInt() + minSize, grid.maxX.toInt() - minSize).toDouble()
return Rectangle2D(grid.minX, grid.minY, lineX - grid.minX, grid.height)
.to(Rectangle2D(lineX, grid.minY, grid.maxX - lineX, grid.height))
}
} | mit | b8159b8c1774b7933db03872bb013835 | 33.926316 | 116 | 0.624058 | 4.13591 | false | false | false | false |
redpen-cc/redpen-intellij-plugin | src/cc/redpen/intellij/SingleCharEditor.kt | 1 | 846 | package cc.redpen.intellij
import java.awt.Color
import javax.swing.DefaultCellEditor
import javax.swing.JComponent
import javax.swing.JTextField
import javax.swing.border.LineBorder
import javax.swing.text.AttributeSet
import javax.swing.text.PlainDocument
internal class SingleCharEditor : DefaultCellEditor(JTextField(SingleCharEditor.SingleCharDocument(), null, 1)) {
init {
(component as JComponent).border = LineBorder(Color.black)
}
override fun stopCellEditing(): Boolean {
return (component as JTextField).text.length == 1 && super.stopCellEditing()
}
internal class SingleCharDocument : PlainDocument() {
override fun insertString(offset: Int, str: String?, a: AttributeSet?) {
if (str != null && str.length + length == 1) super.insertString(offset, str, a)
}
}
}
| apache-2.0 | 4e73b80efff8be55cd659490fecd17c8 | 32.84 | 113 | 0.72104 | 4.208955 | false | false | false | false |
mpecan/chat | src/main/kotlin/si/pecan/services/ChatService.kt | 1 | 3167 | package si.pecan.services
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.stereotype.Service
import si.pecan.*
import si.pecan.dto.Message
import si.pecan.dto.toDto
import si.pecan.model.ChatRoom
import si.pecan.dto.ChatRoom as Dto
import si.pecan.model.InstantMessage
import si.pecan.model.User
import java.time.LocalDateTime
import java.util.*
import javax.transaction.Transactional
import kotlin.experimental.and
@Service
class ChatService(private val userRepository: UserRepository,
private val chatRoomRepository: ChatRoomRepository,
private val instantMessageRepository: InstantMessageRepository,
private val simpMessagingTemplate: SimpMessagingTemplate) {
@Transactional
fun getOrCreateChat(initiatorUsername: String, targetUsername: String): Dto {
val target = userRepository.findByUsername(targetUsername) ?: throw UserNotFound()
val initiator = userRepository.save(userRepository.findByUsername(initiatorUsername)?.apply {
lastActive = LocalDateTime.now()
} ?: throw UserNotFound())
val chatRoom = initiator.chatRooms.find { it.users.any { it == target } } ?: chatRoomRepository.save(ChatRoom().apply {
users = arrayListOf(initiator, target)
createdBy = initiator
})
val theDto = chatRoom.toDto()
chatRoom.users.forEach { simpMessagingTemplate.convertAndSend("/topic/rooms/${it.username}", theDto) }
return theDto
}
fun ChatRoom.toDto(): si.pecan.dto.ChatRoom {
return Dto(
this.id!!,
this.createdBy.toDto(),
this.users.find { it != this.createdBy }!!.toDto(),
this.messages.map(InstantMessage::toDto),
this.created,
if (this.messages.isEmpty()) null else this.messages.last().created
)
}
@Transactional
fun postMessage(username: String, chatId: UUID, messageContent: String): Message {
val chat = chatRoomRepository.findOne(chatId) ?: throw ChatNotFound()
val user = chat.users.find { it.username == username } ?: throw UserNotAllowedToAccessChat()
return instantMessageRepository.save(InstantMessage().apply {
room = chat
content = messageContent
postedBy = user
}).toDto().apply {
this.chatId = chatId
this.postedByUser = userRepository.save(user.apply { lastActive = LocalDateTime.now()}).toDto()
}
}
fun getAllRooms(username: String): List<Dto> = chatRoomRepository
.findChatRoomIds(username)
.map {
var msb: Long = 0
var lsb: Long = 0
assert(it.size == 16) { "data must be 16 bytes in length" }
for (i in 0..7)
msb = (msb shl 8) or (it[i].toLong() and 0xff)
for (i in 8..15)
lsb = (lsb shl 8) or (it[i].toLong() and 0xff)
UUID(msb, lsb)
}
.let { chatRoomRepository.findAll(it) }
.map { it.toDto() }
} | apache-2.0 | 2b67b22dfbb7c37a1b7acd746afea0fc | 38.111111 | 127 | 0.625513 | 4.677991 | false | false | false | false |
ajalt/clikt | samples/helpformat/src/main/kotlin/com/github/ajalt/clikt/samples/helpformat/main.kt | 1 | 1875 | package com.github.ajalt.clikt.samples.helpformat
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.output.CliktHelpFormatter
import com.github.ajalt.clikt.output.HelpFormatter
import com.github.ajalt.clikt.output.Localization
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
class ArgparseLocalization : Localization {
override fun usageTitle(): String = "usage:"
override fun optionsTitle(): String = "optional arguments:"
override fun argumentsTitle(): String = "positional arguments:"
}
class ArgparseHelpFormatter : CliktHelpFormatter(ArgparseLocalization()) {
override fun formatHelp(
prolog: String,
epilog: String,
parameters: List<HelpFormatter.ParameterHelp>,
programName: String,
) = buildString {
// argparse prints arguments before options
addUsage(parameters, programName)
addProlog(prolog)
addArguments(parameters)
addOptions(parameters)
addCommands(parameters)
addEpilog(epilog)
}
}
class Echo : CliktCommand(help = "Echo the STRING(s) to standard output") {
init {
context { helpFormatter = ArgparseHelpFormatter() }
}
val suppressNewline by option("-n", help = "do not output the trailing newline").flag()
val strings by argument(help = "the strings to echo").multiple()
override fun run() {
val message = if (strings.isEmpty()) String(System.`in`.readBytes())
else strings.joinToString(" ", postfix = if (suppressNewline) "" else "\n")
echo(message, trailingNewline = false)
}
}
fun main(args: Array<String>) = Echo().main(args)
| apache-2.0 | ce0e34c6fbfcd99cab2346f4756ce803 | 35.764706 | 91 | 0.717867 | 4.280822 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/google/GoogleExamplesDocument.kt | 1 | 4894 | package cn.yiiguxing.plugin.translate.trans.google
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.trans.text.TranslationDocument
import cn.yiiguxing.plugin.translate.ui.StyledViewer
import cn.yiiguxing.plugin.translate.util.chunked
import cn.yiiguxing.plugin.translate.util.text.*
import com.intellij.ui.JBColor
import com.intellij.ui.scale.JBUIScale
import icons.TranslationIcons
import java.awt.Color
import javax.swing.text.*
class GoogleExamplesDocument private constructor(private val examples: List<List<CharSequence>>) : TranslationDocument {
override val text: String
get() = examples.joinToString("\n") { it.joinToString("") }
override fun applyTo(viewer: StyledViewer) {
viewer.styledDocument.apply {
initStyle()
val startOffset = length
appendExamples()
setParagraphStyle(startOffset, length - startOffset, EXAMPLE_PARAGRAPH_STYLE, false)
}
}
private fun StyledDocument.appendExamples() {
appendExample(examples.first(), false)
if (examples.size > 1) {
newLine()
val startOffset = length
val foldingAttr = SimpleAttributeSet(getStyle(EXAMPLE_FOLDING_STYLE))
StyledViewer.StyleConstants.setMouseListener(foldingAttr, createFoldingMouseListener(examples.drop(1)))
val placeholder = " " + message("title.google.document.examples.show.all", examples.size) + " "
appendString(placeholder, foldingAttr)
setParagraphStyle(startOffset, placeholder.length, EXAMPLE_FOLDING_PARAGRAPH_STYLE, false)
}
}
private fun StyledDocument.appendExample(example: List<CharSequence>, newLine: Boolean = true) {
if (newLine) {
newLine()
}
appendString(" ", ICON_QUOTE_STYLE)
appendString("\t")
for (ex in example) {
appendCharSequence(ex)
}
}
private fun createFoldingMouseListener(foldedExamples: List<List<CharSequence>>): StyledViewer.FoldingMouseListener {
return StyledViewer.FoldingMouseListener(foldedExamples) { viewer, element, _ ->
viewer.styledDocument.apply {
remove(element.startOffset - 1, element.rangeSize + 1)
val startOffset = length
examples.drop(1).forEach { appendExample(it) }
setParagraphStyle(startOffset, length - startOffset, EXAMPLE_PARAGRAPH_STYLE, true)
}
}
}
override fun toString(): String = text
companion object : TranslationDocument.Factory<GExamples?, GoogleExamplesDocument> {
private val BOLD_REGEX = Regex("<b>(.+?)</b>")
private const val EXAMPLE_PARAGRAPH_STYLE = "g_example_p_style"
private const val ICON_QUOTE_STYLE = "g_example_icon_quote_style"
private const val EXAMPLE_BOLD_STYLE = "g_example_bold_style"
private const val EXAMPLE_FOLDING_STYLE = "g_example_folding_style"
private const val EXAMPLE_FOLDING_PARAGRAPH_STYLE = "g_example_folding_ps"
override fun getDocument(input: GExamples?): GoogleExamplesDocument? {
if (input == null || input.examples.isEmpty()) {
return null
}
val examples = input.examples.asSequence()
.map { (example) ->
example.chunked(BOLD_REGEX) { StyledString(it.groupValues[1], EXAMPLE_BOLD_STYLE) }
}
.toList()
return GoogleExamplesDocument(examples)
}
private fun StyledDocument.initStyle() {
val defaultStyle = getStyle(StyleContext.DEFAULT_STYLE)
getStyleOrAdd(EXAMPLE_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setTabSet(style, TabSet(arrayOf(TabStop(JBUIScale.scale(5f)))))
StyleConstants.setForeground(style, JBColor(0x606060, 0xBBBDBF))
}
getStyleOrAdd(EXAMPLE_BOLD_STYLE, defaultStyle) { style ->
StyleConstants.setBold(style, true)
StyleConstants.setForeground(style, JBColor(0x555555, 0xC8CACC))
}
getStyleOrAdd(ICON_QUOTE_STYLE) { style ->
StyleConstants.setIcon(style, TranslationIcons.Quote)
}
getStyleOrAdd(EXAMPLE_FOLDING_STYLE, defaultStyle) { style ->
StyleConstants.setFontSize(style, getFont(style).size - 1)
StyleConstants.setForeground(style, JBColor(0x777777, 0x888888))
val background = JBColor(Color(0, 0, 0, 0x18), Color(0xFF, 0xFF, 0xFF, 0x10))
StyleConstants.setBackground(style, background)
}
getStyleOrAdd(EXAMPLE_FOLDING_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setSpaceAbove(style, JBUIScale.scale(8f))
}
}
}
} | mit | d8695a46376b5bc9f7ff791d72d91606 | 42.318584 | 121 | 0.64385 | 4.652091 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/adapter/KHomeAdapter.kt | 1 | 2924 | package ycj.com.familyledger.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import org.jetbrains.anko.find
import ycj.com.familyledger.R
import ycj.com.familyledger.bean.LedgerBean
/**
* @author: ycj
* @date: 2017-06-14 10:53
* @version V1.0 <>
*/
class KHomeAdapter : RecyclerView.Adapter<KHomeAdapter.MyViewHolder> {
private var mContext: Context
private var dataList: ArrayList<LedgerBean>
constructor(dataList: ArrayList<LedgerBean>, context: Context) {
this.mContext = context
this.dataList = dataList
}
override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
holder!!.tvTitle.text = mContext.getString(R.string.date) + " " + dataList[position].consume_date
holder.tvContent.text = mContext.getString(R.string.cash) + " " + dataList[position].consume_money
holder.tvPhone.text = dataList[position].user_id.toString()
holder.ly.setOnClickListener {
if (listener != null) {
listener!!.onItemClickListener(position)
}
}
holder.ly.setOnLongClickListener({
if (listener != null) {
listener!!.onItemLongClickListener(position)
}
true
})
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.list_item_home, parent, false))
}
override fun getItemCount(): Int {
return dataList.size
}
class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
var tvTitle: TextView = itemView!!.find(R.id.t_title_home)
var tvContent: TextView = itemView!!.find(R.id.t_content_home)
var tvPhone: TextView = itemView!!.find(R.id.tv_phone_home)
var ly: LinearLayout = itemView!!.find(R.id.ly_list_item_home)
var fy: FrameLayout = itemView!!.find(R.id.fy_list_item_home)
}
private var listener: ItemClickListener? = null
fun setOnItemClickListener(listener: ItemClickListener) {
this.listener = listener
}
interface ItemClickListener {
fun onItemClickListener(position: Int)
fun onItemLongClickListener(position: Int)
}
fun addNewItem(position: Int, data: LedgerBean) {
if (position >= dataList.size) return
dataList.add(position, data)
notifyItemInserted(position)
}
fun setDatas(data: List<LedgerBean>) {
if (data.size == 0) return
dataList.clear()
dataList.addAll(data)
notifyDataSetChanged()
}
fun clearData() {
dataList.clear()
notifyDataSetChanged()
}
} | apache-2.0 | bf49f2a113a95cb85469a819a52354a5 | 29.46875 | 107 | 0.667579 | 4.357675 | false | false | false | false |
MHP-A-Porsche-Company/CDUI-Showcase-Android | app/src/main/kotlin/com/mhp/showcase/network/GetArticleNetworkService.kt | 1 | 1841 | package com.mhp.showcase.network
import android.os.Handler
import android.util.Log
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.google.gson.Gson
import com.mhp.showcase.ShowcaseApplication
import com.mhp.showcase.network.model.ContentResponse
import com.mhp.showcase.util.Constants
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import javax.inject.Inject
/**
* Network service to get the definition of blocks for the home screen
*/
class GetArticleNetworkService {
private val tag = GetArticleNetworkService::class.java.simpleName
@Inject
internal lateinit var requestQueue: RequestQueue
@Inject
internal lateinit var gson: Gson
fun getBlocks(id: String): Observable<ContentResponse> {
return Observable.create<ContentResponse>({ it ->
this.startRequesting(e = it, id = id)
})
}
private fun startRequesting(id: String, e: ObservableEmitter<ContentResponse>) {
if (e.isDisposed) {
return
}
val jsObjRequest = JsonObjectRequest(
Request.Method.GET,
Constants.URL_ARTICLE + "-" + id + ".json", null,
Response.Listener {
val blockResponse = gson.fromJson(it.toString(), ContentResponse::class.java)
e.onNext(blockResponse)
Handler().postDelayed({ startRequesting(id, e) }, 2000)
},
Response.ErrorListener {
Log.d(tag, "Network error occurred", it)
}
)
jsObjRequest.setShouldCache(false)
requestQueue.add(jsObjRequest)
}
init {
ShowcaseApplication.graph.inject(this)
}
} | mit | f61fe001d02616cdf8f62be8a2fec5d5 | 29.7 | 97 | 0.659424 | 4.614035 | false | false | false | false |
eugeis/ee | ee-task_des/src/main/kotlin/ee/task/Task.kt | 1 | 3353 | package ee.task
import ee.design.*
import ee.lang.*
object Task : Comp({ namespace("ee.task") }) {
object shared : Module() {
object TaskGroup : Entity() {
val taskFactories = prop(n.List.GT(TaskFactory))
val tasks = prop(n.List.GT(Task))
}
object Result : Values({ base(true) }) {
val action = prop()
val ok = prop { type(n.Boolean).value(true).open(true) }
val failure = prop()
val info = prop()
val error = prop { type(n.Error).nullable(true) }
val results = prop { type(n.List.GT(Result)).mutable(false) }
}
object Task : Controller() {
val name = prop()
val group = prop()
val execute = op {
p { type(lambda { p { name("line") } }).name("output") }
ret(Result)
}
}
object TaskResult : Values() {
val task = prop(Task)
val result = prop(Result)
}
object TaskFactory : Controller() {
val T = G(Task)
val name = prop()
val group = prop()
val supports = op {
p { type(n.List.GT(l.Item)).nullable(false).name("items") }
ret(n.Boolean)
}
val create = op {
p { type(n.List.GT(l.Item)).nullable(false).name("items") }
ret(n.List.GT(T))
}
}
object TaskRepository : Controller() {
val typeFactories = prop(n.List.GT(TaskFactory))
val register = op {
val V = G { type(TaskFactory).name("V") }
p { type(V).nullable(false).initByDefaultTypeValue(false).name("factory") }
}
val find = op {
val T = G { type(l.Item).name("T") }
p { type(n.List.GT(T)).initByDefaultTypeValue(false).name("items") }
ret(n.List.GT(TaskFactory))
}
}
object PathResolver : Controller() {
val home = prop(n.Path)
val itemToHome = prop(n.Map.GT(n.String, n.String))
val resolve = op {
val T = G { type(l.Item).name("T") }
p { type(T).nullable(false).initByDefaultTypeValue(false).name("addItem") }
ret(n.Path)
}
}
object TaskRegistry : Controller() {
val pathResolver = prop(PathResolver)
val register = op {
p { type(TaskRepository).name("repo") }
}
}
object ExecConfig : Values() {
val home = prop(n.Path)
val cmd = prop { type(n.List.GT(n.String)).mutable(false) }
val env = prop { type(n.Map.GT(n.String, n.String)).mutable(false) }
val filterPattern = prop { defaultValue(".*(\\.{4}|exception|error|fatal|success).*") }
val failOnError = prop { type(n.Boolean).value(false) }
val filter = prop { type(n.Boolean).value(false) }
val noConsole = prop { type(n.Boolean).value(false) }
val wait = prop { type(n.Boolean).value(true) }
val timeout = prop { type(n.Long).value(30.seconds) }
val timeoutUnit = prop { type(n.TimeUnit).value(n.TimeUnit.Seconds) }
}
}
}
| apache-2.0 | 88c21b19ce5367c2fab1ae051505ffe8 | 33.214286 | 99 | 0.487325 | 4.059322 | false | false | false | false |
google-home/sample-app-for-matter-android | app/src/main/java/com/google/homesampleapp/data/DevicesRepository.kt | 1 | 3748 | /*
* 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 com.google.homesampleapp.data
import android.content.Context
import com.google.homesampleapp.Device
import com.google.homesampleapp.Devices
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import timber.log.Timber
/**
* Singleton repository that updates and persists the set of devices in the homesampleapp fabric.
*/
@Singleton
class DevicesRepository @Inject constructor(@ApplicationContext context: Context) {
// The datastore managed by DevicesRepository.
private val devicesDataStore = context.devicesDataStore
// The Flow to read data from the DataStore.
val devicesFlow: Flow<Devices> =
devicesDataStore.data.catch { exception ->
// dataStore.data throws an IOException when an error is encountered when reading data
if (exception is IOException) {
Timber.e(exception, "Error reading devices.")
emit(Devices.getDefaultInstance())
} else {
throw exception
}
}
suspend fun incrementAndReturnLastDeviceId(): Long {
val newLastDeviceId = devicesFlow.first().lastDeviceId + 1
Timber.d("incrementAndReturnLastDeviceId(): newLastDeviceId [${newLastDeviceId}] ")
devicesDataStore.updateData { devices ->
devices.toBuilder().setLastDeviceId(newLastDeviceId).build()
}
return newLastDeviceId
}
suspend fun addDevice(device: Device) {
Timber.d("addDevice: device [${device}]")
devicesDataStore.updateData { devices -> devices.toBuilder().addDevices(device).build() }
}
suspend fun updateDevice(device: Device) {
Timber.d("updateDevice: device [${device}]")
val index = getIndex(device.deviceId)
devicesDataStore.updateData { devices -> devices.toBuilder().setDevices(index, device).build() }
}
suspend fun removeDevice(deviceId: Long) {
Timber.d("removeDevice: device [${deviceId}]")
val index = getIndex(deviceId)
if (index == -1) {
throw Exception("Device not found: $deviceId")
}
devicesDataStore.updateData { devicesList ->
devicesList.toBuilder().removeDevices(index).build()
}
}
suspend fun getLastDeviceId(): Long {
return devicesFlow.first().lastDeviceId
}
suspend fun getDevice(deviceId: Long): Device {
val devices = devicesFlow.first()
val index = getIndex(devices, deviceId)
if (index == -1) {
throw Exception("Device not found: $deviceId")
}
return devices.getDevices(index)
}
suspend fun getAllDevices(): Devices {
return devicesFlow.first()
}
private suspend fun getIndex(deviceId: Long): Int {
val devices = devicesFlow.first()
return getIndex(devices, deviceId)
}
private fun getIndex(devices: Devices, deviceId: Long): Int {
val devicesCount = devices.devicesCount
for (index in 0 until devicesCount) {
val device = devices.getDevices(index)
if (deviceId == device.deviceId) {
return index
}
}
return -1
}
}
| apache-2.0 | 2deb7149fb5c04eb3e4214520295259e | 31.591304 | 100 | 0.713714 | 4.52111 | false | false | false | false |
jsargent7089/android | src/main/java/com/nextcloud/client/network/Connectivity.kt | 2 | 1314 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.network
data class Connectivity(
val isConnected: Boolean = false,
val isMetered: Boolean = false,
val isWifi: Boolean = false,
val isServerAvailable: Boolean? = null
) {
companion object {
@JvmField
val DISCONNECTED = Connectivity()
@JvmField
val CONNECTED_WIFI = Connectivity(
isConnected = true,
isMetered = false,
isWifi = true,
isServerAvailable = true
)
}
}
| gpl-2.0 | ac4493112fed7787f6a2ec56f72e3e24 | 31.85 | 78 | 0.688737 | 4.515464 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.