repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tomsteele/burpbuddy | src/main/kotlin/burp/BurpToBuddy.kt | 1 | 5837 | package burp
import com.github.salomonbrys.kotson.jsonArray
import com.github.salomonbrys.kotson.jsonObject
import com.google.gson.JsonArray
import com.google.gson.JsonObject
class BurpToBuddy(private val callbacks: IBurpExtenderCallbacks) {
private fun httpMessagesToJsonArray(httpMessages: Array<IHttpRequestResponse>) : JsonArray {
val messages = jsonArray()
for (message in httpMessages) {
messages.add(httpRequestResponseToJsonObject(message))
}
return messages
}
private fun httpRequestToJsonObject(request: ByteArray) : JsonObject {
val reqInfo = callbacks.helpers.analyzeRequest(request)
val allHeaders = reqInfo.headers
val headers = allHeaders.subList(1, allHeaders.size)
val headersJson = jsonObject()
for (header in headers) {
val values = header.split(":".toRegex(), 2).toTypedArray()
if (values.size == 2) {
headersJson.addProperty(values[0].trim({ it <= ' ' }), values[1].trim({ it <= ' ' }))
}
}
val firstHeader = allHeaders[0].split(" ")
var httpVersion = "0"
var path = ""
if (firstHeader.size == 3) {
httpVersion = firstHeader[2].trim({ it <= ' ' })
path = firstHeader[1].trim({ it <= ' ' })
}
return jsonObject(
"method" to reqInfo.method,
"path" to path,
"http_version" to httpVersion,
"headers" to headersJson,
"raw" to callbacks.helpers.base64Encode(request),
"size" to request.size,
"body" to callbacks.helpers.base64Encode(java.util.Arrays.copyOfRange(request, reqInfo.bodyOffset, request.size)),
"body_offset" to reqInfo.bodyOffset
)
}
private fun cookiesToJsonArray(icookies: List<ICookie>) : JsonArray {
val cookies = jsonArray()
for (cookie in icookies) {
var expiration = ""
if (cookie.expiration != null)
expiration = cookie.expiration.toString()
cookies.add(jsonObject(
"domain" to cookie.domain,
"expiration" to expiration,
"path" to cookie.path,
"name" to cookie.name,
"value" to cookie.value
))
}
return cookies
}
private fun httpResponseToJsonObject(response: ByteArray) : JsonObject {
val respInfo = callbacks.helpers.analyzeResponse(response)
val allHeaders = respInfo.headers
val headers = allHeaders.subList(1, allHeaders.size)
val headersJson = jsonObject()
for (header in headers) {
val values = header.split(":".toRegex(), 2).toTypedArray()
if (values.size == 2) {
headersJson.addProperty(values[0].trim({ it <= ' ' }), values[1].trim({ it <= ' ' }))
}
}
return jsonObject(
"raw" to callbacks.helpers.base64Encode(response),
"body" to callbacks.helpers.base64Encode(java.util.Arrays.copyOfRange(response,
respInfo.bodyOffset, response.size)),
"body_offset" to respInfo.bodyOffset,
"mime_type" to respInfo.statedMimeType,
"size" to response.size,
"status_code" to respInfo.statusCode,
"cookies" to cookiesToJsonArray(respInfo.cookies),
"headers" to headersJson
)
}
fun httpRequestResponseToJsonObject(httpMessage: IHttpRequestResponse) : JsonObject {
var request = jsonObject()
var response = jsonObject()
if (httpMessage.request != null && httpMessage.request.isNotEmpty()) {
request = httpRequestToJsonObject(httpMessage.request)
}
if (httpMessage.response != null && httpMessage.response.isNotEmpty()) {
response = httpResponseToJsonObject(httpMessage.response)
}
return jsonObject(
"http_service" to jsonObject(
"host" to httpMessage.httpService.host,
"port" to httpMessage.httpService.port,
"protocol" to httpMessage.httpService.protocol
),
"request" to request,
"highlight" to httpMessage.highlight,
"comment" to httpMessage.comment,
"response" to response
)
}
fun scanIssuesToJsonArray(scanIssues: Array<IScanIssue>) : JsonArray {
val issues = jsonArray()
for (scanIssue in scanIssues) {
issues.add(scanIssueToJsonObject(scanIssue))
}
return issues
}
fun scanIssueToJsonObject(scanIssue: IScanIssue) : JsonObject {
val service = scanIssue.httpService
return jsonObject(
"url" to scanIssue.url.toString(),
"host" to service.host,
"port" to service.port,
"protocol" to service.protocol,
"name" to scanIssue.issueName,
"type" to scanIssue.issueType,
"severity" to scanIssue.severity,
"confidence" to scanIssue.confidence,
"issue_background" to scanIssue.issueBackground,
"issue_detail" to scanIssue.issueDetail,
"remediation_background" to scanIssue.remediationBackground,
"remediation_detail" to scanIssue.remediationDetail,
"http_messages" to httpMessagesToJsonArray(scanIssue.httpMessages)
)
}
fun apiError(param: String, error: String) : JsonObject {
return jsonObject(
"parameter" to param,
"error" to error
)
}
} | mit | 80aa1b9a0de3c87394a88e47c52666c3 | 38.714286 | 130 | 0.574782 | 4.6696 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/visualization/DataDimensionItemTableInfo.kt | 1 | 3764 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.visualization
import org.hisp.dhis.android.core.arch.db.tableinfos.TableInfo
import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper
import org.hisp.dhis.android.core.common.CoreColumns
object DataDimensionItemTableInfo {
@JvmField
val TABLE_INFO: TableInfo = object : TableInfo() {
override fun name(): String {
return "DataDimensionItem"
}
override fun columns(): CoreColumns {
return Columns()
}
}
class Columns : CoreColumns() {
override fun all(): Array<String> {
return CollectionsHelper.appendInNewArray(
super.all(),
VISUALIZATION,
DATA_DIMENSION_ITEM_TYPE,
INDICATOR,
DATA_ELEMENT,
DATA_ELEMENT_OPERAND,
REPORTING_RATE,
PROGRAM_INDICATOR,
PROGRAM_DATA_ELEMENT,
PROGRAM_ATTRIBUTE,
VALIDATION_RULE
)
}
override fun whereUpdate(): Array<String?> {
return CollectionsHelper.appendInNewArray(
super.all(),
VISUALIZATION,
DATA_DIMENSION_ITEM_TYPE,
INDICATOR,
DATA_ELEMENT,
DATA_ELEMENT_OPERAND,
REPORTING_RATE,
PROGRAM_INDICATOR,
PROGRAM_DATA_ELEMENT,
PROGRAM_ATTRIBUTE,
VALIDATION_RULE
)
}
companion object {
const val VISUALIZATION = "visualization"
const val DATA_DIMENSION_ITEM_TYPE = "dataDimensionItemType"
const val INDICATOR = "indicator"
const val DATA_ELEMENT = "dataElement"
const val DATA_ELEMENT_OPERAND = "dataElementOperand"
const val REPORTING_RATE = "reportingRate"
const val PROGRAM_INDICATOR = "programIndicator"
const val PROGRAM_DATA_ELEMENT = "programDataElement"
const val PROGRAM_ATTRIBUTE = "programAttribute"
const val VALIDATION_RULE = "validationRule"
}
}
}
| bsd-3-clause | 4726f902877ffebf110dad3ebbde3c78 | 39.042553 | 83 | 0.64745 | 4.856774 | false | false | false | false |
songful/PocketHub | app/src/main/java/com/github/pockethub/android/ui/item/news/ReleaseEventItem.kt | 1 | 1421 | package com.github.pockethub.android.ui.item.news
import android.text.TextUtils
import android.view.View
import androidx.text.buildSpannedString
import com.github.pockethub.android.ui.view.OcticonTextView
import com.github.pockethub.android.util.AvatarLoader
import com.meisolsson.githubsdk.model.GitHubEvent
import com.meisolsson.githubsdk.model.Release
import com.meisolsson.githubsdk.model.payload.ReleasePayload
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.news_item.*
class ReleaseEventItem(
avatarLoader: AvatarLoader,
gitHubEvent: GitHubEvent
) : NewsItem(avatarLoader, gitHubEvent) {
override fun bind(holder: ViewHolder, position: Int) {
super.bind(holder, position)
holder.tv_event_icon.text = OcticonTextView.ICON_UPLOAD
holder.tv_event.text = buildSpannedString {
boldActor(this, gitHubEvent)
append(" uploaded a file to ")
boldRepo(this, gitHubEvent)
}
val details = buildSpannedString {
val payload = gitHubEvent.payload() as ReleasePayload?
val download: Release? = payload?.release()
appendText(this, download?.name())
}
if (TextUtils.isEmpty(details)) {
holder.tv_event_details.visibility = View.GONE
} else {
holder.tv_event_details.text = details
}
}
}
| apache-2.0 | 74195aee7a195159e919dd066bcd7cf4 | 35.435897 | 66 | 0.701619 | 4.511111 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/memory/MemoryModelFactory.kt | 1 | 1482 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.models.memory
import org.isoron.uhabits.core.models.EntryList
import org.isoron.uhabits.core.models.ModelFactory
import org.isoron.uhabits.core.models.ScoreList
import org.isoron.uhabits.core.models.StreakList
class MemoryModelFactory : ModelFactory {
override fun buildComputedEntries() = EntryList()
override fun buildOriginalEntries() = EntryList()
override fun buildHabitList() = MemoryHabitList()
override fun buildScoreList() = ScoreList()
override fun buildStreakList() = StreakList()
override fun buildHabitListRepository() = throw NotImplementedError()
override fun buildRepetitionListRepository() = throw NotImplementedError()
}
| gpl-3.0 | e96a20d57242c0a8cc315a8cfa9adf49 | 42.558824 | 78 | 0.765024 | 4.330409 | false | false | false | false |
antlr/grammars-v4 | kotlin/kotlin-formal/examples/fuzzer/subclosuresWithinInitializers.kt-449018151.kt_minimized.kt | 1 | 355 | inline fun <R> inlineRun(block: (() -> R)) = block()
class Outer(val outerProp: String) {
fun foo(arg: String): (String)? {
class Local {
val work1 = run({})
val work2 = inlineRun({})
val obj = object: Any(){
override inline fun toString() = outerProp + arg
}
override fun toString() = "${work1}#${work2}#${obj.toString()}"
}
return Local().toString()
}
} | mit | 89f5734ce0fc8a633e424aede78021f6 | 24.428571 | 63 | 0.642254 | 3.256881 | false | false | false | false |
auricgoldfinger/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/android/Bitmap.kt | 3 | 737 | package com.alexstyl.android
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import java.net.URI
fun Drawable.toBitmap(): Bitmap {
if (this is BitmapDrawable) {
return bitmap
}
val width = if (bounds.isEmpty) intrinsicWidth else bounds.width()
val height = if (bounds.isEmpty) intrinsicHeight else bounds.height()
return Bitmap.createBitmap(width.nonZero(), height.nonZero(), Bitmap.Config.ARGB_8888).also {
val canvas = Canvas(it)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
}
}
private fun Int.nonZero() = if (this <= 0) 1 else this
| mit | 338ab58570a335987064adcbef93a00e | 28.48 | 97 | 0.719132 | 3.962366 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/NamedEntityImpl.kt | 1 | 9948 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class NamedEntityImpl(val dataSource: NamedEntityData) : NamedEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(NamedEntity::class.java, NamedChildEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val myName: String
get() = dataSource.myName
override val additionalProperty: String?
get() = dataSource.additionalProperty
override val children: List<NamedChildEntity>
get() = snapshot.extractOneToManyChildren<NamedChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: NamedEntityData?) : ModifiableWorkspaceEntityBase<NamedEntity>(), NamedEntity.Builder {
constructor() : this(NamedEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity NamedEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isMyNameInitialized()) {
error("Field NamedEntity#myName should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field NamedEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field NamedEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as NamedEntity
this.entitySource = dataSource.entitySource
this.myName = dataSource.myName
this.additionalProperty = dataSource.additionalProperty
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var myName: String
get() = getEntityData().myName
set(value) {
checkModificationAllowed()
getEntityData().myName = value
changedProperty.add("myName")
}
override var additionalProperty: String?
get() = getEntityData().additionalProperty
set(value) {
checkModificationAllowed()
getEntityData().additionalProperty = value
changedProperty.add("additionalProperty")
}
// List of non-abstract referenced types
var _children: List<NamedChildEntity>? = emptyList()
override var children: List<NamedChildEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<NamedChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<NamedChildEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<NamedChildEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): NamedEntityData = result ?: super.getEntityData() as NamedEntityData
override fun getEntityClass(): Class<NamedEntity> = NamedEntity::class.java
}
}
class NamedEntityData : WorkspaceEntityData.WithCalculablePersistentId<NamedEntity>() {
lateinit var myName: String
var additionalProperty: String? = null
fun isMyNameInitialized(): Boolean = ::myName.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<NamedEntity> {
val modifiable = NamedEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): NamedEntity {
return getCached(snapshot) {
val entity = NamedEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun persistentId(): PersistentEntityId<*> {
return NameId(myName)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return NamedEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return NamedEntity(myName, entitySource) {
this.additionalProperty = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NamedEntityData
if (this.entitySource != other.entitySource) return false
if (this.myName != other.myName) return false
if (this.additionalProperty != other.additionalProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as NamedEntityData
if (this.myName != other.myName) return false
if (this.additionalProperty != other.additionalProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + additionalProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + additionalProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 0257a1e3f0ced19d2cc778c643ed8e49 | 35.043478 | 182 | 0.688179 | 5.430131 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/menu/ContextMenuBuilder.kt | 2 | 5348 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.menu
import io.kvision.core.Component
import io.kvision.core.CssSize
import io.kvision.core.UNIT
import io.kvision.dropdown.ContextMenu
import io.kvision.dropdown.separator
import org.apache.causeway.client.kroviz.core.event.ResourceProxy
import org.apache.causeway.client.kroviz.to.Link
import org.apache.causeway.client.kroviz.to.TObject
import org.apache.causeway.client.kroviz.ui.core.Constants
import org.apache.causeway.client.kroviz.utils.IconManager
import org.apache.causeway.client.kroviz.utils.StringUtils
import io.kvision.html.Link as KvisionHtmlLink
object ContextMenuBuilder {
fun buildForObjectWithSaveAndUndo(tObject: TObject): ContextMenu {
val cm = buildForObject(tObject)
amendWithSaveUndo(cm, tObject)
disableSaveUndo(cm)
cm.marginTop = CssSize(Constants.spacing, UNIT.px)
cm.marginBottom = CssSize(Constants.spacing, UNIT.px)
cm.width = CssSize(100, UNIT.perc)
return cm
}
fun buildForObject(
tObject: TObject,
withText: Boolean = true,
// iconName: String = "Actions",
)
: ContextMenu {
val type = tObject.domainType
val text = if (withText) "Actions for $type" else ""
// val icon = IconManager.find(iconName)
val cm = ContextMenu(
// text = text,
// icon = icon,
// style = ButtonStyle.LINK
)
val actions = tObject.getActions()
actions.forEach {
val link = buildActionLink(it.id, text)
val invokeLink = it.getInvokeLink()!!
link.onClick {
ResourceProxy().fetch(invokeLink)
}
cm.add(link)
}
return cm
}
fun buildActionLink(
label: String,
menuTitle: String,
): KvisionHtmlLink {
val actionTitle = StringUtils.deCamel(label)
val actionLink: KvisionHtmlLink = ddLink(
label = actionTitle,
icon = IconManager.find(label),
className = IconManager.findStyleFor(label)
)
val id = "$menuTitle${Constants.actionSeparator}$actionTitle"
actionLink.setDragDropData(Constants.stdMimeType, id)
actionLink.id = id
return actionLink
}
private fun ddLink(
label: String,
icon: String? = null,
className: String? = null,
init: (KvisionHtmlLink.() -> Unit)? = null,
): KvisionHtmlLink {
val link = KvisionHtmlLink(
label = label,
url = null,
icon = icon,
image = null,
separator = null,
labelFirst = true,
className = className
)
link.addCssClass("dropdown-item")
return link.apply {
init?.invoke(this)
}
}
// initially added items will be enabled
private fun amendWithSaveUndo(
cm: ContextMenu,
tObject: TObject,
) {
cm.separator()
val saveLink = tObject.links.first()
val saveAction = buildActionLink(
label = "save",
menuTitle = tObject.domainType
)
saveAction.onClick {
ResourceProxy().fetch(saveLink)
}
cm.add(saveAction)
val undoLink = Link(href = "")
val undoAction = buildActionLink(
label = "undo",
menuTitle = tObject.domainType
)
undoAction.onClick {
ResourceProxy().fetch(undoLink)
}
cm.add(undoAction)
}
// disabled when tObject.isClean
// IMPROVE use tr("Dropdowns (disabled)") to DD.DISABLED.option,
fun disableSaveUndo(cm: ContextMenu) {
val menuItems = cm.getChildren()
val saveItem = menuItems[menuItems.size - 2]
switchCssClass(saveItem, IconManager.OK, IconManager.DISABLED)
val undoItem = menuItems[menuItems.size - 1]
switchCssClass(undoItem, IconManager.OK, IconManager.WARN)
}
fun enableSaveUndo(cm: ContextMenu) {
val menuItems = cm.getChildren()
val saveItem = menuItems[menuItems.size - 2]
switchCssClass(saveItem, IconManager.DISABLED, IconManager.OK)
val undoItem = menuItems[menuItems.size - 1]
switchCssClass(undoItem, IconManager.DISABLED, IconManager.WARN)
}
private fun switchCssClass(menuItem: Component, from: String, to: String) {
menuItem.removeCssClass(from)
menuItem.addCssClass(to)
}
}
| apache-2.0 | 87ef73c7dd28456b3c7c03aabac3e647 | 31.609756 | 79 | 0.633508 | 4.312903 | false | false | false | false |
stupacki/MultiFunctions | multi-functions/src/main/kotlin/io/multifunctions/MultiMapIndexedNotNull.kt | 1 | 4651 | package io.multifunctions
import io.multifunctions.models.Hepta
import io.multifunctions.models.Hexa
import io.multifunctions.models.Penta
import io.multifunctions.models.Quad
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, R : Any> Iterable<Pair<A?, B?>>.mapIndexedNotNull(transform: (Int, A?, B?) -> R?): List<R> =
mapIndexedNotNull { index, (first, second) ->
when {
first == null && second == null -> null
else -> transform(index, first, second)
}
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, C, R : Any> Iterable<Triple<A?, B?, C?>>.mapIndexedNotNull(transform: (Int, A?, B?, C?) -> R?): List<R> =
mapIndexedNotNull { index, (first, second, third) ->
when {
first == null && second == null && third == null -> null
else -> transform(index, first, second, third)
}
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, C, D, R : Any> Iterable<Quad<A?, B?, C?, D?>>.mapIndexedNotNull(
transform: (Int, A?, B?, C?, D?) -> R?
): List<R> =
mapIndexedNotNull { index, (first, second, third, fourth) ->
when {
first == null && second == null && third == null && fourth == null -> null
else -> transform(index, first, second, third, fourth)
}
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, C, D, E, R : Any> Iterable<Penta<A?, B?, C?, D?, E?>>.mapIndexedNotNull(
transform: (Int, A?, B?, C?, D?, E?) -> R?
): List<R> =
mapIndexedNotNull { index, (first, second, third, fourth, fifth) ->
when {
first == null && second == null && third == null && fourth == null && fifth == null -> null
else -> transform(index, first, second, third, fourth, fifth)
}
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, C, D, E, F, R : Any> Iterable<Hexa<A?, B?, C?, D?, E?, F?>>.mapIndexedNotNull(
transform: (Int, A?, B?, C?, D?, E?, F?) -> R?
): List<R> =
mapIndexedNotNull { index, (first, second, third, fourth, fifth, sixth) ->
when {
first == null && second == null && third == null && fourth == null && fifth == null && sixth == null -> null
else -> transform(index, first, second, third, fourth, fifth, sixth)
}
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline infix fun <A, B, C, D, E, F, G, R : Any> Iterable<Hepta<A?, B?, C?, D?, E?, F?, G?>>.mapIndexedNotNull(
transform: (Int, A?, B?, C?, D?, E?, F?, G?) -> R?
): List<R> =
mapIndexedNotNull { index, (first, second, third, fourth, fifth, sixth, seventh) ->
when {
first == null && second == null && third == null && fourth == null && fifth == null && sixth == null && seventh == null -> null
else -> transform(index, first, second, third, fourth, fifth, sixth, seventh)
}
}
| apache-2.0 | 9aae592ced710f856b4b205d38cf9d49 | 46.459184 | 139 | 0.640077 | 3.975214 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/step_quiz_sorting/ui/fragment/SortingStepQuizFragment.kt | 1 | 1242 | package org.stepik.android.view.step_quiz_sorting.ui.fragment
import android.view.View
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.layout_step_quiz_sorting.*
import org.stepic.droid.R
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz.ui.fragment.DefaultStepQuizFragment
import org.stepik.android.view.step_quiz_sorting.ui.delegate.SortingStepQuizFormDelegate
import ru.nobird.app.presentation.redux.container.ReduxView
class SortingStepQuizFragment :
DefaultStepQuizFragment(),
ReduxView<StepQuizFeature.State, StepQuizFeature.Action.ViewAction> {
companion object {
fun newInstance(stepId: Long): Fragment =
SortingStepQuizFragment()
.apply {
this.stepId = stepId
}
}
override val quizLayoutRes: Int =
R.layout.layout_step_quiz_sorting
override val quizViews: Array<View>
get() = arrayOf(sortingRecycler)
override fun createStepQuizFormDelegate(view: View): StepQuizFormDelegate =
SortingStepQuizFormDelegate(view, onQuizChanged = ::syncReplyState)
} | apache-2.0 | 40c8873b950334382bd98c9e8d9c981e | 37.84375 | 88 | 0.751208 | 4.467626 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/VcsToolWindowFactory.kt | 1 | 7149 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED
import com.intellij.openapi.vcs.VcsListener
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.CONTENT_PROVIDER_SUPPLIER_KEY
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.IS_IN_COMMIT_TOOLWINDOW_KEY
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.util.ui.UIUtil.getClientProperty
import com.intellij.util.ui.UIUtil.putClientProperty
import com.intellij.vcs.commit.CommitModeManager
import javax.swing.JPanel
private val Project.changesViewContentManager: ChangesViewContentI
get() = ChangesViewContentManager.getInstance(this)
private val IS_CONTENT_CREATED = Key.create<Boolean>("ToolWindow.IsContentCreated")
private val CHANGES_VIEW_EXTENSION = Key.create<ChangesViewContentEP>("Content.ChangesViewExtension")
private fun Content.getExtension(): ChangesViewContentEP? = getUserData(CHANGES_VIEW_EXTENSION)
abstract class VcsToolWindowFactory : ToolWindowFactory, DumbAware {
override fun init(window: ToolWindow) {
val project = (window as ToolWindowEx).project
updateState(project, window)
val connection = project.messageBus.connect()
connection.subscribe(VCS_CONFIGURATION_CHANGED, VcsListener {
runInEdt {
if (project.isDisposed) return@runInEdt
updateState(project, window)
}
})
connection.subscribe(ChangesViewContentManagerListener.TOPIC, object : ChangesViewContentManagerListener {
override fun toolWindowMappingChanged() {
updateState(project, window)
window.contentManagerIfCreated?.selectFirstContent()
}
})
connection.subscribe(CommitModeManager.COMMIT_MODE_TOPIC, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
updateState(project, window)
window.contentManagerIfCreated?.selectFirstContent()
}
})
ChangesViewContentEP.EP_NAME.addExtensionPointListener(project, ExtensionListener(window), window.disposable)
window.addContentManagerListener(getContentManagerListener(project, window))
}
override fun shouldBeAvailable(project: Project): Boolean = project.vcsManager.hasAnyMappings() || project.vcsManager.isConsoleVisible
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
updateContent(project, toolWindow)
project.changesViewContentManager.attachToolWindow(toolWindow)
putClientProperty(toolWindow.component, IS_CONTENT_CREATED, true)
}
protected open fun updateState(project: Project, toolWindow: ToolWindow) {
updateAvailability(project, toolWindow)
updateContentIfCreated(project, toolWindow)
}
private fun updateAvailability(project: Project, toolWindow: ToolWindow) {
val available = shouldBeAvailable(project)
// force showing stripe button on adding initial mapping even if stripe button was manually removed by the user
if (available && !toolWindow.isAvailable) {
toolWindow.isShowStripeButton = true
}
toolWindow.isAvailable = available
}
private fun updateContentIfCreated(project: Project, toolWindow: ToolWindow) {
if (getClientProperty(toolWindow.component, IS_CONTENT_CREATED) != true) return
updateContent(project, toolWindow)
}
private fun updateContent(project: Project, toolWindow: ToolWindow) {
val changesViewContentManager = project.changesViewContentManager
val wasEmpty = toolWindow.contentManager.contentCount == 0
getExtensions(project, toolWindow).forEach { extension ->
val isVisible = extension.newPredicateInstance(project)?.`fun`(project) != false
val content = changesViewContentManager.findContents { it.getExtension() === extension }.firstOrNull()
if (isVisible && content == null) {
changesViewContentManager.addContent(createExtensionContent(project, extension))
}
else if (!isVisible && content != null) {
changesViewContentManager.removeContent(content)
}
}
if (wasEmpty) toolWindow.contentManager.selectFirstContent()
}
private fun getExtensions(project: Project, toolWindow: ToolWindow): Collection<ChangesViewContentEP> {
return ChangesViewContentEP.EP_NAME.getExtensions(project).filter {
ChangesViewContentManager.getToolWindowId(project, it) == toolWindow.id
}
}
private fun createExtensionContent(project: Project, extension: ChangesViewContentEP): Content {
val displayName: String = extension.newDisplayNameSupplierInstance(project)?.get() ?: extension.tabName
return ContentFactory.SERVICE.getInstance().createContent(JPanel(null), displayName, false).apply {
isCloseable = false
tabName = extension.tabName
putUserData(CHANGES_VIEW_EXTENSION, extension)
putUserData(CONTENT_PROVIDER_SUPPLIER_KEY) { extension.getInstance(project) }
putUserData(IS_IN_COMMIT_TOOLWINDOW_KEY, extension.isInCommitToolWindow)
extension.newPreloaderInstance(project)?.preloadTabContent(this)
}
}
private fun getContentManagerListener(project: Project, toolWindow: ToolWindow) = object : ContentManagerListener {
override fun contentAdded(event: ContentManagerEvent) = scheduleUpdate()
override fun contentRemoved(event: ContentManagerEvent) = scheduleUpdate()
private fun scheduleUpdate() {
invokeLater {
if (project.isDisposed) return@invokeLater
updateState(project, toolWindow)
}
}
}
private inner class ExtensionListener(private val toolWindow: ToolWindowEx) : ExtensionPointListener<ChangesViewContentEP> {
override fun extensionAdded(extension: ChangesViewContentEP, pluginDescriptor: PluginDescriptor) =
updateContentIfCreated(toolWindow.project, toolWindow)
override fun extensionRemoved(extension: ChangesViewContentEP, pluginDescriptor: PluginDescriptor) {
val contentManager = toolWindow.contentManagerIfCreated ?: return
val content = contentManager.contents.firstOrNull { it.getExtension() === extension } ?: return
toolWindow.project.changesViewContentManager.removeContent(content)
}
}
companion object {
internal val Project.vcsManager: ProjectLevelVcsManager
get() = ProjectLevelVcsManager.getInstance(this)
}
} | apache-2.0 | 04cccc23f7a2826247cb283dcd95e71f | 43.409938 | 140 | 0.780809 | 4.992318 | false | false | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/internal/ZipEntry.kt | 1 | 1759 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio.internal
import okio.Path
internal class ZipEntry(
/**
* Absolute path of this entry. If the raw name on disk contains relative paths like `..`, they
* are not present in this path.
*/
val canonicalPath: Path,
/** True if this entry is a directory. When encoded directory entries' names end with `/`. */
val isDirectory: Boolean = false,
/** The comment on this entry. Empty if there is no comment. */
val comment: String = "",
/** The CRC32 of the uncompressed data, or -1 if not set. */
val crc: Long = -1L,
/** The compressed size in bytes, or -1 if unknown. */
val compressedSize: Long = -1L,
/** The uncompressed size in bytes, or -1 if unknown. */
val size: Long = -1L,
/** Either [COMPRESSION_METHOD_DEFLATED] or [COMPRESSION_METHOD_STORED]. */
val compressionMethod: Int = -1,
val lastModifiedAtMillis: Long? = null,
val offset: Long = -1L
) {
val children = mutableListOf<Path>()
}
| apache-2.0 | 98cfe314168899867d08988304aad8dd | 33.490196 | 97 | 0.706083 | 4.100233 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/application/options/editor/EditorTabPlacement.kt | 3 | 2616 | // 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.application.options.editor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettings.Companion.TABS_NONE
import com.intellij.ide.ui.search.BooleanOptionDescription
import com.intellij.ide.ui.search.NotABooleanOptionDescription
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.layout.*
import org.jetbrains.annotations.Nls
import javax.swing.ComboBoxModel
import javax.swing.DefaultComboBoxModel
import javax.swing.SwingConstants.*
internal val TAB_PLACEMENTS = arrayOf(TOP, LEFT, BOTTOM, RIGHT, TABS_NONE)
internal val TAB_PLACEMENT = ApplicationBundle.message("combobox.editor.tab.placement")
internal val tabPlacementsOptionDescriptors = TAB_PLACEMENTS.map<Int, BooleanOptionDescription> { i -> asOptionDescriptor(i) }
internal fun Cell.tabPlacementComboBox(): CellBuilder<ComboBox<Int>> {
return tabPlacementComboBox(DefaultComboBoxModel<Int>(TAB_PLACEMENTS))
}
internal fun Cell.tabPlacementComboBox(model: ComboBoxModel<Int>): CellBuilder<ComboBox<Int>> {
return comboBox(model,
ui::editorTabPlacement,
renderer = SimpleListCellRenderer.create<Int> { label, value, _ ->
label.text = value.asTabPlacement()
})
}
private fun asOptionDescriptor(i: Int): BooleanOptionDescription {
return object : BooleanOptionDescription(TAB_PLACEMENT + " | " + i.asTabPlacement(), ID), NotABooleanOptionDescription {
override fun isOptionEnabled() = ui.editorTabPlacement == i
override fun setOptionState(enabled: Boolean) {
ui.editorTabPlacement = next(ui.editorTabPlacement, enabled)
UISettings.instance.fireUISettingsChanged()
}
private fun next(prev: Int, enabled: Boolean) = when {
prev != i && enabled -> i
prev == i -> if (i == TABS_NONE) TOP else TABS_NONE
else -> prev
}
}
}
@Nls
private fun Int.asTabPlacement(): String {
return when (this) {
TABS_NONE -> ApplicationBundle.message("combobox.tab.placement.none")
TOP -> ApplicationBundle.message("combobox.tab.placement.top")
LEFT -> ApplicationBundle.message("combobox.tab.placement.left")
BOTTOM -> ApplicationBundle.message("combobox.tab.placement.bottom")
RIGHT -> ApplicationBundle.message("combobox.tab.placement.right")
else -> throw IllegalArgumentException("unknown tabPlacement: $this")
}
}
| apache-2.0 | bb0df5079d554805d521605a73ab901e | 41.193548 | 140 | 0.747324 | 4.352745 | false | false | false | false |
zdary/intellij-community | plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUtil.kt | 1 | 5500 | // 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 git4idea.ui.branch.dashboard
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.util.exclusiveCommits
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import git4idea.branch.GitBranchIncomingOutgoingManager
import git4idea.branch.GitBranchType
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.branch.GitBranchManager
import gnu.trove.TIntHashSet
internal object BranchesDashboardUtil {
fun getLocalBranches(project: Project, rootsToFilter: Set<VirtualFile>?): Set<BranchInfo> {
val localMap = mutableMapOf<String, MutableSet<GitRepository>>()
for (repo in GitRepositoryManager.getInstance(project).repositories) {
if (rootsToFilter != null && !rootsToFilter.contains(repo.root)) continue
for (branch in repo.branches.localBranches) {
localMap.computeIfAbsent(branch.name) { hashSetOf() }.add(repo)
}
val currentBranch = repo.currentBranch
if (currentBranch != null) {
localMap.computeIfAbsent(currentBranch.name) { hashSetOf() }.add(repo)
}
}
val gitBranchManager = project.service<GitBranchManager>()
val local = localMap.map { (branchName, repos) ->
BranchInfo(branchName, true, repos.any { it.currentBranch?.name == branchName },
repos.any { gitBranchManager.isFavorite(GitBranchType.LOCAL, it, branchName) },
repos.anyIncomingOutgoingState(branchName),
repos.toList())
}.toHashSet()
return local
}
fun getRemoteBranches(project: Project, rootsToFilter: Set<VirtualFile>?): Set<BranchInfo> {
val remoteMap = mutableMapOf<String, MutableList<GitRepository>>()
for (repo in GitRepositoryManager.getInstance(project).repositories) {
if (rootsToFilter != null && !rootsToFilter.contains(repo.root)) continue
for (remoteBranch in repo.branches.remoteBranches) {
remoteMap.computeIfAbsent(remoteBranch.name) { mutableListOf() }.add(repo)
}
}
val gitBranchManager = project.service<GitBranchManager>()
return remoteMap.map { (branchName, repos) ->
BranchInfo(branchName, false, false,
repos.any { gitBranchManager.isFavorite(GitBranchType.REMOTE, it, branchName) },
null,
repos)
}.toHashSet()
}
fun checkIsMyBranchesSynchronously(log: VcsProjectLog,
branchesToCheck: Collection<BranchInfo>,
indicator: ProgressIndicator): Set<BranchInfo> {
val myCommits = findMyCommits(log)
if (myCommits.isNullOrEmpty()) return emptySet()
indicator.isIndeterminate = false
val myBranches = hashSetOf<BranchInfo>()
for ((step, branch) in branchesToCheck.withIndex()) {
indicator.fraction = step.toDouble() / branchesToCheck.size
for (repo in branch.repositories) {
indicator.checkCanceled()
if (isMyBranch(log, branch.branchName, repo, myCommits)) {
myBranches.add(branch)
}
}
}
return myBranches
}
fun Collection<GitRepository>.anyIncomingOutgoingState(localBranchName: String): IncomingOutgoing? {
for (repository in this) {
val incomingOutgoingState = repository.getIncomingOutgoingState(localBranchName)
if (incomingOutgoingState != null) {
return incomingOutgoingState
}
}
return null
}
fun GitRepository.getIncomingOutgoingState(localBranchName: String): IncomingOutgoing? =
with(project.service<GitBranchIncomingOutgoingManager>()) {
val repo = this@getIncomingOutgoingState
val hasIncoming = hasIncomingFor(repo, localBranchName)
val hasOutgoing = hasOutgoingFor(repo, localBranchName)
when {
hasIncoming && hasOutgoing -> IncomingOutgoing.INCOMING_AND_OUTGOING
hasIncoming -> IncomingOutgoing.INCOMING
hasOutgoing -> IncomingOutgoing.OUTGOING
else -> null
}
}
private fun findMyCommits(log: VcsProjectLog): Set<Int> {
val filterByMe = VcsLogFilterObject.fromUserNames(listOf(VcsLogFilterObject.ME), log.dataManager!!)
return log.dataManager!!.index.dataGetter!!.filter(listOf(filterByMe))
}
private fun isMyBranch(log: VcsProjectLog,
branchName: String,
repo: GitRepository,
myCommits: Set<Int>): Boolean {
// branch is "my" if all its exclusive commits are made by me
val exclusiveCommits = findExclusiveCommits(log, branchName, repo) ?: return false
if (exclusiveCommits.isEmpty) return false
for (commit in exclusiveCommits) {
if (!myCommits.contains(commit)) {
return false
}
}
return true
}
private fun findExclusiveCommits(log: VcsProjectLog, branchName: String, repo: GitRepository): TIntHashSet? {
val dataPack = log.dataManager!!.dataPack
val ref = dataPack.findBranch(branchName, repo.root) ?: return null
if (!ref.type.isBranch) return null
return dataPack.exclusiveCommits(ref, dataPack.refsModel, log.dataManager!!.storage)
}
}
| apache-2.0 | b8d5170b583987cf86ea06cd9e5a62dc | 38.007092 | 140 | 0.701636 | 4.741379 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/sam/constructors/sameWrapperClass.kt | 2 | 308 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
fun box(): String {
val f = { }
val class1 = (Runnable(f) as Object).getClass()
val class2 = (Runnable(f) as Object).getClass()
return if (class1 == class2) "OK" else "$class1 $class2"
}
| apache-2.0 | 11b341c0eb80af354549a04e6b18a687 | 29.8 | 72 | 0.646104 | 3.384615 | false | false | false | false |
FirebaseExtended/mlkit-material-android | app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ObjectGraphicInProminentMode.kt | 1 | 4740 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.ml.md.kotlin.objectdetection
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Paint.Style
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Shader.TileMode
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.google.firebase.ml.vision.objects.FirebaseVisionObject
import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay
import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay.Graphic
import com.google.firebase.ml.md.R
/**
* Draws the detected visionObject info over the camera preview for prominent visionObject detection mode.
*/
internal class ObjectGraphicInProminentMode(
overlay: GraphicOverlay,
private val visionObject: FirebaseVisionObject,
private val confirmationController: ObjectConfirmationController
) : Graphic(overlay) {
private val scrimPaint: Paint = Paint()
private val eraserPaint: Paint
private val boxPaint: Paint
@ColorInt
private val boxGradientStartColor: Int
@ColorInt
private val boxGradientEndColor: Int
private val boxCornerRadius: Int
init {
// Sets up a gradient background color at vertical.
scrimPaint.shader = if (confirmationController.isConfirmed) {
LinearGradient(
0f,
0f,
overlay.width.toFloat(),
overlay.height.toFloat(),
ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_start),
ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_end),
TileMode.CLAMP
)
} else {
LinearGradient(
0f,
0f,
overlay.width.toFloat(),
overlay.height.toFloat(),
ContextCompat.getColor(context, R.color.object_detected_bg_gradient_start),
ContextCompat.getColor(context, R.color.object_detected_bg_gradient_end),
TileMode.CLAMP
)
}
eraserPaint = Paint().apply {
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
boxPaint = Paint().apply {
style = Style.STROKE
strokeWidth = context
.resources
.getDimensionPixelOffset(
if (confirmationController.isConfirmed) {
R.dimen.bounding_box_confirmed_stroke_width
} else {
R.dimen.bounding_box_stroke_width
}
).toFloat()
color = Color.WHITE
}
boxGradientStartColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_start)
boxGradientEndColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_end)
boxCornerRadius = context.resources.getDimensionPixelOffset(R.dimen.bounding_box_corner_radius)
}
override fun draw(canvas: Canvas) {
val rect = overlay.translateRect(visionObject.boundingBox)
// Draws the dark background scrim and leaves the visionObject area clear.
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint)
canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), eraserPaint)
// Draws the bounding box with a gradient border color at vertical.
boxPaint.shader = if (confirmationController.isConfirmed) {
null
} else {
LinearGradient(
rect.left,
rect.top,
rect.left,
rect.bottom,
boxGradientStartColor,
boxGradientEndColor,
TileMode.CLAMP)
}
canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), boxPaint)
}
}
| apache-2.0 | bd4fce901a0bb638bd130faef879800e | 38.173554 | 106 | 0.639241 | 4.947808 | false | false | false | false |
Triple-T/gradle-play-publisher | play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/PublishListings.kt | 1 | 10022 | package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.common.utils.orNull
import com.github.triplet.gradle.common.utils.readProcessed
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.internal.AppDetail
import com.github.triplet.gradle.play.internal.GRAPHICS_PATH
import com.github.triplet.gradle.play.internal.ImageType
import com.github.triplet.gradle.play.internal.LISTINGS_PATH
import com.github.triplet.gradle.play.internal.ListingDetail
import com.github.triplet.gradle.play.tasks.internal.CliOptionsImpl
import com.github.triplet.gradle.play.tasks.internal.PublishTaskBase
import com.github.triplet.gradle.play.tasks.internal.WriteTrackExtensionOptions
import com.github.triplet.gradle.play.tasks.internal.workers.EditWorkerBase
import com.github.triplet.gradle.play.tasks.internal.workers.copy
import com.github.triplet.gradle.play.tasks.internal.workers.paramsForBase
import com.google.common.hash.Hashing
import com.google.common.io.Files
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileType
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
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.DisableCachingByDefault
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import org.gradle.workers.WorkerExecutor
import java.io.File
import java.io.Serializable
import javax.inject.Inject
@DisableCachingByDefault
internal abstract class PublishListings @Inject constructor(
extension: PlayPublisherExtension,
executionDir: Directory,
private val executor: WorkerExecutor,
) : PublishTaskBase(extension),
WriteTrackExtensionOptions by CliOptionsImpl(extension, executionDir) {
@get:Internal
internal abstract val resDir: DirectoryProperty
@get:Incremental
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
protected val detailFiles: FileCollection by lazy {
resDir.asFileTree.matching {
// We can't simply use `project.files` because Gradle would expect those to exist for
// stuff like `@SkipWhenEmpty` to work.
for (detail in AppDetail.values()) include("/${detail.fileName}")
}
}
@get:Incremental
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
protected val listingFiles: FileCollection by lazy {
resDir.asFileTree.matching {
for (detail in ListingDetail.values()) include("/$LISTINGS_PATH/*/${detail.fileName}")
}
}
@get:Incremental
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
protected val mediaFiles: FileCollection by lazy {
resDir.asFileTree.matching {
for (image in ImageType.values()) {
include("/$LISTINGS_PATH/*/$GRAPHICS_PATH/${image.dirName}/*")
}
}
}
// 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 { detailFiles + listingFiles + mediaFiles }
// 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 publishListing(changes: InputChanges) {
val details = processDetails(changes)
val listings = processListings(changes)
val media = processMedia(changes)
if (details == null && listings.isEmpty() && media.isEmpty()) return
executor.noIsolation().submit(Publisher::class) {
paramsForBase(this)
this.details.set(details)
this.listings.set(listings)
this.media.set(media)
}
}
private fun processDetails(changes: InputChanges): Directory? {
val changedDetails =
changes.getFileChanges(detailFiles).filter { it.fileType == FileType.FILE }
if (changedDetails.isEmpty()) return null
if (AppDetail.values().map { resDir.file(it.fileName) }.none { it.get().asFile.exists() }) {
return null
}
return resDir.get()
}
private fun processListings(
changes: InputChanges,
) = changes.getFileChanges(listingFiles).asSequence()
.filter { it.fileType == FileType.FILE }
.map { it.file.parentFile }
.distinct()
// We can't filter out FileType#REMOVED b/c otherwise we won't publish the changes
.filter { it.exists() }
.toList()
private fun processMedia(
changes: InputChanges,
) = changes.getFileChanges(mediaFiles).asSequence()
.filter { it.fileType == FileType.FILE }
.map { it.file.parentFile }
.map { f -> f to ImageType.values().find { f.name == it.dirName } }
.filter { it.second != null }
.filter { it.first.exists() }
.map { it.first to it.second!! }
.associate { it }
.map { Publisher.Media(it.key, it.value) }
internal abstract class Publisher @Inject constructor(
private val executor: WorkerExecutor,
) : EditWorkerBase<Publisher.Params>() {
override fun execute() {
if (parameters.details.isPresent) {
executor.noIsolation().submit(DetailsUploader::class) {
parameters.copy(this)
dir.set(parameters.details)
}
}
for (listing in parameters.listings.get()) {
executor.noIsolation().submit(ListingUploader::class) {
parameters.copy(this)
listingDir.set(listing)
}
}
for (medium in parameters.media.get()) {
executor.noIsolation().submit(MediaUploader::class) {
parameters.copy(this)
imageDir.set(medium.imageDir)
imageType.set(medium.type)
}
}
executor.await()
commit()
}
interface Params : EditPublishingParams {
val details: DirectoryProperty // Optional
val listings: ListProperty<File>
val media: ListProperty<Media>
}
data class Media(val imageDir: File, val type: ImageType) : Serializable
}
internal abstract class DetailsUploader : EditWorkerBase<DetailsUploader.Params>() {
override fun execute() {
val defaultLanguage = AppDetail.DEFAULT_LANGUAGE.read()
val contactEmail = AppDetail.CONTACT_EMAIL.read()
val contactPhone = AppDetail.CONTACT_PHONE.read()
val contactWebsite = AppDetail.CONTACT_WEBSITE.read()
println("Uploading app details")
apiService.edits.publishAppDetails(
defaultLanguage, contactEmail, contactPhone, contactWebsite)
}
private fun AppDetail.read() =
parameters.dir.get().file(fileName).asFile.orNull()?.readProcessed()
interface Params : EditPublishingParams {
val dir: DirectoryProperty
}
}
internal abstract class ListingUploader : EditWorkerBase<ListingUploader.Params>() {
override fun execute() {
val locale = parameters.listingDir.get().asFile.name
val title = ListingDetail.TITLE.read()
val shortDescription = ListingDetail.SHORT_DESCRIPTION.read()
val fullDescription = ListingDetail.FULL_DESCRIPTION.read()
val video = ListingDetail.VIDEO.read()
if (title == null &&
shortDescription == null &&
fullDescription == null &&
video == null) {
return
}
println("Uploading $locale listing")
apiService.edits.publishListing(
locale, title, shortDescription, fullDescription, video)
}
private fun ListingDetail.read() =
parameters.listingDir.get().file(fileName).asFile.orNull()?.readProcessed()
interface Params : EditPublishingParams {
val listingDir: DirectoryProperty
}
}
internal abstract class MediaUploader : EditWorkerBase<MediaUploader.Params>() {
override fun execute() {
val typeName = parameters.imageType.get().publishedName
val files = parameters.imageDir.asFileTree.sorted()
.filterNot { it.extension == "index" }
check(files.size <= parameters.imageType.get().maxNum) {
"You can only upload ${parameters.imageType.get().maxNum} $typeName."
}
val locale = parameters.imageDir.get().asFile // icon
.parentFile // graphics
.parentFile // en-US
.name
val remoteHashes = apiService.edits.getImages(locale, typeName).map { it.sha256 }
val localHashes = files.map {
Files.asByteSource(it).hash(Hashing.sha256()).toString()
}
if (remoteHashes == localHashes) return
apiService.edits.publishImages(locale, typeName, files)
}
interface Params : EditPublishingParams {
val imageDir: DirectoryProperty
val imageType: Property<ImageType>
}
}
}
| mit | b0a10b26a2fd3e1faef0e5adf249d023 | 37.844961 | 100 | 0.64538 | 4.734058 | false | false | false | false |
JuliusKunze/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/ObjCStubs.kt | 1 | 22414 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.gen.jvm.StubGenerator
import org.jetbrains.kotlin.native.interop.indexer.*
private fun ObjCMethod.getKotlinParameterNames(): List<String> {
val selectorParts = this.selector.split(":")
val result = mutableListOf<String>()
// The names of all parameters except first must depend only on the selector:
this.parameters.forEachIndexed { index, _ ->
if (index > 0) {
var name = selectorParts[index]
if (name.isEmpty()) {
name = "_$index"
}
while (name in result) {
name = "_$name"
}
result.add(name)
}
}
this.parameters.firstOrNull()?.let {
var name = it.name ?: ""
if (name.isEmpty()) {
name = "arg"
}
while (name in result) {
name = "_$name"
}
result.add(0, name)
}
return result
}
class ObjCMethodStub(stubGenerator: StubGenerator,
val method: ObjCMethod,
private val container: ObjCContainer) : KotlinStub, NativeBacked {
override fun generate(context: StubGenerationContext): Sequence<String> =
if (context.nativeBridges.isSupported(this)) {
val result = mutableListOf<String>()
result.add("@ObjCMethod".applyToStrings(method.selector, bridgeName))
result.add(header)
if (method.isInit && container is ObjCClass) {
result.add("")
result.add("@ObjCConstructor".applyToStrings(method.selector))
result.add("constructor($joinedKotlinParameters) {}")
}
context.addTopLevelDeclaration(
listOf("@konan.internal.ExportForCompiler",
"@ObjCBridge".applyToStrings(method.selector, method.encoding, implementationTemplate))
+ block(bridgeHeader, bodyLines)
)
result.asSequence()
} else {
sequenceOf(
annotationForUnableToImport,
header
)
}
private val bodyLines: List<String>
private val joinedKotlinParameters: String
private val header: String
private val implementationTemplate: String
internal val bridgeName: String
private val bridgeHeader: String
init {
val bodyGenerator = KotlinCodeBuilder(scope = stubGenerator.kotlinFile)
val kotlinParameters = mutableListOf<Pair<String, KotlinType>>()
val kotlinObjCBridgeParameters = mutableListOf<Pair<String, KotlinType>>()
val nativeBridgeArguments = mutableListOf<TypedKotlinValue>()
val kniReceiverParameter = "kniR"
val kniSuperClassParameter = "kniSC"
val voidPtr = PointerType(VoidType)
val returnType = method.getReturnType(container.classOrProtocol)
val messengerGetter = if (returnType.isLargeOrUnaligned()) "getMessengerLU" else "getMessenger"
kotlinObjCBridgeParameters.add(kniSuperClassParameter to KotlinTypes.nativePtr)
nativeBridgeArguments.add(TypedKotlinValue(voidPtr, "$messengerGetter($kniSuperClassParameter)"))
if (method.nsConsumesSelf) {
// TODO: do this later due to possible exceptions
bodyGenerator.out("objc_retain($kniReceiverParameter.rawPtr)")
}
kotlinObjCBridgeParameters.add(kniReceiverParameter to KotlinTypes.objCObject.type)
nativeBridgeArguments.add(
TypedKotlinValue(voidPtr,
"getReceiverOrSuper($kniReceiverParameter.rawPtr, $kniSuperClassParameter)"))
val kotlinParameterNames = method.getKotlinParameterNames()
method.parameters.forEachIndexed { index, it ->
val name = kotlinParameterNames[index]
val kotlinType = stubGenerator.mirror(it.type).argType
kotlinParameters.add(name to kotlinType)
kotlinObjCBridgeParameters.add(name to kotlinType)
nativeBridgeArguments.add(TypedKotlinValue(it.type, name.asSimpleName()))
}
val kotlinReturnType = if (returnType.unwrapTypedefs() is VoidType) {
KotlinTypes.unit
} else {
stubGenerator.mirror(returnType).argType
}.render(stubGenerator.kotlinFile)
val result = stubGenerator.mappingBridgeGenerator.kotlinToNative(
bodyGenerator,
this@ObjCMethodStub,
returnType,
nativeBridgeArguments
) { nativeValues ->
val selector = "@selector(${method.selector})"
val messengerParameterTypes = mutableListOf<String>()
messengerParameterTypes.add("void*")
messengerParameterTypes.add("SEL")
method.parameters.forEach {
messengerParameterTypes.add(it.getTypeStringRepresentation())
}
val messengerReturnType = returnType.getStringRepresentation()
val messengerType =
"$messengerReturnType (* ${method.cAttributes}) (${messengerParameterTypes.joinToString()})"
val messenger = "(($messengerType) ${nativeValues.first()})"
val messengerArguments = listOf(nativeValues[1]) + selector + nativeValues.drop(2)
"$messenger(${messengerArguments.joinToString()})"
}
bodyGenerator.out("return $result")
this.implementationTemplate = genImplementationTemplate(stubGenerator)
this.bodyLines = bodyGenerator.build()
bridgeName = "objcKniBridge${stubGenerator.nextUniqueId()}"
this.bridgeHeader = buildString {
append("internal fun ")
append(bridgeName)
append('(')
kotlinObjCBridgeParameters.joinTo(this) {
"${it.first.asSimpleName()}: ${it.second.render(stubGenerator.kotlinFile)}"
}
append("): ")
append(kotlinReturnType)
}
this.joinedKotlinParameters = kotlinParameters.joinToString {
"${it.first.asSimpleName()}: ${it.second.render(stubGenerator.kotlinFile)}"
}
this.header = buildString {
if (container !is ObjCProtocol) append("external ")
val modality = when (container) {
is ObjCClassOrProtocol -> if (method.isOverride(container)) {
"override "
} else when (container) {
is ObjCClass -> "open "
is ObjCProtocol -> ""
}
is ObjCCategory -> ""
}
append(modality)
append("fun ")
if (container is ObjCCategory) {
val receiverType = stubGenerator.declarationMapper
.getKotlinClassFor(container.clazz, isMeta = method.isClass).type
.render(stubGenerator.kotlinFile)
append(receiverType)
append('.')
}
append("${method.kotlinName.asSimpleName()}($joinedKotlinParameters): $kotlinReturnType")
if (container is ObjCProtocol && method.isOptional) append(" = optional()")
}
}
private fun genImplementationTemplate(stubGenerator: StubGenerator): String = when (container) {
is ObjCClassOrProtocol -> {
val codeBuilder = NativeCodeBuilder(stubGenerator.simpleBridgeGenerator.topLevelNativeScope)
val result = codeBuilder.genMethodImp(stubGenerator, this, method, container)
stubGenerator.simpleBridgeGenerator.insertNativeBridge(this, emptyList(), codeBuilder.lines)
result
}
is ObjCCategory -> ""
}
}
private val ObjCContainer.classOrProtocol: ObjCClassOrProtocol
get() = when (this) {
is ObjCClassOrProtocol -> this
is ObjCCategory -> this.clazz
}
private fun Type.isLargeOrUnaligned(): Boolean {
val unwrappedType = this.unwrapTypedefs()
return when (unwrappedType) {
is RecordType -> unwrappedType.decl.def!!.size > 16 || this.hasUnalignedMembers()
else -> false
}
}
private fun Type.hasUnalignedMembers(): Boolean = when (this) {
is Typedef -> this.def.aliased.hasUnalignedMembers()
is RecordType -> this.decl.def!!.let { def ->
def.fields.any {
!it.isAligned ||
// Check members of fields too:
it.type.hasUnalignedMembers()
}
}
is ArrayType -> this.elemType.hasUnalignedMembers()
else -> false
// TODO: should the recursive checks be made in indexer when computing `hasUnalignedFields`?
}
private val ObjCMethod.kotlinName: String get() = selector.split(":").first()
private val ObjCClassOrProtocol.protocolsWithSupers: Sequence<ObjCProtocol>
get() = this.protocols.asSequence().flatMap { sequenceOf(it) + it.protocolsWithSupers }
private val ObjCClassOrProtocol.immediateSuperTypes: Sequence<ObjCClassOrProtocol>
get() {
val baseClass = (this as? ObjCClass)?.baseClass
if (baseClass != null) {
return sequenceOf(baseClass) + this.protocols.asSequence()
}
return this.protocols.asSequence()
}
private val ObjCClassOrProtocol.selfAndSuperTypes: Sequence<ObjCClassOrProtocol>
get() = sequenceOf(this) + this.superTypes
private val ObjCClassOrProtocol.superTypes: Sequence<ObjCClassOrProtocol>
get() = this.immediateSuperTypes.flatMap { it.selfAndSuperTypes }.distinct()
private fun ObjCClassOrProtocol.declaredMethods(isClass: Boolean): Sequence<ObjCMethod> =
this.methods.asSequence().filter { it.isClass == isClass }
private fun ObjCClassOrProtocol.inheritedMethods(isClass: Boolean): Sequence<ObjCMethod> =
this.superTypes.flatMap { it.declaredMethods(isClass) }.distinctBy { it.selector }
private fun ObjCClassOrProtocol.methodsWithInherited(isClass: Boolean): Sequence<ObjCMethod> =
this.selfAndSuperTypes.flatMap { it.declaredMethods(isClass) }.distinctBy { it.selector }
private fun ObjCMethod.isOverride(container: ObjCClassOrProtocol): Boolean =
container.superTypes.any { superType -> superType.methods.any(this::replaces) }
abstract class ObjCContainerStub(stubGenerator: StubGenerator,
private val container: ObjCClassOrProtocol,
private val isMeta: Boolean) : KotlinStub {
private val methods: List<ObjCMethod>
private val properties: List<ObjCProperty>
init {
val superMethods = container.inheritedMethods(isMeta)
// Add all methods declared in the class or protocol:
var methods = container.declaredMethods(isMeta)
// Exclude those which are identically declared in super types:
methods -= superMethods
// Add some special methods from super types:
methods += superMethods.filter { it.returnsInstancetype() || it.isInit }
// Add methods from adopted protocols that must be implemented according to Kotlin rules:
if (container is ObjCClass) {
methods += container.protocolsWithSupers.flatMap { it.declaredMethods(isMeta) }.filter { !it.isOptional }
}
// Add methods inherited from multiple supertypes that must be defined according to Kotlin rules:
methods += container.immediateSuperTypes
.flatMap { superType ->
val methodsWithInherited = superType.methodsWithInherited(isMeta)
// Select only those which are represented as non-abstract in Kotlin:
when (superType) {
is ObjCClass -> methodsWithInherited
is ObjCProtocol -> methodsWithInherited.filter { it.isOptional }
}
}
.groupBy { it.selector }
.mapNotNull { (_, inheritedMethods) -> if (inheritedMethods.size > 1) inheritedMethods.first() else null }
this.methods = methods.distinctBy { it.selector }.toList()
this.properties = container.properties.filter { property ->
property.getter.isClass == isMeta &&
// Select only properties that don't override anything:
superMethods.none { property.getter.replaces(it) || property.setter?.replaces(it) ?: false }
}
}
private val methodToStub = methods.map {
it to ObjCMethodStub(stubGenerator, it, container)
}.toMap()
private val methodStubs get() = methodToStub.values
val propertyStubs = properties.map {
createObjCPropertyStub(stubGenerator, it, container, this.methodToStub)
}
private val classHeader: String
init {
val supers = mutableListOf<KotlinType>()
if (container is ObjCClass) {
val baseClass = container.baseClass
val baseClassifier = if (baseClass != null) {
stubGenerator.declarationMapper.getKotlinClassFor(baseClass, isMeta)
} else {
if (isMeta) KotlinTypes.objCObjectBaseMeta else KotlinTypes.objCObjectBase
}
supers.add(baseClassifier.type)
}
container.protocols.forEach {
supers.add(stubGenerator.declarationMapper.getKotlinClassFor(it, isMeta).type)
}
if (supers.isEmpty()) {
assert(container is ObjCProtocol)
val classifier = if (isMeta) KotlinTypes.objCObjectMeta else KotlinTypes.objCObject
supers.add(classifier.type)
}
val keywords = when (container) {
is ObjCClass -> "open class"
is ObjCProtocol -> "interface"
}
val supersString = supers.joinToString { it.render(stubGenerator.kotlinFile) }
val classifier = stubGenerator.declarationMapper.getKotlinClassFor(container, isMeta)
val name = stubGenerator.kotlinFile.declare(classifier)
this.classHeader = "@ExternalObjCClass $keywords $name : $supersString"
}
open fun generateBody(context: StubGenerationContext): Sequence<String> {
var result = (propertyStubs.asSequence() + methodStubs.asSequence())
.flatMap { sequenceOf("") + it.generate(context) }
if (container is ObjCClass && methodStubs.none {
it.method.isInit && it.method.parameters.isEmpty() && context.nativeBridges.isSupported(it)
}) {
// Always generate default constructor.
// If it is not produced for an init method, then include it manually:
result += sequenceOf("", "protected constructor() {}")
}
return result
}
override fun generate(context: StubGenerationContext): Sequence<String> = block(classHeader, generateBody(context))
}
open class ObjCClassOrProtocolStub(
stubGenerator: StubGenerator,
private val container: ObjCClassOrProtocol
) : ObjCContainerStub(
stubGenerator,
container,
isMeta = false
) {
private val metaClassStub =
object : ObjCContainerStub(stubGenerator, container, isMeta = true) {}
override fun generate(context: StubGenerationContext) =
metaClassStub.generate(context) + "" + super.generate(context)
}
class ObjCProtocolStub(stubGenerator: StubGenerator, protocol: ObjCProtocol) :
ObjCClassOrProtocolStub(stubGenerator, protocol)
class ObjCClassStub(private val stubGenerator: StubGenerator, private val clazz: ObjCClass) :
ObjCClassOrProtocolStub(stubGenerator, clazz) {
override fun generateBody(context: StubGenerationContext): Sequence<String> {
val companionSuper = stubGenerator.declarationMapper
.getKotlinClassFor(clazz, isMeta = true).type
.render(stubGenerator.kotlinFile)
return sequenceOf( "companion object : $companionSuper() {}") +
super.generateBody(context)
}
}
class ObjCCategoryStub(
private val stubGenerator: StubGenerator, private val category: ObjCCategory
) : KotlinStub {
// TODO: consider removing members that are also present in the class or its supertypes.
private val methodToStub = category.methods.map {
it to ObjCMethodStub(stubGenerator, it, category)
}.toMap()
private val methodStubs get() = methodToStub.values
private val propertyStubs = category.properties.map {
createObjCPropertyStub(stubGenerator, it, category, methodToStub)
}
override fun generate(context: StubGenerationContext): Sequence<String> {
val description = "${category.clazz.name} (${category.name})"
return sequenceOf("// @interface $description") +
propertyStubs.asSequence().flatMap { sequenceOf("") + it.generate(context) } +
methodStubs.asSequence().flatMap { sequenceOf("") + it.generate(context) } +
sequenceOf("// @end; // $description")
}
}
private fun createObjCPropertyStub(
stubGenerator: StubGenerator,
property: ObjCProperty,
container: ObjCContainer,
methodToStub: Map<ObjCMethod, ObjCMethodStub>
): ObjCPropertyStub {
// Note: the code below assumes that if the property is generated,
// then its accessors are also generated as explicit methods.
val getterStub = methodToStub[property.getter]!!
val setterStub = property.setter?.let { methodToStub[it]!! }
return ObjCPropertyStub(stubGenerator, property, container, getterStub, setterStub)
}
class ObjCPropertyStub(
val stubGenerator: StubGenerator, val property: ObjCProperty, val container: ObjCContainer,
val getterStub: ObjCMethodStub, val setterStub: ObjCMethodStub?
) : KotlinStub {
override fun generate(context: StubGenerationContext): Sequence<String> {
val type = property.getType(container.classOrProtocol)
val kotlinType = stubGenerator.mirror(type).argType.render(stubGenerator.kotlinFile)
val kind = if (property.setter == null) "val" else "var"
val modifiers = if (container is ObjCProtocol) "final " else ""
val receiver = when (container) {
is ObjCClassOrProtocol -> ""
is ObjCCategory -> stubGenerator.declarationMapper
.getKotlinClassFor(container.clazz, isMeta = property.getter.isClass).type
.render(stubGenerator.kotlinFile) + "."
}
val result = mutableListOf(
"$modifiers$kind $receiver${property.name.asSimpleName()}: $kotlinType",
" get() = ${getterStub.bridgeName}(nativeNullPtr, this)"
)
property.setter?.let {
result.add(" set(value) = ${setterStub!!.bridgeName}(nativeNullPtr, this, value)")
}
return result.asSequence()
}
}
fun ObjCClassOrProtocol.kotlinClassName(isMeta: Boolean): String {
val baseClassName = when (this) {
is ObjCClass -> this.name
is ObjCProtocol -> "${this.name}Protocol"
}
return if (isMeta) "${baseClassName}Meta" else baseClassName
}
private fun Parameter.getTypeStringRepresentation() =
(if (this.nsConsumed) "__attribute__((ns_consumed)) " else "") + type.getStringRepresentation()
private fun ObjCMethod.getSelfTypeStringRepresentation() = if (this.nsConsumesSelf) {
"__attribute__((ns_consumed)) id"
} else {
"id"
}
val ObjCMethod.cAttributes get() = if (this.nsReturnsRetained) {
"__attribute__((ns_returns_retained)) "
} else {
""
}
private fun NativeCodeBuilder.genMethodImp(
stubGenerator: StubGenerator,
nativeBacked: NativeBacked,
method: ObjCMethod,
container: ObjCClassOrProtocol
): String {
val returnType = method.getReturnType(container)
val cReturnType = returnType.getStringRepresentation()
val bridgeArguments = mutableListOf<TypedNativeValue>()
val parameters = mutableListOf<Pair<String, String>>()
parameters.add("self" to method.getSelfTypeStringRepresentation())
val receiverType = ObjCIdType(ObjCPointer.Nullability.NonNull, protocols = emptyList())
bridgeArguments.add(TypedNativeValue(receiverType, "self"))
parameters.add("_cmd" to "SEL")
method.parameters.forEachIndexed { index, parameter ->
val name = "p$index"
parameters.add(name to parameter.getTypeStringRepresentation())
bridgeArguments.add(TypedNativeValue(parameter.type, name))
}
val functionName = "knimi_" + stubGenerator.pkgName.replace('.', '_') + stubGenerator.nextUniqueId()
val functionAttr = method.cAttributes
out("$cReturnType $functionName(${parameters.joinToString { it.second + " " + it.first }}) $functionAttr{")
val callExpr = stubGenerator.mappingBridgeGenerator.nativeToKotlin(
this,
nativeBacked,
returnType,
bridgeArguments
) { kotlinValues ->
val kotlinReceiverType = stubGenerator.declarationMapper
.getKotlinClassFor(container, isMeta = method.isClass)
.type.render(stubGenerator.kotlinFile)
val kotlinRawReceiver = kotlinValues.first()
val kotlinReceiver = "$kotlinRawReceiver.uncheckedCast<$kotlinReceiverType>()"
val namedArguments = kotlinValues.drop(1).zip(method.getKotlinParameterNames()) { value, name ->
"${name.asSimpleName()} = $value"
}
"${kotlinReceiver}.${method.kotlinName.asSimpleName()}(${namedArguments.joinToString()})"
}
if (returnType.unwrapTypedefs() is VoidType) {
out(" $callExpr;")
} else {
out(" return $callExpr;")
}
out("}")
return functionName
}
| apache-2.0 | 8906672f78f3a792021cfdd708676578 | 37.183986 | 122 | 0.644776 | 5.09062 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/call/bound/jvmStaticObjectPropertyAccessors.kt | 2 | 1080 | // TODO: investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.*
import kotlin.test.assertEquals
object Host {
@JvmStatic val x = 1
@JvmStatic var y = 2
@JvmStatic val xx: Int
get() = x
@JvmStatic var yy: Int
get() = y
set(value) { y = value }
}
val c_x = Host::x
val c_xx = Host::xx
val c_y = Host::y
val c_yy = Host::yy
fun box(): String {
assertEquals(1, c_x.getter())
assertEquals(1, c_x.getter.call())
assertEquals(1, c_xx.getter())
assertEquals(1, c_xx.getter.call())
assertEquals(2, c_y.getter())
assertEquals(2, c_y.getter.call())
assertEquals(2, c_yy.getter())
assertEquals(2, c_yy.getter.call())
c_y.setter(10)
assertEquals(10, c_y.getter())
assertEquals(10, c_yy.getter())
c_yy.setter(20)
assertEquals(20, c_y.getter())
assertEquals(20, c_yy.getter())
c_y.setter.call(100)
assertEquals(100, c_yy.getter.call())
c_yy.setter.call(200)
assertEquals(200, c_y.getter.call())
return "OK"
}
| apache-2.0 | b989e8d5ec73522a7d3b894c2dc04f3a | 20.176471 | 51 | 0.611111 | 3.050847 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyModuleNameCompletionContributor.kt | 1 | 3894 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.project.DumbAware
import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.PythonRuntimeService
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyImportStatementBase
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.resolve.fromFoothold
import com.jetbrains.python.psi.resolve.resolveQualifiedName
import com.jetbrains.python.psi.types.PyModuleType
import com.jetbrains.python.psi.types.PyType
import org.jetbrains.annotations.TestOnly
/**
* Adds completion variants for modules and packages, inserts a dot after and calls completion on the result,
* see [PyUnresolvedModuleAttributeCompletionContributor]
*/
class PyModuleNameCompletionContributor : CompletionContributor(), DumbAware {
companion object {
// temporary solution for tests that are not prepared for module name completion firing everywhere
@TestOnly
@JvmField
var ENABLED = true
}
/**
* Checks whether completion should be performed for a given [parameters] and delegates actual work to [doFillCompletionVariants].
*/
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (!shouldDoCompletion(parameters)) return
doFillCompletionVariants(parameters, result)
}
fun doFillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
getCompletionVariants(parameters.position.parent, parameters.originalFile).asSequence()
.filterIsInstance<LookupElementBuilder>()
.filter { result.prefixMatcher.prefixMatches(it.lookupString) }
.filterNot { it.lookupString.startsWith('_') }
.forEach { result.addElement(it) }
}
private fun getCompletionVariants(element: PsiElement, file: PsiElement): List<Any> {
val alreadyAddedNames = HashSet<String>()
val result = ArrayList<Any>()
resolveQualifiedName(QualifiedName.fromComponents(), fromFoothold(file))
.asSequence()
.filterIsInstance<PsiDirectory>()
.forEach {
val initPy = it.findFile(PyNames.INIT_DOT_PY)
if (initPy is PyFile) {
val moduleType = PyModuleType(initPy)
val context = ProcessingContext()
context.put(PyType.CTX_NAMES, alreadyAddedNames)
val completionVariants = moduleType.getCompletionVariants("", element, context)
result.addAll(listOf(*completionVariants))
}
else {
result.addAll(PyModuleType.getSubModuleVariants(it, element, alreadyAddedNames))
}
}
return result
}
private fun shouldDoCompletion(parameters: CompletionParameters): Boolean {
if (!ENABLED || PythonRuntimeService.getInstance().isInPydevConsole(parameters.originalFile)) {
return false
}
val element = parameters.position
val parent = element.parent
val provider = element.containingFile.viewProvider
if (provider is MultiplePsiFilesPerDocumentFileViewProvider) {
return false
}
return parent is PyReferenceExpression
&& !parent.isQualified
&& PsiTreeUtil.getParentOfType(element, PyImportStatementBase::class.java) == null
}
}
| apache-2.0 | e36de0c185377086d7e12fc24dacadb1 | 40.425532 | 140 | 0.768362 | 4.885822 | false | false | false | false |
alibaba/p3c | eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt | 2 | 1041 | package com.alibaba.smartfox.eclipse.ui.pmd
/**
* This class contains information for syntax coloring and styling for an
* extension
*/
class SyntaxData(val extension: String) {
var varnameReference: String? = null
var stringStart: String? = null
var stringEnd: String? = null
private var keywords: Collection<String>? = null
private var punctuation: String? = null
var comment: String? = null
var multiLineCommentStart: String? = null
var multiLineCommentEnd: String? = null
fun matches(otherExtension: String): Boolean {
return extension == otherExtension
}
fun isKeyword(word: String): Boolean {
return keywords != null && keywords!!.contains(word)
}
fun isPunctuation(ch: Char): Boolean {
return punctuation != null && punctuation!!.indexOf(ch) >= 0
}
fun setKeywords(keywords: Collection<String>) {
this.keywords = keywords
}
fun setPunctuation(thePunctuationChars: String) {
punctuation = thePunctuationChars
}
}
| apache-2.0 | af90dc51b2581b0da18e303031554793 | 27.135135 | 73 | 0.675312 | 4.448718 | false | false | false | false |
SwiftPengu/ProbabilisticVulnerabilityAnalysis | IEAATParser/src/main/kotlin/nl/utwente/fmt/ieaatparser/prm/PRMTransformer.kt | 1 | 18765 | package nl.utwente.fmt.ieaatparser.prm
import ics.eaat.abstractmodeller.newmodel.*
import nl.utwente.fmt.ieaatparser.antlr.*
import nl.utwente.fmt.ieaatparser.destructurePartition
import nl.utwente.fmt.ieaatparser.generateUUID
import org.antlr.v4.runtime.ANTLRInputStream
import org.antlr.v4.runtime.BailErrorStrategy
import org.antlr.v4.runtime.CommonTokenStream
import org.apache.commons.io.input.ReaderInputStream
import pva.*
import pva.probcode.ProbabilisticCode
import java.io.StringReader
import java.nio.charset.Charset
/**
* Constants
*/
val CONST_ASSET = "Asset"
val CONST_ATTACKSTEP = "AttackStep"
val CONST_DEFENCE = "Defense"
val CONST_ATTACKER = "Attacker"
val CONST_FUNCTIONING = "Functioning"
val CONST_LIKELIHOOD = "Likelihood"
val CONST_WORKDAYS = "Workdays"
val TOP_LEVEL_CYSEMOL_CLASSES = listOf(CONST_ASSET, CONST_ATTACKSTEP, CONST_DEFENCE, CONST_ATTACKER)
val CONST_GETPATHS = "getPaths"
val CONST_ISACCESSIBLE = "isAccessible"
val CONST_ISFUNCTIONING = "isFunctioning"
val USEFUL_P2AMF_METHODS = listOf(CONST_ISACCESSIBLE, CONST_ISFUNCTIONING)
val pvaFactory: PVAFactory = PVAFactory.eINSTANCE
/**
* Map which allows the exporter to export the correct type of invalid orphaned PRM objects
*/
val ORPHAN_FIX: Map<String, ConcreteType> = mapOf(
"BypassDetectionSystems" to pvaFactory.createAttackStepType().apply {
name ="BypassDetectionSystems"
uuid = generateUUID()
succeeded = pvaFactory.createProbabilisticProperty().apply {
uuid = generateUUID()
}
}, "NetworkVulnerabilityScanner" to pvaFactory.createDefenceType().apply {
name ="NetworkVulnerabilityScanner"
uuid = generateUUID()
functioning = pvaFactory.createProbabilisticProperty().apply {
uuid = generateUUID()
}
}
)
/**
* Class containing methods for converting the CySeMoL PRM to an instance of the new EMF PRM model
*/
data class PRMTransformer(val classes : List<OCLClass>) {
fun parse(): PVAContainer {
val modelContainer = pvaFactory.createPVAContainer()
//ensure all instances are generated first
generateConcreteTypes(classes, modelContainer)
//generate all relevant template instances
generateTemplates(classes, modelContainer)
//afterwards, instantiate all relations
generateAssetRelations(classes, modelContainer)
//finally parse the P2AMF code, which needs references to all classes
generateP2AMFTypes(classes, modelContainer)
generateVirtualConnections(modelContainer)
return modelContainer
}
private fun generateVirtualConnections(modelContainer: PVAContainer) {
modelContainer.concreteTypes.flatMap {
it.connectedTo
}.filterIsInstance<VirtualConnection>().forEach { edge ->
parseVirtualEdge(edge,virtualConnectionLookup[edge]!!,modelContainer)
}
}
/**
* Generates all relevant template instances:
* Template Definitions
* Template Connections (connectionPorts)
* Template Properties (attributes)
*/
private fun generateTemplates(classes: List<OCLClass>, pvaModel: PVAContainer) {
classes.flatMap {
it.allInstances.map { it.parent }
}.distinct().map {
it as MetaTemplate
}.filterNot {
it.name == CONST_ATTACKER
}.forEach { metatemplate ->
// Template definitions
val templateDef = createTemplateDefinition(metatemplate, pvaModel)
// TemplateDefinition.TypeInstantiation.properties association
metatemplate.attributes.forEach { attribute ->
val instantiation = templateDef.instantiations.singleOrNull { it.name == attribute.owner.name }
?: throw RuntimeException("Ambiguous or no instantiation found for ${templateDef.name}->${attribute.owner.name}")
instantiation.properties += when(attribute.attribute.name){
CONST_FUNCTIONING -> {
(instantiation.concretization as DefenceType).functioning
}
CONST_LIKELIHOOD -> {
(instantiation.concretization as AttackStepType).succeeded
}
else -> throw RuntimeException("Unsupported attribute ${attribute.attribute.completeName}")
}
}
// Store the created template definition
pvaModel.templateTypes += templateDef
}
}
private fun createTemplateDefinition(metatemplate: MetaTemplate, pvaModel: PVAContainer): TemplateDefinition {
return pvaFactory.createTemplateDefinition().apply {
uuid = generateUUID()
name = metatemplate.toTemplateName()
val templateObjects = metatemplate.templateChildren.filter {
it.name != CONST_WORKDAYS
}.map {
it as TemplateObject
}
// Generate type instantiations
instantiations += templateObjects.distinctBy {
it.name //discard double named template objects
}.map { templateObject ->
val instanceName = templateObject.name
val className = templateObject.oclClass.name
pvaFactory.createTypeInstantiation().apply {
name = instanceName
uuid = generateUUID()
concretization = lookupConcrete(className, pvaModel, { "Failed to find Concrete Type $className" })
}
}
//Generate instantiation and external connections
templateObjects.forEach { templateObject ->
val currentInstantiation = instantiations.singleOrNull { it.name == templateObject.name }
?: throw RuntimeException("No unique instantiation not found! ${templateObject.name}")
//create instantiation connections
currentInstantiation.internalConnections += templateObject.associations.filter {
"Functioning" !in listOf(it.childPort.owner.name, it.parentPort.owner.name)
}.map { association ->
//Determine source and target ports from our perspective
val (sourcePort, targetPort) = listOf<Port>(association.childPort, association.parentPort).partition {
it.owner.name == templateObject.name
}.destructurePartition()
//Create the actual connection
assert(sourcePort.owner.name == templateObject.name, { "${sourcePort.owner.name} is not equal to ${templateObject.name}" })
pvaFactory.createInstantiationConnection().apply {
uuid = generateUUID()
label = sourcePort.name
target = instantiations.singleOrNull { it.name == targetPort.owner.name } ?:
throw RuntimeException("No unique instantiation target found for ${targetPort.owner.name}")
concretization = pvaModel.concreteTypes.flatMap {
it.connectedTo
}.singleOrNull {
it.name == sourcePort.reference.toEdgeName(
sourcePort.reference.childClass.name == sourcePort.connectionEnd.name
)
} ?: throw RuntimeException("Concrete relation not found! ${sourcePort.name}")
}
}
val internalPorts = templateObject.associations.flatMap {
listOf(it.childPort, it.parentPort)
}
currentInstantiation.externalConnections += templateObject.connectionPorts.filter {
it !in internalPorts // Skip ports with internal associations
}.filterNot {
it.connectionEnd.name == CONST_ATTACKSTEP
}.map { port ->
val reversed = port.reference.parentClass != templateObject.oclClass
pvaModel.concreteTypes.flatMap {
it.connectedTo
}.singleOrNull {
it.name == port.reference.toEdgeName(reversed)
} ?: throw RuntimeException("Concrete relation not found! ${port.name}")
}
}
}
}
/**
* Generates all relevant concrete types, being:
* -Asset Types
* -Defence Types
* -AttackStep Types
* -Concrete Connections
*/
private fun generateConcreteTypes(classes: List<OCLClass>, pvaModel: PVAContainer) {
val nonTopLevelClasses = classes.filter {
it.name !in TOP_LEVEL_CYSEMOL_CLASSES
}
//Assets, Defences, and AttackSteps
nonTopLevelClasses.forEach {
pvaModel.concreteTypes += when (it.superclass?.name) {
//Asset types
CONST_ASSET ->
pvaFactory.createAssetType().apply {
uuid = generateUUID()
name = it.name
}
//Attack step types
CONST_ATTACKSTEP ->
pvaFactory.createAttackStepType().apply {
uuid = generateUUID()
name = it.name
succeeded = pvaFactory.createProbabilisticProperty().apply {
name = "succeeded"
uuid = generateUUID()
}
}
//Defence types
CONST_DEFENCE ->
pvaFactory.createDefenceType().apply {
uuid = generateUUID()
name = it.name
functioning = pvaFactory.createProbabilisticProperty().apply {
name = "functioning"
uuid = generateUUID()
}
}
else ->
if (it.name in ORPHAN_FIX.keys) {
println("Warn: ${it.name} has no valid parent, applying fix...")
ORPHAN_FIX[it.name]
} else {
throw RuntimeException("Error: ${it.name} has no valid parent and has no fix.")
}
}
}
//Assumption: All concrete types have been created at this point
//Concrete connections
nonTopLevelClasses.flatMap {
it.references
}.distinct().forEach { reference ->
createConnection(reference, pvaModel)
}
}
private fun createConnection(reference: Reference, pvaModel : PVAContainer) {
val sourceType = lookupConcrete<ConcreteType>(reference.parentClass.name, pvaModel, {"Source lookup failed ${reference.parentClass.name}"})
val targetType = lookupConcrete<ConcreteType>(reference.childClass.name, pvaModel, {"Target lookup failed ${reference.childClass.name}"})
//parent -> child
newConnection(reference,false).apply {
uuid = generateUUID()
name = reference.toEdgeName(false)
label = reference.parentToChildLabel
relationName = reference.label
target = targetType
}.apply {
sourceType.connectedTo += this
}
//child -> parent
newConnection(reference,true).apply {
uuid = generateUUID()
name = reference.toEdgeName(true)
label = reference.childToParentLabel
relationName = reference.label
target = sourceType
}.apply {
targetType.connectedTo += this
}
}
//Store the original reference for each virtualconnection for easy lookup later
private val virtualConnectionLookup = mutableMapOf<VirtualConnection,Reference>()
private fun newConnection(ref : Reference, reversed: Boolean = false) : ConcreteConnection = if(ref.derivedBody==null){
pvaFactory.createConcreteConnection()
}else{
pvaFactory.createVirtualConnection().apply {
this.isReversed = reversed
virtualConnectionLookup[this] = ref
}
}
/**
* Generate all asset relations
* AssetType.attackedBy
* AssetType.defendedBy
*/
private fun generateAssetRelations(classes: List<OCLClass>, pvaModel: PVAContainer) {
val assets = classes.filter {
it.superclass?.name == CONST_ASSET
}
val attackSteps = classes.filter {
it.superclass?.name == CONST_ATTACKSTEP
}
generateAssetTypeAttackedBy(assets, pvaModel)
generateAssetTypeDefendedBy(assets, pvaModel)
generateAttackStepEnables(attackSteps, pvaModel)
}
private fun generateAssetTypeDefendedBy(assets: List<OCLClass>, pvaModel: PVAContainer) {
generateAssetTypeAssociation<DefenceType>(assets, pvaModel, CONST_DEFENCE, { asset, defence ->
asset.defendedBy += defence
})
}
private fun generateAssetTypeAttackedBy(assets: List<OCLClass>, pvaModel: PVAContainer) {
generateAssetTypeAssociation<AttackStepType>(assets, pvaModel, CONST_ATTACKSTEP, { asset, atstep ->
atstep.target = asset // Note: source and target are swapped with regard to the generateAssetTypeDefendedBy method!!!
})
}
/**
* Helper method for assigning the Xby associations of AssetTypes
*/
inline private fun <reified T : ConcreteType> generateAssetTypeAssociation(
assets: List<OCLClass>,
pvaModel: PVAContainer,
typeString: String,
assignToLookup: ((AssetType, T) -> (Unit))) {
assets.forEach { oclAsset ->
//Get the PVA class for the this asset
val assetName = oclAsset.name
val asset: AssetType = lookupConcrete(assetName, pvaModel, {
"Asset lookup failed $assetName"
})
oclAsset.references.filter {
it.parentClass?.superclass?.name == typeString //Only consider references from the correct type
}.forEach { reference ->
assignToLookup(asset,
lookupConcrete(reference.parentClass.name, pvaModel, {
"$typeString lookup failed: ${reference.parentClass.name}"
})
)
}
}
}
/**
* Generate 'enables' edges between attack steps
*/
private fun generateAttackStepEnables(attackSteps: List<OCLClass>, pvaModel: PVAContainer) {
attackSteps.forEach { attackStepClass ->
val attackStepType = lookupConcrete<AttackStepType>(attackStepClass.name,pvaModel)
val code = attackStepClass.operations.single {
it.name == CONST_GETPATHS
}.body
attackStepType.enables += parseGetPaths(attackStepType,code).distinct()
}
}
/**
* Generates all properties present in the CySeMoL
*/
private fun generateP2AMFTypes(classes: List<OCLClass>, pvaModel: PVAContainer) {
classes.filter {
it.name !in TOP_LEVEL_CYSEMOL_CLASSES
}.flatMap { oclclass -> //obtain all method bodies
oclclass.operations.filter {
it.body != null
}.map { op ->
P2AMFOperation(oclclass, op.name, op.body)
}
}.filter { //only store useful methods
it.operationName in USEFUL_P2AMF_METHODS
}.distinctBy { it.body }.forEach { p2amfdef ->
val operationOwner: ConcreteType = lookupConcrete(p2amfdef.parent.name, pvaModel, {
"Owner of operation ${p2amfdef.qualifiedName} not found."
})
parseP2AMF(pvaModel, operationOwner, p2amfdef).let { implementation ->
when(operationOwner){
is DefenceType -> operationOwner.functioning.implementation = implementation
is AttackStepType -> operationOwner.succeeded.implementation = implementation
else -> throw IllegalStateException("Illegal owner type")
}
}
}
}
/**
* Invokes the ANTLR4 parser, and converts its AST to the P2AMF metamodel
*/
private fun parseP2AMF(model: PVAContainer, owner: ConcreteType, code: P2AMFOperation): ProbabilisticCode {
ReaderInputStream(StringReader(code.body), Charset.defaultCharset()).use { stream ->
val lexer = P2AMFLexer(ANTLRInputStream(stream))
val parser = P2AMFParser(CommonTokenStream(lexer)).apply {
this.buildParseTree = true
this.errorHandler = BailErrorStrategy()
}
val parseTree = parser.program()
return P2AMFBuilder(pva = model, codeOwner = owner).visitProgram(parseTree)
}
}
/**
* Invokes the ANTLR4 parser, and converts its AST to the P2AMF metamodel
*/
private fun parseGetPaths(owner: AttackStepType, code: String) : List<AttackStepType> {
ReaderInputStream(StringReader(code), Charset.defaultCharset()).use { stream ->
val lexer = GetPathsLexer(ANTLRInputStream(stream))
val parser = GetPathsParser(CommonTokenStream(lexer)).apply {
this.buildParseTree = true
this.errorHandler = BailErrorStrategy()
}
val parseTree = parser.paths()
return GetPathsBuilder(owner).getEnables(parseTree)
}
}
/**
* Invokes the ANTLR4 parser, and converts its AST to the P2AMF metamodel
*/
private fun parseVirtualEdge(edge: VirtualConnection, ref: Reference, modelContainer: PVAContainer) {
// For virtual edges, the parent of the edge is the perspective of the derivation
val derivationContext: ConcreteType = lookupConcrete(ref.parentClass.name,modelContainer)
ReaderInputStream(StringReader(ref.derivedBody), Charset.defaultCharset()).use { stream ->
val lexer = VirtualEdgesLexer(ANTLRInputStream(stream))
val parser = VirtualEdgesParser(CommonTokenStream(lexer)).apply {
this.buildParseTree = true
this.errorHandler = BailErrorStrategy()
}
val parseTree = parser.path()
//Find the connections, and add them to the edge
edge.path += VirtualEdgeBuilder(derivationContext,edge).buildEdges(parseTree)
}
}
} | mit | 57c6f93182a24f55954811a1595ab19e | 40.609756 | 147 | 0.602078 | 4.903319 | false | false | false | false |
jotomo/AndroidAPS | dana/src/main/java/info/nightscout/androidaps/dana/comm/RecordTypes.kt | 2 | 655 | package info.nightscout.androidaps.dana.comm
object RecordTypes {
const val RECORD_TYPE_BOLUS = 0x01.toByte()
const val RECORD_TYPE_DAILY = 0x02.toByte()
const val RECORD_TYPE_PRIME = 0x03.toByte()
const val RECORD_TYPE_ERROR = 0x04.toByte()
const val RECORD_TYPE_ALARM = 0x05.toByte()
const val RECORD_TYPE_GLUCOSE = 0x06.toByte()
const val RECORD_TYPE_CARBO = 0x08.toByte()
const val RECORD_TYPE_REFILL = 0x09.toByte()
const val RECORD_TYPE_SUSPEND = 0x0B.toByte()
const val RECORD_TYPE_BASALHOUR = 0x0C.toByte()
const val RECORD_TYPE_TB = 0x0D.toByte()
const val RECORD_TYPE_TEMP_BASAL = 0x14.toByte()
} | agpl-3.0 | 73706c6ada5117d5fe21e1eb78daf027 | 40 | 52 | 0.705344 | 3.149038 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/MoveKotlinFileHandler.kt | 3 | 6553 | // 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.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiCompiledElement
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.light.LightElement
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFileHandler
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit
import org.jetbrains.kotlin.idea.refactoring.hasIdentifiersOnly
import org.jetbrains.kotlin.idea.refactoring.move.ContainerChangeInfo
import org.jetbrains.kotlin.idea.refactoring.move.ContainerInfo
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.refactoring.move.updatePackageDirective
import org.jetbrains.kotlin.idea.roots.isOutsideKotlinAwareSourceRoot
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.UserDataProperty
internal var KtFile.allElementsToMove: List<PsiElement>? by UserDataProperty(Key.create("SCOPE_TO_MOVE"))
class MoveKotlinFileHandler : MoveFileHandler() {
internal class FileInfo(file: KtFile) : UsageInfo(file)
// This is special 'PsiElement' whose purpose is to wrap MoveKotlinTopLevelDeclarationsProcessor
// so that it can be kept in the usage info list
private class MoveContext(
val file: PsiFile,
val declarationMoveProcessor: MoveKotlinDeclarationsProcessor
) : LightElement(file.manager, KotlinLanguage.INSTANCE) {
override fun toString() = ""
}
private fun KtFile.getPackageNameInfo(newParent: PsiDirectory?, clearUserData: Boolean): ContainerChangeInfo? {
val shouldUpdatePackageDirective = updatePackageDirective ?: packageMatchesDirectoryOrImplicit()
updatePackageDirective = if (clearUserData) null else shouldUpdatePackageDirective
if (!shouldUpdatePackageDirective) return null
val oldPackageName = packageFqName
val newPackageName = newParent?.getFqNameWithImplicitPrefix() ?: return ContainerChangeInfo(
ContainerInfo.Package(oldPackageName),
ContainerInfo.UnknownPackage
)
if (oldPackageName.asString() == newPackageName.asString()
&& ModuleUtilCore.findModuleForPsiElement(this) == ModuleUtilCore.findModuleForPsiElement(newParent)
) return null
if (!newPackageName.hasIdentifiersOnly()) return null
return ContainerChangeInfo(ContainerInfo.Package(oldPackageName), ContainerInfo.Package(newPackageName))
}
fun initMoveProcessor(psiFile: PsiFile, newParent: PsiDirectory?, withConflicts: Boolean): MoveKotlinDeclarationsProcessor? {
if (psiFile !is KtFile) return null
val packageNameInfo = psiFile.getPackageNameInfo(newParent, false) ?: return null
val project = psiFile.project
val moveTarget = when (val newPackage = packageNameInfo.newContainer) {
ContainerInfo.UnknownPackage -> EmptyKotlinMoveTarget
else -> if (newParent == null) {
return null
} else {
KotlinMoveTargetForDeferredFile(newPackage.fqName!!, newParent.virtualFile) {
MoveFilesOrDirectoriesUtil.doMoveFile(psiFile, newParent)
val file = newParent.findFile(psiFile.name) ?: error("Lost file after move")
file as KtFile
}
}
}
return MoveKotlinDeclarationsProcessor(
MoveDeclarationsDescriptor(
project = project,
moveSource = MoveSource(psiFile),
moveTarget = moveTarget,
delegate = MoveDeclarationsDelegate.TopLevel,
allElementsToMove = psiFile.allElementsToMove,
analyzeConflicts = withConflicts
)
)
}
override fun canProcessElement(element: PsiFile?): Boolean {
if (element is PsiCompiledElement || element !is KtFile) return false
return !isOutsideKotlinAwareSourceRoot(element)
}
override fun findUsages(
psiFile: PsiFile,
newParent: PsiDirectory?,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean
): List<UsageInfo> {
return findUsages(psiFile, newParent, true)
}
fun findUsages(
psiFile: PsiFile,
newParent: PsiDirectory?,
withConflicts: Boolean
): List<UsageInfo> {
if (psiFile !is KtFile) return emptyList()
val usages = arrayListOf<UsageInfo>(FileInfo(psiFile))
initMoveProcessor(psiFile, newParent, withConflicts)?.let {
usages += it.findUsages()
usages += it.getConflictsAsUsages()
}
return usages
}
override fun prepareMovedFile(file: PsiFile, moveDestination: PsiDirectory, oldToNewMap: MutableMap<PsiElement, PsiElement>) {
if (file !is KtFile) return
val moveProcessor = initMoveProcessor(file, moveDestination, false) ?: return
val moveContext = MoveContext(file, moveProcessor)
oldToNewMap[moveContext] = moveContext
val packageNameInfo = file.getPackageNameInfo(moveDestination, true) ?: return
val newFqName = packageNameInfo.newContainer.fqName
if (newFqName != null) {
file.packageDirective?.fqName = newFqName.quoteIfNeeded()
}
}
override fun updateMovedFile(file: PsiFile) {
}
override fun retargetUsages(usageInfos: List<UsageInfo>?, oldToNewMap: Map<PsiElement, PsiElement>) {
val currentFile = (usageInfos?.firstOrNull() as? FileInfo)?.element
val moveContext = oldToNewMap.keys.firstOrNull { it is MoveContext && it.file == currentFile } as? MoveContext ?: return
retargetUsages(usageInfos, moveContext.declarationMoveProcessor)
}
fun retargetUsages(usageInfos: List<UsageInfo>?, moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor) {
usageInfos?.let { moveDeclarationsProcessor.doPerformRefactoring(it) }
}
}
| apache-2.0 | 5cb2e05bebd3ab4e28918ae1a66c4b63 | 43.277027 | 158 | 0.720586 | 5.250801 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/testSources/com/intellij/openapi/roots/TestCustomSourceRoot.kt | 5 | 3899 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("unused")
package com.intellij.openapi.roots
import com.intellij.jps.impl.JpsPluginBean
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.lang.UrlClassLoader
import org.jdom.Element
import org.jetbrains.jps.model.ex.JpsElementBase
import org.jetbrains.jps.model.ex.JpsElementTypeBase
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
import java.io.File
class TestCustomRootModelSerializerExtension : JpsModelSerializerExtension() {
override fun getModuleSourceRootPropertiesSerializers(): List<JpsModuleSourceRootPropertiesSerializer<*>> =
listOf(TestCustomSourceRootPropertiesSerializer(TestCustomSourceRootType.INSTANCE, TestCustomSourceRootType.TYPE_ID))
companion object {
fun registerTestCustomSourceRootType(tempPluginRoot: File, disposable: Disposable) {
val jpsPluginDisposable = Disposer.newDisposable()
Disposer.register(disposable, Disposable {
runWriteActionAndWait {
Disposer.dispose(jpsPluginDisposable)
}
})
FileUtil.writeToFile(File(tempPluginRoot, "META-INF/services/${JpsModelSerializerExtension::class.java.name}"),
TestCustomRootModelSerializerExtension::class.java.name)
val pluginClassLoader = UrlClassLoader.build()
.parent(TestCustomRootModelSerializerExtension::class.java.classLoader)
.files(listOf(tempPluginRoot.toPath()))
.get()
val pluginDescriptor = DefaultPluginDescriptor(PluginId.getId("com.intellij.custom.source.root.test"), pluginClassLoader)
JpsPluginBean.EP_NAME.point.registerExtension(JpsPluginBean(), pluginDescriptor, jpsPluginDisposable)
}
}
}
class TestCustomSourceRootType private constructor() : JpsElementTypeBase<TestCustomSourceRootProperties>(), JpsModuleSourceRootType<TestCustomSourceRootProperties> {
override fun isForTests(): Boolean = false
override fun createDefaultProperties(): TestCustomSourceRootProperties = TestCustomSourceRootProperties("default properties")
companion object {
val INSTANCE = TestCustomSourceRootType()
const val TYPE_ID = "custom-source-root-type"
}
}
class TestCustomSourceRootProperties(initialTestString: String?) : JpsElementBase<TestCustomSourceRootProperties>() {
var testString: String? = initialTestString
set(value) {
if (value != field) {
field = value
fireElementChanged()
}
}
override fun createCopy(): TestCustomSourceRootProperties {
return TestCustomSourceRootProperties(testString)
}
override fun applyChanges(modified: TestCustomSourceRootProperties) {
testString = modified.testString
}
}
class TestCustomSourceRootPropertiesSerializer(
type: JpsModuleSourceRootType<TestCustomSourceRootProperties>, typeId: String)
: JpsModuleSourceRootPropertiesSerializer<TestCustomSourceRootProperties>(type, typeId) {
override fun loadProperties(sourceRootTag: Element): TestCustomSourceRootProperties {
val testString = sourceRootTag.getAttributeValue("testString")
return TestCustomSourceRootProperties(testString)
}
override fun saveProperties(properties: TestCustomSourceRootProperties, sourceRootTag: Element) {
val testString = properties.testString
if (testString != null) {
sourceRootTag.setAttribute("testString", testString)
}
}
}
| apache-2.0 | 9828e09803bc553afc44e5e9ec1b41ac | 40.924731 | 166 | 0.790972 | 5.348422 | false | true | false | false |
siosio/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/CloneDialogLoginPanel.kt | 1 | 7010 | // 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.ui.cloneDialog
import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonShortcuts.ENTER
import com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.ComponentValidator
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes.ERROR_ATTRIBUTES
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.layout.*
import com.intellij.ui.scale.JBUIScale.scale
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.JBUI.emptyInsets
import com.intellij.util.ui.UIUtil.getRegularPanelInsets
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.ui.GithubLoginPanel
import org.jetbrains.plugins.github.i18n.GithubBundle.message
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.SwingConstants.TOP
internal class CloneDialogLoginPanel(private val account: GithubAccount?) :
JBPanel<CloneDialogLoginPanel>(VerticalLayout(0)),
Disposable {
private val authenticationManager get() = GithubAuthenticationManager.getInstance()
private val errorPanel = JPanel(VerticalLayout(10))
private val loginPanel = GithubLoginPanel(GithubApiRequestExecutor.Factory.getInstance()) { name, server ->
if (account == null) authenticationManager.isAccountUnique(name, server) else true
}
private val inlineCancelPanel = simplePanel()
private val loginButton = JButton(message("button.login.mnemonic"))
private val backLink = LinkLabel<Any?>(IdeBundle.message("button.back"), null).apply { verticalAlignment = TOP }
private var errors = emptyList<ValidationInfo>()
private var loginIndicator: ProgressIndicator? = null
var isCancelVisible: Boolean
get() = backLink.isVisible
set(value) {
backLink.isVisible = value
}
init {
buildLayout()
if (account != null) {
loginPanel.setServer(account.server.toUrl(), false)
loginPanel.setLogin(account.name, false)
}
loginButton.addActionListener { login() }
LoginAction().registerCustomShortcutSet(ENTER, loginPanel)
}
fun setCancelHandler(listener: () -> Unit) =
backLink.setListener(
{ _, _ ->
cancelLogin()
listener()
},
null
)
fun setTokenUi() {
setupNewUi(false)
loginPanel.setTokenUi()
}
fun setOAuthUi() {
setupNewUi(true)
loginPanel.setOAuthUi()
login()
}
fun setServer(path: String, editable: Boolean) = loginPanel.setServer(path, editable)
override fun dispose() = Unit
private fun buildLayout() {
add(JPanel(HorizontalLayout(0)).apply {
add(loginPanel)
add(inlineCancelPanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { left = scale(6) }) })
})
add(errorPanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { top = 0 }) })
}
private fun setupNewUi(isOAuth: Boolean) {
loginButton.isVisible = !isOAuth
backLink.text = if (isOAuth) IdeBundle.message("link.cancel") else IdeBundle.message("button.back")
loginPanel.footer = { if (!isOAuth) buttonPanel() } // footer is used to put buttons in 2-nd column - align under text boxes
if (isOAuth) inlineCancelPanel.addToCenter(backLink)
inlineCancelPanel.isVisible = isOAuth
clearErrors()
}
private fun LayoutBuilder.buttonPanel() =
row("") {
cell {
loginButton()
backLink().withLargeLeftGap()
}
}
fun cancelLogin() {
loginIndicator?.cancel()
loginIndicator = null
}
private fun login() {
cancelLogin()
loginPanel.setError(null)
clearErrors()
if (!doValidate()) return
val modalityState = ModalityState.stateForComponent(this)
val indicator = EmptyProgressIndicator(modalityState)
loginIndicator = indicator
loginPanel.acquireLoginAndToken(indicator)
.completionOnEdt(modalityState) {
loginIndicator = null
clearErrors()
}
.errorOnEdt(modalityState) { doValidate() }
.successOnEdt(modalityState) { (login, token) ->
if (account != null) {
authenticationManager.updateAccountToken(account, token)
}
else {
authenticationManager.registerAccount(login, loginPanel.getServer(), token)
}
}
}
private fun doValidate(): Boolean {
errors = loginPanel.doValidateAll()
setErrors(errors)
val toFocus = errors.firstOrNull()?.component
if (toFocus?.isVisible == true) IdeFocusManager.getGlobalInstance().requestFocus(toFocus, true)
return errors.isEmpty()
}
private fun clearErrors() {
for (component in errors.mapNotNull { it.component }) {
ComponentValidator.getInstance(component).ifPresent { it.updateInfo(null) }
}
errorPanel.removeAll()
errors = emptyList()
}
private fun setErrors(errors: Collection<ValidationInfo>) {
for (error in errors) {
val component = error.component
if (component != null) {
ComponentValidator.getInstance(component)
.orElseGet { ComponentValidator(this).installOn(component) }
.updateInfo(error)
}
else {
errorPanel.add(toErrorComponent(error))
}
}
errorPanel.revalidate()
errorPanel.repaint()
}
private fun toErrorComponent(info: ValidationInfo): JComponent =
SimpleColoredComponent().apply {
myBorder = empty()
ipad = emptyInsets()
append(info.message, ERROR_ATTRIBUTES)
}
private inner class LoginAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.getData(CONTEXT_COMPONENT) != backLink
}
override fun actionPerformed(e: AnActionEvent) = login()
}
} | apache-2.0 | 0ad47639be6216e1565ca804d6017cf5 | 32.070755 | 140 | 0.73766 | 4.519665 | false | false | false | false |
zsmb13/MaterialDrawerKt | app/src/main/java/co/zsmb/materialdrawerktexample/originalactivities/FullscreenDrawerActivity.kt | 1 | 3021 | package co.zsmb.materialdrawerktexample.originalactivities
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import co.zsmb.materialdrawerkt.builders.drawer
import co.zsmb.materialdrawerkt.draweritems.badgeable.primaryItem
import co.zsmb.materialdrawerkt.draweritems.badgeable.secondaryItem
import co.zsmb.materialdrawerkt.draweritems.divider
import co.zsmb.materialdrawerkt.draweritems.sectionHeader
import co.zsmb.materialdrawerktexample.R
import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome
import com.mikepenz.materialdrawer.Drawer
import kotlinx.android.synthetic.main.activity_sample_fullscreen_dark_toolbar.*
class FullscreenDrawerActivity : AppCompatActivity() {
private lateinit var result: Drawer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample_fullscreen_dark_toolbar)
setSupportActionBar(toolbar)
toolbar.setBackgroundColor(android.graphics.Color.BLACK)
toolbar.background.alpha = 90
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(false)
result = drawer {
savedInstance = savedInstanceState
toolbar = [email protected]
translucentStatusBar = false
primaryItem(R.string.drawer_item_home) { iicon = FontAwesome.Icon.faw_home }
primaryItem(R.string.drawer_item_free_play) { iicon = FontAwesome.Icon.faw_gamepad }
primaryItem(R.string.drawer_item_custom) { iicon = FontAwesome.Icon.faw_eye }
sectionHeader(R.string.drawer_item_section_header)
secondaryItem(R.string.drawer_item_settings) { iicon = FontAwesome.Icon.faw_cog }
secondaryItem(R.string.drawer_item_help) { iicon = FontAwesome.Icon.faw_question }
secondaryItem(R.string.drawer_item_open_source) { iicon = FontAwesome.Icon.faw_github }
secondaryItem(R.string.drawer_item_contact) { iicon = FontAwesome.Icon.faw_bullhorn }
divider()
for (i in 1..20) {
primaryItem("Custom $i") { iicon = FontAwesome.Icon.faw_android }
}
selectedItemByPosition = 5
}
if (android.os.Build.VERSION.SDK_INT >= 19) {
result.drawerLayout.fitsSystemWindows = false
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
android.R.id.home -> {
onBackPressed(); true
}
else -> super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle) {
result.saveInstanceState(outState)
super.onSaveInstanceState(outState)
}
override fun onBackPressed() {
if (result.isDrawerOpen)
result.closeDrawer()
else
super.onBackPressed()
}
}
| apache-2.0 | 578b45ffa3a279e9c0a00d3e35ac6395 | 38.233766 | 99 | 0.688183 | 4.73511 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/protocol/protocol-model-generator/src/OutputClassScope.kt | 24 | 2619 | package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.TextOutput
internal class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : ClassScope(generator, classNamePath) {
fun <P : ItemDescriptor.Named> writeWriteCalls(out: TextOutput, parameters: List<Pair<P, BoxableType>>, qualifier: String?) {
for ((descriptor, type) in parameters) {
out.newLine()
if (qualifier != null) {
out.append(qualifier).append('.')
}
appendWriteValueInvocation(out, descriptor, descriptor.name(), type)
}
}
fun <P : ItemDescriptor.Named> writeMethodParameters(out: TextOutput, parameters: List<Pair<P, BoxableType>>, prependComma: Boolean) {
var needComa = prependComma
for ((descriptor, type) in parameters) {
if (needComa) {
out.comma()
}
else {
needComa = true
}
val shortText = type.getShortText(classContextNamespace)
out.append(descriptor.name()).append(": ")
out.append(if (shortText == "String") "CharSequence" else shortText)
if (descriptor.optional) {
val defaultValue: String
if (descriptor is ProtocolMetaModel.Parameter && descriptor.default != null) {
defaultValue = descriptor.default!!
}
else {
// todo generic solution to specify default value
defaultValue = if (descriptor.name() == "enabled") "true" else if (descriptor.name() == "maxStringLength") "100" else type.defaultValue ?: "null"
if (defaultValue == "null") {
out.append('?')
}
}
out.append(" = ").append(defaultValue)
}
}
}
private fun appendWriteValueInvocation(out: TextOutput, descriptor: ItemDescriptor.Named, valueRefName: String, type: BoxableType) {
// todo CallArgument (we should allow write null as value)
val allowNullableString = descriptor.name() == "value" && type.writeMethodName == "writeString"
out.append(if (allowNullableString) "writeNullableString" else type.writeMethodName).append('(')
out.quote(descriptor.name()).comma().append(valueRefName)
if (!allowNullableString && descriptor.optional && type.defaultValue != null && descriptor.name() != "depth" && type != BoxableType.MAP) {
out.comma().append(if (descriptor.name() == "enabled") "true" else if (descriptor.name() == "maxStringLength") "100" else type.defaultValue!!)
}
out.append(')')
}
override val typeDirection = TypeData.Direction.OUTPUT
}
| apache-2.0 | fb5a87335cfc07f7bcbcf97c125207df | 41.241935 | 155 | 0.673158 | 4.431472 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/MenuFrameHeader.kt | 3 | 4113 | // 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.wm.impl.customFrameDecorations.header
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.impl.IdeMenuBar
import com.intellij.openapi.wm.impl.customFrameDecorations.header.title.CustomHeaderTitle
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.util.ui.JBUI
import com.jetbrains.CustomWindowDecoration.*
import net.miginfocom.swing.MigLayout
import java.awt.Frame
import java.awt.Rectangle
import javax.swing.JComponent
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
import javax.swing.event.ChangeListener
import kotlin.math.roundToInt
internal class MenuFrameHeader(frame: JFrame, val headerTitle: CustomHeaderTitle, val myIdeMenu: IdeMenuBar) : FrameHeader(frame), MainFrameCustomHeader {
private val menuHolder: JComponent
private var changeListener: ChangeListener
private val mainMenuUpdater: UISettingsListener
private var disposable: Disposable? = null
init {
layout = MigLayout("novisualpadding, fillx, ins 0, gap 0, top, hidemode 2", "[pref!][][grow][pref!]")
val empty = JBUI.Borders.empty(V, H, V, 0)
productIcon.border = empty
add(productIcon)
changeListener = ChangeListener {
updateCustomDecorationHitTestSpots()
}
headerTitle.onBoundsChanged = { windowStateChanged() }
menuHolder = JPanel(MigLayout("filly, ins 0, novisualpadding, hidemode 3", "[pref!]${JBUI.scale(10)}"))
menuHolder.border = JBUI.Borders.empty(0, H - 1, 0, 0)
menuHolder.isOpaque = false
menuHolder.add(myIdeMenu, "wmin 0, wmax pref, top, growy")
add(menuHolder, "wmin 0, top, growy, pushx")
val view = headerTitle.view.apply {
border = empty
}
add(view, "left, growx, gapbottom 1")
add(buttonPanes.getView(), "top, wmin pref")
setCustomFrameTopBorder({ myState != Frame.MAXIMIZED_VERT && myState != Frame.MAXIMIZED_BOTH }, {true})
mainMenuUpdater = UISettingsListener {
menuHolder.isVisible = UISettings.getInstance().showMainMenu
SwingUtilities.invokeLater { updateCustomDecorationHitTestSpots() }
}
menuHolder.isVisible = UISettings.getInstance().showMainMenu
}
override fun updateMenuActions(forceRebuild: Boolean) {
myIdeMenu.updateMenuActions(forceRebuild)
}
override fun getComponent(): JComponent = this
override fun updateActive() {
super.updateActive()
headerTitle.setActive(myActive)
}
override fun installListeners() {
myIdeMenu.selectionModel.addChangeListener(changeListener)
val disp = Disposer.newDisposable()
Disposer.register(ApplicationManager.getApplication(), disp)
ApplicationManager.getApplication().messageBus.connect(disp).subscribe(UISettingsListener.TOPIC, mainMenuUpdater)
mainMenuUpdater.uiSettingsChanged(UISettings.getInstance())
disposable = disp
super.installListeners()
}
override fun uninstallListeners() {
myIdeMenu.selectionModel.removeChangeListener(changeListener)
disposable?.let {
if (!Disposer.isDisposed(it))
Disposer.dispose(it)
disposable = null
}
super.uninstallListeners()
}
override fun getHitTestSpots(): List<Pair<RelativeRectangle, Int>> {
val hitTestSpots = super.getHitTestSpots().toMutableList()
if (menuHolder.isVisible) {
val menuRect = Rectangle(menuHolder.size)
val state = frame.extendedState
if (state != Frame.MAXIMIZED_VERT && state != Frame.MAXIMIZED_BOTH) {
val topGap = (menuRect.height / 3).toFloat().roundToInt()
menuRect.y += topGap
menuRect.height -= topGap
}
hitTestSpots.add(Pair(RelativeRectangle(menuHolder, menuRect), MENU_BAR))
}
hitTestSpots.addAll(headerTitle.getBoundList().map { Pair(it, OTHER_HIT_SPOT) })
return hitTestSpots
}
} | apache-2.0 | c18914759d76c2dddbf428f8433d08f2 | 33.864407 | 154 | 0.743982 | 4.334036 | false | true | false | false |
androidx/androidx | compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/Canvas.kt | 3 | 22813 | /*
* 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
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.graphics.internal.JvmDefaultWithCompatibility
/**
* Create a new Canvas instance that targets its drawing commands
* to the provided [ImageBitmap]
*/
fun Canvas(image: ImageBitmap): Canvas = ActualCanvas(image)
internal expect fun ActualCanvas(image: ImageBitmap): Canvas
expect class NativeCanvas
/**
* Saves a copy of the current transform and clip on the save stack and executes the
* provided lambda with the current transform applied. Once the lambda has been executed,
* the transformation is popped from the stack, undoing the transformation.
*
*
* See also:
*
* [Canvas.saveLayer], which does the same thing but additionally also groups the
* commands
*/
/* expect */ inline fun Canvas.withSave(block: () -> Unit) {
try {
save()
block()
} finally {
restore()
}
}
/**
* Saves a copy of the current transform and clip on the save stack, and then
* creates a new group which subsequent calls will become a part of. When the
* lambda is executed and the save stack is popped, the group will be flattened into
* a layer and have the given `paint`'s [Paint.colorFilter] and [Paint.blendMode]
* applied.
*
* This lets you create composite effects, for example making a group of
* drawing commands semi-transparent. Without using [Canvas.saveLayer], each part of
* the group would be painted individually, so where they overlap would be
* darker than where they do not. By using [Canvas.saveLayer] to group them
* together, they can be drawn with an opaque color at first, and then the
* entire group can be made transparent using the [Canvas.saveLayer]'s paint.
*
*
* ## Using saveLayer with clips
*
* When a rectangular clip operation (from [Canvas.clipRect]) is not axis-aligned
* with the raster buffer, or when the clip operation is not rectalinear (e.g.
* because it is a rounded rectangle clip created by [Canvas.clipPath]), the edge of the
* clip needs to be anti-aliased.
*
* If two draw calls overlap at the edge of such a clipped region, without
* using [Canvas.saveLayer], the first drawing will be anti-aliased with the
* background first, and then the second will be anti-aliased with the result
* of blending the first drawing and the background. On the other hand, if
* [Canvas.saveLayer] is used immediately after establishing the clip, the second
* drawing will cover the first in the layer, and thus the second alone will
* be anti-aliased with the background when the layer is clipped and
* composited (when lambda is finished executing).
*
* ## Performance considerations
*
* Generally speaking, [Canvas.saveLayer] is relatively expensive.
*
* There are a several different hardware architectures for GPUs (graphics
* processing units, the hardware that handles graphics), but most of them
* involve batching commands and reordering them for performance. When layers
* are used, they cause the rendering pipeline to have to switch render
* target (from one layer to another). Render target switches can flush the
* GPU's command buffer, which typically means that optimizations that one
* could get with larger batching are lost. Render target switches also
* generate a lot of memory churn because the GPU needs to copy out the
* current frame buffer contents from the part of memory that's optimized for
* writing, and then needs to copy it back in once the previous render target
* (layer) is restored.
*
* See also:
*
* * [Canvas.save], which saves the current state, but does not create a new layer
* for subsequent commands.
* * [BlendMode], which discusses the use of [Paint.blendMode] with
* [saveLayer].
*/
@Suppress("DEPRECATION")
inline fun Canvas.withSaveLayer(bounds: Rect, paint: Paint, block: () -> Unit) {
try {
saveLayer(bounds, paint)
block()
} finally {
restore()
}
}
/**
* Add a rotation (in degrees clockwise) to the current transform at the given pivot point.
* The pivot coordinate remains unchanged by the rotation transformation
*
* @param degrees to rotate clockwise
* @param pivotX The x-coord for the pivot point
* @param pivotY The y-coord for the pivot point
*/
fun Canvas.rotate(degrees: Float, pivotX: Float, pivotY: Float) {
if (degrees == 0.0f) return
translate(pivotX, pivotY)
rotate(degrees)
translate(-pivotX, -pivotY)
}
/**
* Add a rotation (in radians clockwise) to the current transform at the given pivot point.
* The pivot coordinate remains unchanged by the rotation transformation
*
* @param pivotX The x-coord for the pivot point
* @param pivotY The y-coord for the pivot point
*/
fun Canvas.rotateRad(radians: Float, pivotX: Float = 0.0f, pivotY: Float = 0.0f) {
rotate(degrees(radians), pivotX, pivotY)
}
/**
* Add an axis-aligned scale to the current transform, scaling by the first
* argument in the horizontal direction and the second in the vertical
* direction at the given pivot coordinate. The pivot coordinate remains
* unchanged by the scale transformation.
*
* If [sy] is unspecified, [sx] will be used for the scale in both
* directions.
*
* @param sx The amount to scale in X
* @param sy The amount to scale in Y
* @param pivotX The x-coord for the pivot point
* @param pivotY The y-coord for the pivot point
*/
fun Canvas.scale(sx: Float, sy: Float = sx, pivotX: Float, pivotY: Float) {
if (sx == 1.0f && sy == 1.0f) return
translate(pivotX, pivotY)
scale(sx, sy)
translate(-pivotX, -pivotY)
}
/**
* Return an instance of the native primitive that implements the Canvas interface
*/
expect val Canvas.nativeCanvas: NativeCanvas
@JvmDefaultWithCompatibility
interface Canvas {
/**
* Saves a copy of the current transform and clip on the save stack.
*
* Call [restore] to pop the save stack.
*
* See also:
*
* * [saveLayer], which does the same thing but additionally also groups the
* commands done until the matching [restore].
*/
fun save()
/**
* Pops the current save stack, if there is anything to pop.
* Otherwise, does nothing.
*
* Use [save] and [saveLayer] to push state onto the stack.
*
* If the state was pushed with with [saveLayer], then this call will also
* cause the new layer to be composited into the previous layer.
*/
fun restore()
/**
* Saves a copy of the current transform and clip on the save stack, and then
* creates a new group which subsequent calls will become a part of. When the
* save stack is later popped, the group will be flattened into a layer and
* have the given `paint`'s [Paint.colorFilter] and [Paint.blendMode]
* applied.
*
* This lets you create composite effects, for example making a group of
* drawing commands semi-transparent. Without using [saveLayer], each part of
* the group would be painted individually, so where they overlap would be
* darker than where they do not. By using [saveLayer] to group them
* together, they can be drawn with an opaque color at first, and then the
* entire group can be made transparent using the [saveLayer]'s paint.
*
* Call [restore] to pop the save stack and apply the paint to the group.
*
* ## Using saveLayer with clips
*
* When a rectangular clip operation (from [clipRect]) is not axis-aligned
* with the raster buffer, or when the clip operation is not rectalinear (e.g.
* because it is a rounded rectangle clip created by [clipPath], the edge of the
* clip needs to be anti-aliased.
*
* If two draw calls overlap at the edge of such a clipped region, without
* using [saveLayer], the first drawing will be anti-aliased with the
* background first, and then the second will be anti-aliased with the result
* of blending the first drawing and the background. On the other hand, if
* [saveLayer] is used immediately after establishing the clip, the second
* drawing will cover the first in the layer, and thus the second alone will
* be anti-aliased with the background when the layer is clipped and
* composited (when [restore] is called).
*
*
* (Incidentally, rather than using [clipPath] with a rounded rectangle defined in a path to
* draw rounded rectangles like this, prefer the [drawRoundRect] method.
*
* ## Performance considerations
*
* Generally speaking, [saveLayer] is relatively expensive.
*
* There are a several different hardware architectures for GPUs (graphics
* processing units, the hardware that handles graphics), but most of them
* involve batching commands and reordering them for performance. When layers
* are used, they cause the rendering pipeline to have to switch render
* target (from one layer to another). Render target switches can flush the
* GPU's command buffer, which typically means that optimizations that one
* could get with larger batching are lost. Render target switches also
* generate a lot of memory churn because the GPU needs to copy out the
* current frame buffer contents from the part of memory that's optimized for
* writing, and then needs to copy it back in once the previous render target
* (layer) is restored.
*
* See also:
*
* * [save], which saves the current state, but does not create a new layer
* for subsequent commands.
* * [BlendMode], which discusses the use of [Paint.blendMode] with
* [saveLayer].
*/
fun saveLayer(bounds: Rect, paint: Paint)
/**
* Add a translation to the current transform, shifting the coordinate space
* horizontally by the first argument and vertically by the second argument.
*/
fun translate(dx: Float, dy: Float)
/**
* Add an axis-aligned scale to the current transform, scaling by the first
* argument in the horizontal direction and the second in the vertical
* direction.
*
* If [sy] is unspecified, [sx] will be used for the scale in both
* directions.
*
* @param sx The amount to scale in X
* @param sy The amount to scale in Y
*/
fun scale(sx: Float, sy: Float = sx)
/**
* Add a rotation (in degrees clockwise) to the current transform
*
* @param degrees to rotate clockwise
*/
fun rotate(degrees: Float)
/**
* Add an axis-aligned skew to the current transform, with the first argument
* being the horizontal skew in degrees clockwise around the origin, and the
* second argument being the vertical skew in degrees clockwise around the
* origin.
*/
fun skew(sx: Float, sy: Float)
/**
* Add an axis-aligned skew to the current transform, with the first argument
* being the horizontal skew in radians clockwise around the origin, and the
* second argument being the vertical skew in radians clockwise around the
* origin.
*/
fun skewRad(sxRad: Float, syRad: Float) {
skew(degrees(sxRad), degrees(syRad))
}
/**
* Multiply the current transform by the specified 4⨉4 transformation matrix
* specified as a list of values in column-major order.
*/
fun concat(matrix: Matrix)
/**
* Reduces the clip region to the intersection of the current clip and the
* given rectangle.
*
* Use [ClipOp.Difference] to subtract the provided rectangle from the
* current clip.
*/
@Suppress("DEPRECATION")
fun clipRect(rect: Rect, clipOp: ClipOp = ClipOp.Intersect) =
clipRect(rect.left, rect.top, rect.right, rect.bottom, clipOp)
/**
* Reduces the clip region to the intersection of the current clip and the
* given bounds.
*
* Use [ClipOp.Difference] to subtract the provided rectangle from the
* current clip.
*
* @param left Left bound of the clip region
* @param top Top bound of the clip region
* @param right Right bound of the clip region
* @param bottom Bottom bound of the clip region
*/
fun clipRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
clipOp: ClipOp = ClipOp.Intersect
)
/**
* Reduces the clip region to the intersection of the current clip and the
* given [Path].
*/
fun clipPath(path: Path, clipOp: ClipOp = ClipOp.Intersect)
/**
* Draws a line between the given points using the given paint. The line is
* stroked, the value of the [Paint.style] is ignored for this call.
*
* The `p1` and `p2` arguments are interpreted as offsets from the origin.
*/
fun drawLine(p1: Offset, p2: Offset, paint: Paint)
/**
* Draws a rectangle with the given [Paint]. Whether the rectangle is filled
* or stroked (or both) is controlled by [Paint.style].
*/
fun drawRect(rect: Rect, paint: Paint) = drawRect(
left = rect.left,
top = rect.top,
right = rect.right,
bottom = rect.bottom,
paint = paint
)
/**
* Draws a rectangle with the given [Paint]. Whether the rectangle is filled
* or stroked (or both) is controlled by [Paint.style].
*
* @param left The left bound of the rectangle
* @param top The top bound of the rectangle
* @param right The right bound of the rectangle
* @param bottom The bottom bound of the rectangle
* @param paint Paint used to color the rectangle with a fill or stroke
*/
fun drawRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
paint: Paint
)
/**
* Draws a rounded rectangle with the given [Paint]. Whether the rectangle is
* filled or stroked (or both) is controlled by [Paint.style].
*/
fun drawRoundRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
radiusX: Float,
radiusY: Float,
paint: Paint
)
/**
* Draws an axis-aligned oval that fills the given axis-aligned rectangle
* with the given [Paint]. Whether the oval is filled or stroked (or both) is
* controlled by [Paint.style].
*/
fun drawOval(rect: Rect, paint: Paint) = drawOval(
left = rect.left,
top = rect.top,
right = rect.right,
bottom = rect.bottom,
paint = paint
)
/**
* Draws an axis-aligned oval that fills the given bounds provided with the given
* [Paint]. Whether the rectangle is filled
* or stroked (or both) is controlled by [Paint.style].
*
* @param left The left bound of the rectangle
* @param top The top bound of the rectangle
* @param right The right bound of the rectangle
* @param bottom The bottom bound of the rectangle
* @param paint Paint used to color the rectangle with a fill or stroke
*/
fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint)
/**
* Draws a circle centered at the point given by the first argument and
* that has the radius given by the second argument, with the [Paint] given in
* the third argument. Whether the circle is filled or stroked (or both) is
* controlled by [Paint.style].
*/
fun drawCircle(center: Offset, radius: Float, paint: Paint)
/**
* Draw an arc scaled to fit inside the given rectangle. It starts from
* startAngle degrees around the oval up to startAngle + sweepAngle
* degrees around the oval, with zero degrees being the point on
* the right hand side of the oval that crosses the horizontal line
* that intersects the center of the rectangle and with positive
* angles going clockwise around the oval. If useCenter is true, the arc is
* closed back to the center, forming a circle sector. Otherwise, the arc is
* not closed, forming a circle segment.
*
* This method is optimized for drawing arcs and should be faster than [Path.arcTo].
*/
fun drawArc(
rect: Rect,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
) = drawArc(
left = rect.left,
top = rect.top,
right = rect.right,
bottom = rect.bottom,
startAngle = startAngle,
sweepAngle = sweepAngle,
useCenter = useCenter,
paint = paint
)
/**
* Draw an arc scaled to fit inside the given rectangle. It starts from
* startAngle degrees around the oval up to startAngle + sweepAngle
* degrees around the oval, with zero degrees being the point on
* the right hand side of the oval that crosses the horizontal line
* that intersects the center of the rectangle and with positive
* angles going clockwise around the oval. If useCenter is true, the arc is
* closed back to the center, forming a circle sector. Otherwise, the arc is
* not closed, forming a circle segment.
*
* This method is optimized for drawing arcs and should be faster than [Path.arcTo].
*
* @param left Left bound of the arc
* @param top Top bound of the arc
* @param right Right bound of the arc
* @param bottom Bottom bound of the arc
* @param startAngle Starting angle of the arc relative to 3 o'clock
* @param sweepAngle Sweep angle in degrees clockwise
* @param useCenter Flag indicating whether or not to include the center of the oval in the
* arc, and close it if it is being stroked. This will draw a wedge.
*/
fun drawArc(
left: Float,
top: Float,
right: Float,
bottom: Float,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
)
/**
* Draw an arc scaled to fit inside the given rectangle. It starts from
* startAngle radians around the oval up to startAngle + sweepAngle
* radians around the oval, with zero radians being the point on
* the right hand side of the oval that crosses the horizontal line
* that intersects the center of the rectangle and with positive
* angles going clockwise around the oval. If useCenter is true, the arc is
* closed back to the center, forming a circle sector. Otherwise, the arc is
* not closed, forming a circle segment.
*
* This method is optimized for drawing arcs and should be faster than [Path.arcTo].
*/
fun drawArcRad(
rect: Rect,
startAngleRad: Float,
sweepAngleRad: Float,
useCenter: Boolean,
paint: Paint
) {
drawArc(rect, degrees(startAngleRad), degrees(sweepAngleRad), useCenter, paint)
}
/**
* Draws the given [Path] with the given [Paint]. Whether this shape is
* filled or stroked (or both) is controlled by [Paint.style]. If the path is
* filled, then subpaths within it are implicitly closed (see [Path.close]).
*/
fun drawPath(path: Path, paint: Paint)
/**
* Draws the given [ImageBitmap] into the canvas with its top-left corner at the
* given [Offset]. The image is composited into the canvas using the given [Paint].
*/
fun drawImage(image: ImageBitmap, topLeftOffset: Offset, paint: Paint)
/**
* Draws the subset of the given image described by the `src` argument into
* the canvas in the axis-aligned rectangle given by the `dst` argument.
*
* This might sample from outside the `src` rect by up to half the width of
* an applied filter.
*
* @param image ImageBitmap to draw
* @param srcOffset: Optional offset representing the top left offset of the source image
* to draw, this defaults to the origin of [image]
* @param srcSize: Optional dimensions of the source image to draw relative to [srcOffset],
* this defaults the width and height of [image]
* @param dstOffset: Offset representing the top left offset of the destination image
* to draw
* @param dstSize: Dimensions of the destination to draw
* @param paint Paint used to composite the [ImageBitmap] pixels into the canvas
*/
fun drawImageRect(
image: ImageBitmap,
srcOffset: IntOffset = IntOffset.Zero,
srcSize: IntSize = IntSize(image.width, image.height),
dstOffset: IntOffset = IntOffset.Zero,
dstSize: IntSize = srcSize,
paint: Paint
)
/**
* Draws a sequence of points according to the given [PointMode].
*
* The `points` argument is interpreted as offsets from the origin.
*
* See also:
*
* * [drawRawPoints], which takes `points` as a [FloatArray] rather than a
* [List<Offset>].
*/
fun drawPoints(pointMode: PointMode, points: List<Offset>, paint: Paint)
/**
* Draws a sequence of points according to the given [PointMode].
*
* The `points` argument is interpreted as a list of pairs of floating point
* numbers, where each pair represents an x and y offset from the origin.
*
* See also:
*
* * [drawPoints], which takes `points` as a [List<Offset>] rather than a
* [List<Float32List>].
*/
fun drawRawPoints(pointMode: PointMode, points: FloatArray, paint: Paint)
fun drawVertices(vertices: Vertices, blendMode: BlendMode, paint: Paint)
/**
* Enables Z support which defaults to disabled. This allows layers drawn
* with different elevations to be rearranged based on their elevation. It
* also enables rendering of shadows.
* @see disableZ
*/
fun enableZ()
/**
* Disables Z support, preventing any layers drawn after this point from being visually
* reordered or having shadows rendered. This is not impacted by any [save] or [restore]
* calls as it is not considered part of the matrix or clip.
* @see enableZ
*/
fun disableZ()
} | apache-2.0 | fe891523659ba45ecdbc2accfce2aebc | 37.275168 | 96 | 0.674674 | 4.328463 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/HighlightingFileRoot.kt | 1 | 3813 | // 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.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.analysis.problemsView.ProblemsListener
import com.intellij.analysis.problemsView.ProblemsProvider
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.ex.RangeHighlighterEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
open class HighlightingFileRoot(panel: ProblemsViewPanel, val file: VirtualFile) : Root(panel) {
private val problems = mutableSetOf<HighlightingProblem>()
private val filter = ProblemFilter(panel.state)
protected val provider = object : ProblemsProvider {
override val project = panel.project
}
protected open val watcher = createWatcher(provider, this, file, HighlightSeverity.INFORMATION.myVal + 1)
init {
Disposer.register(this, provider)
Disposer.register(provider, watcher)
}
fun findProblem(highlighter: RangeHighlighterEx) = watcher.findProblem(highlighter)
override fun getProblemCount() = synchronized(problems) { problems.count(filter) }
override fun getProblemFiles() = when (getProblemCount() > 0) {
true -> listOf(file)
else -> emptyList()
}
override fun getFileProblemCount(file: VirtualFile) = when (this.file == file) {
true -> getProblemCount()
else -> 0
}
override fun getFileProblems(file: VirtualFile) = when (this.file == file) {
true -> synchronized(problems) { problems.filter(filter) }
else -> emptyList()
}
protected open fun createWatcher(provider: ProblemsProvider,
listener: ProblemsListener,
file: VirtualFile,
level: Int): HighlightingWatcher =
HighlightingWatcher(provider, this, file, HighlightSeverity.INFORMATION.myVal + 1)
override fun getOtherProblemCount() = 0
override fun getOtherProblems(): Collection<Problem> = emptyList()
override fun problemAppeared(problem: Problem) {
if (problem !is HighlightingProblem || problem.file != file) return
notify(problem, synchronized(problems) { SetUpdateState.add(problem, problems) })
if (Registry.`is`("wolf.the.problem.solver")) return
// start filling HighlightingErrorsProvider if WolfTheProblemSolver is disabled
if (!ProblemsView.isProjectErrorsEnabled() || problem.severity < HighlightSeverity.ERROR.myVal) return
HighlightingErrorsProviderBase.getInstance(problem.provider.project).problemsAppeared(file)
}
override fun problemDisappeared(problem: Problem) {
if (problem !is HighlightingProblem || problem.file != file) return
notify(problem, synchronized(problems) { SetUpdateState.remove(problem, problems) })
}
override fun problemUpdated(problem: Problem) {
if (problem !is HighlightingProblem || problem.file != file) return
notify(problem, synchronized(problems) { SetUpdateState.update(problem, problems) })
}
private fun notify(problem: Problem, state: SetUpdateState) = when (state) {
SetUpdateState.ADDED -> super.problemAppeared(problem)
SetUpdateState.REMOVED -> super.problemDisappeared(problem)
SetUpdateState.UPDATED -> super.problemUpdated(problem)
SetUpdateState.IGNORED -> {
}
}
override fun getChildren(node: FileNode) = when {
!panel.state.groupByToolId -> super.getChildren(node)
else -> getFileProblems(node.file).groupBy { it.group }.flatMap { entry ->
entry.key?.let { listOf(GroupNode(node, it, entry.value)) } ?: entry.value.map { ProblemNode(node, node.file, it) }
}
}
}
| apache-2.0 | adac5ad6f0b853131bf3ba0c355d0e5f | 40.901099 | 158 | 0.732756 | 4.517773 | false | true | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/run/PythonScripts.kt | 1 | 10966 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PythonScripts")
package com.jetbrains.python.run
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.ParametersList
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.LocalPtyOptions
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.target.*
import com.intellij.execution.target.TargetEnvironment.TargetPath
import com.intellij.execution.target.TargetEnvironment.UploadRoot
import com.intellij.execution.target.local.LocalTargetPtyOptions
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.target.value.TargetValue
import com.intellij.execution.target.value.getRelativeTargetPath
import com.intellij.execution.target.value.joinToStringFunction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.io.FileUtil
import com.intellij.remote.RemoteSdkPropertiesPaths
import com.intellij.util.io.isAncestor
import com.jetbrains.python.HelperPackage
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.packaging.PyExecutionException
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import com.jetbrains.python.sdk.PythonSdkType
import java.nio.file.Path
private val LOG = Logger.getInstance("#com.jetbrains.python.run.PythonScripts")
fun PythonExecution.buildTargetedCommandLine(targetEnvironment: TargetEnvironment,
sdk: Sdk?,
interpreterParameters: List<String>,
isUsePty: Boolean = false): TargetedCommandLine {
val commandLineBuilder = TargetedCommandLineBuilder(targetEnvironment.request)
workingDir?.apply(targetEnvironment)?.let { commandLineBuilder.setWorkingDirectory(it) }
charset?.let { commandLineBuilder.setCharset(it) }
val interpreterPath = getInterpreterPath(sdk)
if (!interpreterPath.isNullOrEmpty()) {
commandLineBuilder.setExePath(targetEnvironment.targetPlatform.platform.toSystemDependentName(interpreterPath))
}
commandLineBuilder.addParameters(interpreterParameters)
when (this) {
is PythonScriptExecution -> pythonScriptPath?.let { commandLineBuilder.addParameter(it.apply(targetEnvironment)) }
?: throw IllegalArgumentException("Python script path must be set")
is PythonModuleExecution -> moduleName?.let { commandLineBuilder.addParameters(listOf("-m", moduleName)) }
?: throw IllegalArgumentException("Python module name must be set")
}
for (parameter in parameters) {
commandLineBuilder.addParameter(parameter.apply(targetEnvironment))
}
for ((name, value) in envs) {
commandLineBuilder.addEnvironmentVariable(name, value.apply(targetEnvironment))
}
val environmentVariablesForVirtualenv = mutableMapOf<String, String>()
// TODO [Targets API] It would be cool to activate environment variables for any type of target
sdk?.let { PythonSdkType.patchEnvironmentVariablesForVirtualenv(environmentVariablesForVirtualenv, it) }
// TODO [Targets API] [major] PATH env for virtualenv should extend existing PATH env
environmentVariablesForVirtualenv.forEach { (name, value) -> commandLineBuilder.addEnvironmentVariable(name, value) }
// TODO [Targets API] [major] `PythonSdkFlavor` should be taken into account to pass (at least) "IRONPYTHONPATH" or "JYTHONPATH"
// environment variables for corresponding interpreters
if (isUsePty) {
commandLineBuilder.ptyOptions = LocalTargetPtyOptions(LocalPtyOptions.DEFAULT)
}
return commandLineBuilder.build()
}
/**
* Returns the path to Python interpreter executable. The path is the path on
* the target environment.
*/
fun getInterpreterPath(sdk: Sdk?): String? {
if (sdk == null) return null
// `RemoteSdkPropertiesPaths` suits both `PyRemoteSdkAdditionalDataBase` and `PyTargetAwareAdditionalData`
return sdk.sdkAdditionalData?.let { (it as? RemoteSdkPropertiesPaths)?.interpreterPath } ?: sdk.homePath
}
data class Upload(val localPath: String, val targetPath: TargetEnvironmentFunction<String>)
private fun resolveUploadPath(localPath: String, uploads: Iterable<Upload>): TargetEnvironmentFunction<String> {
val localFileSeparator = Platform.current().fileSeparator
val matchUploads = uploads.mapNotNull { upload ->
if (FileUtil.isAncestor(upload.localPath, localPath, false)) {
FileUtil.getRelativePath(upload.localPath, localPath, localFileSeparator)?.let { upload to it }
}
else {
null
}
}
if (matchUploads.size > 1) {
LOG.warn("Several uploads matches the local path '$localPath': $matchUploads")
}
val (upload, localRelativePath) = matchUploads.firstOrNull()
?: throw IllegalStateException("Failed to find uploads for the local path '$localPath'")
return upload.targetPath.getRelativeTargetPath(localRelativePath)
}
fun prepareHelperScriptExecution(helperPackage: HelperPackage,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): PythonScriptExecution =
PythonScriptExecution().apply {
val uploads = applyHelperPackageToPythonPath(helperPackage, helpersAwareTargetRequest)
pythonScriptPath = resolveUploadPath(helperPackage.asParamString(), uploads)
}
private const val PYTHONPATH_ENV = "PYTHONPATH"
/**
* Requests the upload of PyCharm helpers root directory to the target.
*/
fun PythonExecution.applyHelperPackageToPythonPath(helperPackage: HelperPackage,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> {
return applyHelperPackageToPythonPath(helperPackage.pythonPathEntries, helpersAwareTargetRequest)
}
fun PythonExecution.applyHelperPackageToPythonPath(pythonPathEntries: List<String>,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> {
val localHelpersRootPath = PythonHelpersLocator.getHelpersRoot().absolutePath
val targetPlatform = helpersAwareTargetRequest.targetEnvironmentRequest.targetPlatform
val targetUploadPath = helpersAwareTargetRequest.preparePyCharmHelpers()
val targetPathSeparator = targetPlatform.platform.pathSeparator
val uploads = pythonPathEntries.map {
// TODO [Targets API] Simplify the paths resolution
val relativePath = FileUtil.getRelativePath(localHelpersRootPath, it, Platform.current().fileSeparator)
?: throw IllegalStateException("Helpers PYTHONPATH entry '$it' cannot be resolved" +
" against the root path of PyCharm helpers '$localHelpersRootPath'")
Upload(it, targetUploadPath.getRelativeTargetPath(relativePath))
}
val pythonPathEntriesOnTarget = uploads.map { it.targetPath }
val pythonPathValue = pythonPathEntriesOnTarget.joinToStringFunction(separator = targetPathSeparator.toString())
appendToPythonPath(pythonPathValue, targetPlatform)
return uploads
}
/**
* Suits for coverage and profiler scripts.
*/
fun PythonExecution.addPythonScriptAsParameter(targetScript: PythonExecution) {
when (targetScript) {
is PythonScriptExecution -> targetScript.pythonScriptPath?.let { pythonScriptPath -> addParameter(pythonScriptPath) }
?: throw IllegalArgumentException("Python script path must be set")
is PythonModuleExecution -> targetScript.moduleName?.let { moduleName -> addParameters("-m", moduleName) }
?: throw IllegalArgumentException("Python module name must be set")
}
}
fun PythonExecution.addParametersString(parametersString: String) {
ParametersList.parse(parametersString).forEach { parameter -> addParameter(parameter) }
}
private fun PythonExecution.appendToPythonPath(value: TargetEnvironmentFunction<String>, targetPlatform: TargetPlatform) {
appendToPythonPath(envs, value, targetPlatform)
}
fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>,
value: TargetEnvironmentFunction<String>,
targetPlatform: TargetPlatform) {
envs.merge(PYTHONPATH_ENV, value) { whole, suffix ->
listOf(whole, suffix).joinToPathValue(targetPlatform)
}
}
fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>,
paths: Collection<TargetEnvironmentFunction<String>>,
targetPlatform: TargetPlatform) {
val value = paths.joinToPathValue(targetPlatform)
envs.merge(PYTHONPATH_ENV, value) { whole, suffix ->
listOf(whole, suffix).joinToPathValue(targetPlatform)
}
}
/**
* Joins the provided paths collection to single [TargetValue] using target
* platform's path separator.
*
* The result is applicable for `PYTHONPATH` and `PATH` environment variables.
*/
fun Collection<TargetEnvironmentFunction<String>>.joinToPathValue(targetPlatform: TargetPlatform): TargetEnvironmentFunction<String> =
this.joinToStringFunction(separator = targetPlatform.platform.pathSeparator.toString())
fun PythonExecution.extendEnvs(additionalEnvs: Map<String, TargetEnvironmentFunction<String>>, targetPlatform: TargetPlatform) {
for ((key, value) in additionalEnvs) {
if (key == PYTHONPATH_ENV) {
appendToPythonPath(value, targetPlatform)
}
else {
addEnvironmentVariable(key, value)
}
}
}
/**
* Execute this command in a given environment, throwing an `ExecutionException` in case of a timeout or a non-zero exit code.
*/
@Throws(ExecutionException::class)
fun TargetedCommandLine.execute(env: TargetEnvironment, indicator: ProgressIndicator): ProcessOutput {
val process = env.createProcess(this, indicator)
val capturingHandler = CapturingProcessHandler(process, charset, getCommandPresentation(env))
val output = capturingHandler.runProcess()
if (output.isTimeout || output.exitCode != 0) {
val fullCommand = collectCommandsSynchronously()
throw PyExecutionException("", fullCommand[0], fullCommand.drop(1), output)
}
return output
}
/**
* Checks whether the base directory of [project] is registered in [this] request. Adds it if it is not.
*/
fun TargetEnvironmentRequest.ensureProjectDirIsOnTarget(project: Project) {
val basePath = project.basePath?.let { Path.of(it) } ?: return
if (uploadVolumes.none { it.localRootPath.isAncestor(basePath) }) {
uploadVolumes += UploadRoot(localRootPath = basePath, targetRootPath = TargetPath.Temporary())
}
} | apache-2.0 | 026dd0b1ee6da6910e6d781fd05968c7 | 49.077626 | 140 | 0.757706 | 4.973243 | false | false | false | false |
jwren/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/utils/hash.kt | 1 | 1314 | package com.intellij.ide.starter.utils
import org.apache.commons.lang3.CharUtils
private val OFFSET: Int = "AAAAAAA".hashCode();
fun convertToHashCodeWithOnlyLetters(hash: Int): String {
val offsettedHash = (hash - OFFSET).toLong()
var longHash: Long = offsettedHash and 0xFFFFFFFFL
val generatedChars = CharArray(7)
val aChar: Char = 'A'
generatedChars.indices.forEach { index ->
generatedChars[6 - index] = (aChar + ((longHash % 31).toInt()))
longHash /= 31;
}
return generatedChars.filter { CharUtils.isAsciiAlphanumeric(it) }.joinToString(separator = "")
}
/**
* Simplifies test grouping by replacing numbers, hashes, hex numbers with predefined constant values <ID>, <HASH>, <HEX>
* Eg:
* text@3ba5aac, text => text<ID>, text
* some-text.db451f59 => some-text.<HASH>
* 0x01 => <HEX>
* text1234text => text<NUM>text
**/
fun generifyErrorMessage(originalMessage: String): String {
return originalMessage // text@3ba5aac, text => text<ID>, text
.replace("[\$@#][A-Za-z0-9-_]+".toRegex(), "<ID>") // some-text.db451f59 => some-text.<HASH>
.replace("[.]([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*".toRegex(), ".<HASH>") // 0x01 => <HEX>
.replace("0x[0-9a-fA-F]+".toRegex(), "<HEX>") // text1234text => text<NUM>text
.replace("[0-9]+".toRegex(), "<NUM>")
} | apache-2.0 | d9f753a3f6f7cd7ffb0ca1d0549211e0 | 35.527778 | 121 | 0.653729 | 3.091765 | false | false | false | false |
anastr/SpeedView | speedviewlib/src/main/java/com/github/anastr/speedviewlib/components/note/ImageNote.kt | 1 | 1883 | package com.github.anastr.speedviewlib.components.note
import android.content.Context
import android.graphics.*
/**
* this Library build By Anas Altair
* see it on [GitHub](https://github.com/anastr/SpeedView)
*/
class ImageNote
/**
* @param context you can use `getApplicationContext()` method.
* @param image to display.
* @param width set custom width.
* @param height set custom height.
* @throws IllegalArgumentException if `width <= 0 OR height <= 0`.
*/
@JvmOverloads constructor(context: Context, private val image: Bitmap, private val width: Int = image.width, private val height: Int = image.height) : Note<ImageNote>(context) {
private val imageRect = RectF()
private val notePaint = Paint(Paint.ANTI_ALIAS_FLAG)
/**
* @param context you can use `getApplicationContext()` method.
* @param resource the image id.
*/
constructor(context: Context, resource: Int) : this(context, BitmapFactory.decodeResource(context.resources, resource))
/**
* @param context you can use `getApplicationContext()` method.
* @param resource the image id.
* @param width set custom width.
* @param height set custom height.
* @throws IllegalArgumentException if `width <= 0 OR height <= 0`.
*/
constructor(context: Context, resource: Int, width: Int, height: Int) : this(context, BitmapFactory.decodeResource(context.resources, resource), width, height)
init {
require(width > 0) { "width must be bigger than 0" }
require(height > 0) { "height must be bigger than 0" }
}
override fun build(viewWidth: Int) {
noticeContainsSizeChange(this.width, this.height)
}
override fun drawContains(canvas: Canvas, leftX: Float, topY: Float) {
imageRect.set(leftX, topY, leftX + width, topY + height)
canvas.drawBitmap(image, null, imageRect, notePaint)
}
}
| apache-2.0 | 49efd98f99157b9107297e2336d683e7 | 36.66 | 177 | 0.687201 | 4.023504 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/ParseXMLAction.kt | 1 | 2907 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import android.util.Xml
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import ch.rmy.android.http_shortcuts.utils.SimpleXMLContentHandler
import org.json.JSONArray
import org.json.JSONObject
import org.xml.sax.Attributes
import java.util.Stack
class ParseXMLAction(private val xmlInput: String) : BaseAction() {
override suspend fun execute(executionContext: ExecutionContext): JSONObject {
var root: JSONObject? = null
var activeElement: JSONObject? = null
val elementStack = Stack<JSONObject>()
try {
Xml.parse(
xmlInput,
object : SimpleXMLContentHandler {
override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes) {
val element = createElement(localName, attributes)
activeElement
?.getJSONArray("children")
?.put(element)
?: run {
root = element
}
elementStack.push(element)
activeElement = element
}
override fun endElement(uri: String?, localName: String, qName: String?) {
elementStack.pop()
activeElement = elementStack.lastOrNull()
}
override fun characters(characters: CharArray, start: Int, length: Int) {
val element = activeElement ?: return
val text = element.optString("text") + characters.slice(start until (start + length)).joinToString(separator = "")
element.put("text", text)
}
},
)
} catch (e: Throwable) {
if (!e.javaClass.name.contains("ParseException")) {
logException(e)
}
throw ActionException {
getString(R.string.error_invalid_xml, e.message)
}
}
return root!!
}
private fun createElement(name: String, attributes: Attributes): JSONObject =
JSONObject()
.put("name", name)
.put("attributes", attributes.parse())
.put("children", JSONArray())
private fun Attributes.parse(): JSONObject {
val result = JSONObject()
for (i in 0 until length) {
val attributeName = getLocalName(i)
val attributeValue = getValue(i)
result.put(attributeName, attributeValue)
}
return result
}
}
| mit | b7e762f0acff8311f8936c873e96478f | 37.76 | 138 | 0.556932 | 5.34375 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/PersistentMapManager.kt | 4 | 2937 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.configurationStore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.io.*
import com.intellij.util.loadElement
import com.intellij.util.write
import org.jdom.Element
import java.nio.file.Path
private val LOG = logger<FileSystemExternalSystemStorage>()
internal interface ExternalSystemStorage {
val isDirty: Boolean
fun remove(name: String)
fun read(name: String): Element?
fun write(name: String, element: Element?, filter: JDOMUtil.ElementOutputFilter? = null)
fun forceSave()
fun rename(oldName: String, newName: String)
}
internal class ModuleFileSystemExternalSystemStorage(project: Project) : FileSystemExternalSystemStorage("modules", project) {
companion object {
private fun nameToFilename(name: String) = "${sanitizeFileName(name)}.xml"
}
override fun nameToPath(name: String) = super.nameToPath(nameToFilename(name))
}
internal class ProjectFileSystemExternalSystemStorage(project: Project) : FileSystemExternalSystemStorage("project", project)
internal abstract class FileSystemExternalSystemStorage(dirName: String, project: Project) : ExternalSystemStorage {
override val isDirty = false
protected val dir: Path = ExternalProjectsDataStorage.getProjectConfigurationDir(project).resolve(dirName)
var hasSomeData: Boolean
private set
init {
val fileAttributes = dir.basicAttributesIfExists()
hasSomeData = when {
fileAttributes == null -> false
fileAttributes.isRegularFile -> {
// old binary format
dir.parent.deleteChildrenStartingWith(dir.fileName.toString())
false
}
else -> {
LOG.assertTrue(fileAttributes.isDirectory)
true
}
}
}
protected open fun nameToPath(name: String): Path = dir.resolve(name)
override fun forceSave() {
}
override fun remove(name: String) {
if (!hasSomeData) {
return
}
nameToPath(name).delete()
}
override fun read(name: String): Element? {
if (!hasSomeData) {
return null
}
return nameToPath(name).inputStreamIfExists()?.use {
loadElement(it)
}
}
override fun write(name: String, element: Element?, filter: JDOMUtil.ElementOutputFilter?) {
if (element == null) {
remove(name)
return
}
hasSomeData = true
element.write(nameToPath(name), filter = filter)
}
override fun rename(oldName: String, newName: String) {
if (!hasSomeData) {
return
}
val oldFile = nameToPath(oldName)
if (oldFile.exists()) {
oldFile.move(nameToPath(newName))
}
}
} | apache-2.0 | e665013a35cf7ce61d31385c159277ca | 26.457944 | 140 | 0.722165 | 4.45 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | java/java-impl/src/com/intellij/codeInsight/intention/impl/UastJvmElementFactory.kt | 3 | 4634 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.actions.*
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JvmPsiConversionHelper
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.uast.*
import com.intellij.codeInsight.intention.JvmCommonIntentionActionsFactory as UastJvmCommonIntentionActionsFactory
import com.intellij.codeInsight.intention.MethodInsertionInfo as UastMethodInsertionInfo
@Deprecated("to be removed in 2018.1")
class UastJvmElementFactory(val renderer: JavaElementRenderer) : JvmElementActionsFactory() {
private fun getUastFactory(target: JvmModifiersOwner) = (target as? PsiElement)?.language?.let {
UastJvmCommonIntentionActionsFactory.forLanguage(it)
}
override fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> =
with(request) {
listOfNotNull(
getUastFactory(target)?.createChangeModifierAction(target.asUast<UDeclaration>(), renderer.render(modifier), shouldPresent))
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val project = (targetClass as? PsiElement)?.project ?: return emptyList()
return with(request) {
getUastFactory(targetClass)?.createAddCallableMemberActions(
UastMethodInsertionInfo.Constructor(
targetClass.asUast(),
modifiers.map { renderer.render(it) },
emptyList(),
parametersAsUParameters(project, parameters)
)
) ?: emptyList()
}
}
private fun parametersAsUParameters(project: Project, parameters: ExpectedParameters): List<UParameter> {
val helper = JvmPsiConversionHelper.getInstance(project)
val factory = JavaPsiFacade.getElementFactory(project)
return parameters.mapIndexed { i, pair ->
factory.createParameter(
pair.first.names.firstOrNull() ?: "arg$i",
pair.second.firstOrNull()?.theType?.let(helper::convertType)
?: PsiType.getTypeByName("java.lang.Object", project, GlobalSearchScope.allScope(project))
).asUast<UParameter>()
}
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val project = (targetClass as? PsiElement)?.project ?: return emptyList()
val helper = JvmPsiConversionHelper.getInstance(project)
return with(request) {
getUastFactory(targetClass)?.createAddCallableMemberActions(
UastMethodInsertionInfo.Method(
targetClass.asUast(),
request.methodName,
modifiers.map { renderer.render(it) },
emptyList(),
returnType.firstOrNull()?.theType?.let(helper::convertType) ?: PsiType.VOID,
parametersAsUParameters(project, parameters),
modifiers.contains(JvmModifier.ABSTRACT)
)
) ?: emptyList()
}
}
override fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
val project = (targetClass as? PsiElement)?.project ?: return emptyList()
val helper = JvmPsiConversionHelper.getInstance(project)
return with(request) {
getUastFactory(targetClass)?.createAddBeanPropertyActions(targetClass.asUast<UClass>(), propertyName,
renderer.render(visibilityModifier),
helper.convertType(propertyType), setterRequired,
getterRequired) ?: emptyList()
}
}
}
@Deprecated("remove after kotlin plugin will be ported")
private inline fun <reified T : UElement> JvmModifiersOwner.asUast(): T = when (this) {
is T -> this
is PsiElement -> this.let {
ServiceManager.getService(project, UastContext::class.java)
.convertElement(this, null, T::class.java) as T?
}
?: throw UnsupportedOperationException("cant convert $this to ${T::class}")
else -> throw UnsupportedOperationException("cant convert $this to ${T::class}")
} | apache-2.0 | afafc37cc14a0d74a977a851d161fe53 | 44.441176 | 140 | 0.716659 | 5.04793 | false | false | false | false |
sg26565/hott-transmitter-config | HoTT-Util/src/main/kotlin/de/treichels/hott/util/LogFormatter.kt | 1 | 1589 | package de.treichels.hott.util
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.management.ManagementFactory
import java.text.MessageFormat
import java.util.logging.Formatter
import java.util.logging.LogRecord
fun getThreadById(id: Int): Thread = Thread.getAllStackTraces().keys.first { it.id.toInt() == id }
class LogFormatter : Formatter() {
companion object {
private val start: Long = ManagementFactory.getRuntimeMXBean().startTime
}
fun getStackTrace(t: Throwable): String {
val stringWriter = StringWriter()
val printWriter = PrintWriter(stringWriter)
t.printStackTrace(printWriter)
return stringWriter.toString()
}
override fun format(record: LogRecord?): String {
if (record == null) return ""
val now: Long = record.millis - start
val parameters: Array<out Any>? = record.parameters;
val message: String = if (parameters == null || parameters.isEmpty()) record.message else MessageFormat.format(record.message, *parameters)
val threadName: String = getThreadById(record.threadID).name
val className: String = record.sourceClassName
val methodName: String = record.sourceMethodName
val result: String = String.format("----------------------------------------------------------%n%d [%s] %s.%s%n%s%n", now, threadName, className , methodName, message)
val throwable: Throwable? = record.thrown
return if (throwable != null) {
result + getStackTrace(throwable)
} else
result
}
} | lgpl-3.0 | 070f3e3a35e439332279c14909cb2c3a | 37.780488 | 175 | 0.660164 | 4.701183 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/ui/util/TypefaceManager.kt | 2 | 1668 | package com.quran.labs.androidquran.ui.util
import android.content.Context
import android.graphics.Typeface
import com.quran.labs.androidquran.data.QuranFileConstants
object TypefaceManager {
const val TYPE_UTHMANI_HAFS = 1
const val TYPE_NOOR_HAYAH = 2
const val TYPE_UTHMANIC_WARSH = 3
private var typeface: Typeface? = null
private var arabicTafseerTypeface: Typeface? = null
private var arabicHeaderFooterTypeface: Typeface? = null
private var dyslexicTypeface: Typeface? = null
@JvmStatic
fun getUthmaniTypeface(context: Context): Typeface {
return typeface ?: run {
val fontName = when (QuranFileConstants.FONT_TYPE) {
TYPE_NOOR_HAYAH -> "noorehira.ttf"
TYPE_UTHMANIC_WARSH -> "uthmanic_warsh_ver09.ttf"
else -> "uthmanic_hafs_ver12.otf"
}
val instance = Typeface.createFromAsset(context.assets, fontName)
typeface = instance
instance
}
}
fun getTafseerTypeface(context: Context): Typeface {
return arabicTafseerTypeface ?: run {
val instance = Typeface.createFromAsset(context.assets, "kitab.ttf")
arabicTafseerTypeface = instance
instance
}
}
fun getDyslexicTypeface(context: Context): Typeface {
return dyslexicTypeface ?: run {
val instance = Typeface.createFromAsset(context.assets, "OpenDyslexic.otf")
dyslexicTypeface = instance
instance
}
}
fun getHeaderFooterTypeface(context: Context): Typeface {
return arabicHeaderFooterTypeface ?: run {
val instance = Typeface.createFromAsset(context.assets, "UthmanTN1Ver10.otf")
arabicHeaderFooterTypeface = instance
instance
}
}
}
| gpl-3.0 | 358f5e1897a7d9a2519ee329eb9fb89a | 28.785714 | 83 | 0.713429 | 3.87907 | false | false | false | false |
drmaas/ratpack-kotlin | ratpack-kotlin-dsl/src/main/kotlin/ratpack/kotlin/handling/KContext.kt | 1 | 1328 | package ratpack.kotlin.handling
import ratpack.form.Form
import ratpack.handling.Context
import ratpack.http.TypedData
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
class KContext(val delegate: Context) : Context by delegate {
fun httpDate(date: LocalDateTime) = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.of(date, ZoneId.of("GMT")))
inline fun byContent(crossinline cb: KByContentSpec.(KByContentSpec) -> Unit) = delegate.byContent { val s = KByContentSpec(it); s.cb(s) }
inline fun byMethod (crossinline cb: KByMethodSpec.(KByMethodSpec) -> Unit) = delegate.byMethod { val s = KByMethodSpec(it); s.cb(s) }
inline fun withBody(crossinline cb: TypedData.(TypedData) -> Unit) = request.body.then { it.cb(it) }
inline fun withForm(crossinline cb: Form.(Form) -> Unit) = context.parse(Form::class.java).then { it.cb(it) }
fun send(body: String = "", status: Int = 200) {
response.status(status)
if (body == "")
response.send()
else
response.send(body)
}
fun ok(body: String = "", status: Int = 200) = send(body, status)
fun ok(status: Int = 200) = ok("", status)
fun halt(body: String = "", status: Int = 500) = send(body, status)
fun halt(status: Int = 500) = halt("", status)
}
| apache-2.0 | c8f43380b574648291908214ada7b662 | 38.058824 | 140 | 0.704819 | 3.467363 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/graphql/builder/Table.kt | 1 | 2025 | package org.evomaster.core.problem.graphql.builder
/**
* Intermediate data structure to parse and organize the object graphQl-schema types
* WARN: this class MUST be kept immutable
* */
data class Table(
/**
* Specify the name of the type.
* For example, in petclinic.graphqls:
* typeName: Query
*/
val typeName: String,
/**
* Specify the name of the field. I.e. the name of field in a node
* For example: pettypes (inside Query) in petclinic.graphqls.
*/
val fieldName: String,
/**
* Describing the kind of the field name
* For example: pettypes is a LIST
*/
val KindOfFieldName: String = "null",
/**
* Describing if the kind of the field name is nullable
* isKindOfFieldNameOptional: false
*/
val isKindOfFieldNameOptional: Boolean = false,
/**
* Describing the type of the field
* For example: PetType,
*/
val fieldType: String,
/**
* Describing the kind of the Field Type, eg: SCALAR, OBJECT,INPUT_OBJECT, ENUM
* For example: PetType is an OBJECT
*/
val kindOfFieldType: String,
/**
* Describing if the kind of the table field type is nullable
* For example: the OBJECT: PetType is not optional
*/
val isKindOfFieldTypeOptional: Boolean = false,
/**
* Describing if the field name has arguments
*/
val isFieldNameWithArgs: Boolean = false,
/**
* Containing the enum values
*/
val enumValues: List<String> = listOf(),
/**
* Containing the union possible types
*/
val unionTypes: List<String> = listOf(),
/**
* Containing the interface possible types
*/
val interfaceTypes: List<String> = listOf()
){
val uniqueId = "$typeName.$fieldName.$fieldType"
} | lgpl-3.0 | 9a5791212170b2cf9030e811165cf6c5 | 26.013333 | 87 | 0.562469 | 4.6875 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/ProfileCreationFragment.kt | 1 | 8887 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Aline Bonnet <[email protected]>
* Author: Adrien Beraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import cx.ring.R
import cx.ring.databinding.FragAccProfileCreateBinding
import cx.ring.mvp.BaseSupportFragment
import cx.ring.utils.AndroidFileUtils.createImageFile
import cx.ring.utils.AndroidFileUtils.loadBitmap
import cx.ring.utils.ContentUriHandler
import cx.ring.utils.ContentUriHandler.getUriForFile
import cx.ring.views.AvatarDrawable
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.core.Single
import net.jami.account.ProfileCreationPresenter
import net.jami.account.ProfileCreationView
import net.jami.model.AccountCreationModel
import java.io.IOException
@AndroidEntryPoint
class ProfileCreationFragment : BaseSupportFragment<ProfileCreationPresenter, ProfileCreationView>(), ProfileCreationView {
var model: AccountCreationModel? = null
private set
private var tmpProfilePhotoUri: Uri? = null
private var binding: FragAccProfileCreateBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return FragAccProfileCreateBinding.inflate(inflater, container, false).apply {
binding = this
}.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
retainInstance = true
if (model == null) {
activity?.finish()
return
}
if (binding!!.profilePhoto.drawable == null) {
binding!!.profilePhoto.setImageDrawable(
AvatarDrawable.Builder()
.withNameData(model!!.fullName, model!!.username)
.withCircleCrop(true)
.build(view.context)
)
}
presenter.initPresenter(model!!)
binding!!.gallery.setOnClickListener { presenter.galleryClick() }
binding!!.camera.setOnClickListener { presenter.cameraClick() }
binding!!.nextCreateAccount.setOnClickListener { presenter.nextClick() }
binding!!.skipCreateAccount.setOnClickListener { presenter.skipClick() }
binding!!.username.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
presenter.fullNameUpdated(s.toString())
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
when (requestCode) {
REQUEST_CODE_PHOTO -> if (resultCode == Activity.RESULT_OK) {
if (tmpProfilePhotoUri == null) {
if (intent != null) {
val bundle = intent.extras
val b = if (bundle == null) null else bundle["data"] as Bitmap?
if (b != null) {
presenter.photoUpdated(Single.just(b))
}
}
} else {
presenter.photoUpdated(loadBitmap(requireContext(), tmpProfilePhotoUri!!).map { b: Bitmap -> b })
}
}
REQUEST_CODE_GALLERY -> if (resultCode == Activity.RESULT_OK && intent != null) {
presenter.photoUpdated(loadBitmap(requireContext(), intent.data!!).map { b -> b })
}
else -> super.onActivityResult(requestCode, resultCode, intent)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION_CAMERA -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
presenter.cameraPermissionChanged(true)
presenter.cameraClick()
}
REQUEST_PERMISSION_READ_STORAGE -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
presenter.galleryClick()
}
}
}
override fun displayProfileName(profileName: String) {
binding!!.username.setText(profileName)
}
override fun goToGallery() {
try {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, REQUEST_CODE_GALLERY)
} catch (e: Exception) {
Toast.makeText(requireContext(), R.string.gallery_error_message, Toast.LENGTH_SHORT)
.show()
}
}
override fun goToPhotoCapture() {
try {
val context = requireContext()
val file = createImageFile(context)
val uri = getUriForFile(context, ContentUriHandler.AUTHORITY_FILES, file)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(MediaStore.EXTRA_OUTPUT, uri)
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
.putExtra("android.intent.extras.CAMERA_FACING", 1)
.putExtra("android.intent.extras.LENS_FACING_FRONT", 1)
.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
tmpProfilePhotoUri = uri
startActivityForResult(intent, REQUEST_CODE_PHOTO)
} catch (e: IOException) {
Log.e(TAG, "Can't create temp file", e)
} catch (e: ActivityNotFoundException) {
Log.e(TAG, "Could not start activity")
}
}
override fun askStoragePermission() {
requestPermissions(
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_PERMISSION_READ_STORAGE
)
}
override fun askPhotoPermission() {
requestPermissions(
arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
), REQUEST_PERMISSION_CAMERA
)
}
override fun goToNext(accountCreationModel: AccountCreationModel, saveProfile: Boolean) {
val wizardActivity: Activity? = activity
if (wizardActivity is AccountWizardActivity) {
wizardActivity.profileCreated(accountCreationModel, saveProfile)
}
}
override fun setProfile(accountCreationModel: AccountCreationModel) {
val model = accountCreationModel as AccountCreationModelImpl
val newAccount = model.newAccount
binding!!.profilePhoto.setImageDrawable(
AvatarDrawable.Builder()
.withPhoto(model.photo as Bitmap?)
.withNameData(accountCreationModel.fullName, accountCreationModel.username)
.withId(newAccount?.username)
.withCircleCrop(true)
.build(requireContext())
)
}
companion object {
val TAG = ProfileCreationFragment::class.simpleName!!
const val REQUEST_CODE_PHOTO = 1
const val REQUEST_CODE_GALLERY = 2
const val REQUEST_PERMISSION_CAMERA = 3
const val REQUEST_PERMISSION_READ_STORAGE = 4
fun newInstance(model: AccountCreationModelImpl): ProfileCreationFragment {
val fragment = ProfileCreationFragment()
fragment.model = model
return fragment
}
}
} | gpl-3.0 | 3cbdd3edbb38ab519879770c8ba2d474 | 39.217195 | 135 | 0.650838 | 4.874931 | false | false | false | false |
rfcx/rfcx-guardian-android | role-guardian/src/main/java/org/rfcx/guardian/guardian/manager/CredentialKeeper.kt | 1 | 1750 | package org.rfcx.guardian.guardian.manager
import android.content.Context
import org.rfcx.guardian.guardian.entity.UserAuthResponse
class CredentialKeeper(val context: Context) {
fun save(user: UserAuthResponse) {
val preferences = PreferenceManager.getInstance(context)
// Required
preferences.putString(PreferenceManager.USER_GUID, user.guid)
preferences.putString(PreferenceManager.ID_TOKEN, user.idToken)
preferences.putLong(PreferenceManager.TOKEN_EXPIRED_AT, user.expiredAt)
// Optional
if (user.accessToken != null) {
preferences.putString(PreferenceManager.ACCESS_TOKEN, user.accessToken)
}
if (user.refreshToken != null) {
preferences.putString(PreferenceManager.REFRESH_TOKEN, user.refreshToken)
}
if (user.email != null) {
preferences.putString(PreferenceManager.EMAIL, user.email)
}
if (user.nickname != null) {
preferences.putString(PreferenceManager.NICKNAME, user.nickname)
}
preferences.putStringSet(PreferenceManager.ROLES, user.roles)
preferences.putStringSet(PreferenceManager.ACCESSIBLE_SITES, user.accessibleSites)
if (user.defaultSite != null) {
preferences.putString(PreferenceManager.DEFAULT_SITE, user.defaultSite)
}
}
fun clear() {
val preferences = PreferenceManager.getInstance(context)
preferences.clear()
}
fun hasValidCredentials(): Boolean {
val preferences = PreferenceManager.getInstance(context)
return preferences.getString(PreferenceManager.ID_TOKEN, "").isNotEmpty() && preferences.getStringSet(PreferenceManager.ROLES).contains("rfcxUser")
}
}
| apache-2.0 | a930f17c5ad97505e135c95b63ceb60c | 37.888889 | 155 | 0.692 | 4.901961 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/test/kotlin/com/almasb/fxgl/animation/AnimationTest.kt | 1 | 7755 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
@file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE")
package com.almasb.fxgl.animation
import javafx.animation.Interpolator
import javafx.util.Duration
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.function.Consumer
/**
* @author Almas Baimagambetov ([email protected])
*/
class AnimationTest {
@Test
fun `Set animation interpolator`() {
val i1 = Interpolators.ELASTIC.EASE_OUT()
val builder = AnimationBuilder()
val animValue = AnimatedValue(1.0, 5.0)
val anim = builder
.interpolator(i1)
.duration(Duration.seconds(4.0))
.buildAnimation(animValue, Consumer { })
assertThat(anim.interpolator, `is`(i1))
val i2 = Interpolators.BACK.EASE_IN()
anim.interpolator = i2
assertThat(anim.interpolator, `is`(i2))
assertThat(anim.animatedValue, `is`(animValue))
}
@Test
fun `Simple Animation`() {
var count = 0.0
val anim = AnimationBuilder()
.interpolator(Interpolator.LINEAR)
.duration(Duration.seconds(4.0))
.buildAnimation(AnimatedValue(1.0, 5.0), Consumer { count = it })
assertFalse(anim.isAnimating)
assertFalse(anim.isAutoReverse)
assertFalse(anim.isReverse)
assertFalse(anim.isPaused)
assertThat(count, `is`(0.0))
anim.start()
assertTrue(anim.isAnimating)
assertFalse(anim.isPaused)
assertThat(count, `is`(1.0))
for (i in 2..5) {
anim.onUpdate(1.0)
assertThat(count, `is`(i.toDouble()))
}
assertFalse(anim.isAnimating)
}
@Test
fun `Infinite Animation`() {
var count = 0
val anim = AnimationBuilder()
.duration(Duration.seconds(2.0))
.repeatInfinitely()
.buildAnimation(AnimatedValue(1, 3), Consumer { count = it })
anim.start()
for (i in 0..100) {
assertThat(count, `is`(1))
anim.onUpdate(1.0)
assertThat(count, `is`(2))
anim.onUpdate(1.0)
assertThat(count, `is`(3))
// push over the cycle
anim.onUpdate(0.1)
}
assertTrue(anim.isAnimating)
}
@Test
fun `Simple Reverse Animation`() {
var count = 0.0
val anim = AnimationBuilder()
.interpolator(Interpolator.LINEAR)
.duration(Duration.seconds(4.0))
.autoReverse(true)
.repeat(3)
.buildAnimation(AnimatedValue(1.0, 5.0), Consumer { count = it })
assertFalse(anim.isAnimating)
assertTrue(anim.isAutoReverse)
assertFalse(anim.isReverse)
assertFalse(anim.isPaused)
assertThat(count, `is`(0.0))
anim.start()
assertTrue(anim.isAnimating)
assertFalse(anim.isPaused)
assertThat(count, `is`(1.0))
for (i in 2..5) {
anim.onUpdate(1.0)
assertThat(count, `is`(i.toDouble()))
}
assertThat(count, `is`(5.0))
assertTrue(anim.isAnimating)
assertTrue(anim.isReverse)
for (i in 4 downTo 1) {
anim.onUpdate(1.0)
assertThat(count, `is`(i.toDouble()))
}
assertThat(count, `is`(1.0))
assertTrue(anim.isAnimating)
assertFalse(anim.isReverse)
for (i in 2..5) {
anim.onUpdate(1.0)
assertThat(count, `is`(i.toDouble()))
}
assertThat(count, `is`(5.0))
assertFalse(anim.isAnimating)
assertFalse(anim.isReverse)
}
@Test
fun `On Animation Finished`() {
var count = 0
val anim = AnimationBuilder()
.interpolator(Interpolator.LINEAR)
.duration(Duration.seconds(2.0))
.onFinished(Runnable { count = 15 })
.buildAnimation(AnimatedValue(1, 3), Consumer { })
assertThat(count, `is`(0))
anim.start()
anim.onUpdate(2.0)
assertThat(count, `is`(15))
}
@Test
fun `On Animation Cycle Finished`() {
var count = 0
val anim = AnimationBuilder()
.repeat(2)
.interpolator(Interpolator.LINEAR)
.duration(Duration.seconds(2.0))
.onCycleFinished(Runnable { count = 2 })
.onFinished(Runnable { count = 15 })
.buildAnimation(AnimatedValue(1, 3), Consumer { })
assertThat(count, `is`(0))
anim.start()
anim.onUpdate(2.0)
assertThat(count, `is`(2))
anim.onUpdate(2.0)
assertThat(count, `is`(15))
}
@Test
fun `Animation with a delay`() {
var count = 0
val anim = AnimationBuilder()
.delay(Duration.seconds(1.5))
.duration(Duration.seconds(2.0))
.buildAnimation(AnimatedValue(1, 3), Consumer { count = it })
assertThat(count, `is`(0))
anim.start()
assertThat(count, `is`(1))
anim.onUpdate(1.0)
assertThat(count, `is`(1))
anim.onUpdate(0.5)
assertThat(count, `is`(1))
anim.onUpdate(1.0)
assertThat(count, `is`(2))
anim.onUpdate(1.0)
assertThat(count, `is`(3))
}
@Test
fun `Stop animation`() {
var count = 0
val anim = AnimationBuilder()
.duration(Duration.seconds(3.0))
.buildAnimation(AnimatedValue(1, 4), Consumer { count = it })
assertThat(count, `is`(0))
anim.start()
anim.onUpdate(2.0)
assertThat(count, `is`(3))
anim.stop()
assertThat(count, `is`(3))
anim.onUpdate(1.0)
assertThat(count, `is`(3))
}
@Test
fun `Pause and resume animation`() {
var count = 0
val anim = AnimationBuilder()
.duration(Duration.seconds(3.0))
.buildAnimation(AnimatedValue(1, 4), Consumer { count = it })
assertThat(count, `is`(0))
anim.start()
anim.onUpdate(2.0)
assertThat(count, `is`(3))
anim.pause()
assertThat(count, `is`(3))
anim.onUpdate(1.0)
assertThat(count, `is`(3))
anim.resume()
anim.onUpdate(1.0)
assertThat(count, `is`(4))
}
@Test
fun `Start and stop noop if animation has started stopped`() {
val anim = AnimationBuilder()
.interpolator(Interpolators.EXPONENTIAL.EASE_OUT())
.duration(Duration.seconds(3.0))
.buildAnimation(AnimatedValue(1, 4), Consumer { })
anim.stop()
anim.start()
anim.start()
anim.onUpdate(3.0)
assertFalse(anim.isAnimating)
}
@Test
fun `Start reverse`() {
var count = 0
val anim = AnimationBuilder()
.duration(Duration.seconds(3.0))
.buildAnimation(AnimatedValue(1, 4), Consumer { count = it })
anim.startReverse()
assertTrue(anim.isAnimating)
assertTrue(anim.isReverse)
assertThat(count, `is`(4))
// does nothing since we are animating already
anim.startReverse()
for (i in 3 downTo 1) {
anim.onUpdate(1.0)
assertThat(count, `is`(i))
}
}
} | mit | e6520fbd26d7e80d59ebb6a49a99718a | 23.2375 | 81 | 0.546357 | 4.096672 | false | false | false | false |
janicduplessis/react-native | ReactAndroid/src/main/java/com/facebook/react/views/view/ReactMapBufferPropSetter.kt | 1 | 17462 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.views.view
import android.graphics.Color
import android.graphics.Rect
import androidx.core.view.ViewCompat
import com.facebook.react.bridge.DynamicFromObject
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.JavaOnlyMap
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.common.mapbuffer.MapBuffer
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.PointerEvents
object ReactMapBufferPropSetter {
// ViewProps values
private const val VP_ACCESSIBILITY_ACTIONS = 0
private const val VP_ACCESSIBILITY_HINT = 1
private const val VP_ACCESSIBILITY_LABEL = 2
private const val VP_ACCESSIBILITY_LABELLED_BY = 3
private const val VP_ACCESSIBILITY_LIVE_REGION = 4
private const val VP_ACCESSIBILITY_ROLE = 5
private const val VP_ACCESSIBILITY_STATE = 6
private const val VP_ACCESSIBILITY_VALUE = 7
private const val VP_ACCESSIBLE = 8
private const val VP_BACKFACE_VISIBILITY = 9
private const val VP_BG_COLOR = 10
private const val VP_BORDER_COLOR = 11
private const val VP_BORDER_RADII = 12
private const val VP_BORDER_STYLE = 13
private const val VP_COLLAPSABLE = 14
private const val VP_ELEVATION = 15
private const val VP_FOCUSABLE = 16
private const val VP_HAS_TV_FOCUS = 17
private const val VP_HIT_SLOP = 18
private const val VP_IMPORTANT_FOR_ACCESSIBILITY = 19
private const val VP_NATIVE_BACKGROUND = 20
private const val VP_NATIVE_FOREGROUND = 21
private const val VP_NATIVE_ID = 22
private const val VP_OFFSCREEN_ALPHA_COMPOSITING = 23
private const val VP_OPACITY = 24
private const val VP_POINTER_EVENTS = 25
private const val VP_POINTER_ENTER = 26
private const val VP_POINTER_LEAVE = 27
private const val VP_POINTER_MOVE = 28
private const val VP_REMOVE_CLIPPED_SUBVIEW = 29
private const val VP_RENDER_TO_HARDWARE_TEXTURE = 30
private const val VP_SHADOW_COLOR = 31
private const val VP_TEST_ID = 32
private const val VP_TRANSFORM = 33
private const val VP_ZINDEX = 34
private const val VP_POINTER_ENTER_CAPTURE = 38
private const val VP_POINTER_LEAVE_CAPTURE = 39
private const val VP_POINTER_MOVE_CAPTURE = 40
private const val VP_POINTER_OUT = 41
private const val VP_POINTER_OUT_CAPTURE = 42
private const val VP_POINTER_OVER = 43
private const val VP_POINTER_OVER_CAPTURE = 44
// Yoga values
private const val YG_BORDER_WIDTH = 100
private const val YG_OVERFLOW = 101
// AccessibilityAction values
private const val ACCESSIBILITY_ACTION_NAME = 0
private const val ACCESSIBILITY_ACTION_LABEL = 1
// AccessibilityState values
private const val ACCESSIBILITY_STATE_BUSY = 0
private const val ACCESSIBILITY_STATE_DISABLED = 1
private const val ACCESSIBILITY_STATE_EXPANDED = 2
private const val ACCESSIBILITY_STATE_SELECTED = 3
private const val ACCESSIBILITY_STATE_CHECKED = 4
private const val EDGE_TOP = 0
private const val EDGE_LEFT = 1
private const val EDGE_RIGHT = 2
private const val EDGE_BOTTOM = 3
private const val EDGE_START = 4
private const val EDGE_END = 5
private const val EDGE_ALL = 6
private const val CORNER_TOP_LEFT = 0
private const val CORNER_TOP_RIGHT = 1
private const val CORNER_BOTTOM_RIGHT = 2
private const val CORNER_BOTTOM_LEFT = 3
private const val CORNER_TOP_START = 4
private const val CORNER_TOP_END = 5
private const val CORNER_BOTTOM_END = 6
private const val CORNER_BOTTOM_START = 7
private const val CORNER_ALL = 8
private const val NATIVE_DRAWABLE_KIND = 0
private const val NATIVE_DRAWABLE_ATTRIBUTE = 1
private const val NATIVE_DRAWABLE_COLOR = 2
private const val NATIVE_DRAWABLE_BORDERLESS = 3
private const val NATIVE_DRAWABLE_RIPPLE_RADIUS = 4
private const val UNDEF_COLOR = Int.MAX_VALUE
fun setProps(view: ReactViewGroup, viewManager: ReactViewManager, props: MapBuffer) {
for (entry in props) {
when (entry.key) {
VP_ACCESSIBILITY_ACTIONS -> {
viewManager.accessibilityActions(view, entry.mapBufferValue)
}
VP_ACCESSIBILITY_HINT -> {
viewManager.setAccessibilityHint(view, entry.stringValue.takeIf { it.isNotEmpty() })
}
VP_ACCESSIBILITY_LABEL -> {
viewManager.setAccessibilityLabel(view, entry.stringValue.takeIf { it.isNotEmpty() })
}
VP_ACCESSIBILITY_LABELLED_BY -> {
viewManager.accessibilityLabelledBy(view, entry.mapBufferValue)
}
VP_ACCESSIBILITY_LIVE_REGION -> {
view.accessibilityLiveRegion(entry.intValue)
}
VP_ACCESSIBILITY_ROLE -> {
viewManager.setAccessibilityRole(view, entry.stringValue.takeIf { it.isNotEmpty() })
}
VP_ACCESSIBILITY_STATE -> {
viewManager.accessibilityState(view, entry.mapBufferValue)
}
VP_ACCESSIBILITY_VALUE -> {
viewManager.accessibilityValue(view, entry.stringValue)
}
VP_ACCESSIBLE -> {
viewManager.setAccessible(view, entry.booleanValue)
}
VP_BACKFACE_VISIBILITY -> {
viewManager.backfaceVisibility(view, entry.intValue)
}
VP_BG_COLOR -> {
// TODO: color for some reason can be object in Java but not in C++
viewManager.backgroundColor(view, entry.intValue)
}
VP_BORDER_COLOR -> {
viewManager.borderColor(view, entry.mapBufferValue)
}
VP_BORDER_RADII -> {
viewManager.borderRadius(view, entry.mapBufferValue)
}
VP_BORDER_STYLE -> {
viewManager.borderStyle(view, entry.intValue)
}
VP_ELEVATION -> {
viewManager.setElevation(view, entry.doubleValue.toFloat())
}
VP_FOCUSABLE -> {
viewManager.setFocusable(view, entry.booleanValue)
}
VP_HAS_TV_FOCUS -> {
viewManager.setTVPreferredFocus(view, entry.booleanValue)
}
VP_HIT_SLOP -> {
view.hitSlop(entry.mapBufferValue)
}
VP_IMPORTANT_FOR_ACCESSIBILITY -> {
view.importantForAccessibility(entry.intValue)
}
VP_NATIVE_BACKGROUND -> {
viewManager.nativeBackground(view, entry.mapBufferValue)
}
VP_NATIVE_FOREGROUND -> {
viewManager.nativeForeground(view, entry.mapBufferValue)
}
VP_NATIVE_ID -> {
viewManager.setNativeId(view, entry.stringValue.takeIf { it.isNotEmpty() })
}
VP_OFFSCREEN_ALPHA_COMPOSITING -> {
viewManager.setNeedsOffscreenAlphaCompositing(view, entry.booleanValue)
}
VP_OPACITY -> {
viewManager.setOpacity(view, entry.doubleValue.toFloat())
}
VP_POINTER_EVENTS -> {
view.pointerEvents(entry.intValue)
}
VP_POINTER_ENTER -> {
viewManager.setPointerEnter(view, entry.booleanValue)
}
VP_POINTER_LEAVE -> {
viewManager.setPointerLeave(view, entry.booleanValue)
}
VP_POINTER_MOVE -> {
viewManager.setPointerMove(view, entry.booleanValue)
}
VP_POINTER_ENTER_CAPTURE -> {
viewManager.setPointerEnterCapture(view, entry.booleanValue)
}
VP_POINTER_LEAVE_CAPTURE -> {
viewManager.setPointerLeaveCapture(view, entry.booleanValue)
}
VP_POINTER_MOVE_CAPTURE -> {
viewManager.setPointerMoveCapture(view, entry.booleanValue)
}
VP_POINTER_OUT -> {
viewManager.setPointerOut(view, entry.booleanValue)
}
VP_POINTER_OUT_CAPTURE -> {
viewManager.setPointerOutCapture(view, entry.booleanValue)
}
VP_POINTER_OVER -> {
viewManager.setPointerOver(view, entry.booleanValue)
}
VP_POINTER_OVER_CAPTURE -> {
viewManager.setPointerOverCapture(view, entry.booleanValue)
}
VP_REMOVE_CLIPPED_SUBVIEW -> {
viewManager.setRemoveClippedSubviews(view, entry.booleanValue)
}
VP_RENDER_TO_HARDWARE_TEXTURE -> {
viewManager.setRenderToHardwareTexture(view, entry.booleanValue)
}
VP_SHADOW_COLOR -> {
// TODO: color for some reason can be object in Java but not in C++
viewManager.shadowColor(view, entry.intValue)
}
VP_TEST_ID -> {
viewManager.setTestId(view, entry.stringValue.takeIf { it.isNotEmpty() })
}
VP_TRANSFORM -> {
viewManager.transform(view, entry.mapBufferValue)
}
VP_ZINDEX -> {
viewManager.setZIndex(view, entry.intValue.toFloat())
}
YG_BORDER_WIDTH -> {
viewManager.borderWidth(view, entry.mapBufferValue)
}
YG_OVERFLOW -> {
viewManager.overflow(view, entry.intValue)
}
}
}
}
private fun ReactViewManager.accessibilityActions(view: ReactViewGroup, mapBuffer: MapBuffer) {
val actions = mutableListOf<ReadableMap>()
for (entry in mapBuffer) {
val map = JavaOnlyMap()
val action = entry.mapBufferValue
if (action != null) {
map.putString("name", action.getString(ACCESSIBILITY_ACTION_NAME))
if (action.contains(ACCESSIBILITY_ACTION_LABEL)) {
map.putString("label", action.getString(ACCESSIBILITY_ACTION_LABEL))
}
}
actions.add(map)
}
setAccessibilityActions(view, JavaOnlyArray.from(actions))
}
private fun ReactViewGroup.accessibilityLiveRegion(value: Int) {
val mode =
when (value) {
0 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE
1 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE
2 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_ASSERTIVE
else -> ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE
}
ViewCompat.setAccessibilityLiveRegion(this, mode)
}
private fun ReactViewManager.accessibilityState(view: ReactViewGroup, value: MapBuffer) {
val accessibilityState = JavaOnlyMap()
accessibilityState.putBoolean("selected", value.getBoolean(ACCESSIBILITY_STATE_SELECTED))
accessibilityState.putBoolean("busy", value.getBoolean(ACCESSIBILITY_STATE_BUSY))
accessibilityState.putBoolean("expanded", value.getBoolean(ACCESSIBILITY_STATE_EXPANDED))
accessibilityState.putBoolean("disabled", value.getBoolean(ACCESSIBILITY_STATE_DISABLED))
when (value.getInt(ACCESSIBILITY_STATE_CHECKED)) {
// Unchecked
0 -> accessibilityState.putBoolean("checked", false)
// Checked
1 -> accessibilityState.putBoolean("checked", true)
// Mixed
2 -> accessibilityState.putString("checked", "mixed")
// 3 -> None
}
setViewState(view, accessibilityState)
}
private fun ReactViewManager.accessibilityValue(view: ReactViewGroup, value: String) {
val map = JavaOnlyMap()
if (value.isNotEmpty()) {
map.putString("text", value)
}
setAccessibilityValue(view, map)
}
private fun ReactViewManager.accessibilityLabelledBy(view: ReactViewGroup, value: MapBuffer) {
val converted =
if (value.count == 0) {
DynamicFromObject(null)
} else {
val array = JavaOnlyArray()
for (label in value) {
array.pushString(label.stringValue)
}
DynamicFromObject(array)
}
setAccessibilityLabelledBy(view, converted)
}
private fun ReactViewManager.backfaceVisibility(view: ReactViewGroup, value: Int) {
val stringName =
when (value) {
1 -> "visible"
2 -> "hidden"
else -> "auto"
}
setBackfaceVisibility(view, stringName)
}
private fun ReactViewManager.backgroundColor(view: ReactViewGroup, value: Int) {
val color = value.takeIf { it != UNDEF_COLOR } ?: Color.TRANSPARENT
setBackgroundColor(view, color)
}
private fun ReactViewManager.borderColor(view: ReactViewGroup, value: MapBuffer) {
for (entry in value) {
val index =
when (val key = entry.key) {
EDGE_ALL -> 0
EDGE_LEFT -> 1
EDGE_RIGHT -> 2
EDGE_TOP -> 3
EDGE_BOTTOM -> 4
EDGE_START -> 5
EDGE_END -> 6
else -> throw IllegalArgumentException("Unknown key for border color: $key")
}
val colorValue = entry.intValue
setBorderColor(view, index, colorValue.takeIf { it != -1 })
}
}
private fun ReactViewManager.borderRadius(view: ReactViewGroup, value: MapBuffer) {
for (entry in value) {
val index =
when (val key = entry.key) {
CORNER_ALL -> 0
CORNER_TOP_LEFT -> 1
CORNER_TOP_RIGHT -> 2
CORNER_BOTTOM_RIGHT -> 3
CORNER_BOTTOM_LEFT -> 4
CORNER_TOP_START -> 5
CORNER_TOP_END -> 6
CORNER_BOTTOM_START -> 7
CORNER_BOTTOM_END -> 8
else -> throw IllegalArgumentException("Unknown key for border style: $key")
}
val borderRadius = entry.doubleValue
if (!borderRadius.isNaN()) {
setBorderRadius(view, index, borderRadius.toFloat())
}
}
}
private fun ReactViewManager.borderStyle(view: ReactViewGroup, value: Int) {
val stringValue =
when (value) {
0 -> "solid"
1 -> "dotted"
2 -> "dashed"
else -> null
}
setBorderStyle(view, stringValue)
}
private fun ReactViewGroup.hitSlop(value: MapBuffer) {
val rect =
Rect(
PixelUtil.toPixelFromDIP(value.getDouble(EDGE_LEFT)).toInt(),
PixelUtil.toPixelFromDIP(value.getDouble(EDGE_TOP)).toInt(),
PixelUtil.toPixelFromDIP(value.getDouble(EDGE_RIGHT)).toInt(),
PixelUtil.toPixelFromDIP(value.getDouble(EDGE_BOTTOM)).toInt(),
)
hitSlopRect = rect
}
private fun ReactViewGroup.importantForAccessibility(value: Int) {
val mode =
when (value) {
0 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO
1 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES
2 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO
3 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
else -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO
}
ViewCompat.setImportantForAccessibility(this, mode)
}
private fun ReactViewGroup.pointerEvents(value: Int) {
val pointerEvents =
when (value) {
0 -> PointerEvents.AUTO
1 -> PointerEvents.NONE
2 -> PointerEvents.BOX_NONE
3 -> PointerEvents.BOX_ONLY
else -> throw IllegalArgumentException("Unknown value for pointer events: $value")
}
setPointerEvents(pointerEvents)
}
private fun ReactViewManager.transform(view: ReactViewGroup, value: MapBuffer) {
val list = JavaOnlyArray()
for (entry in value) {
list.pushDouble(entry.doubleValue)
}
setTransform(view, list)
}
private fun ReactViewManager.borderWidth(view: ReactViewGroup, value: MapBuffer) {
for (entry in value) {
val index =
when (val key = entry.key) {
EDGE_ALL -> 0
EDGE_LEFT -> 1
EDGE_RIGHT -> 2
EDGE_TOP -> 3
EDGE_BOTTOM -> 4
EDGE_START -> 5
EDGE_END -> 6
else -> throw IllegalArgumentException("Unknown key for border width: $key")
}
val borderWidth = entry.doubleValue
if (!borderWidth.isNaN()) {
setBorderWidth(view, index, borderWidth.toFloat())
}
}
}
private fun ReactViewManager.overflow(view: ReactViewGroup, value: Int) {
val stringValue =
when (value) {
0 -> "visible"
1 -> "hidden"
2 -> "scroll"
else -> throw IllegalArgumentException("Unknown overflow value: $value")
}
setOverflow(view, stringValue)
}
private fun ReactViewManager.shadowColor(view: ReactViewGroup, value: Int) {
val color = value.takeIf { it != UNDEF_COLOR } ?: Color.BLACK
setShadowColor(view, color)
}
private fun ReactViewManager.nativeBackground(view: ReactViewGroup, value: MapBuffer) {
setNativeBackground(view, value.toJsDrawableDescription())
}
private fun ReactViewManager.nativeForeground(view: ReactViewGroup, value: MapBuffer) {
setNativeForeground(view, value.toJsDrawableDescription())
}
private fun MapBuffer.toJsDrawableDescription(): ReadableMap? {
if (count == 0) {
return null
}
val kind = getInt(NATIVE_DRAWABLE_KIND)
val result = JavaOnlyMap()
when (kind) {
0 -> {
result.putString("type", "ThemeAttrAndroid")
result.putString("attribute", getString(NATIVE_DRAWABLE_ATTRIBUTE))
}
1 -> {
result.putString("type", "RippleAndroid")
if (contains(NATIVE_DRAWABLE_COLOR)) {
result.putInt("color", getInt(NATIVE_DRAWABLE_COLOR))
}
result.putBoolean("borderless", getBoolean(NATIVE_DRAWABLE_BORDERLESS))
if (contains(NATIVE_DRAWABLE_RIPPLE_RADIUS)) {
result.putDouble("rippleRadius", getDouble(NATIVE_DRAWABLE_RIPPLE_RADIUS))
}
}
else -> throw IllegalArgumentException("Unknown native drawable: $kind")
}
return result
}
}
| mit | e0ba6ae3ac4d75630b468226344ac094 | 34.205645 | 97 | 0.650498 | 4.45232 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/command/profession/ProfessionViewCommand.kt | 1 | 5662 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.professions.bukkit.command.profession
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKProfessionService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class ProfessionViewCommand(val plugin: RPKProfessionsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.professions.command.profession.view")) {
sender.sendMessage(plugin.messages["no-permission-profession-view"])
return true
}
val target = if (sender.hasPermission("rpkit.professions.command.profession.view.other")) {
when {
args.size > 1 -> {
val player = plugin.server.getPlayer(args[0])
if (player == null) {
sender.sendMessage(plugin.messages["profession-view-invalid-player-not-online"])
return true
} else {
player
}
}
sender is Player -> sender
else -> {
sender.sendMessage(plugin.messages["profession-view-invalid-player-please-specify-from-console"])
return true
}
}
} else {
if (sender is Player) {
sender
} else {
sender.sendMessage(plugin.messages["profession-view-invalid-player-please-specify-from-console"])
return true
}
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(target)
if (minecraftProfile == null) {
if (target == sender) {
sender.sendMessage(plugin.messages["no-minecraft-profile-self"])
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile-other", mapOf(
"player" to target.name
)])
}
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
if (target == sender) {
sender.sendMessage(plugin.messages["no-character-self"])
} else {
sender.sendMessage(plugin.messages["no-character-other", mapOf(
"player" to target.name
)])
}
return true
}
val professionService = Services[RPKProfessionService::class.java]
if (professionService == null) {
sender.sendMessage(plugin.messages["no-profession-service"])
return true
}
professionService.getProfessions(character).thenAcceptAsync { characterProfessions ->
sender.sendMessage(plugin.messages["profession-view-valid-title"])
characterProfessions.forEach { profession ->
val level = professionService.getProfessionLevel(character, profession).join()
val experienceSinceLastLevel =
if (level > 1) {
professionService.getProfessionExperience(character, profession).join() - profession.getExperienceNeededForLevel(level)
} else {
professionService.getProfessionExperience(character, profession).join()
}
val experienceNeededForNextLevel =
profession.getExperienceNeededForLevel(level + 1) - profession.getExperienceNeededForLevel(level)
sender.sendMessage(plugin.messages["profession-view-valid-item", mapOf(
"profession" to profession.name.value,
"level" to level.toString(),
"total_experience" to professionService.getProfessionExperience(character, profession).toString(),
"total_next_level_experience" to profession.getExperienceNeededForLevel(level + 1).toString(),
"experience" to experienceSinceLastLevel.toString(),
"next_level_experience" to experienceNeededForNextLevel.toString()
)])
}
}
return true
}
}
| apache-2.0 | ed21e26a9fbb8e51157f0be5c573a243 | 45.409836 | 143 | 0.616743 | 5.311445 | false | false | false | false |
dropbox/dropbox-sdk-java | examples/examples/src/main/java/com/dropbox/core/examples/account_info_legacy/AccountInfoLegacyExample.kt | 1 | 1338 | package com.dropbox.core.examples.account_info_legacy
import com.dropbox.core.DbxAuthInfo
import com.dropbox.core.DbxRequestConfig
import com.dropbox.core.DbxWebAuth
import com.dropbox.core.examples.CredentialsUtil
import com.dropbox.core.stone.StoneDeserializerLogger
import com.dropbox.core.v2.DbxClientV2
import com.dropbox.core.v2.users.Name
/**
* An example command-line application that runs through the web-based OAuth
* flow (using [DbxWebAuth]).
*/
object AccountInfoLegacyExample {
@JvmStatic
fun main(args: Array<String>) {
val authInfo = CredentialsUtil.getAuthInfo()
runExample(authInfo)
}
fun runExample(authInfo: DbxAuthInfo) {
// Create a DbxClientV2, which is what you use to make API calls.
val requestConfig = DbxRequestConfig("examples-account-info")
val dbxClient = DbxClientV2(requestConfig, authInfo.accessToken, authInfo.host)
val callback = StoneDeserializerLogger.LoggerCallback { _: Any?, s: String? ->
println("This is from StoneDeserializerLogger: ")
println(s)
}
StoneDeserializerLogger.registerCallback(Name::class.java, callback)
// Make the /account/info API call.
val dbxAccountInfo = dbxClient.users().currentAccount
print(dbxAccountInfo.toStringMultiline())
}
}
| mit | 9852694226259215a4e427413f543dbf | 35.162162 | 87 | 0.721973 | 4.03012 | false | true | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/LangComboBoxUI.kt | 1 | 2928 | package cn.yiiguxing.plugin.translate.ui
import cn.yiiguxing.plugin.translate.trans.Lang
import cn.yiiguxing.plugin.translate.ui.icon.ComboArrowIcon
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import java.awt.Component
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Rectangle
import javax.swing.*
import javax.swing.plaf.basic.BasicComboBoxUI
/**
* LangComboBoxUI
*/
class LangComboBoxUI(
private val myComboBox: ComboBox<Lang>,
horizontalAlignment: Int = SwingConstants.LEFT
) : BasicComboBoxUI() {
private val label: JLabel
private val arrowIcon: ComboArrowIcon
init {
myComboBox.apply {
border = BorderFactory.createEmptyBorder()
renderer = SimpleListCellRenderer.create<Lang> { label, value, _ ->
label.text = value.langName
label.font = [email protected]
}
isEditable = false
}
arrowIcon = ComboArrowIcon()
label = JLabel(arrowIcon).apply {
horizontalTextPosition = SwingConstants.LEFT
setHorizontalAlignment(horizontalAlignment)
}
}
override fun installDefaults() {
super.installDefaults()
if (myComboBox !== comboBox) {
throw IllegalStateException("Not expected component.")
}
}
override fun createArrowButton(): JButton? = null
override fun getSizeForComponent(comp: Component): Dimension =
super.getSizeForComponent(comp).apply { width += JBUI.scale(10) }
override fun getMinimumSize(c: JComponent): Dimension {
if (!isMinimumSizeDirty) {
return Dimension(cachedMinimumSize)
}
return displaySize.let {
JBInsets.addTo(it, insets)
it.width += label.iconTextGap + arrowIcon.iconWidth
cachedMinimumSize.size = it
isMinimumSizeDirty = false
Dimension(it)
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) = Unit
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
with(myComboBox) {
val foregroundColor = if (isEnabled) {
foreground
} else {
UIManager.getColor("ComboBox.disabledForeground")
}
label.foreground = foregroundColor
arrowIcon.color = foregroundColor
label.font = font
label.text = selected?.langName
}
currentValuePane.paintComponent(g, label, myComboBox,
Rectangle(bounds).also { JBInsets.removeFrom(it, padding) })
}
override fun rectangleForCurrentValue(): Rectangle = Rectangle(comboBox.width, comboBox.height).apply {
JBInsets.removeFrom(this, insets)
}
}
| mit | 1395f29ea4cca580eaf015d380ecf82f | 28.877551 | 107 | 0.651981 | 4.847682 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/message/signature/HtmlSignatureRemover.kt | 1 | 4832 | package com.fsck.k9.message.signature
import com.fsck.k9.helper.jsoup.AdvancedNodeTraversor
import com.fsck.k9.helper.jsoup.NodeFilter
import com.fsck.k9.helper.jsoup.NodeFilter.HeadFilterDecision
import com.fsck.k9.helper.jsoup.NodeFilter.TailFilterDecision
import java.util.Stack
import java.util.regex.Pattern
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.nodes.Node
import org.jsoup.nodes.TextNode
import org.jsoup.parser.Tag
class HtmlSignatureRemover {
private fun stripSignatureInternal(content: String): String {
val document = Jsoup.parse(content)
val nodeTraversor = AdvancedNodeTraversor(StripSignatureFilter())
nodeTraversor.filter(document.body())
return toCompactString(document)
}
private fun toCompactString(document: Document): String {
document.outputSettings()
.prettyPrint(false)
.indentAmount(0)
return document.html()
}
private class StripSignatureFilter : NodeFilter {
private var signatureFound = false
private var signatureParentNode: Node? = null
override fun head(node: Node, depth: Int): HeadFilterDecision {
if (signatureFound) return HeadFilterDecision.REMOVE
if (node.isBlockquote()) {
return HeadFilterDecision.SKIP_ENTIRELY
} else if (node.isSignatureDelimiter()) {
val precedingLineBreak = node.findPrecedingLineBreak()
if (precedingLineBreak != null && node.isFollowedByLineBreak()) {
signatureFound = true
signatureParentNode = node.parent()
precedingLineBreak.takeIf { it.isBR() }?.remove()
return HeadFilterDecision.REMOVE
}
}
return HeadFilterDecision.CONTINUE
}
override fun tail(node: Node, depth: Int): TailFilterDecision {
if (signatureFound) {
val signatureParentNode = this.signatureParentNode
if (node == signatureParentNode) {
return if (signatureParentNode.isEmpty()) {
this.signatureParentNode = signatureParentNode.parent()
TailFilterDecision.REMOVE
} else {
TailFilterDecision.STOP
}
}
}
return TailFilterDecision.CONTINUE
}
private fun Node.isBlockquote(): Boolean {
return this is Element && tag() == BLOCKQUOTE
}
private fun Node.isSignatureDelimiter(): Boolean {
return this is TextNode && DASH_SIGNATURE_HTML.matcher(wholeText).matches()
}
private fun Node.findPrecedingLineBreak(): Node? {
val stack = Stack<Node>()
stack.push(this)
while (stack.isNotEmpty()) {
val node = stack.pop()
val previousSibling = node.previousSibling()
if (previousSibling == null) {
val parent = node.parent()
if (parent is Element && parent.isBlock) {
return parent
} else {
stack.push(parent)
}
} else if (previousSibling.isLineBreak()) {
return previousSibling
}
}
return null
}
private fun Node.isFollowedByLineBreak(): Boolean {
val stack = Stack<Node>()
stack.push(this)
while (stack.isNotEmpty()) {
val node = stack.pop()
val nextSibling = node.nextSibling()
if (nextSibling == null) {
val parent = node.parent()
if (parent is Element && parent.isBlock) {
return true
} else {
stack.push(parent)
}
} else if (nextSibling.isLineBreak()) {
return true
}
}
return false
}
private fun Node?.isBR() = this is Element && tag() == BR
private fun Node?.isLineBreak() = isBR() || (this is Element && this.isBlock)
private fun Node.isEmpty(): Boolean = childNodeSize() == 0
}
companion object {
private val DASH_SIGNATURE_HTML = Pattern.compile("\\s*-- \\s*", Pattern.CASE_INSENSITIVE)
private val BLOCKQUOTE = Tag.valueOf("blockquote")
private val BR = Tag.valueOf("br")
@JvmStatic
fun stripSignature(content: String): String {
return HtmlSignatureRemover().stripSignatureInternal(content)
}
}
}
| apache-2.0 | 10907796fca1d089a64f62e4c0590f89 | 33.028169 | 98 | 0.559603 | 5.097046 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/string/StringScheme.kt | 1 | 5179 | package com.fwdekker.randomness.string
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.CapitalizationMode
import com.fwdekker.randomness.RandomnessIcons
import com.fwdekker.randomness.Scheme
import com.fwdekker.randomness.SchemeDecorator
import com.fwdekker.randomness.TypeIcon
import com.fwdekker.randomness.array.ArrayDecorator
import com.fwdekker.randomness.string.StringScheme.Companion.LOOK_ALIKE_CHARACTERS
import com.github.curiousoddman.rgxgen.RgxGen
import com.github.curiousoddman.rgxgen.parsing.dflt.RgxGenParseException
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Color
import kotlin.random.asJavaRandom
/**
* Contains settings for generating random strings.
*
* @property pattern The regex-like pattern according to which the string is generated.
* @property isRegex `true` if and only if [pattern] should be interpreted as a regex.
* @property capitalization The capitalization mode of the generated string.
* @property removeLookAlikeSymbols Whether the symbols in [LOOK_ALIKE_CHARACTERS] should be removed.
* @property arrayDecorator Settings that determine whether the output should be an array of values.
*/
data class StringScheme(
var pattern: String = DEFAULT_PATTERN,
var isRegex: Boolean = DEFAULT_IS_REGEX,
var capitalization: CapitalizationMode = DEFAULT_CAPITALIZATION,
var removeLookAlikeSymbols: Boolean = DEFAULT_REMOVE_LOOK_ALIKE_SYMBOLS,
var arrayDecorator: ArrayDecorator = ArrayDecorator()
) : Scheme() {
@get:Transient
override val name = Bundle("string.title")
override val typeIcon = BASE_ICON
override val decorators: List<SchemeDecorator>
get() = listOf(arrayDecorator)
/**
* Returns strings of random alphanumerical characters.
*
* @param count the number of strings to generate
* @return strings of random alphanumerical characters
*/
override fun generateUndecoratedStrings(count: Int): List<String> {
val rawStrings =
if (isRegex) {
val rgxGen = RgxGen(pattern)
List(count) { rgxGen.generate(random.asJavaRandom()) }
} else {
List(count) { pattern }
}
return rawStrings.map { rawString ->
val capitalizedString = capitalization.transform(rawString, random)
if (removeLookAlikeSymbols) capitalizedString.filterNot { it in LOOK_ALIKE_CHARACTERS }
else capitalizedString
}
}
/**
* Returns `true` if and only if this scheme does not use any regex functionality beyond escape characters.
*
* @return `true` if and only if this scheme does not use any regex functionality beyond escape characters
*/
fun isSimple() =
doValidate() == null &&
generateStrings()[0] == if (isRegex) pattern.replace(Regex("\\\\(.)"), "$1") else pattern
override fun doValidate() =
when {
!isRegex -> arrayDecorator.doValidate()
pattern.takeLastWhile { it == '\\' }.length.mod(2) != 0 -> Bundle("string.error.trailing_backslash")
pattern == "{}" || pattern.contains(Regex("[^\\\\]\\{}")) -> Bundle("string.error.empty_curly")
pattern == "[]" || pattern.contains(Regex("[^\\\\]\\[]")) -> Bundle("string.error.empty_square")
else ->
@Suppress("TooGenericExceptionCaught") // Consequence of incomplete validation in RgxGen
try {
RgxGen(pattern).generate()
arrayDecorator.doValidate()
} catch (e: RgxGenParseException) {
e.message
} catch (e: Exception) {
"Uncaught RgxGen exception: ${e.message}"
}
}
override fun deepCopy(retainUuid: Boolean) =
StringScheme(
pattern = pattern,
isRegex = isRegex,
capitalization = capitalization,
removeLookAlikeSymbols = removeLookAlikeSymbols,
arrayDecorator = arrayDecorator.deepCopy(retainUuid)
).also { if (retainUuid) it.uuid = this.uuid }
/**
* Holds constants.
*/
companion object {
/**
* Symbols that look like other symbols.
*
* To be precise, this string contains the symbols `0`, `1`, `l`, `I`, `O`, `|`, and `﹒`.
*/
const val LOOK_ALIKE_CHARACTERS = "01lLiIoO|﹒"
/**
* The base icon for strings.
*/
val BASE_ICON = TypeIcon(RandomnessIcons.SCHEME, "abc", listOf(Color(244, 175, 61, 154)))
/**
* The default value of the [pattern] field.
*/
const val DEFAULT_PATTERN = "[a-zA-Z0-9]{7,11}"
/**
* The default value of the [isRegex] field.
*/
const val DEFAULT_IS_REGEX = true
/**
* The default value of the [capitalization] field.
*/
val DEFAULT_CAPITALIZATION = CapitalizationMode.RETAIN
/**
* The default value of the [removeLookAlikeSymbols] field.
*/
const val DEFAULT_REMOVE_LOOK_ALIKE_SYMBOLS = false
}
}
| mit | f3ab32652b52c9be938236310f33174f | 35.964286 | 112 | 0.63285 | 4.44206 | false | false | false | false |
square/kotlinpoet | kotlinpoet/src/test/java/com/squareup/kotlinpoet/PropertySpecTest.kt | 1 | 21620 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.kotlinpoet
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.FunSpec.Companion.GETTER
import com.squareup.kotlinpoet.FunSpec.Companion.SETTER
import com.squareup.kotlinpoet.KModifier.EXTERNAL
import com.squareup.kotlinpoet.KModifier.PRIVATE
import com.squareup.kotlinpoet.KModifier.PUBLIC
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import java.io.Serializable
import java.util.function.Function
import kotlin.reflect.KClass
import kotlin.test.Test
@OptIn(ExperimentalKotlinPoetApi::class)
class PropertySpecTest {
annotation class TestAnnotation
@Test fun nullable() {
val type = String::class.asClassName().copy(nullable = true)
val a = PropertySpec.builder("foo", type).build()
assertThat(a.toString()).isEqualTo("val foo: kotlin.String?\n")
}
@Test fun delegated() {
val prop = PropertySpec.builder("foo", String::class)
.delegate("Delegates.notNull()")
.build()
assertThat(prop.toString()).isEqualTo("val foo: kotlin.String by Delegates.notNull()\n")
}
@Test fun emptySetter() {
val prop = PropertySpec.builder("foo", String::class)
.mutable()
.setter(
FunSpec.setterBuilder()
.addModifiers(PRIVATE)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|var foo: kotlin.String
| private set
|
""".trimMargin(),
)
}
// https://github.com/square/kotlinpoet/issues/952
@Test fun emptySetterCannotHaveBody() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("foo", String::class)
.mutable()
.setter(
FunSpec.setterBuilder()
.addStatement("body()")
.build(),
)
.build()
}.hasMessageThat().isEqualTo("parameterless setter cannot have code")
}
@Test fun externalGetterAndSetter() {
val prop = PropertySpec.builder("foo", String::class)
.mutable()
.getter(
FunSpec.getterBuilder()
.addModifiers(EXTERNAL)
.build(),
)
.setter(
FunSpec.setterBuilder()
.addModifiers(EXTERNAL)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|var foo: kotlin.String
| external get
| external set
|
""".trimMargin(),
)
}
@Test fun externalGetterCannotHaveBody() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("foo", String::class)
.getter(
FunSpec.getterBuilder()
.addModifiers(EXTERNAL)
.addStatement("return %S", "foo")
.build(),
)
.build()
}.hasMessageThat().isEqualTo("external getter cannot have code")
}
@Test fun publicGetterAndSetter() {
val prop = PropertySpec.builder("foo", String::class)
.mutable()
.getter(
FunSpec.getterBuilder()
.addModifiers(PUBLIC)
.addStatement("return %S", "_foo")
.build(),
)
.setter(
FunSpec.setterBuilder()
.addModifiers(PUBLIC)
.addParameter("value", String::class)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|var foo: kotlin.String
| public get() = "_foo"
| public set(`value`) {
| }
|
""".trimMargin(),
)
}
@Test fun inlineSingleAccessorVal() {
val prop = PropertySpec.builder("foo", String::class)
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return %S", "foo")
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|inline val foo: kotlin.String
| get() = "foo"
|
""".trimMargin(),
)
}
@Test fun inlineSingleAccessorVar() {
val prop = PropertySpec.builder("foo", String::class)
.mutable()
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return %S", "foo")
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|var foo: kotlin.String
| inline get() = "foo"
|
""".trimMargin(),
)
}
@Test fun inlineBothAccessors() {
val prop = PropertySpec.builder("foo", String::class.asTypeName())
.mutable()
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return %S", "foo")
.build(),
)
.setter(
FunSpec.setterBuilder()
.addModifiers(KModifier.INLINE)
.addParameter("value", String::class)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|inline var foo: kotlin.String
| get() = "foo"
| set(`value`) {
| }
|
""".trimMargin(),
)
}
@Test fun inlineForbiddenOnProperty() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("foo", String::class)
.addModifiers(KModifier.INLINE)
.build()
}.hasMessageThat().isEqualTo(
"KotlinPoet doesn't allow setting the inline modifier on " +
"properties. You should mark either the getter, the setter, or both inline.",
)
}
@Test fun equalsAndHashCode() {
val type = Int::class
var a = PropertySpec.builder("foo", type).build()
var b = PropertySpec.builder("foo", type).build()
assertThat(a == b).isTrue()
assertThat(a.hashCode()).isEqualTo(b.hashCode())
a = PropertySpec.builder("FOO", type, KModifier.PUBLIC, KModifier.LATEINIT).build()
b = PropertySpec.builder("FOO", type, KModifier.PUBLIC, KModifier.LATEINIT).build()
assertThat(a == b).isTrue()
assertThat(a.hashCode()).isEqualTo(b.hashCode())
}
@Test fun escapeKeywordInPropertyName() {
val prop = PropertySpec.builder("object", String::class)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|val `object`: kotlin.String
|
""".trimMargin(),
)
}
@Test fun escapeKeywordInVariableName() {
val prop = PropertySpec.builder("object", String::class)
.mutable()
.build()
assertThat(prop.toString()).isEqualTo(
"""
|var `object`: kotlin.String
|
""".trimMargin(),
)
}
@Test fun externalTopLevel() {
val prop = PropertySpec.builder("foo", String::class)
.addModifiers(KModifier.EXTERNAL)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|external val foo: kotlin.String
|
""".trimMargin(),
)
}
@Test fun escapePunctuationInPropertyName() {
val prop = PropertySpec.builder("with-hyphen", String::class)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|val `with-hyphen`: kotlin.String
|
""".trimMargin(),
)
}
@Test fun generalBuilderEqualityTest() {
val originatingElement = FakeElement()
val prop = PropertySpec.builder("tacos", Int::class)
.mutable()
.addAnnotation(ClassName("com.squareup.kotlinpoet", "Vegan"))
.addKdoc("Can make it vegan!")
.addModifiers(KModifier.PUBLIC)
.addTypeVariable(TypeVariableName("T"))
.delegate("Delegates.notNull()")
.receiver(Int::class)
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return %S", 42)
.build(),
)
.setter(
FunSpec.setterBuilder()
.addModifiers(KModifier.INLINE)
.addParameter("value", Int::class)
.build(),
)
.addOriginatingElement(originatingElement)
.build()
val newProp = prop.toBuilder().build()
assertThat(newProp).isEqualTo(prop)
assertThat(newProp.originatingElements).containsExactly(originatingElement)
}
@Test fun modifyModifiers() {
val builder = PropertySpec
.builder("word", String::class)
.addModifiers(PRIVATE)
builder.modifiers.clear()
builder.modifiers.add(KModifier.INTERNAL)
assertThat(builder.build().modifiers).containsExactly(KModifier.INTERNAL)
}
@Test fun modifyAnnotations() {
val builder = PropertySpec
.builder("word", String::class)
.addAnnotation(
AnnotationSpec.builder(JvmName::class.asClassName())
.addMember("name = %S", "jvmWord")
.build(),
)
val javaWord = AnnotationSpec.builder(JvmName::class.asClassName())
.addMember("name = %S", "javaWord")
.build()
builder.annotations.clear()
builder.annotations.add(javaWord)
assertThat(builder.build().annotations).containsExactly(javaWord)
}
// https://github.com/square/kotlinpoet/issues/437
@Test fun typeVariable() {
val t = TypeVariableName("T", Any::class)
val prop = PropertySpec.builder("someFunction", t, PRIVATE)
.addTypeVariable(t)
.receiver(KClass::class.asClassName().parameterizedBy(t))
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return stuff as %T", t)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|private inline val <T : kotlin.Any> kotlin.reflect.KClass<T>.someFunction: T
| get() = stuff as T
|
""".trimMargin(),
)
}
@Test fun typeVariablesWithWhere() {
val t = TypeVariableName("T", Serializable::class, Cloneable::class)
val r = TypeVariableName("R", Any::class)
val function = Function::class.asClassName().parameterizedBy(t, r)
val prop = PropertySpec.builder("property", String::class, PRIVATE)
.receiver(function)
.addTypeVariables(listOf(t, r))
.getter(
FunSpec.getterBuilder()
.addStatement("return %S", "")
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|private val <T, R : kotlin.Any> java.util.function.Function<T, R>.`property`: kotlin.String where T : java.io.Serializable, T : kotlin.Cloneable
| get() = ""
|
""".trimMargin(),
)
}
@Test fun reifiedTypeVariable() {
val t = TypeVariableName("T").copy(reified = true)
val prop = PropertySpec.builder("someFunction", t, PRIVATE)
.addTypeVariable(t)
.receiver(KClass::class.asClassName().parameterizedBy(t))
.getter(
FunSpec.getterBuilder()
.addModifiers(KModifier.INLINE)
.addStatement("return stuff as %T", t)
.build(),
)
.build()
assertThat(prop.toString()).isEqualTo(
"""
|private inline val <reified T> kotlin.reflect.KClass<T>.someFunction: T
| get() = stuff as T
|
""".trimMargin(),
)
}
@Test fun reifiedTypeVariableNotAllowedWhenNoAccessors() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("property", String::class)
.addTypeVariable(TypeVariableName("T").copy(reified = true))
.build()
}.hasMessageThat().isEqualTo(
"only type parameters of properties with inline getters and/or setters can be reified!",
)
}
@Test fun reifiedTypeVariableNotAllowedWhenGetterNotInline() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("property", String::class)
.addTypeVariable(TypeVariableName("T").copy(reified = true))
.getter(
FunSpec.getterBuilder()
.addStatement("return %S", "")
.build(),
)
.build()
}.hasMessageThat().isEqualTo(
"only type parameters of properties with inline getters and/or setters can be reified!",
)
}
@Test fun reifiedTypeVariableNotAllowedWhenSetterNotInline() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("property", String::class.asTypeName())
.mutable()
.addTypeVariable(TypeVariableName("T").copy(reified = true))
.setter(
FunSpec.setterBuilder()
.addParameter("value", String::class)
.addStatement("println()")
.build(),
)
.build()
}.hasMessageThat().isEqualTo(
"only type parameters of properties with inline getters and/or setters can be reified!",
)
}
@Test fun reifiedTypeVariableNotAllowedWhenOnlySetterIsInline() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("property", String::class.asTypeName())
.mutable()
.addTypeVariable(TypeVariableName("T").copy(reified = true))
.getter(
FunSpec.getterBuilder()
.addStatement("return %S", "")
.build(),
)
.setter(
FunSpec.setterBuilder()
.addModifiers(KModifier.INLINE)
.addParameter("value", String::class)
.addStatement("println()")
.build(),
)
.build()
}.hasMessageThat().isEqualTo(
"only type parameters of properties with inline getters and/or setters can be reified!",
)
}
@Test fun setterNotAllowedWhenPropertyIsNotMutable() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("property", String::class.asTypeName())
.setter(
FunSpec.setterBuilder()
.addModifiers(KModifier.INLINE)
.addParameter("value", String::class)
.addStatement("println()")
.build(),
)
.build()
}.hasMessageThat().isEqualTo("only a mutable property can have a setter")
}
// https://github.com/square/kotlinpoet/issues/462
@Test fun codeBlockInitializer() {
val param = ParameterSpec.builder("arg", ANY).build()
val initializer = CodeBlock.builder()
.beginControlFlow("{ %L ->", param)
.addStatement("println(\"arg=\$%N\")", param)
.endControlFlow()
.build()
val lambdaTypeName = ClassName.bestGuess("com.example.SomeTypeAlias")
val property = PropertySpec.builder("property", lambdaTypeName)
.initializer(initializer)
.build()
assertThat(property.toString()).isEqualTo(
"""
|val `property`: com.example.SomeTypeAlias = { arg: kotlin.Any ->
| println("arg=${'$'}arg")
|}
|
|
""".trimMargin(),
)
}
@Test fun doublePropertyInitialization() {
val codeBlockInitializer = PropertySpec.builder("listA", String::class)
.initializer(CodeBlock.builder().add("foo").build())
.initializer(CodeBlock.builder().add("bar").build())
.build()
assertThat(CodeBlock.of("bar")).isEqualTo(codeBlockInitializer.initializer)
val formatInitializer = PropertySpec.builder("listA", String::class)
.initializer("foo")
.initializer("bar")
.build()
assertThat(CodeBlock.of("bar")).isEqualTo(formatInitializer.initializer)
}
@Test fun propertyKdocWithoutLinebreak() {
val property = PropertySpec.builder("topping", String::class)
.addKdoc("The topping you want on your pizza")
.build()
assertThat(property.toString()).isEqualTo(
"""
|/**
| * The topping you want on your pizza
| */
|val topping: kotlin.String
|
""".trimMargin(),
)
}
@Test fun propertyKdocWithLinebreak() {
val property = PropertySpec.builder("topping", String::class)
.addKdoc("The topping you want on your pizza\n")
.build()
assertThat(property.toString()).isEqualTo(
"""
|/**
| * The topping you want on your pizza
| */
|val topping: kotlin.String
|
""".trimMargin(),
)
}
@Test fun getterKdoc() {
val property = PropertySpec.builder("amount", Int::class)
.initializer("4")
.getter(
FunSpec.getterBuilder()
.addKdoc("Simple multiplier")
.addStatement("return %L * 5", "field")
.build(),
)
.build()
assertThat(property.toString()).isEqualTo(
"""
|val amount: kotlin.Int = 4
| /**
| * Simple multiplier
| */
| get() = field * 5
|
""".trimMargin(),
)
}
@Test fun constProperty() {
val text = "This is a long string with a newline\nin the middle."
val spec = FileSpec.builder("testsrc", "Test")
.addProperty(
PropertySpec.builder("FOO", String::class, KModifier.CONST)
.initializer("%S", text)
.build(),
)
.build()
assertThat(spec.toString()).isEqualTo(
"""
|package testsrc
|
|import kotlin.String
|
|public const val FOO: String = "This is a long string with a newline\nin the middle."
|
""".trimMargin(),
)
}
@Test fun annotatedLambdaType() {
val annotation = AnnotationSpec.builder(ClassName("com.squareup.tacos", "Annotation")).build()
val type = LambdaTypeName.get(returnType = UNIT).copy(annotations = listOf(annotation))
val spec = FileSpec.builder("com.squareup.tacos", "Taco")
.addProperty(PropertySpec.builder("foo", type).build())
.build()
assertThat(spec.toString()).isEqualTo(
"""
|package com.squareup.tacos
|
|import kotlin.Unit
|
|public val foo: @Annotation () -> Unit
|
""".trimMargin(),
)
}
// https://github.com/square/kotlinpoet/issues/1002
@Test fun visibilityOmittedOnAccessors() {
val file = FileSpec.builder("com.squareup.tacos", "Taco")
.addProperty(
PropertySpec.builder("foo", String::class, PRIVATE)
.mutable()
.getter(
FunSpec.getterBuilder()
.addStatement("return %S", "foo")
.build(),
)
.setter(
FunSpec.setterBuilder()
.addParameter("foo", String::class)
.build(),
)
.build(),
)
.build()
assertThat(file.toString()).isEqualTo(
//language=kotlin
"""
package com.squareup.tacos
import kotlin.String
private var foo: String
get() = "foo"
set(foo) {
}
""".trimIndent(),
)
}
@Test fun varWithContextReceiverWithoutCustomAccessors() {
val mutablePropertySpecBuilder = {
PropertySpec.builder("foo", STRING)
.mutable()
.contextReceivers(INT)
}
assertThrows<IllegalArgumentException> {
mutablePropertySpecBuilder()
.getter(
FunSpec.getterBuilder()
.build(),
)
.build()
}.hasMessageThat()
.isEqualTo("mutable properties with context receivers require a $SETTER")
assertThrows<IllegalArgumentException> {
mutablePropertySpecBuilder()
.setter(
FunSpec.setterBuilder()
.build(),
)
.build()
}.hasMessageThat()
.isEqualTo("properties with context receivers require a $GETTER")
}
@Test fun valWithContextReceiverWithoutGetter() {
assertThrows<IllegalArgumentException> {
PropertySpec.builder("foo", STRING)
.mutable(false)
.contextReceivers(INT)
.build()
}.hasMessageThat()
.isEqualTo("properties with context receivers require a $GETTER")
}
@Test fun varWithContextReceiver() {
val propertySpec = PropertySpec.builder("foo", INT)
.mutable()
.contextReceivers(STRING)
.getter(
FunSpec.getterBuilder()
.addStatement("return \"\"")
.build(),
)
.setter(
FunSpec.setterBuilder()
.addParameter(
ParameterSpec.builder("value", STRING)
.build(),
)
.addStatement("")
.build(),
)
.build()
assertThat(propertySpec.toString()).isEqualTo(
"""
|context(kotlin.String)
|var foo: kotlin.Int
| get() = ""
| set(`value`) {
|
| }
|
""".trimMargin(),
)
}
@Test fun valWithContextReceiver() {
val propertySpec = PropertySpec.builder("foo", INT)
.mutable(false)
.contextReceivers(STRING)
.getter(
FunSpec.getterBuilder()
.addStatement("return length")
.build(),
)
.build()
assertThat(propertySpec.toString()).isEqualTo(
"""
|context(kotlin.String)
|val foo: kotlin.Int
| get() = length
|
""".trimMargin(),
)
}
@OptIn(DelicateKotlinPoetApi::class)
@Test
fun annotatedValWithContextReceiver() {
val propertySpec = PropertySpec.builder("foo", INT)
.mutable(false)
.addAnnotation(AnnotationSpec.get(TestAnnotation()))
.contextReceivers(STRING)
.getter(
FunSpec.getterBuilder()
.addStatement("return length")
.build(),
)
.build()
assertThat(propertySpec.toString()).isEqualTo(
"""
|context(kotlin.String)
|@com.squareup.kotlinpoet.PropertySpecTest.TestAnnotation
|val foo: kotlin.Int
| get() = length
|
""".trimMargin(),
)
}
}
| apache-2.0 | 75d7402519540d2ac40080810f68d8e3 | 27.114434 | 151 | 0.598381 | 4.460491 | false | true | false | false |
peterholak/mogul | native/src/mogul/microdom/primitives/LayoutBox.kt | 2 | 2854 | package mogul.microdom.primitives
import mogul.platform.Cairo
import mogul.microdom.*
sealed class Direction {
abstract fun postDrawTranslateX(cairo: Cairo, child: Node, spacing: Int): Int
abstract fun postDrawTranslateY(cairo: Cairo, child: Node, spacing: Int): Int
abstract fun totalWidth(cairo: Cairo, children: List<Node>, spacing: Int): Int
abstract fun totalHeight(cairo: Cairo, children: List<Node>, spacing: Int): Int
}
object HorizontalDirection : Direction() {
override fun totalWidth(cairo: Cairo, children: List<Node>, spacing: Int) =
children.sumBy { it.layoutSize(cairo).width + spacing } - spacing
override fun totalHeight(cairo: Cairo, children: List<Node>, spacing: Int) =
children.maxBy { it.layoutSize(cairo).height }!!.layoutSize(cairo).height
override fun postDrawTranslateX(cairo: Cairo, child: Node, spacing: Int) =
child.layoutSize(cairo).width + spacing
override fun postDrawTranslateY(cairo: Cairo, child: Node, spacing: Int) = 0
}
object VerticalDirection : Direction() {
override fun totalWidth(cairo: Cairo, children: List<Node>, spacing: Int) =
children.maxBy { it.layoutSize(cairo).width }!!.layoutSize(cairo).width
override fun totalHeight(cairo: Cairo, children: List<Node>, spacing: Int) =
children.sumBy { it.layoutSize(cairo).height + spacing } - spacing
override fun postDrawTranslateX(cairo: Cairo, child: Node, spacing: Int) = 0
override fun postDrawTranslateY(cairo: Cairo, child: Node, spacing: Int) =
child.layoutSize(cairo).height + spacing
}
// The spacing should be later replaced by a flexbox-like style property
class LayoutBox(
val direction: Direction = HorizontalDirection,
val spacing: Int = 0,
override var style: Style = Style(),
override var events: Events = Events(),
children: List<Node> = emptyList()
) : Container(children) {
override fun draw(cairo: Cairo) {
cairo.save()
style.margin?.let { cairo.translate(it.left, it.top) }
children.forEach { child ->
child.topLeft = cairo.userToDevice(child.style.margin?.left ?: 0, child.style.margin?.top ?: 0).position
child.draw(cairo)
cairo.translate(
x = direction.postDrawTranslateX(cairo, child, spacing),
y = direction.postDrawTranslateY(cairo, child, spacing)
)
}
cairo.restore()
}
// TODO: optimize, one pass is enough, or just put this function to Rectangle
override fun defaultInnerSize(cairo: Cairo): Size {
if (children.isEmpty()) return Size(0, 0)
return Size(
direction.totalWidth(cairo, children, spacing),
direction.totalHeight(cairo, children, spacing)
)
}
}
| mit | 64a00649f1c5471f93714a6e477f53e4 | 39.197183 | 116 | 0.660126 | 4.100575 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/codeinsight/TerraformConfigCompletionContributor.kt | 1 | 31999 | /*
* 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 org.intellij.plugins.hcl.terraform.config.codeinsight
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElementWeigher
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.patterns.PlatformPatterns.not
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.DebugUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import com.intellij.util.SmartList
import org.intellij.plugins.debug
import org.intellij.plugins.hcl.HCLElementTypes
import org.intellij.plugins.hcl.HCLParserDefinition
import org.intellij.plugins.hcl.codeinsight.HCLCompletionContributor
import org.intellij.plugins.hcl.patterns.HCLPatterns.Array
import org.intellij.plugins.hcl.patterns.HCLPatterns.AtLeastOneEOL
import org.intellij.plugins.hcl.patterns.HCLPatterns.Block
import org.intellij.plugins.hcl.patterns.HCLPatterns.File
import org.intellij.plugins.hcl.patterns.HCLPatterns.FileOrBlock
import org.intellij.plugins.hcl.patterns.HCLPatterns.IdentifierOrStringLiteral
import org.intellij.plugins.hcl.patterns.HCLPatterns.IdentifierOrStringLiteralOrSimple
import org.intellij.plugins.hcl.patterns.HCLPatterns.Nothing
import org.intellij.plugins.hcl.patterns.HCLPatterns.Object
import org.intellij.plugins.hcl.patterns.HCLPatterns.Property
import org.intellij.plugins.hcl.patterns.HCLPatterns.PropertyOrBlock
import org.intellij.plugins.hcl.patterns.HCLPatterns.WhiteSpace
import org.intellij.plugins.hcl.psi.*
import org.intellij.plugins.hcl.terraform.config.Constants
import org.intellij.plugins.hcl.terraform.config.model.*
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.TerraformConfigFile
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.TerraformVariablesFile
import org.intellij.plugins.hil.HILFileType
import org.intellij.plugins.hil.codeinsight.ReferenceCompletionHelper.findByFQNRef
import org.intellij.plugins.hil.psi.ILExpression
import org.intellij.plugins.hil.psi.TypeCachedValueProvider
import org.intellij.plugins.nullize
import java.util.*
class TerraformConfigCompletionContributor : HCLCompletionContributor() {
init {
// Block first word
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(File)
.andNot(psiElement().afterSiblingSkipping2(WhiteSpace, IdentifierOrStringLiteralOrSimple)),
BlockKeywordCompletionProvider)
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Block)
.withSuperParent(3, File)
.withParent(not(psiElement().and(IdentifierOrStringLiteral).afterSiblingSkipping2(WhiteSpace, IdentifierOrStringLiteralOrSimple))),
BlockKeywordCompletionProvider)
// Block type or name
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(FileOrBlock)
.afterSiblingSkipping2(WhiteSpace, IdentifierOrStringLiteralOrSimple)
, BlockTypeOrNameCompletionProvider)
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(psiElement().and(IdentifierOrStringLiteral).afterSiblingSkipping2(WhiteSpace, IdentifierOrStringLiteralOrSimple))
.withSuperParent(2, FileOrBlock)
, BlockTypeOrNameCompletionProvider)
//region InBlock Property key
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(Object)
.withSuperParent(2, Block)
, BlockPropertiesCompletionProvider)
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Property)
.withSuperParent(3, Object)
.withSuperParent(4, Block)
, BlockPropertiesCompletionProvider)
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Block)
.withSuperParent(3, Object)
.withSuperParent(4, Block)
, BlockPropertiesCompletionProvider)
// Leftmost identifier of block could be start of new property in case of eol betwen it ant next identifier
//```
//resource "X" "Y" {
// count<caret>
// provider {}
//}
//```
extend(CompletionType.BASIC, psiElement(HCLElementTypes.ID)
.inFile(TerraformConfigFile)
.withParent(psiElement(HCLIdentifier::class.java).beforeLeafSkipping(Nothing, AtLeastOneEOL))
.withSuperParent(2, Block)
.withSuperParent(3, Object)
.withSuperParent(4, Block)
, BlockPropertiesCompletionProvider)
//endregion
//region InBlock Property value
extend(null, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Property)
.withSuperParent(3, Object)
.withSuperParent(4, Block)
, PropertyValueCompletionProvider)
// depends_on completion
extend(null, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Array)
.withSuperParent(3, Property)
.withSuperParent(4, Object)
.withSuperParent(5, Block)
, PropertyValueCompletionProvider)
//endregion
//region InBlock PropertyWithObjectValue Key
// property = { <caret> }
// property = { "<caret>" }
// property { <caret> }
// property { "<caret>" }
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(Object)
.withSuperParent(2, PropertyOrBlock)
.withSuperParent(3, Object)
.withSuperParent(4, Block)
, PropertyObjectKeyCompletionProvider)
// property = { <caret>a="" }
// property = { "<caret>a"="" }
// property { <caret>="" }
// property { "<caret>"="" }
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformConfigFile)
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Property)
.withSuperParent(3, Object)
.withSuperParent(4, PropertyOrBlock)
.withSuperParent(5, Object)
.withSuperParent(6, Block)
, PropertyObjectKeyCompletionProvider)
//endregion
//region .tfvars
// Variables in .tvars files
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformVariablesFile)
.andOr(
psiElement()
.withParent(File),
psiElement()
.withParent(IdentifierOrStringLiteral)
.withSuperParent(2, Property)
.withSuperParent(3, File)
), VariableNameTFVARSCompletionProvider)
extend(CompletionType.BASIC, psiElement().withElementType(HCLParserDefinition.IDENTIFYING_LITERALS)
.inFile(TerraformVariablesFile)
.andOr(
psiElement()
.withSuperParent(1, IdentifierOrStringLiteral)
.withSuperParent(2, Property)
.withSuperParent(3, Object)
.withSuperParent(4, Property)
.withSuperParent(5, File),
psiElement()
.withSuperParent(1, Object)
.withSuperParent(2, Property)
.withSuperParent(3, File)
), MappedVariableTFVARSCompletionProvider)
//endregion
}
companion object {
@JvmField val ROOT_BLOCK_KEYWORDS: Set<String> = TypeModel.RootBlocks.map(BlockType::literal).toHashSet()
val ROOT_BLOCKS_SORTED: List<BlockType> = TypeModel.RootBlocks.sortedBy { it.literal }
private val LOG = Logger.getInstance(TerraformConfigCompletionContributor::class.java)
fun DumpPsiFileModel(element: PsiElement): () -> String {
return { DebugUtil.psiToString(element.containingFile, true) }
}
fun create(value: String, quote: Boolean = true): LookupElementBuilder {
var builder = LookupElementBuilder.create(value)
if (quote) {
builder = builder.withInsertHandler(QuoteInsertHandler)
}
return builder
}
fun create(value: PropertyOrBlockType, lookupString: String? = null): LookupElementBuilder {
var builder = LookupElementBuilder.create(value, lookupString ?: value.name)
builder = builder.withRenderer(TerraformLookupElementRenderer())
if (value is BlockType) {
builder = builder.withInsertHandler(ResourceBlockNameInsertHandler(value))
} else if (value is PropertyType) {
builder = builder.withInsertHandler(ResourcePropertyInsertHandler)
}
return builder
}
private fun failIfInUnitTestsMode(position: PsiElement, addition: String? = null) {
LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode, {
var ret = ""
if (addition != null) {
ret = "$addition\n"
}
ret += " Position: $position\nFile: " + DumpPsiFileModel(position)()
ret
})
}
fun getOriginalObject(parameters: CompletionParameters, obj: HCLObject): HCLObject {
val originalObject = parameters.originalFile.findElementAt(obj.textRange.startOffset)?.parent
return originalObject as? HCLObject ?: obj
}
fun getClearTextValue(element: PsiElement?): String? {
return when {
element == null -> null
element is HCLIdentifier -> element.id
element is HCLStringLiteral -> element.value
element.node?.elementType == HCLElementTypes.ID -> element.text
HCLParserDefinition.STRING_LITERALS.contains(element.node?.elementType) -> HCLPsiUtil.stripQuotes(element.text)
else -> return null
}
}
fun getIncomplete(parameters: CompletionParameters): String? {
val position = parameters.position
val text = TerraformConfigCompletionContributor.getClearTextValue(position) ?: position.text
if (text == CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED) return null
return text.replace(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED, "").nullize(true)
}
}
private object PreferRequiredProperty : LookupElementWeigher("hcl.required.property") {
override fun weigh(element: LookupElement): Comparable<Nothing>? {
val obj = element.`object`
if (obj is PropertyOrBlockType) {
if (obj.required) return 0
else return 1
}
return 10
}
}
abstract class OurCompletionProvider : CompletionProvider<CompletionParameters>() {
protected fun getTypeModel(project: Project): TypeModel {
return TypeModelProvider.getModel(project)
}
@Suppress("UNUSED_PARAMETER")
protected fun addResultsWithCustomSorter(result: CompletionResultSet, parameters: CompletionParameters, toAdd: Collection<LookupElementBuilder>) {
if (toAdd.isEmpty()) return
result
.withRelevanceSorter(
// CompletionSorter.defaultSorter(parameters, result.prefixMatcher)
CompletionSorter.emptySorter()
.weigh(PreferRequiredProperty))
.addAllElements(toAdd)
}
}
private object BlockKeywordCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
val parent = position.parent
val leftNWS = position.getPrevSiblingNonWhiteSpace()
LOG.debug { "TF.BlockKeywordCompletionProvider{position=$position, parent=$parent, left=${position.prevSibling}, lnws=$leftNWS}" }
assert(getClearTextValue(leftNWS) == null, DumpPsiFileModel(position))
result.addAllElements(ROOT_BLOCKS_SORTED.map { create(it) })
}
}
object BlockTypeOrNameCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
val list = SmartList<LookupElementBuilder>()
doCompletion(position, list, parameters.invocationCount)
result.addAllElements(list)
}
fun doCompletion(position: PsiElement, consumer: MutableList<LookupElementBuilder>, invocationCount: Int = 1) {
val parent = position.parent
LOG.debug { "TF.BlockTypeOrNameCompletionProvider{position=$position, parent=$parent}" }
val obj = when {
parent is HCLIdentifier -> parent
parent is HCLStringLiteral -> parent
// Next line for the case of two IDs (not Identifiers) nearby (start of block in empty file)
HCLParserDefinition.IDENTIFYING_LITERALS.contains(position.node.elementType) -> position
else -> return failIfInUnitTestsMode(position)
}
val leftNWS = obj.getPrevSiblingNonWhiteSpace()
LOG.debug { "TF.BlockTypeOrNameCompletionProvider{position=$position, parent=$parent, obj=$obj, lnws=$leftNWS}" }
val type = getClearTextValue(leftNWS) ?: return failIfInUnitTestsMode(position)
val cache = HashMap<String, Boolean>()
val project = position.project
when (type) {
"resource" ->
consumer.addAll(getTypeModel(project).resources.values.filter { invocationCount >= 3 || isProviderUsed(parent, it.provider.type, cache) }.map { create(it.type).withInsertHandler(ResourceBlockSubNameInsertHandler(it)) })
"data" ->
consumer.addAll(getTypeModel(project).dataSources.values.filter { invocationCount >= 3 || isProviderUsed(parent, it.provider.type, cache) }.map { create(it.type).withInsertHandler(ResourceBlockSubNameInsertHandler(it)) })
"provider" ->
consumer.addAll(getTypeModel(project).providers.values.map { create(it.type).withInsertHandler(ResourceBlockSubNameInsertHandler(it)) })
"provisioner" ->
consumer.addAll(getTypeModel(project).provisioners.values.map { create(it.type).withInsertHandler(ResourceBlockSubNameInsertHandler(it)) })
"backend" ->
consumer.addAll(getTypeModel(project).backends.values.map { create(it.type).withInsertHandler(ResourceBlockSubNameInsertHandler(it)) })
}
return
}
fun isProviderUsed(element: PsiElement, providerName: String, cache: MutableMap<String, Boolean>): Boolean {
val hclElement = PsiTreeUtil.getParentOfType(element, HCLElement::class.java, false)
if (hclElement == null) {
failIfInUnitTestsMode(element, "Completion called on element without any HCLElement as parent")
return true
}
return isProviderUsed(hclElement.getTerraformModule(), providerName, cache)
}
fun isProviderUsed(module: Module, providerName: String, cache: MutableMap<String, Boolean>): Boolean {
if (!cache.containsKey(providerName)) {
val providers = module.getDefinedProviders()
cache[providerName] = providers.isEmpty() || providers.any { it.first.name == providerName }
|| module.model.getProviderType(providerName)?.properties?.isEmpty() ?: false
}
return cache[providerName]!!
}
}
private object BlockPropertiesCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
var _parent: PsiElement? = position.parent
var right: Type? = null
var isProperty = false
var isBlock = false
val original = parameters.originalPosition ?: return
val original_parent = original.parent
if (HCLElementTypes.L_CURLY === original.node.elementType && original_parent is HCLObject) {
LOG.debug { "Origin is '{' inside Object, O.P.P = ${original_parent.parent}" }
if (original_parent.parent is HCLBlock) return
}
if (_parent is HCLIdentifier || _parent is HCLStringLiteral) {
val pob = _parent.parent // Property or Block
if (pob is HCLProperty) {
val value = pob.value
if (value === _parent) return
right = value.getValueType()
if (right == Types.String && value is PsiLanguageInjectionHost) {
// Check for Injection
InjectedLanguageManager.getInstance(pob.project).enumerate(value, object : PsiLanguageInjectionHost.InjectedPsiVisitor {
override fun visit(injectedPsi: PsiFile, places: MutableList<PsiLanguageInjectionHost.Shred>) {
if (injectedPsi.fileType == HILFileType) {
right = Types.StringWithInjection
val root = injectedPsi.firstChild
if (root == injectedPsi.lastChild && root is ILExpression) {
val type = TypeCachedValueProvider.getType(root)
if (type != null && type != Types.Any) {
right = type
}
}
}
}
})
}
isProperty = true
} else if (pob is HCLBlock) {
isBlock = true
if (pob.nameElements.firstOrNull() == _parent) {
if (_parent.nextSibling is PsiWhiteSpace && _parent.nextSibling.text.contains("\n")) {
isBlock = false
_parent = _parent.parent.parent
}
}
}
if (isBlock || isProperty) {
_parent = pob?.parent // Object
}
LOG.debug { "TF.BlockPropertiesCompletionProvider{position=$position, parent=$_parent, original=$original, right=$right, isBlock=$isBlock, isProperty=$isProperty}" }
} else {
LOG.debug { "TF.BlockPropertiesCompletionProvider{position=$position, parent=$_parent, original=$original, no right part}" }
}
val parent: HCLObject = _parent as? HCLObject ?: return failIfInUnitTestsMode(position, "Parent should be HCLObject")
val use = getOriginalObject(parameters, parent)
val block = use.parent
if (block is HCLBlock) {
val props = ModelHelper.getBlockProperties(block)
doAddCompletion(isBlock, isProperty, use, result, right, parameters, props)
}
}
private fun doAddCompletion(isBlock: Boolean, isProperty: Boolean, parent: HCLObject, result: CompletionResultSet, right: Type?, parameters: CompletionParameters, properties: Array<out PropertyOrBlockType>) {
if (properties.isEmpty()) return
val incomplete = getIncomplete(parameters)
if (incomplete != null) {
LOG.debug { "Including properties which contains incomplete result: $incomplete" }
}
addResultsWithCustomSorter(result, parameters, properties
.filter { it.name != Constants.HAS_DYNAMIC_ATTRIBUTES }
.filter { isRightOfPropertyWithCompatibleType(isProperty, it, right) || (isBlock && it is BlockType) || (!isProperty && !isBlock) }
// TODO: Filter should be based on 'max-count' model property (?)
.filter { (it is PropertyType && (parent.findProperty(it.name) == null || (incomplete != null && it.name.contains(incomplete)))) || (it is BlockType) }
.map { create(it) })
}
private fun isRightOfPropertyWithCompatibleType(isProperty: Boolean, it: PropertyOrBlockType, right: Type?): Boolean {
if (!isProperty) return false
if (it !is PropertyType) return false
if (right == Types.StringWithInjection) {
// StringWithInjection means TypeCachedValueProvider was unable to understand type of interpolation
return true
}
return it.type == right
}
}
private object PropertyValueCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
val parent = position.parent
val inArray = (parent.parent is HCLArray)
LOG.debug { "TF.PropertyValueCompletionProvider{position=$position, parent=$parent}" }
val property = PsiTreeUtil.getParentOfType(position, HCLProperty::class.java) ?: return
val block = PsiTreeUtil.getParentOfType(property, HCLBlock::class.java) ?: return
val type = block.getNameElementUnquoted(0)
// TODO: Replace with 'ReferenceHint'
if (property.name == "provider" && (type == "resource" || type == "data")) {
val providers = property.getTerraformModule().getDefinedProviders()
result.addAllElements(providers.map { create(it.second) })
return
}
if (property.name == "depends_on" && (type == "resource" || type == "data") && inArray) {
val resources = property.getTerraformModule().getDeclaredResources()
.map { "${it.getNameElementUnquoted(1)}.${it.name}" }
val datas = property.getTerraformModule().getDeclaredDataSources()
.map { "data.${it.getNameElementUnquoted(1)}.${it.name}" }
val current = (if (type == "data") "data." else "") + "${block.getNameElementUnquoted(1)}.${block.name}"
result.addAllElements(resources.plus(datas).minus(current).map { create(it) })
return
}
val props = ModelHelper.getBlockProperties(block).filterIsInstance(PropertyType::class.java)
val hints = props.filter { it.name == property.name && it.hint != null }.map { it.hint }
val hint = hints.firstOrNull() ?: return
if (hint is SimpleValueHint) {
result.addAllElements(hint.hint.map { create(it) })
return
}
if (hint is ReferenceHint) {
val module = property.getTerraformModule()
hint.hint
.mapNotNull { findByFQNRef(it, module) }
.flatten()
.mapNotNull {
return@mapNotNull when (it) {
// TODO: Enable or remove next two lines
// is HCLBlock -> HCLQualifiedNameProvider.getQualifiedModelName(it)
// is HCLProperty -> HCLQualifiedNameProvider.getQualifiedModelName(it)
is String -> "" + '$' + "{$it}"
else -> null
}
}
.forEach { result.addElement(create(it)) }
return
}
// TODO: Support other hint types
}
}
private object VariableNameTFVARSCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
val parent = position.parent
LOG.debug { "TF.VariableNameTFVARSCompletionProvider{position=$position, parent=$parent}" }
val module: Module
if (parent is HCLFile) {
module = parent.getTerraformModule()
} else if (parent is HCLElement) {
val pp = parent.parent as? HCLProperty ?: return
if (parent !== pp.nameIdentifier) return
module = parent.getTerraformModule()
} else return
val variables = module.getAllVariables()
result.addAllElements(variables.map { create(it.second.name, false).withInsertHandler(ResourcePropertyInsertHandler) })
}
}
private object MappedVariableTFVARSCompletionProvider : OurCompletionProvider() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val position = parameters.position
val parent = position.parent
LOG.debug { "TF.MappedVariableTFVARSCompletionProvider{position=$position, parent=$parent}" }
val varProperty: HCLProperty
if (parent is HCLObject) {
val pp = parent.parent
if (pp is HCLProperty) {
varProperty = pp
} else return
} else if (parent is HCLElement) {
if (!HCLPsiUtil.isPropertyKey(parent)) return
val ppp = parent.parent.parent as? HCLObject ?: return
val pppp = ppp.parent as? HCLProperty ?: return
varProperty = pppp
} else return
if (varProperty.parent !is HCLFile) return
val variable = varProperty.getTerraformModule().findVariable(varProperty.name) ?: return
val default = variable.second.`object`?.findProperty("default")?.value as? HCLObject ?: return
result.addAllElements(default.propertyList.map { create(it.name).withInsertHandler(ResourcePropertyInsertHandler) })
}
}
}
object ModelHelper {
private val LOG = Logger.getInstance(ModelHelper::class.java)
fun getBlockProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(0) ?: return emptyArray()
val props: Array<out PropertyOrBlockType>
// Special case for 'backend' blocks, since it's located not in root
if (type == "backend" && TerraformPatterns.Backend.accepts(block)) {
return getBackendProperties(block)
}
if (type in TypeModel.RootBlocksMap.keys && block.parent !is PsiFile) {
return emptyArray()
}
props = when (type) {
"provider" -> getProviderProperties(block)
"resource" -> getResourceProperties(block)
"data" -> getDataSourceProperties(block)
// Inner for 'resource'
"lifecycle" -> TypeModel.ResourceLifecycle.properties
"provisioner" -> getProvisionerProperties(block)
// Can be inner for both 'resource' and 'provisioner'
"connection" -> getConnectionProperties(block)
"module" -> getModuleProperties(block)
"terraform" -> getTerraformProperties(block)
else -> return TypeModel.RootBlocksMap[type]?.properties?:getModelBlockProperties(block, type)
}
return props
}
private fun getModelBlockProperties(block: HCLBlock, type: String): Array<out PropertyOrBlockType> {
// TODO: Speedup, remove recursive up-traverse
val bp = block.parent
if (bp is HCLObject) {
val bpp = bp.parent
if (bpp is HCLBlock) {
val properties = getBlockProperties(bpp)
val candidates = properties.filterIsInstance(BlockType::class.java).filter { it.literal == type }
return candidates.map { it.properties.toList() }.flatten().toTypedArray()
} else return emptyArray()
}
return emptyArray()
}
fun getProviderProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(1)
val providerType = if (type != null) getTypeModel(block.project).getProviderType(type) else null
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.AbstractProvider.properties)
if (providerType?.properties != null) {
properties.addAll(providerType.properties)
}
return properties.toTypedArray()
}
fun getProvisionerProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(1)
val provisionerType = if (type != null) getTypeModel(block.project).getProvisionerType(type) else null
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.AbstractResourceProvisioner.properties)
if (provisionerType?.properties != null) {
properties.addAll(provisionerType.properties)
}
return properties.toTypedArray()
}
fun getBackendProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(1)
val backendType = type?.let { getTypeModel(block.project).getBackendType(it) } ?: return emptyArray()
return backendType.properties.toList().toTypedArray()
}
@Suppress("UNUSED_PARAMETER")
fun getTerraformProperties(block: HCLBlock): Array<PropertyOrBlockType> {
val base: Array<out PropertyOrBlockType> = TypeModel.Terraform.properties
return (base.toList() + TypeModel.AbstractBackend).toTypedArray()
}
fun getConnectionProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.`object`?.findProperty("type")?.value
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.Connection.properties)
if (type is HCLStringLiteral) {
val v = type.value.toLowerCase().trim()
when (v) {
"ssh" -> properties.addAll(TypeModel.ConnectionPropertiesSSH)
"winrm" -> properties.addAll(TypeModel.ConnectionPropertiesWinRM)
// TODO: Support interpolation resolving
else -> LOG.warn("Unsupported 'connection' block type '${type.value}'")
}
}
if (type == null) {
// ssh by default
properties.addAll(TypeModel.ConnectionPropertiesSSH)
}
return properties.toTypedArray()
}
fun getResourceProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(1)
val resourceType = if (type != null) getTypeModel(block.project).getResourceType(type) else null
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.AbstractResource.properties)
if (resourceType?.properties != null) {
properties.addAll(resourceType.properties)
}
return ( properties.toTypedArray())
}
fun getDataSourceProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val type = block.getNameElementUnquoted(1)
val dataSourceType = if (type != null) getTypeModel(block.project).getDataSourceType(type) else null
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.AbstractDataSource.properties)
if (dataSourceType?.properties != null) {
properties.addAll(dataSourceType.properties)
}
return (properties.toTypedArray())
}
fun getModuleProperties(block: HCLBlock): Array<out PropertyOrBlockType> {
val properties = ArrayList<PropertyOrBlockType>()
properties.addAll(TypeModel.Module.properties)
val module = Module.getAsModuleBlock(block)
if (module != null) {
val variables = module.getAllVariables()
for (v in variables) {
val name = v.first.name
val hasDefault = v.second.`object`?.findProperty(TypeModel.Variable_Default.name) != null
// TODO: Add 'string' hint, AFAIK only strings coud be passed to module parameters
properties.add(PropertyType(name, Types.String, required = !hasDefault))
}
}
return (properties.toTypedArray())
}
fun getTypeModel(project: Project): TypeModel {
return TypeModelProvider.getModel(project)
}
}
| apache-2.0 | bb0c62255c04a073b3611687bc5dd9ef | 44.582621 | 231 | 0.701366 | 4.620794 | false | false | false | false |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/BaseActivity.kt | 1 | 1930 | package com.jiangkang.ktools
import android.database.ContentObserver
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import com.jiangkang.ktools.device.MediaContentObserver
open class BaseActivity : AppCompatActivity() {
private var mHandlerThread: HandlerThread? = null
private var handler: Handler? = null
private var mInternalObserver: ContentObserver? = null
private var mExternalObserver: ContentObserver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initHandler()
initObserver()
addObservers()
}
private fun addObservers() {
contentResolver.registerContentObserver(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
false,
mInternalObserver!!)
contentResolver.registerContentObserver(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
false,
mExternalObserver!!
)
}
private fun initHandler() {
mHandlerThread = HandlerThread("ScreenShot")
mHandlerThread!!.start()
handler = Handler(mHandlerThread!!.looper)
}
private fun initObserver() {
mInternalObserver = MediaContentObserver(this, handler, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
mExternalObserver = MediaContentObserver(this, handler, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
}
override fun onDestroy() {
super.onDestroy()
removeObservers()
}
private fun removeObservers() {
contentResolver.unregisterContentObserver(mInternalObserver!!)
contentResolver.unregisterContentObserver(mExternalObserver!!)
}
companion object {
const val VIEW_NAME_HEADER_TITLE = "activity:title"
}
}
| mit | 6a69f54477bce295c9b870171cf8fe7c | 27.80597 | 109 | 0.691192 | 5.160428 | false | false | false | false |
FurhatRobotics/example-skills | OpenAIChat/src/main/kotlin/furhatos/app/openaichat/flow/parent.kt | 1 | 1425 | package furhatos.app.openaichat.flow
import furhatos.event.actions.ActionLipSync
import furhatos.flow.kotlin.*
val Parent: State = state {
onUserLeave(instant = true) {
if (users.count > 0) {
if (it == users.current) {
furhat.attend(users.other)
goto(Idle)
} else {
furhat.glance(it)
}
} else {
goto(Idle)
}
}
onUserEnter(instant = true) {
furhat.glance(it)
}
/** Averts the eye gaze of the robot at appropriate times to avoid robot staring at the user */
onEvent<ActionLipSync>(instant=true) {
var silences = it.phones.phones.dropWhile { it.name == "_s" }.dropLastWhile { it.name == "_s" }.filter { it.name == "_s" }.toMutableList()
if (silences.isNotEmpty()) {
runThread(true) {
var last = 0.0f
while (silences.isNotEmpty()) {
val silence = silences.removeAt(0)
val sleepTime = (silence.start - 0.2) - last
val avertTime = 0.2 + (silence.end - silence.start)
if (sleepTime > 0.0) {
Thread.sleep((sleepTime * 1000.0).toLong())
furhat.gesture(GazeAversion(avertTime))
}
last = silence.end
}
}
}
}
} | mit | 29ed5a5f113749581ab6b1706c21b16c | 30 | 146 | 0.492632 | 4.118497 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/tileentity/electric/TileElectricFurnace.kt | 2 | 4783 | package tileentity.electric
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.config.Config
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.gui.ValueAverage
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitElectricity
import com.cout970.magneticraft.registry.ITEM_HANDLER
import com.cout970.magneticraft.tileentity.TileBase
import com.cout970.magneticraft.util.add
import com.cout970.magneticraft.util.interpolate
import com.cout970.magneticraft.util.newNbt
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.FurnaceRecipes
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.items.ItemStackHandler
/**
* Created by cout970 on 04/07/2016.
*/
@TileRegister("electric_furnace")
class TileElectricFurnace : TileBase() {
var mainNode = ElectricNode({ world }, { pos }, capacity = 1.25)
val traitElectricity = TraitElectricity(this, listOf(mainNode))
override val traits: List<ITileTrait> = listOf(traitElectricity)
val inventory = Inventory()
val production = ValueAverage()
var burningTime = 0f
override fun update() {
if (worldObj.isServer) {
if (mainNode.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE && canSmelt()) {
val applied = mainNode.applyPower(
-Config.electricFurnaceMaxConsumption * interpolate(mainNode.voltage, 60.0, 70.0), false)
burningTime += SPEED * applied.toFloat() / Config.electricFurnaceMaxConsumption.toFloat()
production += applied
if (burningTime > MAX_BURNING_TIME) {
smelt()
burningTime -= MAX_BURNING_TIME
}
}
production.tick()
}
super.update()
}
fun canSmelt(): Boolean {
//has input
if (inventory[0] == null) return false
//has recipe
val result = FurnaceRecipes.instance().getSmeltingResult(inventory[0]) ?: return false
//is output slot empty
if (inventory[1] == null) return true
//or can accept the result
inventory.ignoreFilter = true
val ret = inventory.insertItem(1, result, true) == null
inventory.ignoreFilter = false
return ret
}
fun smelt() {
inventory.ignoreFilter = true
val item = inventory.extractItem(0, 1, false)
val result = FurnaceRecipes.instance().getSmeltingResult(item)?.copy()
inventory.insertItem(1, result, false)
inventory.ignoreFilter = false
}
override fun save(): NBTTagCompound {
val nbt = newNbt {
add("inventory", inventory.serializeNBT())
add("meltingTime", burningTime)
}
return super.save().also { it.merge(nbt) }
}
override fun load(nbt: NBTTagCompound) {
inventory.deserializeNBT(nbt.getCompoundTag("inventory"))
burningTime = nbt.getFloat("meltingTime")
super.load(nbt)
}
companion object {
val MAX_BURNING_TIME = 100f //100 ticks => 5 seconds
val SPEED = 2 // 2 times faster than a vanilla furnace
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? {
if (capability == ITEM_HANDLER) return inventory as T
return super.getCapability(capability, facing)
}
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean {
if (capability == ITEM_HANDLER) return true
return super.hasCapability(capability, facing)
}
override fun onBreak() {
super.onBreak()
if (worldObj.isServer) {
(0 until inventory.slots)
.mapNotNull { inventory[it] }
.forEach { dropItem(it, pos) }
}
}
inner class Inventory : ItemStackHandler(2) {
var ignoreFilter = false
override fun insertItem(slot: Int, stack: ItemStack?, simulate: Boolean): ItemStack? {
if (slot == 0 || ignoreFilter) {
return super.insertItem(slot, stack, simulate)
}
return stack
}
override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? {
if (slot == 1 || ignoreFilter) {
return super.extractItem(slot, amount, simulate)
}
return null
}
}
} | gpl-2.0 | 3be421f2918fa0550f56e544ce53f4c6 | 34.701493 | 113 | 0.65001 | 4.49108 | false | false | false | false |
mozilla-mobile/focus-android | app/src/androidTest/java/org/mozilla/focus/activity/robots/BrowserRobot.kt | 1 | 21894 | /* 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.activity.robots
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.IdlingResource
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withContentDescription
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiObject
import androidx.test.uiautomator.UiObjectNotFoundException
import androidx.test.uiautomator.UiSelector
import androidx.test.uiautomator.Until
import org.hamcrest.Matchers.not
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.mozilla.focus.R
import org.mozilla.focus.helpers.Constants.RETRY_COUNT
import org.mozilla.focus.helpers.TestHelper.mDevice
import org.mozilla.focus.helpers.TestHelper.packageName
import org.mozilla.focus.helpers.TestHelper.pageLoadingTime
import org.mozilla.focus.helpers.TestHelper.progressBar
import org.mozilla.focus.helpers.TestHelper.waitingTime
import org.mozilla.focus.helpers.TestHelper.waitingTimeShort
import org.mozilla.focus.idlingResources.SessionLoadedIdlingResource
import java.time.LocalDate
class BrowserRobot {
private lateinit var sessionLoadedIdlingResource: SessionLoadedIdlingResource
val progressBar =
mDevice.findObject(
UiSelector().resourceId("$packageName:id/progress"),
)
fun verifyBrowserView() =
assertTrue(
mDevice.findObject(UiSelector().resourceId("$packageName:id/engineView"))
.waitForExists(waitingTime),
)
fun verifyPageContent(expectedText: String) {
mDevice.wait(Until.findObject(By.textContains(expectedText)), waitingTime)
}
fun verifyTrackingProtectionAlert(expectedText: String) {
mDevice.wait(Until.findObject(By.textContains(expectedText)), waitingTime)
assertTrue(
mDevice.findObject(UiSelector().textContains(expectedText))
.waitForExists(waitingTime),
)
// close the JavaScript alert
mDevice.pressBack()
}
fun verifyPageURL(expectedText: String) {
browserURLbar.waitForExists(waitingTime)
sessionLoadedIdlingResource = SessionLoadedIdlingResource()
runWithIdleRes(sessionLoadedIdlingResource) {
assertTrue(
mDevice.findObject(UiSelector().textContains(expectedText))
.waitForExists(waitingTime),
)
}
}
fun clickGetLocationButton() = clickPageObject(webPageItemContainingText("Get Location"))
fun clickGetCameraButton() = clickPageObject(webPageItemContainingText("Open camera"))
fun verifyCameraPermissionPrompt(url: String) {
assertTrue(
mDevice.findObject(UiSelector().text("Allow $url to use your camera?"))
.waitForExists(waitingTime),
)
}
fun verifyLocationPermissionPrompt(url: String) {
assertTrue(
mDevice.findObject(UiSelector().text("Allow $url to use your location?"))
.waitForExists(waitingTime),
)
}
fun allowSitePermissionRequest() {
if (permissionAllowBtn.waitForExists(waitingTime)) {
permissionAllowBtn.click()
}
}
fun denySitePermissionRequest() {
if (permissionDenyBtn.waitForExists(waitingTime)) {
permissionDenyBtn.click()
}
}
fun longPressLink(linkText: String) = longClickPageObject(webPageItemWithText(linkText))
fun openLinkInNewTab() {
mDevice.findObject(
UiSelector().textContains("Open link in private tab"),
).waitForExists(waitingTime)
openLinkInPrivateTab.perform(click())
}
fun verifyNumberOfTabsOpened(tabsCount: Int) {
assertTrue(
mDevice.findObject(
UiSelector().description("$tabsCount open tabs. Tap to switch tabs."),
).waitForExists(waitingTime),
)
}
fun verifyTabsCounterNotShown() {
assertFalse(
mDevice.findObject(UiSelector().resourceId("$packageName:id/counter_root"))
.waitForExists(waitingTimeShort),
)
}
fun verifyShareAppsListOpened() =
assertTrue(shareAppsList.waitForExists(waitingTime))
fun clickPlayButton() = clickPageObject(webPageItemWithText("Play"))
fun clickPauseButton() = clickPageObject(webPageItemWithText("Pause"))
fun waitForPlaybackToStart() {
for (i in 1..RETRY_COUNT) {
try {
assertTrue(webPageItemWithText("Media file is playing").waitForExists(pageLoadingTime))
break
} catch (e: AssertionError) {
if (i == RETRY_COUNT) {
throw e
} else {
clickPlayButton()
}
}
}
// dismiss the js alert
mDevice.findObject(UiSelector().textContains("ok")).click()
}
fun verifyPlaybackStopped() {
assertTrue(webPageItemWithText("Media file is paused").waitForExists(waitingTime))
// dismiss the js alert
mDevice.findObject(UiSelector().textContains("ok")).click()
}
fun verifySiteTrackingProtectionIconShown() = assertTrue(securityIcon.waitForExists(waitingTime))
fun verifySiteSecurityIndicatorShown() = assertTrue(site_security_indicator.waitForExists(waitingTime))
fun verifyLinkContextMenu(linkAddress: String) {
onView(withId(R.id.titleView)).check(matches(withText(linkAddress)))
openLinkInPrivateTab.check(matches(isDisplayed()))
copyLink.check(matches(isDisplayed()))
shareLink.check(matches(isDisplayed()))
}
fun verifyImageContextMenu(hasLink: Boolean, linkAddress: String) {
onView(withId(R.id.titleView)).check(matches(withText(linkAddress)))
if (hasLink) {
openLinkInPrivateTab.check(matches(isDisplayed()))
downloadLink.check(matches(isDisplayed()))
}
copyLink.check(matches(isDisplayed()))
shareLink.check(matches(isDisplayed()))
shareImage.check(matches(isDisplayed()))
openImageInNewTab.check(matches(isDisplayed()))
saveImage.check(matches(isDisplayed()))
copyImageLocation.check(matches(isDisplayed()))
}
fun clickContextMenuCopyLink(): ViewInteraction = copyLink.perform(click())
fun clickShareImage(): ViewInteraction = shareImage.perform(click())
fun clickShareLink(): ViewInteraction = shareLink.perform(click())
fun clickCopyImageLocation(): ViewInteraction = copyImageLocation.perform(click())
fun clickLinkMatchingText(expectedText: String) = clickPageObject(webPageItemContainingText(expectedText))
fun verifyOpenLinksInAppsPrompt(openLinksInAppsEnabled: Boolean, link: String) = assertOpenLinksInAppsPrompt(openLinksInAppsEnabled, link)
fun clickOpenLinksInAppsCancelButton() {
for (i in 1..RETRY_COUNT) {
try {
openLinksInAppsCancelButton.click()
assertTrue(openLinksInAppsMessage.waitUntilGone(waitingTime))
break
} catch (e: AssertionError) {
if (i == RETRY_COUNT) {
throw e
}
}
}
}
fun clickOpenLinksInAppsOpenButton() = openLinksInAppsOpenButton.click()
fun clickDropDownForm() = clickPageObject(webPageItemWithResourceId("dropDown"))
fun clickCalendarForm() = clickPageObject(webPageItemWithResourceId("calendar"))
fun selectDate() {
mDevice.findObject(UiSelector().resourceId("android:id/month_view")).waitForExists(waitingTime)
mDevice.findObject(
UiSelector()
.textContains("$currentDay")
.descriptionContains("$currentDay $currentMonth $currentYear"),
).click()
}
fun clickButtonWithText(button: String) = mDevice.findObject(UiSelector().textContains(button)).click()
fun clickSubmitDateButton() = clickPageObject(webPageItemWithResourceId("submitDate"))
fun verifySelectedDate() {
mDevice.findObject(
UiSelector()
.textContains("Submit date")
.resourceId("submitDate"),
).waitForExists(waitingTime)
assertTrue(
mDevice.findObject(
UiSelector()
.text("Selected date is: $currentDate"),
).waitForExists(waitingTime),
)
}
fun clickAndWriteTextInInputBox(text: String) {
clickPageObject(webPageItemWithResourceId("textInput"))
setPageObjectText(webPageItemWithResourceId("textInput"), text)
}
fun longPressTextInputBox() = longClickPageObject(webPageItemWithResourceId("textInput"))
fun longClickText(expectedText: String) = longClickPageObject(webPageItemContainingText(expectedText))
fun longClickAndCopyText(expectedText: String) {
var currentTries = 0
while (currentTries++ < 3) {
try {
longClickPageObject(webPageItemContainingText(expectedText))
webPageItemContainingText("Copy").waitForExists(waitingTime)
mDevice.findObject(By.textContains("Copy")).click()
break
} catch (e: NullPointerException) {
browserScreen {
}.openMainMenu {
}.clickReloadButton {}
}
}
}
fun verifyCopyOptionDoesNotExist() =
assertFalse(mDevice.findObject(UiSelector().textContains("Copy")).waitForExists(waitingTime))
fun clickAndPasteTextInInputBox() {
var currentTries = 0
while (currentTries++ < 3) {
try {
mDevice.findObject(UiSelector().textContains("Paste")).waitForExists(waitingTime)
mDevice.findObject(By.textContains("Paste")).click()
break
} catch (e: NullPointerException) {
longPressTextInputBox()
}
}
}
fun clickSubmitTextInputButton() = clickPageObject(webPageItemWithResourceId("submitInput"))
fun selectDropDownOption(optionName: String) {
mDevice.findObject(
UiSelector().resourceId("$packageName:id/customPanel"),
).waitForExists(waitingTime)
mDevice.findObject(UiSelector().textContains(optionName)).click()
}
fun clickSubmitDropDownButton() = clickPageObject(webPageItemWithResourceId("submitOption"))
fun verifySelectedDropDownOption(optionName: String) {
mDevice.findObject(
UiSelector()
.textContains("Submit drop down option")
.resourceId("submitOption"),
).waitForExists(waitingTime)
assertTrue(
mDevice.findObject(
UiSelector()
.text("Selected option is: $optionName"),
).waitForExists(waitingTime),
)
}
fun enterFindInPageQuery(expectedText: String) {
mDevice.wait(Until.findObject(By.res("$packageName:id/find_in_page_query_text")), waitingTime)
findInPageQuery.perform(ViewActions.clearText())
mDevice.wait(Until.gone(By.res("$packageName:id/find_in_page_result_text")), waitingTime)
findInPageQuery.perform(ViewActions.typeText(expectedText))
mDevice.wait(Until.findObject(By.res("$packageName:id/find_in_page_result_text")), waitingTime)
}
fun verifyFindNextInPageResult(ratioCounter: String) {
mDevice.wait(Until.findObject(By.text(ratioCounter)), waitingTime)
val resultsCounter = mDevice.findObject(By.text(ratioCounter))
findInPageResult.check(matches(withText((ratioCounter))))
findInPageNextButton.perform(click())
resultsCounter.wait(Until.textNotEquals(ratioCounter), waitingTime)
}
fun verifyFindPrevInPageResult(ratioCounter: String) {
mDevice.wait(Until.findObject(By.text(ratioCounter)), waitingTime)
val resultsCounter = mDevice.findObject(By.text(ratioCounter))
findInPageResult.check(matches(withText((ratioCounter))))
findInPagePrevButton.perform(click())
resultsCounter.wait(Until.textNotEquals(ratioCounter), waitingTime)
}
fun closeFindInPage() {
findInPageCloseButton.perform(click())
findInPageQuery.check(matches(not(isDisplayed())))
}
fun verifyCookiesEnabled(areCookiesEnabled: String) {
mDevice.findObject(UiSelector().resourceId("detected_value")).waitForExists(waitingTime)
assertTrue(
webPageItemContainingText(areCookiesEnabled).waitForExists(waitingTime),
)
}
fun clickSetCookiesButton() = clickPageObject(webPageItemWithResourceId("setCookies"))
fun clickPageObject(webPageItem: UiObject) {
for (i in 1..RETRY_COUNT) {
try {
webPageItem.also {
it.waitForExists(waitingTime)
it.click()
}
break
} catch (e: UiObjectNotFoundException) {
if (i == RETRY_COUNT) {
throw e
} else {
browserScreen {
}.openMainMenu {
}.clickReloadButton {
progressBar.waitUntilGone(waitingTime)
}
}
}
}
}
fun longClickPageObject(webPageItem: UiObject) {
for (i in 1..RETRY_COUNT) {
try {
webPageItem.also {
it.waitForExists(waitingTime)
it.longClick()
}
break
} catch (e: UiObjectNotFoundException) {
if (i == RETRY_COUNT) {
throw e
} else {
browserScreen {
}.openMainMenu {
}.clickReloadButton {
progressBar.waitUntilGone(waitingTime)
}
}
}
}
}
private fun setPageObjectText(webPageItem: UiObject, text: String) {
for (i in 1..RETRY_COUNT) {
try {
webPageItem.also {
it.waitForExists(waitingTime)
it.setText(text)
}
break
} catch (e: UiObjectNotFoundException) {
if (i == RETRY_COUNT) {
throw e
} else {
browserScreen {
}.openMainMenu {
}.clickReloadButton {
progressBar.waitUntilGone(waitingTime)
}
}
}
}
}
class Transition {
fun openSearchBar(interact: SearchRobot.() -> Unit): SearchRobot.Transition {
browserURLbar.waitForExists(waitingTime)
browserURLbar.click()
SearchRobot().interact()
return SearchRobot.Transition()
}
fun clearBrowsingData(interact: HomeScreenRobot.() -> Unit): HomeScreenRobot.Transition {
eraseBrowsingButton
.check(matches(isDisplayed()))
.perform(click())
HomeScreenRobot().interact()
return HomeScreenRobot.Transition()
}
fun openMainMenu(interact: ThreeDotMainMenuRobot.() -> Unit): ThreeDotMainMenuRobot.Transition {
browserURLbar.waitForExists(waitingTime)
mainMenu
.check(matches(isDisplayed()))
.perform(click())
ThreeDotMainMenuRobot().interact()
return ThreeDotMainMenuRobot.Transition()
}
fun openSiteSettingsMenu(interact: HomeScreenRobot.() -> Unit): HomeScreenRobot.Transition {
securityIcon.click()
HomeScreenRobot().interact()
return HomeScreenRobot.Transition()
}
fun openSiteSecurityInfoSheet(interact: SiteSecurityInfoSheetRobot.() -> Unit): SiteSecurityInfoSheetRobot.Transition {
if (securityIcon.exists()) {
securityIcon.click()
} else {
site_security_indicator.click()
}
SiteSecurityInfoSheetRobot().interact()
return SiteSecurityInfoSheetRobot.Transition()
}
fun openTabsTray(interact: TabsTrayRobot.() -> Unit): TabsTrayRobot.Transition {
tabsCounter.perform(click())
TabsTrayRobot().interact()
return TabsTrayRobot.Transition()
}
fun goToPreviousPage(interact: BrowserRobot.() -> Unit): BrowserRobot.Transition {
mDevice.pressBack()
progressBar.waitUntilGone(waitingTime)
BrowserRobot().interact()
return BrowserRobot.Transition()
}
fun clickSaveImage(interact: DownloadRobot.() -> Unit): DownloadRobot.Transition {
saveImage.perform(click())
DownloadRobot().interact()
return DownloadRobot.Transition()
}
}
}
fun browserScreen(interact: BrowserRobot.() -> Unit): BrowserRobot.Transition {
BrowserRobot().interact()
return BrowserRobot.Transition()
}
inline fun runWithIdleRes(ir: IdlingResource?, pendingCheck: () -> Unit) {
try {
IdlingRegistry.getInstance().register(ir)
pendingCheck()
} finally {
IdlingRegistry.getInstance().unregister(ir)
}
}
private fun assertOpenLinksInAppsPrompt(openLinksInAppsEnabled: Boolean, link: String) {
if (openLinksInAppsEnabled) {
mDevice.findObject(UiSelector().resourceId("$packageName:id/parentPanel")).waitForExists(waitingTime)
assertTrue(openLinksInAppsMessage.waitForExists(waitingTimeShort))
assertTrue(openLinksInAppsLink(link).exists())
assertTrue(openLinksInAppsCancelButton.waitForExists(waitingTimeShort))
assertTrue(openLinksInAppsOpenButton.waitForExists(waitingTimeShort))
} else {
assertFalse(
mDevice.findObject(
UiSelector().resourceId("$packageName:id/parentPanel"),
).waitForExists(waitingTimeShort),
)
}
}
private fun openLinksInAppsLink(link: String) = mDevice.findObject(UiSelector().textContains(link))
private val browserURLbar = mDevice.findObject(
UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_url_view"),
)
private val eraseBrowsingButton = onView(withContentDescription("Erase browsing history"))
private val tabsCounter = onView(withId(R.id.counter_root))
private val mainMenu = onView(withId(R.id.mozac_browser_toolbar_menu))
private val shareAppsList =
mDevice.findObject(UiSelector().resourceId("android:id/resolver_list"))
private val securityIcon =
mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/mozac_browser_toolbar_tracking_protection_indicator"),
)
private val site_security_indicator =
mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/mozac_browser_toolbar_security_indicator"),
)
// Link long-tap context menu items
private val openLinkInPrivateTab = onView(withText("Open link in private tab"))
private val copyLink = onView(withText("Copy link"))
private val shareLink = onView(withText("Share link"))
// Image long-tap context menu items
private val openImageInNewTab = onView(withText("Open image in new tab"))
private val downloadLink = onView(withText("Download link"))
private val saveImage = onView(withText("Save image"))
private val copyImageLocation = onView(withText("Copy image location"))
private val shareImage = onView(withText("Share image"))
// Find in page toolbar
private val findInPageQuery = onView(withId(R.id.find_in_page_query_text))
private val findInPageResult = onView(withId(R.id.find_in_page_result_text))
private val findInPageNextButton = onView(withId(R.id.find_in_page_next_btn))
private val findInPagePrevButton = onView(withId(R.id.find_in_page_prev_btn))
private val findInPageCloseButton = onView(withId(R.id.find_in_page_close_btn))
private val openLinksInAppsMessage = mDevice.findObject(UiSelector().resourceId("$packageName:id/alertTitle"))
private val openLinksInAppsCancelButton = mDevice.findObject(UiSelector().textContains("CANCEL"))
private val openLinksInAppsOpenButton =
mDevice.findObject(
UiSelector()
.index(1)
.textContains("OPEN")
.className("android.widget.Button")
.packageName(packageName),
)
private val currentDate = LocalDate.now()
private val currentDay = currentDate.dayOfMonth
private val currentMonth = currentDate.month
private val currentYear = currentDate.year
private val permissionAllowBtn = mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/allow_button"),
)
private val permissionDenyBtn = mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/deny_button"),
)
private fun webPageItemContainingText(itemText: String) =
mDevice.findObject(UiSelector().textContains(itemText))
private fun webPageItemWithText(itemText: String) =
mDevice.findObject(UiSelector().text(itemText))
private fun webPageItemWithResourceId(resourceId: String) =
mDevice.findObject(UiSelector().resourceId(resourceId))
| mpl-2.0 | a186070acbe8dd0ec5c9d3286817ca56 | 34.484603 | 142 | 0.653604 | 4.996349 | false | false | false | false |
toastkidjp/Jitte | api/src/main/java/jp/toastkid/api/lib/WebViewCookieHandler.kt | 2 | 1359 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.api.lib
import android.webkit.CookieManager
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
/**
* For sharing [WebView]'s cookie.
*
* @author toastkidjp
*/
class WebViewCookieHandler : CookieJar {
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val urlString = url.toString()
val cookieManager = CookieManager.getInstance()
cookies.forEach { cookieManager.setCookie(urlString, it.toString()) }
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val urlString = url.toString()
val cookieManager = CookieManager.getInstance()
val cookiesString = cookieManager.getCookie(urlString)
return if (cookiesString != null && cookiesString.isNotEmpty()) {
cookiesString
.split(DELIMITER)
.mapNotNull { Cookie.parse(url, it) }
} else {
emptyList()
}
}
companion object {
private const val DELIMITER = ";"
}
} | epl-1.0 | 7ec57647f42a926ad68692cddab64fd1 | 26.755102 | 88 | 0.665195 | 4.575758 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/formatter/settings/RsCodeStyleSettings.kt | 4 | 730 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter.settings
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
class RsCodeStyleSettings(container: CodeStyleSettings) :
CustomCodeStyleSettings(RsCodeStyleSettings::class.java.simpleName, container) {
@JvmField var ALIGN_RET_TYPE = true
@JvmField var ALIGN_WHERE_CLAUSE = false
@JvmField var ALIGN_TYPE_PARAMS = false
@JvmField var ALIGN_WHERE_BOUNDS = true
@JvmField var ALLOW_ONE_LINE_MATCH = false
@JvmField var MIN_NUMBER_OF_BLANKS_BETWEEN_ITEMS = 1
@JvmField var PRESERVE_PUNCTUATION = false
}
| mit | 39b0e1038746a6783a7048dc69c71c9e | 33.761905 | 84 | 0.761644 | 4.124294 | false | false | false | false |
http4k/http4k | http4k-testing/approval/src/main/kotlin/org/http4k/testing/ApprovalContent.kt | 1 | 825 | package org.http4k.testing
import org.http4k.core.HttpMessage
import java.io.InputStream
/**
* Determines which parts of the HttpMessage will be compared.
*/
interface ApprovalContent {
operator fun invoke(input: InputStream): InputStream
operator fun invoke(input: HttpMessage): InputStream
companion object {
fun EntireHttpMessage() = object : ApprovalContent {
override fun invoke(input: InputStream) = input
override fun invoke(input: HttpMessage) = input.toString().byteInputStream()
}
fun HttpBodyOnly(formatter: (String) -> String = { it }) = object : ApprovalContent {
override fun invoke(input: InputStream) = input
override fun invoke(input: HttpMessage) = formatter(input.bodyString()).byteInputStream()
}
}
}
| apache-2.0 | 3358f6117b061b95ae30e6547215f0c8 | 30.730769 | 101 | 0.681212 | 4.6875 | false | false | false | false |
rascarlo/AURdroid | app/src/main/java/com/rascarlo/aurdroid/network/AurWebApiService.kt | 1 | 2663 | package com.rascarlo.aurdroid.network
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.rascarlo.aurdroid.BuildConfig
import com.rascarlo.aurdroid.utils.Constants
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import timber.log.Timber
import java.util.concurrent.TimeUnit
// okhttp logging interceptor
private val httpLoggingInterceptor = HttpLoggingInterceptor()
.setLevel(
when {
BuildConfig.DEBUG -> {
HttpLoggingInterceptor.Level.BODY
}
else -> {
HttpLoggingInterceptor.Level.BASIC
}
}
)
// okhttp client
private val okHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor)
.addNetworkInterceptor(Interceptor { chain ->
val httpUrl: HttpUrl = chain.request().url
.newBuilder()
.build()
// construct the new request
val request: Request = chain.request().newBuilder().url(httpUrl).build()
// log the request
Timber.d(request.toString())
// return the new request
chain.proceed(request)
})
.build()
// moshi
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// retrofit
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(Constants.BASE_URL)
.client(okHttpClient)
.build()
// api
object AurWebApi {
val retrofitService: AurWebApiService by lazy {
retrofit.create(AurWebApiService::class.java)
}
}
// api service
interface AurWebApiService {
/**
* get packages
* @param field: search by
* @param keyword: package to search
* @return [SearchResponse]
*/
@GET(value = "rpc/?v=5&type=search")
suspend fun getPackages(
@Query(value = "by") field: String,
@Query(value = "arg") keyword: String
): SearchResponse
/**
* get info
* @param name: package name
* @return [InfoResponse]
*/
@GET(value = "rpc/?v=5&type=info")
suspend fun getInfo(
@Query(value = "arg") name: String
): InfoResponse
} | gpl-3.0 | c9da0cbd29ac8ddb22b06e0ba510469b | 27.042105 | 86 | 0.682689 | 4.416252 | false | false | false | false |
akvo/akvo-flow-mobile | data/src/main/java/org/akvo/flow/data/entity/form/QuestionGroupMapper.kt | 1 | 1974 | /*
* Copyright (C) 2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Flow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.data.entity.form
import android.database.Cursor
import org.akvo.flow.database.tables.QuestionGroupTable
import javax.inject.Inject
class QuestionGroupMapper @Inject constructor() {
fun mapGroups(groupCursor: Cursor?): MutableList<DataQuestionGroup> {
val groups = mutableListOf<DataQuestionGroup>()
if (groupCursor != null && groupCursor.moveToFirst()) {
do {
val groupId = groupCursor.getLong(groupCursor.getColumnIndexOrThrow(QuestionGroupTable.COLUMN_GROUP_ID))
val heading = groupCursor.getString(groupCursor.getColumnIndexOrThrow(QuestionGroupTable.COLUMN_HEADING))
val repeatable = groupCursor.getInt(groupCursor.getColumnIndexOrThrow(QuestionGroupTable.COLUMN_REPEATABLE)) == 1
val formId = groupCursor.getString(groupCursor.getColumnIndexOrThrow(QuestionGroupTable.COLUMN_FORM_ID))
val order = groupCursor.getInt(groupCursor.getColumnIndexOrThrow(QuestionGroupTable.COLUMN_ORDER))
groups.add(DataQuestionGroup(groupId, heading, repeatable, formId, order))
} while (groupCursor.moveToNext())
}
groupCursor?.close()
return groups
}
}
| gpl-3.0 | 9c890835b632a32bf364eeebab14a1c1 | 44.906977 | 129 | 0.721378 | 4.486364 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/presenter/chat/ChatViewModel.kt | 1 | 17223 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.presenter.chat
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.toshi.R
import com.toshi.extensions.isGroupId
import com.toshi.manager.messageQueue.AsyncOutgoingMessageQueue
import com.toshi.manager.model.ExternalPaymentTask
import com.toshi.manager.model.PaymentTask
import com.toshi.manager.model.ResendToshiPaymentTask
import com.toshi.manager.model.ToshiPaymentTask
import com.toshi.model.local.Conversation
import com.toshi.model.local.Group
import com.toshi.model.local.Recipient
import com.toshi.model.local.User
import com.toshi.model.local.network.Networks
import com.toshi.model.sofa.Control
import com.toshi.model.sofa.PaymentRequest
import com.toshi.model.sofa.SofaMessage
import com.toshi.util.FileUtil
import com.toshi.util.SingleLiveEvent
import com.toshi.util.logging.LogUtil
import com.toshi.view.BaseApplication
import com.toshi.view.notification.ChatNotificationManager
import rx.Single
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import java.io.File
class ChatViewModel(private val threadId: String) : ViewModel() {
private val subscriptions by lazy { CompositeSubscription() }
private val recipientManager by lazy { BaseApplication.get().recipientManager }
private val userManager by lazy { BaseApplication.get().userManager }
private val transactionManager by lazy { BaseApplication.get().transactionManager }
private val toshiManager by lazy { BaseApplication.get().toshiManager }
private val chatManager by lazy { BaseApplication.get().chatManager }
private val chatMessageQueue by lazy { ChatMessageQueue(AsyncOutgoingMessageQueue()) }
var capturedImageName: String? = null
val recipient by lazy { MutableLiveData<Recipient>() }
val conversation by lazy { SingleLiveEvent<Conversation>() }
val recipientError by lazy { SingleLiveEvent<Int>() }
val confirmPayment by lazy { SingleLiveEvent<ConfirmPaymentInfo>() }
val resendPayment by lazy { SingleLiveEvent<ResendPaymentInfo>() }
val respondToPaymentRequest by lazy { SingleLiveEvent<SofaMessage>() }
val acceptConversation by lazy { SingleLiveEvent<Unit>() }
val declineConversation by lazy { SingleLiveEvent<Unit>() }
val updateMessage by lazy { SingleLiveEvent<SofaMessage>() }
val updateConversation by lazy { SingleLiveEvent<Conversation>() }
val newMessage by lazy { SingleLiveEvent<SofaMessage>() }
val deleteMessage by lazy { SingleLiveEvent<SofaMessage>() }
val deleteError by lazy { SingleLiveEvent<Int>() }
val error by lazy { SingleLiveEvent<Int>() }
val viewProfileWithId by lazy { SingleLiveEvent<String>() }
val isLoading by lazy { MutableLiveData<Boolean>() }
init {
if (threadId.isGroupId()) loadGroupRecipient(threadId)
else loadUserRecipient(threadId)
}
private fun loadGroupRecipient(groupId: String) {
val sub = Group.fromId(groupId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isLoading.value = true }
.doOnError { isLoading.value = false }
.doOnSuccess { isLoading.value = false }
.subscribe(
{ handleGroupLoaded(it) },
{ handleRecipientLoadFailed() }
)
subscriptions.add(sub)
}
private fun loadUserRecipient(toshiId: String) {
val sub = recipientManager
.getUserFromToshiId(toshiId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isLoading.value = true }
.doOnError { isLoading.value = false }
.doOnSuccess { isLoading.value = false }
.map { Recipient(it) }
.subscribe(
{ handleRecipientLoaded(it) },
{ handleRecipientLoadFailed() }
)
subscriptions.add(sub)
}
private fun handleGroupLoaded(group: Group?) = group
?.let { handleRecipientLoaded(Recipient(it)) }
?: handleRecipientLoadFailed()
private fun handleRecipientLoaded(recipient: Recipient?) = recipient
?.let { init(it) }
?: handleRecipientLoadFailed()
private fun handleRecipientLoadFailed() {
recipientError.value = R.string.error__app_loading
}
private fun init(recipient: Recipient) {
this.recipient.value = recipient
chatMessageQueue.init(recipient)
initPendingTransactionsObservable(recipient)
initChatMessageStore(recipient)
}
private fun initPendingTransactionsObservable(recipient: Recipient) {
// Todo - handle groups
if (recipient.isGroup) return
val subscription = PendingTransactionsObservable()
.init(recipient.user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { it.sofaMessage }
.subscribe(
{ updateMessage.value = it },
{ LogUtil.exception(it) }
)
subscriptions.add(subscription)
}
private fun initChatMessageStore(recipient: Recipient) {
ChatNotificationManager.suppressNotificationsForConversation(recipient.threadId)
val conversationObservables = chatManager.registerForConversationChanges(recipient.threadId)
val chatSub = conversationObservables
.newMessageSubject
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ newMessage.value = it },
{ LogUtil.exception(it) }
)
val updateSub = conversationObservables
.updateMessageSubject
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ updateMessage.value = it },
{ LogUtil.exception(it) }
)
val updateConversationSub = conversationObservables
.conversationUpdatedSubject
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { chatMessageQueue.updateRecipient(it.recipient) }
.doOnNext { this.recipient.value = it.recipient }
.subscribe(
{ updateConversation.value = it },
{ LogUtil.exception(it) }
)
val deleteSub = chatManager
.registerForDeletedMessages(recipient.threadId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ deleteMessage.value = it },
{ LogUtil.exception(it) }
)
subscriptions.addAll(
chatSub,
updateSub,
updateConversationSub,
deleteSub
)
}
fun loadConversation() {
val sub = getRecipient()
.flatMap { chatManager.loadConversationAndResetUnreadCounter(threadId) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ handleConversation(it) },
{ LogUtil.exception(it) }
)
subscriptions.add(sub)
}
private fun handleConversation(conversation: Conversation) {
this.conversation.value = conversation
val isConversationEmpty = conversation.allMessages?.isEmpty() ?: true
if (isConversationEmpty) tryInitAppConversation(conversation.recipient)
}
private fun tryInitAppConversation(recipient: Recipient) {
if (recipient.isGroup || !recipient.user.isBot) return
val localUser = getCurrentLocalUser() ?: return
chatManager.sendInitMessage(localUser, recipient)
}
fun sendPaymentWithValue(value: String) {
val sub = getRecipient()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { ConfirmPaymentInfo(it.user, value) }
.subscribe(
{ confirmPayment.value = it },
{ LogUtil.exception(it) }
)
subscriptions.add(sub)
}
fun sendPaymentRequestWithValue(value: String) {
val sub = toshiManager
.getWallet()
.flatMap { generateLocalPrice(value, it.paymentAddress) }
.observeOn(Schedulers.io())
.subscribe(
{ sendPaymentRequest(it) },
{ LogUtil.exception(it) }
)
subscriptions.add(sub)
}
private fun generateLocalPrice(value: String, paymentAddress: String) = PaymentRequest()
.setDestinationAddress(paymentAddress)
.setValue(value)
.generateLocalPrice()
private fun sendPaymentRequest(paymentRequest: PaymentRequest) {
val localUser = getCurrentLocalUser()
localUser?.let {
chatMessageQueue.addPaymentRequestToQueue(paymentRequest, it)
} ?: run {
error.value = R.string.sending_payment_request_error
LogUtil.w("User is null when sending payment request")
}
}
fun sendMessage(userInput: String) {
val localUser = getCurrentLocalUser()
localUser?.let {
chatMessageQueue.addMessageToQueue(userInput, it)
} ?: run {
error.value = R.string.sending_message_error
LogUtil.w("User is null when sending message")
}
}
fun sendCommandMessage(control: Control) {
val localUser = getCurrentLocalUser()
localUser?.let {
chatMessageQueue.addCommandMessageToQueue(control, it)
} ?: run {
error.value = R.string.sending_message_error
LogUtil.w("User is null when sending command message")
}
}
fun sendMediaMessage(file: File) {
val sub = FileUtil.compressImage(FileUtil.MAX_SIZE.toLong(), file)
.subscribe(
{ compressedFile -> sendMediaMessage(compressedFile.absolutePath) },
{ LogUtil.exception("Unable to compress image $it") }
)
subscriptions.add(sub)
}
private fun sendMediaMessage(filePath: String) {
val localUser = getCurrentLocalUser()
localUser?.let {
chatMessageQueue.addMediaMessageToQueue(filePath, it)
} ?: run {
error.value = R.string.sending_message_error
LogUtil.w("User is null when sending media message")
}
}
fun updatePaymentRequestState(existingMessage: SofaMessage, @PaymentRequest.State paymentState: Int) {
val sub = getRecipient()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ updatePaymentRequestState(existingMessage, it, paymentState) },
{ LogUtil.exception(it) }
)
subscriptions.add(sub)
}
private fun updatePaymentRequestState(existingMessage: SofaMessage,
recipient: Recipient,
@PaymentRequest.State paymentState: Int) {
// Todo - Handle groups
transactionManager.updatePaymentRequestState(recipient.user, existingMessage, paymentState)
}
// If the receiver of the payment has changed wallet, the id service doesn't know about it
// so the PaymentTask will be of type ExternalPaymentTask
fun sendPayment(paymentTask: PaymentTask) {
when (paymentTask) {
is ToshiPaymentTask -> transactionManager.sendPayment(paymentTask)
is ExternalPaymentTask -> transactionManager.sendExternalPayment(paymentTask)
else -> LogUtil.w("Invalid payment task in this context")
}
}
fun resendPayment(sofaMessage: SofaMessage, paymentTask: PaymentTask) {
if (paymentTask is ToshiPaymentTask) transactionManager.resendPayment(ResendToshiPaymentTask(paymentTask, sofaMessage))
else LogUtil.w("Invalid payment task in this context")
}
fun resendMessage(sofaMessage: SofaMessage) = chatManager.resendPendingMessage(sofaMessage)
fun deleteMessage(sofaMessage: SofaMessage) {
val recipient = recipient.value
if (recipient == null) {
deleteError.value = R.string.delete_message_error
return
}
val sub = chatManager
.deleteMessage(recipient, sofaMessage)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ deleteMessage.value = sofaMessage },
{ deleteError.value = R.string.delete_message_error }
)
subscriptions.add(sub)
}
fun showResendPaymentConfirmationDialog(sofaMessage: SofaMessage) {
val sub = getRecipient()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { ResendPaymentInfo(it.user, sofaMessage) }
.subscribe(
{ resendPayment.value = it },
{ LogUtil.exception(it) }
)
subscriptions.add(sub)
}
fun viewRecipientProfile() {
val sub = getRecipient()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ viewProfileWithId.value = it.threadId },
{ viewProfileWithId.value = null }
)
subscriptions.add(sub)
}
fun acceptConversation(conversation: Conversation) {
val sub = chatManager
.acceptConversation(conversation)
.observeOn(AndroidSchedulers.mainThread())
.toCompletable()
.subscribe(
{ acceptConversation.value = Unit },
{ LogUtil.w("Error while accepting conversation $it") }
)
subscriptions.add(sub)
}
fun declineConversation(conversation: Conversation) {
val sub = chatManager
.rejectConversation(conversation)
.observeOn(AndroidSchedulers.mainThread())
.toCompletable()
.subscribe(
{ declineConversation.value = Unit },
{ LogUtil.w("Error while accepting conversation $it") }
)
subscriptions.add(sub)
}
fun respondToPaymentRequest(messageId: String) {
val sub = chatManager
.getSofaMessageById(messageId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ respondToPaymentRequest.value = it },
{ respondToPaymentRequest.value = null }
)
subscriptions.add(sub)
}
fun getCurrentLocalUser(): User? {
return userManager
.getCurrentUser()
.toBlocking()
.value()
}
private fun getRecipient(): Single<Recipient> {
return Single
.fromCallable<Recipient> {
while (recipient.value == null) Thread.sleep(50)
return@fromCallable recipient.value
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
}
fun getNetworks() = Networks.getInstance()
override fun onCleared() {
super.onCleared()
subscriptions.clear()
chatMessageQueue.clear()
stopListeningForMessageChanges()
}
private fun stopListeningForMessageChanges() {
recipient.value?.let {
chatManager
.stopListeningForChanges(it.threadId)
ChatNotificationManager.stopNotificationSuppression(it.threadId)
}
}
} | gpl-3.0 | 69c640edd91cb7aba58ac6237bebd3bb | 36.938326 | 127 | 0.606921 | 5.271809 | false | false | false | false |
ligi/PlugHub | app/src/main/java/org/ligi/plughub/EdiMaxCommunicator.kt | 1 | 1270 | package org.ligi.plughub
import com.squareup.okhttp.*
import java.net
public class EdiMaxCommunicator (cfg: EdiMaxConfig) {
val cfg: EdiMaxConfig = cfg
public fun executeCommand(cmd: String, function: (param: String?) -> Unit) {
Thread(Runnable {
val body = RequestBody.create(null, cmd);
val client = OkHttpClient();
client.setAuthenticator(auth())
val request = Request.Builder()
.url("http://${cfg.host}:${cfg.port}/smartplug.cgi")
.post(body)
.build();
try {
val response = client.newCall(request).execute()
function(response.body().string())
} catch(e: Exception) {
function(null)
}
}).start()
}
inner class auth : Authenticator {
override fun authenticateProxy(proxy: net.Proxy?, response: Response?): Request? {
return null
}
override fun authenticate(proxy: net.Proxy?, response: Response?): Request? {
val credential = Credentials.basic("admin", cfg.pass);
return response?.request()?.newBuilder()?.header("Authorization", credential)?.build();
}
}
}
| gpl-3.0 | 9e590000fcc6bdf39c207112c3b95f0b | 26.608696 | 99 | 0.554331 | 4.703704 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/wc/shippinglabels/WCShippingLabelStoreTest.kt | 1 | 35767 | package org.wordpress.android.fluxc.wc.shippinglabels
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import com.yarolegovich.wellsql.WellSql
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests
import org.wordpress.android.fluxc.TestSiteSqlUtils
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.shippinglabels.WCAddressVerificationResult
import org.wordpress.android.fluxc.model.shippinglabels.WCAddressVerificationResult.Valid
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.CustomPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption.PredefinedPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCPaymentMethod
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingAccountSettings
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelCreationEligibility
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelMapper
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress.Type.DESTINATION
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress.Type.ORIGIN
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelPackageData
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult.ShippingOption
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult.ShippingPackage
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.LabelItem
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.SLCreationEligibilityApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient.ShippingRatesApiResponse.ShippingOption.Rate
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient.VerifyAddressResponse
import org.wordpress.android.fluxc.persistence.WellSqlConfig
import org.wordpress.android.fluxc.store.WCShippingLabelStore
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import java.math.BigDecimal
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@Suppress("LargeClass")
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner::class)
class WCShippingLabelStoreTest {
private val restClient = mock<ShippingLabelRestClient>()
private val orderId = 25L
private val refundShippingLabelId = 12L
private val site = SiteModel().apply { id = 321 }
private val errorSite = SiteModel().apply { id = 123 }
private val mapper = WCShippingLabelMapper()
private lateinit var store: WCShippingLabelStore
private val sampleShippingLabelApiResponse = WCShippingLabelTestUtils.generateSampleShippingLabelApiResponse()
private val error = WooError(INVALID_RESPONSE, NETWORK_ERROR, "Invalid site ID")
private val printPaperSize = "label"
private val samplePrintShippingLabelApiResponse =
WCShippingLabelTestUtils.generateSamplePrintShippingLabelApiResponse()
private val address = ShippingLabelAddress(country = "CA", address = "1370 Lewisham Dr.")
private val successfulVerifyAddressApiResponse = VerifyAddressResponse(
isSuccess = true,
isTrivialNormalization = false,
suggestedAddress = address,
error = null
)
private val samplePackagesApiResponse = WCShippingLabelTestUtils.generateSampleGetPackagesApiResponse()
private val sampleAccountSettingsApiResponse = WCShippingLabelTestUtils.generateSampleAccountSettingsApiResponse()
private val sampleShippingRatesApiResponse = WCShippingLabelTestUtils.generateSampleGetShippingRatesApiResponse()
private val samplePurchaseShippingLabelsResponse =
WCShippingLabelTestUtils.generateSamplePurchaseShippingLabelsApiResponse()
private val originAddress = ShippingLabelAddress(
"Company",
"Ondrej Ruttkay",
"",
"US",
"NY",
"42 Jewel St.",
"",
"Brooklyn",
"11222"
)
private val destAddress = ShippingLabelAddress(
"Company",
"Ondrej Ruttkay",
"",
"US",
"NY",
"82 Jewel St.",
"",
"Brooklyn",
"11222"
)
private val packages = listOf(
ShippingLabelPackage(
"Krabka 1",
"medium_flat_box_top",
10f,
10f,
10f,
10f,
false
),
ShippingLabelPackage(
"Krabka 2",
"medium_flat_box_side",
5f,
5f,
5f,
5f,
false
)
)
private val purchaseLabelPackagesData = listOf(
WCShippingLabelPackageData(
id = "id1",
boxId = "medium_flat_box_top",
isLetter = false,
height = 10f,
width = 10f,
length = 10f,
weight = 10f,
shipmentId = "shp_id",
rateId = "rate_id",
serviceId = "service-1",
serviceName = "USPS - Priority Mail International label",
carrierId = "usps",
products = listOf(10)
)
)
private val sampleListOfOneCustomPackage = listOf(
CustomPackage(
"Package 1",
false,
"10 x 10 x 10",
1.0f
)
)
private val sampleListOfOnePredefinedPackage = listOf(
PredefinedOption(
title = "USPS Priority Mail Flat Rate Boxes",
carrier = "usps",
predefinedPackages = listOf(
PredefinedPackage(
id = "small_flat_box",
title = "Small Flat Box",
isLetter = false,
dimensions = "10 x 10 x 10",
boxWeight = 1.0f
)
)
)
)
@Before
fun setUp() {
val appContext = RuntimeEnvironment.application.applicationContext
val config = SingleStoreWellSqlConfigForTests(
appContext,
listOf(
SiteModel::class.java,
WCShippingLabelModel::class.java,
WCShippingLabelCreationEligibility::class.java
),
WellSqlConfig.ADDON_WOOCOMMERCE
)
WellSql.init(config)
config.reset()
store = WCShippingLabelStore(
restClient,
initCoroutineEngine(),
mapper
)
// Insert the site into the db so it's available later when testing shipping labels
TestSiteSqlUtils.siteSqlUtils.insertOrUpdateSite(site)
}
@Test
fun `fetch shipping labels for order`() = test {
val result = fetchShippingLabelsForOrder()
val shippingLabelModels = mapper.map(sampleShippingLabelApiResponse!!, site)
assertThat(result.model?.size).isEqualTo(shippingLabelModels.size)
assertThat(result.model?.first()?.remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(result.model?.first()?.localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(result.model?.first()?.remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(result.model?.first()?.carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(result.model?.first()?.packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(result.model?.first()?.refundableAmount).isEqualTo(shippingLabelModels.first().refundableAmount)
assertThat(result.model?.first()?.rate).isEqualTo(shippingLabelModels.first().rate)
assertThat(result.model?.first()?.getProductNameList()?.size)
.isEqualTo(shippingLabelModels.first().getProductNameList().size)
assertThat(result.model?.first()?.getProductIdsList()?.size)
.isEqualTo(shippingLabelModels.first().getProductIdsList().size)
assertThat(result.model?.get(1)?.getProductIdsList()?.size).isEqualTo(0)
assertNotNull(result.model?.first()?.refund)
val invalidRequestResult = store.fetchShippingLabelsForOrder(errorSite, orderId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `get stored shipping labels for order`() = test {
fetchShippingLabelsForOrder()
val storedShippingLabelsList = store.getShippingLabelsForOrder(site, orderId)
val shippingLabelModels = mapper.map(sampleShippingLabelApiResponse!!, site)
assertThat(storedShippingLabelsList.size).isEqualTo(shippingLabelModels.size)
assertThat(storedShippingLabelsList.first().remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(storedShippingLabelsList.first().localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(storedShippingLabelsList.first().remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(storedShippingLabelsList.first().carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(storedShippingLabelsList.first().packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(storedShippingLabelsList.first().refundableAmount)
.isEqualTo(shippingLabelModels.first().refundableAmount)
assertThat(storedShippingLabelsList.first().rate).isEqualTo(shippingLabelModels.first().rate)
assertNotNull(storedShippingLabelsList.first().refund)
assertThat(storedShippingLabelsList.first().getProductNameList().size)
.isEqualTo(shippingLabelModels.first().getProductNameList().size)
assertThat(storedShippingLabelsList.first().getProductIdsList().size)
.isEqualTo(shippingLabelModels.first().getProductIdsList().size)
assertThat(storedShippingLabelsList[1].getProductIdsList().size).isEqualTo(0)
val invalidRequestResult = store.getShippingLabelsForOrder(errorSite, orderId)
assertThat(invalidRequestResult.size).isEqualTo(0)
}
@Test
fun `refund shipping label for order`() = test {
val result = refundShippingLabelForOrder()
assertTrue(result.model!!)
val invalidRequestResult = store.refundShippingLabelForOrder(errorSite, orderId, refundShippingLabelId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `print shipping label for order`() = test {
val result = printShippingLabelForOrder()
assertThat(result.model).isEqualTo(samplePrintShippingLabelApiResponse?.b64Content)
val invalidRequestResult = store.printShippingLabel(errorSite, printPaperSize, refundShippingLabelId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `verify shipping address`() = test {
val result = verifyAddress(ORIGIN)
assertThat(result.model).isEqualTo(Valid(address, successfulVerifyAddressApiResponse.isTrivialNormalization))
val invalidRequestResult = verifyAddress(DESTINATION)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
@Suppress("LongMethod")
fun `get shipping rates`() = test {
val expectedRatesResult = WCShippingRatesResult(
listOf(
ShippingPackage(
"default_box",
listOf(
ShippingOption(
"default",
listOf(
Rate(
title = "USPS - Media Mail",
insurance = "100",
rate = BigDecimal(3.5),
rateId = "rate_cb976896a09c4171a93ace57ed66ce5b",
serviceId = "MediaMail",
carrierId = "usps",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = false,
retailRate = BigDecimal(3.5),
isSelected = false,
isPickupFree = false,
deliveryDays = 2,
deliveryDateGuaranteed = false,
deliveryDate = null
),
Rate(
title = "FedEx - Ground",
insurance = "100",
rate = BigDecimal(21.5),
rateId = "rate_1b202bd43a8c4c929c73bb46989ef745",
serviceId = "FEDEX_GROUND",
carrierId = "fedex",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = false,
retailRate = BigDecimal(21.5),
isSelected = false,
isPickupFree = false,
deliveryDays = 1,
deliveryDateGuaranteed = true,
deliveryDate = null
)
)
),
ShippingOption(
"with_signature",
listOf(
Rate(
title = "USPS - Media Mail",
insurance = "100",
rate = BigDecimal(13.5),
rateId = "rate_cb976896a09c4171a93ace57ed66ce5b",
serviceId = "MediaMail",
carrierId = "usps",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = true,
retailRate = BigDecimal(13.5),
isSelected = false,
isPickupFree = true,
deliveryDays = 2,
deliveryDateGuaranteed = false,
deliveryDate = null
),
Rate(
title = "FedEx - Ground",
insurance = "100",
rate = BigDecimal(121.5),
rateId = "rate_1b202bd43a8c4c929c73bb46989ef745",
serviceId = "FEDEX_GROUND",
carrierId = "fedex",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = true,
retailRate = BigDecimal(121.5),
isSelected = false,
isPickupFree = true,
deliveryDays = 1,
deliveryDateGuaranteed = true,
deliveryDate = null
)
)
)
)
)
)
)
val result = getShippingRates()
assertThat(result.model).isEqualTo(expectedRatesResult)
}
@Test
fun `get packages`() = test {
val expectedResult = WCPackagesResult(
listOf(
CustomPackage("Krabica", false, "1 x 2 x 3", 1f),
CustomPackage("Obalka", true, "2 x 3 x 4", 5f)
),
listOf(
PredefinedOption("USPS Priority Mail Flat Rate Boxes",
"usps",
listOf(
PredefinedPackage(
"small_flat_box",
"Small Flat Rate Box",
false,
"21.91 x 13.65 x 4.13",
0f
),
PredefinedPackage(
"medium_flat_box_top",
"Medium Flat Rate Box 1, Top Loading",
false,
"28.57 x 22.22 x 15.24",
0f
)
)
),
PredefinedOption(
"DHL Express",
"dhlexpress",
listOf(PredefinedPackage(
"LargePaddedPouch",
"Large Padded Pouch",
true,
"30.22 x 35.56 x 2.54",
0f
))
)
)
)
val result = getPackages()
assertThat(result.model).isEqualTo(expectedResult)
val invalidRequestResult = getPackages(true)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `get account settings`() = test {
val expectedPaymentMethodList = listOf(WCPaymentMethod(
paymentMethodId = 4144354,
name = "John Doe",
cardType = "visa",
cardDigits = "5454",
expiry = "2023-12-31"
))
val result = getAccountSettings()
val model = result.model!!
assertThat(model.canManagePayments).isTrue()
assertThat(model.lastUsedBoxId).isEqualTo("small_flat_box")
assertThat(model.selectedPaymentMethodId).isEqualTo(4144354)
assertThat(model.paymentMethods).isEqualTo(expectedPaymentMethodList)
val invalidRequestResult = getAccountSettings(true)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `purchase shipping label error`() = test {
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
))
.thenReturn(WooPayload(error))
val invalidRequestResult = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
@Suppress("LongMethod")
fun `purchase shipping labels with polling`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
val statusIntermediateResponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(false)
val statusDoneReponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(true)
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any()))
.thenReturn(WooPayload(statusIntermediateResponse))
.thenReturn(WooPayload(statusDoneReponse))
ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
val shippingLabelModels = mapper.map(
samplePurchaseShippingLabelsResponse,
orderId,
originAddress,
destAddress,
site
)
verify(restClient).purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)
verify(restClient).fetchShippingLabelsStatus(
site,
orderId,
samplePurchaseShippingLabelsResponse.labels!!.map { it.labelId!! })
verify(restClient).fetchShippingLabelsStatus(
site,
orderId,
statusIntermediateResponse.labels!!
.filter { it.status != LabelItem.STATUS_PURCHASED }
.map { it.labelId!! })
assertThat(result.model!!.size).isEqualTo(shippingLabelModels.size)
assertThat(result.model!!.first().remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(result.model!!.first().localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(result.model!!.first().remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(result.model!!.first().carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(result.model!!.first().packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(result.model!!.first().refundableAmount).isEqualTo(shippingLabelModels.first().refundableAmount)
}
@Test
fun `purchase shipping labels with polling fail after 3 retries`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any())).thenReturn(WooPayload(error))
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
verify(restClient).purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)
verify(restClient, times(3)).fetchShippingLabelsStatus(
site,
orderId,
samplePurchaseShippingLabelsResponse.labels!!.map { it.labelId!! })
assertThat(result.error).isEqualTo(error)
}
@Test
fun `purchase shipping labels with polling one label failed`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
val statusIntermediateResponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(false)
val statusErrorResponse = WCShippingLabelTestUtils.generateErrorShippingLabelsStatusApiResponse()
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any()))
.thenReturn(WooPayload(statusIntermediateResponse))
.thenReturn(WooPayload(statusErrorResponse))
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
assertThat(result.isError).isTrue()
assertThat(result.error.message).isEqualTo(statusErrorResponse.labels!!.first().error)
}
@Test
fun `fetch shipping label eligibility`() = test {
val result = fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
assertThat(result.model).isNotNull
assertThat(result.model!!.isEligible).isTrue
val failedResult = fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isError = true
)
assertThat(failedResult.model).isNull()
assertThat(failedResult.error).isEqualTo(error)
}
@Test
fun `get stored eligibility`() = test {
fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
val eligibility = store.isOrderEligibleForShippingLabelCreation(
site = site,
orderId = orderId,
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false
)
assertThat(eligibility).isNotNull
assertThat(eligibility!!.isEligible).isTrue
}
@Test
fun `invalidate cached data if parameters are different`() = test {
fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
val eligibility = store.isOrderEligibleForShippingLabelCreation(
site = site,
orderId = orderId,
canCreatePackage = true,
canCreatePaymentMethod = false,
canCreateCustomsForm = false
)
assertThat(eligibility).isNull()
}
@Test
fun `creating packages returns true if the API call succeeds`() = test {
val response = WooPayload(true)
whenever(restClient.createPackages(site = any(), customPackages = any(), predefinedOptions = any()))
.thenReturn(response)
val expectedResult = WooResult(true)
val successfulRequestResult = store.createPackages(
site = site,
customPackages = sampleListOfOneCustomPackage,
predefinedPackages = emptyList()
)
assertEquals(successfulRequestResult, expectedResult)
}
@Test
fun `creating packages returns error if the API call fails`() = test {
// In practice, the API returns more specific error message(s) depending on the error case.
// In `createPackages()` that error message isn't modified further, so here we use a mock message instead.
val errorMessage = "error message"
val response = WooPayload<Boolean>(WooError(GENERIC_ERROR, UNKNOWN, errorMessage))
whenever(restClient.createPackages(site = any(), customPackages = any(), predefinedOptions = any()))
.thenReturn(response)
val expectedResult = WooResult<Boolean>(response.error)
val errorRequestResult = store.createPackages(
site = site,
customPackages = emptyList(),
predefinedPackages = sampleListOfOnePredefinedPackage
)
assertEquals(errorRequestResult, expectedResult)
assertEquals(expectedResult.error.message, errorMessage)
}
private suspend fun fetchShippingLabelsForOrder(): WooResult<List<WCShippingLabelModel>> {
val fetchShippingLabelsPayload = WooPayload(sampleShippingLabelApiResponse)
whenever(restClient.fetchShippingLabelsForOrder(orderId, site)).thenReturn(fetchShippingLabelsPayload)
whenever(restClient.fetchShippingLabelsForOrder(orderId, errorSite)).thenReturn(WooPayload(error))
return store.fetchShippingLabelsForOrder(site, orderId)
}
private suspend fun refundShippingLabelForOrder(): WooResult<Boolean> {
val refundShippingLabelPayload = WooPayload(sampleShippingLabelApiResponse)
whenever(restClient.refundShippingLabelForOrder(
site, orderId, refundShippingLabelId
)).thenReturn(refundShippingLabelPayload)
whenever(restClient.refundShippingLabelForOrder(
errorSite, orderId, refundShippingLabelId
)).thenReturn(WooPayload(error))
return store.refundShippingLabelForOrder(site, orderId, refundShippingLabelId)
}
private suspend fun printShippingLabelForOrder(): WooResult<String> {
val printShippingLabelPayload = WooPayload(samplePrintShippingLabelApiResponse)
whenever(restClient.printShippingLabels(
site, printPaperSize, listOf(refundShippingLabelId)
)).thenReturn(printShippingLabelPayload)
whenever(restClient.printShippingLabels(
errorSite, printPaperSize, listOf(refundShippingLabelId)
)).thenReturn(WooPayload(error))
return store.printShippingLabel(site, printPaperSize, refundShippingLabelId)
}
private suspend fun verifyAddress(type: ShippingLabelAddress.Type): WooResult<WCAddressVerificationResult> {
val verifyAddressPayload = WooPayload(successfulVerifyAddressApiResponse)
whenever(restClient.verifyAddress(
site,
address,
ORIGIN
)).thenReturn(verifyAddressPayload)
whenever(restClient.verifyAddress(
site,
address,
DESTINATION
)).thenReturn(WooPayload(error))
return store.verifyAddress(site, address, type)
}
private suspend fun getShippingRates(): WooResult<WCShippingRatesResult> {
val rates = WooPayload(sampleShippingRatesApiResponse)
whenever(restClient.getShippingRates(any(), any(), any(), any(), any(), anyOrNull()))
.thenReturn(rates)
return store.getShippingRates(site, orderId, originAddress, destAddress, packages, null)
}
private suspend fun getPackages(isError: Boolean = false): WooResult<WCPackagesResult> {
val getPackagesPayload = WooPayload(samplePackagesApiResponse)
if (isError) {
whenever(restClient.getPackageTypes(any())).thenReturn(WooPayload(error))
} else {
whenever(restClient.getPackageTypes(any())).thenReturn(getPackagesPayload)
}
return store.getPackageTypes(site)
}
private suspend fun getAccountSettings(isError: Boolean = false): WooResult<WCShippingAccountSettings> {
if (isError) {
whenever(restClient.getAccountSettings(any())).thenReturn(WooPayload(error))
} else {
val accountSettingsPayload = WooPayload(sampleAccountSettingsApiResponse)
whenever(restClient.getAccountSettings(any())).thenReturn(accountSettingsPayload)
}
return store.getAccountSettings(site)
}
private suspend fun fetchSLCreationEligibility(
canCreatePackage: Boolean,
canCreatePaymentMethod: Boolean,
canCreateCustomsForm: Boolean,
isEligible: Boolean = false,
isError: Boolean = false
): WooResult<WCShippingLabelCreationEligibility> {
if (isError) {
whenever(restClient.checkShippingLabelCreationEligibility(any(), any(), any(), any(), any()))
.thenReturn(WooPayload(error))
} else {
val result = SLCreationEligibilityApiResponse(
isEligible = isEligible,
reason = if (isEligible) null else "reason"
)
whenever(restClient.checkShippingLabelCreationEligibility(any(), any(), any(), any(), any()))
.thenReturn(WooPayload(result))
}
return store.fetchShippingLabelCreationEligibility(
site = site,
orderId = orderId,
canCreatePackage = canCreatePackage,
canCreatePaymentMethod = canCreatePaymentMethod,
canCreateCustomsForm = canCreateCustomsForm
)
}
}
| gpl-2.0 | 280fab200c4cddb2c1b340f51afc025a | 42.618293 | 140 | 0.585931 | 5.483213 | false | true | false | false |
adityaDave2017/my-vocab | app/src/main/java/com/android/vocab/provider/bean/WordType.kt | 1 | 962 | package com.android.vocab.provider.bean
import android.os.Parcel
import android.os.Parcelable
@Suppress("unused", "UNUSED_PARAMETER")
class WordType(var typeId: Long = 0L,
var typeName: String = "",
var abbr: String = ""): Parcelable {
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
return "WordType(typeId=$typeId, typeName='$typeName', typeAbbr='$abbr')"
}
companion object CREATOR : Parcelable.Creator<WordType> {
override fun createFromParcel(parcel: Parcel): WordType {
return WordType(parcel)
}
override fun newArray(size: Int): Array<WordType?> {
return arrayOfNulls(size)
}
}
} | mit | d2dd023ad7d03b047c275ce9ee74ddee | 24.342105 | 81 | 0.608108 | 4.669903 | false | false | false | false |
androidx/androidx-ci-action | AndroidXCI/lib/src/test/kotlin/dev/androidx/ci/github/GithubApiTest.kt | 1 | 3889 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.androidx.ci.github
import com.google.common.truth.Truth.assertThat
import dev.androidx.ci.config.Config
import dev.androidx.ci.github.dto.ArtifactsResponse
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
internal class GithubApiTest {
private val mockWebServer = MockWebServer()
private val api = GithubApi.build(
config = Config.Github(
endPoint = mockWebServer.url("/").toString(),
owner = "foo",
repo = "bar",
token = "someToken"
)
)
@Test
fun artifacts() {
mockWebServer.enqueue(
MockResponse().setResponseCode(505) // fail first, should retry
)
mockWebServer.enqueue(
MockResponse().setBody(
ARTIFACTS_RESPONSE
)
)
val result = runBlocking {
api.artifacts("run123")
}
assertThat(result).isEqualTo(
ArtifactsResponse(
artifacts = listOf(
ArtifactsResponse.Artifact(
id = "56945664",
url = "https://url/56945664",
name = "artifacts_activity",
archiveDownloadUrl = "https://download/test/56945664/zip"
),
ArtifactsResponse.Artifact(
id = "56945672",
url = "https://url/56945672",
name = "artifacts_work",
archiveDownloadUrl = "https://download/56945672/zip"
)
)
)
)
val request = mockWebServer.takeRequest()
assertThat(request.headers["Authorization"]).isEqualTo(
"token someToken"
)
}
companion object {
val ARTIFACTS_RESPONSE = """
{
"total_count": 2,
"artifacts": [
{
"id": 56945664,
"node_id": "MDg6QXJ0aWZhY3Q1Njk0NTY2NA==",
"name": "artifacts_activity",
"size_in_bytes": 109786686,
"url": "https://url/56945664",
"archive_download_url": "https://download/test/56945664/zip",
"expired": false,
"created_at": "2021-04-28T13:07:35Z",
"updated_at": "2021-04-28T13:07:42Z",
"expires_at": "2021-07-27T12:54:00Z"
},
{
"id": 56945672,
"node_id": "MDg6QXJ0aWZhY3Q1Njk0NTY3Mg==",
"name": "artifacts_work",
"size_in_bytes": 143343777,
"url": "https://url/56945672",
"archive_download_url": "https://download/56945672/zip",
"expired": false,
"created_at": "2021-04-28T13:07:35Z",
"updated_at": "2021-04-28T13:07:42Z",
"expires_at": "2021-07-27T12:54:35Z"
}
]
}
""".trimIndent()
}
}
| apache-2.0 | 1b3570556ba27c93782bfde328de17d0 | 34.354545 | 81 | 0.529699 | 4.321111 | false | false | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncMoviesRatings.kt | 1 | 3194 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.user
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.user.SyncMoviesRatings.Params
import net.simonvt.cathode.api.entity.RatingItem
import net.simonvt.cathode.api.service.SyncService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.MovieColumns
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.settings.TraktTimestamps
import retrofit2.Call
import javax.inject.Inject
class SyncMoviesRatings @Inject constructor(
private val context: Context,
private val movieHelper: MovieDatabaseHelper,
private val syncService: SyncService
) : CallAction<Params, List<RatingItem>>() {
override fun key(params: Params): String = "SyncMoviesRatings"
override fun getCall(params: Params): Call<List<RatingItem>> = syncService.getMovieRatings()
override suspend fun handleResponse(params: Params, response: List<RatingItem>) {
val ops = arrayListOf<ContentProviderOperation>()
val movieIds = mutableListOf<Long>()
val movies = context.contentResolver.query(
Movies.MOVIES,
arrayOf(MovieColumns.ID),
MovieColumns.RATED_AT + ">0"
)
movies.forEach { cursor -> movieIds.add(cursor.getLong(MovieColumns.ID)) }
movies.close()
for (rating in response) {
val traktId = rating.movie!!.ids.trakt!!
val result = movieHelper.getIdOrCreate(traktId)
val movieId = result.movieId
movieIds.remove(movieId)
val op = ContentProviderOperation.newUpdate(Movies.withId(movieId))
.withValue(MovieColumns.USER_RATING, rating.rating)
.withValue(MovieColumns.RATED_AT, rating.rated_at.timeInMillis)
.build()
ops.add(op)
}
for (movieId in movieIds) {
val op = ContentProviderOperation.newUpdate(Movies.withId(movieId))
.withValue(MovieColumns.USER_RATING, 0)
.withValue(MovieColumns.RATED_AT, 0)
.build()
ops.add(op)
}
context.contentResolver.batch(ops)
if (params.userActivityTime > 0L) {
TraktTimestamps.getSettings(context)
.edit()
.putLong(TraktTimestamps.MOVIE_RATING, params.userActivityTime)
.apply()
}
}
data class Params(val userActivityTime: Long = 0L)
}
| apache-2.0 | b0728019b20ac383e7c1d207ff756aff | 34.488889 | 94 | 0.744208 | 4.202632 | false | false | false | false |
FHannes/intellij-community | python/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt | 3 | 12930 | /*
* 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.
*/
@file:JvmName("PyResolveImportUtil")
package com.jetbrains.python.psi.resolve
import com.google.common.base.Preconditions
import com.intellij.facet.FacetManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.FileIndexFacade
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.codeInsight.typing.PyTypeShed
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil
import com.jetbrains.python.facet.PythonPathContributingFacet
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyImportResolver
import com.jetbrains.python.pyi.PyiFile
import com.jetbrains.python.sdk.PySdkUtil
import com.jetbrains.python.sdk.PythonSdkType
/**
* Python resolve utilities for qualified names.
*
* TODO: Merge with ResolveImportUtil, maybe make these functions the methods of PyQualifiedNameResolveContext.
*
* @author vlan
*/
/**
* Resolves a qualified [name] a list of modules / top-level elements according to the [context].
*/
fun resolveQualifiedName(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
checkAccess()
if (!context.isValid) {
return emptyList()
}
val relativeDirectory = context.containingDirectory
val relativeResults = resolveWithRelativeLevel(name, context)
val foundRelativeImport = relativeDirectory != null &&
relativeResults.any { isRelativeImportResult(name, relativeDirectory, it, context) }
val cache = findCache(context)
val mayCache = cache != null && !foundRelativeImport
val key = cachePrefix(context).append(name)
if (mayCache) {
val cachedResults = cache?.get(key)
if (cachedResults != null) {
return relativeResults + cachedResults
}
}
val foreignResults = foreignResults(name, context)
val pythonResults = listOf(relativeResults,
resultsFromRoots(name, context),
relativeResultsFromSkeletons(name, context)).flatten().distinct()
val allResults = pythonResults + foreignResults
val results = if (name.componentCount > 0) findFirstResults(pythonResults) + foreignResults else allResults
if (mayCache) {
cache?.put(key, results)
}
return results
}
/**
* Resolves a [name] to the first module member defined at the top-level.
*/
fun resolveTopLevelMember(name: QualifiedName, context : PyQualifiedNameResolveContext): PsiElement? {
checkAccess()
val memberName = name.lastComponent ?: return null
return resolveQualifiedName(name.removeLastComponent(), context)
.asSequence()
.filterIsInstance(PyFile::class.java)
.flatMap { it.multiResolveName(memberName).asSequence() }
.map { it.element }
.firstOrNull()
}
/**
* Resolves a [name] relative to the specified [directory].
*/
fun resolveModuleAt(name: QualifiedName, directory: PsiDirectory?, context: PyQualifiedNameResolveContext): List<PsiElement> {
checkAccess()
val empty = emptyList<PsiElement>()
if (directory == null || !directory.isValid) {
return empty
}
return name.components.fold(listOf<PsiElement>(directory)) { seekers, component ->
if (component == null) empty
else seekers.flatMap {
val children = ResolveImportUtil.resolveChildren(it, component, context.footholdFile, !context.withMembers,
!context.withPlainDirectories, context.withoutStubs)
PyUtil.filterTopPriorityResults(children.toTypedArray())
}
}
}
/**
* Creates a [PyQualifiedNameResolveContext] from a [foothold] element.
*/
fun fromFoothold(foothold: PsiElement): PyQualifiedNameResolveContext {
val module = ModuleUtilCore.findModuleForPsiElement(foothold.containingFile ?: foothold)
return PyQualifiedNameResolveContextImpl(foothold.manager, module, foothold, PythonSdkType.findPythonSdk(module))
}
/**
* Creates a [PyQualifiedNameResolveContext] from a [module].
*/
fun fromModule(module: Module): PyQualifiedNameResolveContext =
PyQualifiedNameResolveContextImpl(PsiManager.getInstance(module.project), module, null, PythonSdkType.findPythonSdk(module))
/**
* Creates a [PyQualifiedNameResolveContext] from an [sdk].
*/
fun fromSdk(project: Project, sdk: Sdk): PyQualifiedNameResolveContext =
PyQualifiedNameResolveContextImpl(PsiManager.getInstance(project), module = null, foothold = null, sdk = sdk)
private fun cachePrefix(context: PyQualifiedNameResolveContext): QualifiedName {
val results = mutableListOf<String>()
if (context.withoutStubs) {
results.add("without-stubs")
}
if (context.withoutForeign) {
results.add("without-foreign")
}
if (context.withoutRoots) {
results.add("without-roots")
}
return QualifiedName.fromComponents(results)
}
private fun foreignResults(name: QualifiedName, context: PyQualifiedNameResolveContext) =
if (context.withoutForeign)
emptyList()
else
Extensions.getExtensions(PyImportResolver.EP_NAME)
.asSequence()
.map { it.resolveImportReference(name, context, !context.withoutRoots) }
.filterNotNull()
.toList()
private fun relativeResultsFromSkeletons(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
val footholdFile = context.footholdFile
if (context.withoutRoots && footholdFile != null) {
val virtualFile = footholdFile.virtualFile
if (virtualFile == null || FileIndexFacade.getInstance(context.project).isInContent(virtualFile)) {
return emptyList()
}
val containingDirectory = context.containingDirectory
if (containingDirectory != null) {
val containingName = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null)
if (containingName != null && containingName.componentCount > 0) {
val absoluteName = containingName.append(name)
val sdk = PythonSdkType.findPythonSdk(footholdFile) ?: return emptyList()
val skeletonsVirtualFile = PySdkUtil.findSkeletonsDir(sdk) ?: return emptyList()
val skeletonsDir = context.psiManager.findDirectory(skeletonsVirtualFile)
return resolveModuleAt(absoluteName, skeletonsDir, context)
}
}
}
return emptyList()
}
fun relativeResultsForStubsFromRoots(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
if (context.footholdFile !is PyiFile || context.relativeLevel <= 0) {
return emptyList()
}
val containingDirectory = context.containingDirectory ?: return emptyList()
val containingName = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null) ?: return emptyList()
if (containingName.componentCount <= 0) {
return emptyList()
}
val absoluteName = containingName.append(name)
return resultsFromRoots(absoluteName, context.copyWithRelative(-1).copyWithRoots())
}
/**
* Filters the results according to their import priority in sys.path.
*/
private fun findFirstResults(results: List<PsiElement>) =
if (results.all(::isNamespacePackage))
results
else {
val stubFile = results.firstOrNull { it is PyiFile || PyUtil.turnDirIntoInit(it) is PyiFile }
if (stubFile != null)
listOf(stubFile)
else
listOfNotNull(results.firstOrNull { !isNamespacePackage(it) })
}
private fun isNamespacePackage(element: PsiElement): Boolean {
if (element is PsiDirectory) {
val level = PyUtil.getLanguageLevelForVirtualFile(element.project, element.virtualFile)
if (level.isAtLeast(LanguageLevel.PYTHON33)) {
return PyUtil.turnDirIntoInit(element) == null
}
}
return false
}
private fun resolveWithRelativeLevel(name: QualifiedName, context : PyQualifiedNameResolveContext): List<PsiElement> {
val footholdFile = context.footholdFile
if (context.relativeLevel >= 0 && footholdFile != null && !PyUserSkeletonsUtil.isUnderUserSkeletonsDirectory(footholdFile)) {
return resolveModuleAt(name, context.containingDirectory, context) + relativeResultsForStubsFromRoots(name, context)
}
return emptyList()
}
private fun resultsFromRoots(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
if (context.withoutRoots) {
return emptyList()
}
val moduleResults = mutableListOf<PsiElement>()
val sdkResults = mutableListOf<PsiElement>()
val sdk = context.effectiveSdk
val module = context.module
val footholdFile = context.footholdFile
val visitor = RootVisitor { root, module, sdk, isModuleSource ->
val results = if (isModuleSource) moduleResults else sdkResults
val effectiveSdk = sdk ?: context.effectiveSdk
if (!root.isValid ||
root == PyUserSkeletonsUtil.getUserSkeletonsDirectory() ||
effectiveSdk != null && PyTypeShed.isInside(root) && !PyTypeShed.maySearchForStubInRoot(name, root, effectiveSdk)) {
return@RootVisitor true
}
results.addAll(resolveInRoot(name, root, context))
if (isAcceptRootAsTopLevelPackage(context) && name.matchesPrefix(QualifiedName.fromDottedString(root.name))) {
results.addAll(resolveInRoot(name, root.parent, context))
}
return@RootVisitor true
}
when {
context.visitAllModules -> {
ModuleManager.getInstance(context.project).modules.forEach {
RootVisitorHost.visitRoots(it, true, visitor)
}
when {
sdk != null ->
RootVisitorHost.visitSdkRoots(sdk, visitor)
footholdFile != null ->
RootVisitorHost.visitSdkRoots(footholdFile, visitor)
}
}
module != null -> {
val otherSdk = sdk != context.sdk
RootVisitorHost.visitRoots(module, otherSdk, visitor)
if (otherSdk && sdk != null) {
RootVisitorHost.visitSdkRoots(sdk, visitor)
}
}
footholdFile != null -> {
RootVisitorHost.visitRoots(footholdFile, visitor)
}
sdk != null -> {
RootVisitorHost.visitSdkRoots(sdk, visitor)
}
else -> throw IllegalStateException()
}
return moduleResults + sdkResults
}
private fun isAcceptRootAsTopLevelPackage(context: PyQualifiedNameResolveContext): Boolean {
context.module?.let {
FacetManager.getInstance(it).allFacets.forEach {
if (it is PythonPathContributingFacet && it.acceptRootAsTopLevelPackage()) {
return true
}
}
}
return false
}
private fun resolveInRoot(name: QualifiedName, root: VirtualFile, context: PyQualifiedNameResolveContext): List<PsiElement> {
return if (root.isDirectory) resolveModuleAt(name, context.psiManager.findDirectory(root), context) else emptyList()
}
private fun findCache(context: PyQualifiedNameResolveContext): PythonPathCache? {
return when {
context.visitAllModules -> null
context.module != null ->
if (context.effectiveSdk != context.sdk) null else PythonModulePathCache.getInstance(context.module)
context.footholdFile != null -> {
val sdk = PyBuiltinCache.findSdkForNonModuleFile(context.footholdFile)
if (sdk != null) PythonSdkPathCache.getInstance(context.project, sdk) else null
}
else -> null
}
}
private fun isRelativeImportResult(name: QualifiedName, directory: PsiDirectory, result: PsiElement,
context: PyQualifiedNameResolveContext): Boolean {
if (context.relativeLevel > 0) {
return true
}
else {
val py2 = LanguageLevel.forElement(directory).isOlderThan(LanguageLevel.PYTHON30)
return context.relativeLevel == 0 && py2 && PyUtil.isPackage(directory, false, null) &&
result is PsiFileSystemItem && name != QualifiedNameFinder.findShortestImportableQName(result)
}
}
private fun checkAccess() {
Preconditions.checkState(ApplicationManager.getApplication().isReadAccessAllowed, "This method requires read access")
}
| apache-2.0 | 3d5374a631f5c4796e1f9148fdcca663 | 37.254438 | 128 | 0.739985 | 4.412969 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/search/SingleSearchActivity.kt | 1 | 7375 | package cc.aoeiuv020.panovel.search
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.webkit.*
import androidx.appcompat.app.AppCompatActivity
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.detail.NovelDetailActivity
import cc.aoeiuv020.panovel.report.Reporter
import cc.aoeiuv020.panovel.util.onActivityDestroy
import cc.aoeiuv020.panovel.util.safelyShow
import kotlinx.android.synthetic.main.activity_single_search.*
import org.jetbrains.anko.*
/**
* 负责单个网站的搜索功能,
* 还有登录也在这里,
*/
class SingleSearchActivity : AppCompatActivity(), IView, AnkoLogger {
companion object {
fun start(ctx: Context, site: String) {
ctx.startActivity<SingleSearchActivity>("site" to site)
}
}
private lateinit var siteName: String
private lateinit var presenter: SingleSearchPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_search)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
siteName = intent?.getStringExtra("site") ?: run {
Reporter.unreachable()
finish()
return
}
debug { "receive site: $siteName" }
title = siteName
srlRefresh.isRefreshing = true
srlRefresh.setOnRefreshListener {
wvSite.reload()
srlRefresh.isRefreshing = false
}
initWebView()
presenter = SingleSearchPresenter(siteName)
presenter.attach(this)
presenter.start()
}
@SuppressLint("SetJavaScriptEnabled")
private fun initWebView() {
wvSite.apply {
webViewClient = MyWebViewClient()
webChromeClient = WebChromeClient()
settings.apply {
javaScriptEnabled = true
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
@Suppress("DEPRECATION")
databasePath = ctx.cacheDir.resolve("webView").path
}
databaseEnabled = true
domStorageEnabled = true
cacheMode = WebSettings.LOAD_DEFAULT
setAppCacheEnabled(true)
}
}
CookieManager.getInstance().apply {
setAcceptCookie(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setAcceptThirdPartyCookies(wvSite, true)
}
}
}
override fun onDestroy() {
wvSite.onActivityDestroy()
super.onDestroy()
}
override fun onNewIntent(intent: Intent) {
debug {
"onNewIntent ${intent.data}"
}
// 以防万一,从别的浏览器跳到这里时不要显示下拉刷新中,
srlRefresh.isRefreshing = false
wvSite.loadUrl(intent.data.toString())
}
private inner class MyWebViewClient : WebViewClient(), AnkoLogger {
// 过时代替方法使用要api>=21,
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
debug { "shouldOverrideUrlLoading $url" }
if (url == null || url.startsWith("http")) {
return false
}
// 自定义协议之类的调用其他app打开,
// 主要是为了支持QQ一键登录的wtloginmqq协议,拉起QQ,
return try {
// wtloginmqq://ptlogin/qlogin?p=https%3A%2F%2Fssl.ptlogin2.qq.com%2Fjump%3Fu1%3Dhttps%253A%252F%252Flogin.book.qq.com%252Flogin%252Fqqptcallback%253Ftype%253Dwap%2526appid%253D13%2526areaid%253D1%2526auto%253D1%2526ticket%253D1%2526ajaxdm%253Dyuewen%2526returnurl%253Dhttps%25253A%25252F%25252Fm.qidian.com%25252Fuser%25253Ffrom%25253Dlogin%26pt_report%3D1%26style%3D9%26pt_ua%3D5447A8135284D842CEE5CFD29AF3FB09%26pt_browser%3DChrome&schemacallback=googlechrome%3A%2F%2F
// https://ssl.ptlogin2.qq.com/jump?u1=https%3A%2F%2Flogin.book.qq.com%2Flogin%2Fqqptcallback%3Ftype%3Dwap%26appid%3D13%26areaid%3D1%26auto%3D1%26ticket%3D1%26ajaxdm%3Dyuewen%26returnurl%3Dhttps%253A%252F%252Fm.qidian.com%252Fuser%253Ffrom%253Dlogin&pt_report=1&style=9&pt_ua=5447A8135284D842CEE5CFD29AF3FB09&pt_browser=Chrome
// schemacallback=googlechrome%3A%2F%2F
if (url.startsWith("wtloginmqq://")) {
// 把schemacallback破坏掉,否则有可能会自动判断浏览器然后选择性的跳回调,直接跳到chrome,
val newUrl = url.replace("schemacallback", "s")
browse(newUrl)
} else {
browse(url)
}
} catch (e: Exception) {
val message = "解析地址($url)失败,"
Reporter.post(message, e)
browse(url)
}
}
}
override fun onResume() {
super.onResume()
presenter.pushCookies()
}
override fun onPause() {
presenter.pullCookies()
super.onPause()
}
fun showRemoveCookiesDone() {
alert(
title = getString(R.string.success),
message = ctx.getString(R.string.message_cookies_removed)
) {
okButton { }
}.safelyShow()
}
fun getCurrentUrl(): String? = wvSite.url
fun openPage(url: String) {
srlRefresh.isRefreshing = false
wvSite.loadUrl(url)
}
private fun open() {
// TODO: 这里需要个loading dialog,
getCurrentUrl()?.let { url ->
presenter.open(url)
}
}
private fun removeCookies() {
presenter.removeCookies()
}
fun openNovelDetail(novel: Novel) {
NovelDetailActivity.start(ctx, novel)
}
fun showError(message: String, e: Throwable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
// 太丑了,
return
}
alert(
title = ctx.getString(R.string.error),
message = message + e.message
) {
okButton { }
}.safelyShow()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onBackPressed() {
if (wvSite.canGoBack()) {
wvSite.goBack()
} else {
finish()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_single_search, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.search -> FuzzySearchActivity.startSingleSite(ctx, siteName)
R.id.browse -> getCurrentUrl()?.let { browse(it) }
R.id.open -> open()
R.id.close -> finish()
R.id.removeCookies -> removeCookies()
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
| gpl-3.0 | c238178673428b8de71d7ae4de500b05 | 31.723502 | 487 | 0.612026 | 4.002818 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/ObjectTypeDefinition.kt | 1 | 1172 | package graphql.language
import java.util.ArrayList
open class ObjectTypeDefinition(override var name: String) : AbstractNode(), TypeDefinition {
val implements: MutableList<Type> = ArrayList()
val directives: MutableList<Directive> = ArrayList()
val fieldDefinitions: MutableList<FieldDefinition> = ArrayList()
override val children: List<Node>
get() {
val result = ArrayList<Node>()
result.addAll(implements)
result.addAll(directives)
result.addAll(fieldDefinitions)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as ObjectTypeDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "ObjectTypeDefinition{" +
"name='" + name + '\'' +
", implements=" + implements +
", directives=" + directives +
", fieldDefinitions=" + fieldDefinitions +
'}'
}
}
| mit | 0d45c11cc713fe11095f36d5775e55b6 | 27.585366 | 93 | 0.579352 | 5.232143 | false | false | false | false |
Kerr1Gan/ShareBox | share/src/main/java/com/ethan/and/ui/fragment/FilePickDialogFragment.kt | 1 | 5711 | package com.ethan.and.ui.fragment
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.content.pm.PackageInfo
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatDialogFragment
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.flybd.sharebox.R
import com.ethan.and.async.FindAllFilesHelper
import com.ethan.and.getMainApplication
import com.ethan.and.ui.dialog.FilePickDialog
import com.ethan.and.ui.holder.FileExpandableInfo
import com.flybd.sharebox.util.file.FileUtil
import java.util.*
/**
* Created by KerriGan on 2017/6/11.
*/
@SuppressLint("ValidFragment")
class FilePickDialogFragment : AppCompatDialogFragment {
companion object {
private const val TAG = "FilePickDialogFragment"
}
private var mActivity: FragmentActivity? = null
private val array = arrayOf("Movie", "Music", "Photo", "Doc", "Apk", "Rar")
private var mLoadingDialog: AlertDialog? = null
private var mFindFilesHelper: FindAllFilesHelper? = null
constructor() : super()
constructor(activity: FragmentActivity) : super() {
mActivity = activity
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val map = activity!!.getMainApplication().getSavedInstance()
var flag = false
for (key in array) {
if (map.get(FilePickDialog.EXTRA_PROPERTY_LIST + key) == null) {
Log.i(TAG, "instance key $key is null")
flag = true
}
}
return if (flag) {
val builder = AlertDialog.Builder(context!!)
builder.setTitle(R.string.is_being_initialized)
.setView(R.layout.dialog_file_pick_loading)
.setPositiveButton(R.string.positive, { dialog: DialogInterface, which: Int ->
})
builder.setCancelable(false)
mLoadingDialog = builder.create()
mLoadingDialog?.setCanceledOnTouchOutside(false)
mLoadingDialog?.setOnShowListener { dialog ->
onShowDialog(dialog)
}
mLoadingDialog?.setOnCancelListener { dialog ->
onCancelDialog(dialog)
}
mLoadingDialog!!
} else {
FilePickDialog(context!!, mActivity)
}
}
private fun onShowDialog(dialog: DialogInterface) {
val saveInstance = activity!!.getMainApplication().getSavedInstance()
mFindFilesHelper = FindAllFilesHelper(context!!)
mFindFilesHelper?.setProgressCallback { taskIndex, taskSize ->
mActivity?.runOnUiThread {
val pert = taskIndex * 1f / (taskSize * 1f) * 100
val bar = (dialog as AlertDialog).findViewById<View>(R.id.progress_bar) as ProgressBar
val txt = dialog.findViewById<View>(R.id.percent) as TextView
txt.setText("${pert.toInt()}%")
bar.progress = pert.toInt()
}
}
mFindFilesHelper?.startScanning { map ->
run {
for (entry in map) {
val title = entry.key
val fileList = entry.value
val localMap = LinkedHashMap<String, MutableList<String>>()
if (title.equals("Apk", true)) {
val arrayList = ArrayList<String>()
if (context == null) return@run
val installedApps = FileUtil.getInstalledApps(context!!, false)
Collections.sort(installedApps, object : Comparator<PackageInfo> {
override fun compare(lhs: PackageInfo?, rhs: PackageInfo?): Int {
if (lhs == null || rhs == null) {
return 0
}
if (lhs.lastUpdateTime < rhs.lastUpdateTime) {
return 1
} else if (lhs.lastUpdateTime > rhs.lastUpdateTime) {
return -1
} else {
return 0
}
}
})
for (packageInfo in installedApps) {
arrayList.add(packageInfo.applicationInfo.sourceDir)
}
localMap.put(context!!.getString(R.string.installed), arrayList)
}
if (fileList is MutableList<String>) {
val names = FileUtil.foldFiles(fileList, localMap)
val newArr = ArrayList<FileExpandableInfo>()
names?.let {
for (name in names.iterator()) {
val vh = FileExpandableInfo(name, localMap.get(name))
newArr.add(vh)
}
}
saveInstance.put(FilePickDialog.EXTRA_PROPERTY_LIST + title, newArr)
}
}
mActivity?.let {
FilePickDialogFragment(mActivity!!).show(mActivity?.supportFragmentManager, "show_file_pick_dialog")
}
}
dialog.cancel()
}
}
private fun onCancelDialog(dialog: DialogInterface) {
mFindFilesHelper?.release()
}
} | apache-2.0 | 0fc1dc746473a613cd0019bfbb543532 | 38.393103 | 120 | 0.544913 | 5.244261 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/completion/RsDeriveCompletionProvider.kt | 1 | 2409 | package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.rust.lang.RsLanguage
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.RsOuterAttr
import org.rust.lang.core.psi.ext.parentOfType
object RsDeriveCompletionProvider : CompletionProvider<CompletionParameters>() {
private val DERIVABLE_TRAITS = listOf(
"Eq", "PartialEq",
"Ord", "PartialOrd",
"Copy", "Clone",
"Hash",
"Default",
"Debug",
"RustcEncodable", "RustcDecodable"
)
override fun addCompletions(parameters: CompletionParameters,
context: ProcessingContext?,
result: CompletionResultSet) {
val outerAttrElem = parameters.position.parentOfType<RsOuterAttr>()
?: return
val alreadyDerived = outerAttrElem.metaItem.metaItemArgs?.metaItemList.orEmpty()
.mapNotNull { it.identifier.text }
val lookupElements = DERIVABLE_TRAITS.filter { it !in alreadyDerived }
.map { LookupElementBuilder.create(it) }
result.addAllElements(lookupElements)
}
val elementPattern: ElementPattern<PsiElement> get() {
val deriveAttr = psiElement(META_ITEM)
.withParent(psiElement(OUTER_ATTR))
.with(object : PatternCondition<PsiElement>("derive") {
// `withFirstChild` does not handle leaf elements.
// See a note in [com.intellij.psi.PsiElement.getChildren]
override fun accepts(t: PsiElement, context: ProcessingContext?): Boolean =
t.firstChild.text == "derive"
})
val traitMetaItem = psiElement(META_ITEM)
.withParent(
psiElement(META_ITEM_ARGS)
.withParent(deriveAttr)
)
return psiElement()
.inside(traitMetaItem)
.withLanguage(RsLanguage)
}
}
| mit | a26694284d422afa9d13e52346b95ae5 | 37.238095 | 91 | 0.668327 | 4.837349 | false | false | false | false |
npryce/hamkrest | src/main/kotlin/com/natpryce/hamkrest/matching.kt | 1 | 11836 | package com.natpryce.hamkrest
import kotlin.reflect.KFunction1
import kotlin.reflect.KFunction2
import kotlin.reflect.KProperty1
/**
* The result of matching some actual value against criteria defined by a [Matcher].
*/
sealed class MatchResult {
/**
* Represents that the actual value matched.
*/
object Match : MatchResult() {
override fun toString(): String = "Match"
}
/**
* Represents that the actual value did not match, and includes a human-readable description of the reason.
*
* @param description human readable text that explains why the value did not match.
*/
class Mismatch(override val description: String) : MatchResult(), SelfDescribing {
override fun toString() = "Mismatch[${describe(description)}]"
}
}
/**
* Acceptability criteria for a value of type [T]. A Matcher reports if a value of type T matches
* the criteria and describes the criteria in human-readable language.
*
* A Matcher is either a "primitive" matcher, that implements the criteria in code, or a logical combination
* (`not`, `and`, or `or`) of other matchers.
*
* To implement your own primitive matcher, create a subclass of [Matcher.Primitive].
*/
interface Matcher<in T> : (T) -> MatchResult, SelfDescribing {
/**
* Reports whether the [actual] value meets the criteria and, if not, why it does not match.
*/
override fun invoke(actual: T): MatchResult
/**
* The description of this criteria.
*/
override val description: String
/**
* Describes the negation of this criteria.
*/
val negatedDescription: String get() = "not $description"
/**
* Returns a matcher that matches the negation of this criteria.
*/
operator fun not(): Matcher<T> {
return Negation(this)
}
/**
* Returns this matcher as a predicate, that can be used for testing, finding and filtering collections
* and [kotlin.sequences.Sequence]s.
*/
fun asPredicate(): (T) -> Boolean = { this(it) == MatchResult.Match }
/**
* The negation of a matcher.
*
* @property negated the matcher to be negated
*/
class Negation<in T>(private val negated: Matcher<T>) : Matcher<T> {
override fun invoke(actual: T): MatchResult =
when (negated(actual)) {
MatchResult.Match -> MatchResult.Mismatch(negatedDescription)
is MatchResult.Mismatch -> MatchResult.Match
}
override val description = negated.negatedDescription
override val negatedDescription = negated.description
override operator fun not() = negated
}
/**
* The logican disjunction ("or") of two matchers. Evaluation is short-cut, so that if the [left]
* matcher matches, the [right] matcher is never invoked.
*
* Use the infix [or] function or [anyOf] to combine matchers with a Disjunction.
*
* @property left The left operand. This operand is always evaluated.
* @property right The right operand. This operand will not be evaluated if the result can be determined from [left].
*/
class Disjunction<in T>(private val left: Matcher<T>, private val right: Matcher<T>) : Matcher<T> {
override fun invoke(actual: T): MatchResult =
left(actual).let { l ->
when (l) {
MatchResult.Match -> l
is MatchResult.Mismatch -> right(actual).let { r ->
when (r) {
MatchResult.Match -> r
is MatchResult.Mismatch -> l
}
}
}
}
override val description: String = "${left.description} or ${right.description}"
}
/**
* The logican conjunction ("and") of two matchers. Evaluation is short-cut, so that if the [left]
* matcher fails to match, the [right] matcher is never invoked.
*
* Use the infix [and] function or [allOf] to combine matchers with a Disjunction.
*
* @property left The left operand. This operand is always evaluated.
* @property right The right operand. This operand will not be evaluated if the result can be determined from [left].
*/
class Conjunction<in T>(private val left: Matcher<T>, private val right: Matcher<T>) : Matcher<T> {
override fun invoke(actual: T): MatchResult =
left(actual).let { l ->
when (l) {
MatchResult.Match -> right(actual)
is MatchResult.Mismatch -> l
}
}
override val description: String = "${left.description} and ${right.description}"
}
/**
* Base class of matchers for which the match criteria is coded, not composed. Subclass this to write
* your own matchers.
*/
abstract class Primitive<in T> : Matcher<T>
companion object {
/**
* Converts a unary predicate into a Matcher. The description is derived from the name of the predicate.
*
* @param fn the predicate to convert into a [Matcher]<T>.
*/
operator fun <T> invoke(fn: KFunction1<T, Boolean>): Matcher<T> = Matcher(fn.name, fn)
/**
* Converts a binary predicate and second argument into a Matcher that receives the first argument.
* The description is derived from the name of the predicate.
*
* @param fn The predicate to convert into a [Matcher]<T>
* @param cmp The second argument to be passed to [fn]
*/
operator fun <T, U> invoke(fn: KFunction2<T, U, Boolean>, cmp: U): Matcher<T> = object : Matcher.Primitive<T>() {
override fun invoke(actual: T): MatchResult = match(fn(actual, cmp)) { "was: ${describe(actual)}" }
override val description: String = "${identifierToDescription(fn.name)} ${describe(cmp)}"
override val negatedDescription: String = "${identifierToNegatedDescription(fn.name)} ${describe(cmp)}"
}
/**
* Converts a binary predicate into a factory function that receives the second argument of the predicate and
* returns a Matcher that receives the first argument. The description of the matcher is derived from the name
* of the predicate.
*
* @param fn The predicate to convert into a [Matcher]<T>
*/
operator fun <T, U> invoke(fn: KFunction2<T, U, Boolean>): (U) -> Matcher<T> = { Matcher(fn, it) }
/**
* Converts a property into a Matcher. The description is derived from the name of the property.
*
* @param property the property to convert into a [Matcher]<T>.
*/
operator fun <T> invoke(property: KProperty1<T, Boolean>): Matcher<T> = Matcher(property.name, property)
/**
* Converts a unary predicate into a Matcher.
* The description of the matcher uses [name] to describe the [feature].
*
* @param name the name to be used to describe [feature]
* @param feature the predicate to convert into a [Matcher]<T>.
*/
operator fun <T> invoke(name: String, feature: (T) -> Boolean): Matcher<T> = object : Matcher<T> {
override fun invoke(actual: T): MatchResult = match(feature(actual)) { "was: ${describe(actual)}" }
override val description = identifierToDescription(name)
override val negatedDescription = identifierToNegatedDescription(name)
override fun asPredicate(): (T) -> Boolean = feature
}
}
}
/**
* Syntactic sugar to create a [Matcher.Disjunction]
*/
infix fun <T> Matcher<T>.or(that: Matcher<T>): Matcher<T> = Matcher.Disjunction(this, that)
/**
* Syntactic sugar to create a [Matcher.Disjunction]
*/
infix fun <T> KFunction1<T, Boolean>.or(that: Matcher<T>): Matcher<T> = Matcher.Disjunction(Matcher(this), that)
/**
* Syntactic sugar to create a [Matcher.Disjunction]
*/
infix fun <T> Matcher<T>.or(that: KFunction1<T, Boolean>): Matcher<T> = Matcher.Disjunction(this, Matcher(that))
/**
* Syntactic sugar to create a [Matcher.Disjunction]
*/
infix fun <T> KFunction1<T, Boolean>.or(that: KFunction1<T, Boolean>): Matcher<T> = Matcher.Disjunction(Matcher(this), Matcher(that))
/**
* Syntactic sugar to create a [Matcher.Conjunction]
*/
infix fun <T> Matcher<T>.and(that: Matcher<T>): Matcher<T> = Matcher.Conjunction<T>(this, that)
/**
* Syntactic sugar to create a [Matcher.Conjunction]
*/
infix fun <T> KFunction1<T, Boolean>.and(that: Matcher<T>): Matcher<T> = Matcher.Conjunction(Matcher(this), that)
/**
* Syntactic sugar to create a [Matcher.Conjunction]
*/
infix fun <T> Matcher<T>.and(that: KFunction1<T, Boolean>): Matcher<T> = Matcher.Conjunction(this, Matcher(that))
/**
* Syntactic sugar to create a [Matcher.Conjunction]
*/
infix fun <T> KFunction1<T, Boolean>.and(that: KFunction1<T, Boolean>): Matcher<T> = Matcher.Conjunction(Matcher(this), Matcher(that))
/**
* Returns a matcher that matches if all of the supplied matchers match.
*/
fun <T> allOf(matchers: List<Matcher<T>>): Matcher<T> = matchers.reducedWith(Matcher<T>::and)
/**
* Returns a matcher that matches if all of the supplied matchers match.
*/
fun <T> allOf(vararg matchers: Matcher<T>): Matcher<T> = allOf(matchers.asList())
/**
* Returns a matcher that matches if any of the supplied matchers match.
*/
fun <T> anyOf(matchers: List<Matcher<T>>): Matcher<T> = matchers.reducedWith(Matcher<T>::or)
/**
* Returns a matcher that matches if any of the supplied matchers match.
*/
fun <T> anyOf(vararg matchers: Matcher<T>): Matcher<T> = anyOf(matchers.asList())
/**
* Returns a matcher that applies [featureMatcher] to the result of applying [feature] to a value.
* The description of the matcher uses [name] to describe the [feature].
*
* @param name the name to be used to describe [feature]
* @param feature a function that extracts a feature of a value to be matched by [featureMatcher]
* @param featureMatcher a matcher applied to the result of the [feature]
*/
fun <T, R> has(name: String, feature: (T) -> R, featureMatcher: Matcher<R>): Matcher<T> = object : Matcher.Primitive<T>() {
override fun invoke(actual: T) =
featureMatcher(feature(actual)).let {
when (it) {
is MatchResult.Mismatch -> MatchResult.Mismatch("had ${name} that ${it.description}")
else -> it
}
}
override val description = "has ${name} that ${featureMatcher.description}"
override val negatedDescription = "does not have ${name} that ${featureMatcher.description}"
}
/**
* Returns a matcher that applies [propertyMatcher] to the current value of [property] of an object.
*/
fun <T, R> has(property: KProperty1<T, R>, propertyMatcher: Matcher<R>): Matcher<T> =
has(identifierToDescription(property.name), property, propertyMatcher)
/**
* Returns a matcher that applies [featureMatcher] to the result of applying [feature] to a value.
*
* @param feature a function that extracts a feature of a value to be matched by [featureMatcher]
* @param featureMatcher a matcher applied to the result of the [feature]
*/
fun <T, R> has(feature: KFunction1<T, R>, featureMatcher: Matcher<R>): Matcher<T> =
has(identifierToDescription(feature.name), feature, featureMatcher)
fun <T> Matcher<T>.describedBy(fn: () -> String) = object : Matcher<T> by this {
override val description: String get() = fn()
}
@Suppress("UNCHECKED_CAST")
private fun <T> List<Matcher<T>>.reducedWith(op: (Matcher<T>, Matcher<T>) -> Matcher<T>): Matcher<T> = when {
isEmpty() -> anything
else -> reduce(op)
} | apache-2.0 | 19caf5a4c3f26a93a2297d8c8adb0888 | 38.855219 | 134 | 0.637884 | 4.192703 | false | false | false | false |
samtstern/quickstart-android | inappmessaging/app/src/main/java/com/google/firebase/fiamquickstart/kotlin/KotlinMainActivity.kt | 1 | 2015 | package com.google.firebase.fiamquickstart.kotlin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.fiamquickstart.R
import com.google.firebase.fiamquickstart.databinding.ActivityMainBinding
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.inappmessaging.FirebaseInAppMessaging
import com.google.firebase.inappmessaging.ktx.inAppMessaging
import com.google.firebase.ktx.Firebase
class KotlinMainActivity : AppCompatActivity() {
private lateinit var firebaseAnalytics: FirebaseAnalytics
private lateinit var firebaseIam: FirebaseInAppMessaging
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAnalytics = Firebase.analytics
firebaseIam = Firebase.inAppMessaging
firebaseIam.isAutomaticDataCollectionEnabled = true
firebaseIam.setMessagesSuppressed(false)
binding.eventTriggerButton.setOnClickListener { view ->
firebaseAnalytics.logEvent("engagement_party", Bundle())
Snackbar.make(view, "'engagement_party' event triggered!", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.show()
}
// Get and display/log the Instance ID
FirebaseInstanceId.getInstance().instanceId
.addOnSuccessListener { instanceIdResult ->
val instanceId = instanceIdResult.id
binding.instanceIdText.text = getString(R.string.instance_id_fmt, instanceId)
Log.d(TAG, "InstanceId: $instanceId")
}
}
companion object {
private const val TAG = "FIAM-Quickstart"
}
}
| apache-2.0 | c68064a79c661c0e47beff0724dcd4ee | 37.75 | 97 | 0.723573 | 5.114213 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/tab/impl/SearchTabConfiguration.kt | 1 | 2870 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model.tab.impl
import android.content.Context
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.annotation.TabAccountFlags
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_QUERY
import de.vanita5.twittnuker.fragment.statuses.StatusesSearchFragment
import de.vanita5.twittnuker.model.Tab
import de.vanita5.twittnuker.model.tab.DrawableHolder
import de.vanita5.twittnuker.model.tab.StringHolder
import de.vanita5.twittnuker.model.tab.TabConfiguration
import de.vanita5.twittnuker.model.tab.argument.TextQueryArguments
import de.vanita5.twittnuker.model.tab.conf.StringExtraConfiguration
class SearchTabConfiguration : TabConfiguration() {
override val name = StringHolder.resource(R.string.action_search)
override val icon = DrawableHolder.Builtin.SEARCH
override val accountFlags = TabAccountFlags.FLAG_HAS_ACCOUNT or TabAccountFlags.FLAG_ACCOUNT_REQUIRED
override val fragmentClass = StatusesSearchFragment::class.java
override fun getExtraConfigurations(context: Context) = arrayOf(
StringExtraConfiguration(EXTRA_QUERY, R.string.search_statuses, null).maxLines(1).headerTitle(R.string.query)
)
override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
val arguments = tab.arguments as TextQueryArguments
when (extraConf.key) {
EXTRA_QUERY -> {
val query = (extraConf as StringExtraConfiguration).value ?: return false
arguments.query = query
}
}
return true
}
override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
val arguments = tab.arguments as? TextQueryArguments ?: return false
when (extraConf.key) {
EXTRA_QUERY -> {
(extraConf as StringExtraConfiguration).value = arguments.query
}
}
return true
}
} | gpl-3.0 | c5b88ccd1b4b21e27f331badaa25a428 | 38.875 | 121 | 0.74007 | 4.40184 | false | true | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/helpers/timetable/TimetableDatabaseInterface.kt | 1 | 3456 | package com.sapuseven.untis.helpers.timetable
import com.sapuseven.untis.data.databases.UserDatabase
import com.sapuseven.untis.data.timetable.PeriodData.Companion.ELEMENT_NAME_UNKNOWN
import com.sapuseven.untis.interfaces.TableModel
import com.sapuseven.untis.models.untis.masterdata.Klasse
import com.sapuseven.untis.models.untis.masterdata.Room
import com.sapuseven.untis.models.untis.masterdata.Subject
import com.sapuseven.untis.models.untis.masterdata.Teacher
import com.sapuseven.untis.models.untis.timetable.PeriodElement
import java.io.Serializable
class TimetableDatabaseInterface(@Transient val database: UserDatabase, id: Long) : Serializable {
private var allClasses: Map<Int, Klasse> = mapOf()
private var allTeachers: Map<Int, Teacher> = mapOf()
private var allSubjects: Map<Int, Subject> = mapOf()
private var allRooms: Map<Int, Room> = mapOf()
enum class Type {
CLASS,
TEACHER,
SUBJECT,
ROOM
}
init {
database.getAdditionalUserData<Klasse>(id, Klasse())?.let { item -> allClasses = item.toList().sortedBy { it.second.name }.toMap() }
database.getAdditionalUserData<Teacher>(id, Teacher())?.let { item -> allTeachers = item.toList().sortedBy { it.second.name }.toMap() }
database.getAdditionalUserData<Subject>(id, Subject())?.let { item -> allSubjects = item.toList().sortedBy { it.second.name }.toMap() }
database.getAdditionalUserData<Room>(id, Room())?.let { item -> allRooms = item.toList().sortedBy { it.second.name }.toMap() }
}
fun getShortName(id: Int, type: Type?): String {
return when (type) {
Type.CLASS -> allClasses[id]?.name
Type.TEACHER -> allTeachers[id]?.name
Type.SUBJECT -> allSubjects[id]?.name
Type.ROOM -> allRooms[id]?.name
else -> null
} ?: ELEMENT_NAME_UNKNOWN
}
fun getLongName(id: Int, type: Type): String {
return when (type) {
Type.CLASS -> allClasses[id]?.longName
Type.TEACHER -> allTeachers[id]?.firstName + " " + allTeachers[id]?.lastName
Type.SUBJECT -> allSubjects[id]?.longName
Type.ROOM -> allRooms[id]?.longName
} ?: ""
}
fun isAllowed(id: Int, type: Type?): Boolean {
return when (type) {
Type.CLASS -> allClasses[id]?.displayable
Type.TEACHER -> allTeachers[id]?.displayAllowed
Type.SUBJECT -> allSubjects[id]?.displayAllowed
Type.ROOM -> allRooms[id]?.displayAllowed
else -> null
} ?: false
}
private fun tableModelToPeriodElement(values: Collection<TableModel>): List<PeriodElement> {
return values.map { item: TableModel ->
when (item) {
is Klasse -> PeriodElement(Type.CLASS.name, item.id, item.id)
is Teacher -> PeriodElement(Type.TEACHER.name, item.id, item.id)
is Subject -> PeriodElement(Type.SUBJECT.name, item.id, item.id)
is Room -> PeriodElement(Type.ROOM.name, item.id, item.id)
else -> PeriodElement("", -1, -1)
}
}
}
fun elementContains(element: PeriodElement, other: String): Boolean {
return when (Type.valueOf(element.type)) {
Type.CLASS -> allClasses[element.id]?.compareTo(other)
Type.TEACHER -> allTeachers[element.id]?.compareTo(other)
Type.SUBJECT -> allSubjects[element.id]?.compareTo(other)
Type.ROOM -> allRooms[element.id]?.compareTo(other)
} == 0
}
fun getElements(type: Type?): List<PeriodElement> {
return tableModelToPeriodElement(when (type) {
Type.CLASS -> allClasses.values
Type.TEACHER -> allTeachers.values
Type.SUBJECT -> allSubjects.values
Type.ROOM -> allRooms.values
else -> emptyList()
})
}
} | gpl-3.0 | 73ea768373b8b13fd397feeb7dc62ef6 | 36.576087 | 137 | 0.715278 | 3.449102 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/AffirmPaymentActivity.kt | 1 | 2156 | package com.stripe.example.activity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.stripe.android.model.Address
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.example.R
import com.stripe.example.databinding.PaymentExampleActivityBinding
class AffirmPaymentActivity : StripeIntentActivity() {
private val viewBinding: PaymentExampleActivityBinding by lazy {
PaymentExampleActivityBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
viewBinding.confirmWithPaymentButton.text =
resources.getString(R.string.confirm_affirm_button)
viewBinding.paymentExampleIntro.text =
resources.getString(R.string.affirm_example_intro)
viewModel.inProgress.observe(this, { enableUi(!it) })
viewModel.status.observe(this, Observer(viewBinding.status::setText))
viewBinding.confirmWithPaymentButton.setOnClickListener {
createAndConfirmPaymentIntent(
country = "US",
paymentMethodCreateParams = confirmParams,
shippingDetails = ConfirmPaymentIntentParams.Shipping(
Address.Builder()
.setCity("San Francisco")
.setCountry("US")
.setLine1("123 Market St")
.setLine2("#345")
.setPostalCode("94107")
.setState("CA")
.build(),
name = "Jane Doe"
),
supportedPaymentMethods = "affirm"
)
}
}
private fun enableUi(enable: Boolean) {
viewBinding.progressBar.visibility = if (enable) View.INVISIBLE else View.VISIBLE
viewBinding.confirmWithPaymentButton.isEnabled = enable
}
private companion object {
private val confirmParams = PaymentMethodCreateParams.createAffirm()
}
}
| mit | 16897b9edd7f9d2ff49dc7c91a543f2d | 36.172414 | 89 | 0.648423 | 5.39 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/theme/Theme.kt | 1 | 1305 | package com.stripe.android.link.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.unit.dp
internal val MinimumTouchTargetSize = 48.dp
internal val AppBarHeight = 56.dp
internal val PrimaryButtonHeight = 56.dp
internal val HorizontalPadding = 20.dp
private val LocalColors = staticCompositionLocalOf { LinkThemeConfig.colors(false) }
@Composable
internal fun DefaultLinkTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = LinkThemeConfig.colors(darkTheme)
CompositionLocalProvider(LocalColors provides colors) {
MaterialTheme(
colors = colors.materialColors,
typography = Typography,
shapes = MaterialTheme.shapes,
content = content
)
}
}
internal val MaterialTheme.linkColors: LinkColors
@Composable
@ReadOnlyComposable
get() = LocalColors.current
internal val MaterialTheme.linkShapes: LinkShapes
@Composable
@ReadOnlyComposable
get() = LinkShapes
| mit | 071148007c9a75cdd1344573b2f41fac | 29.348837 | 84 | 0.765517 | 4.906015 | false | false | false | false |
sksamuel/scrimage | scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/canvas/DrawableTest.kt | 1 | 2487 | package com.sksamuel.scrimage.core.canvas
import com.sksamuel.scrimage.ImmutableImage
import com.sksamuel.scrimage.canvas.Canvas
import com.sksamuel.scrimage.canvas.GraphicsContext
import com.sksamuel.scrimage.canvas.drawables.Line
import com.sksamuel.scrimage.canvas.drawables.Polygon
import com.sksamuel.scrimage.canvas.drawables.Rect
import com.sksamuel.scrimage.canvas.painters.ColorPainter
import com.sksamuel.scrimage.color.RGBColor
import com.sksamuel.scrimage.color.X11Colorlist
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.awt.AlphaComposite
import java.awt.Color
class DrawableTest : FunSpec({
fun assertSameImage(img1: ImmutableImage, img2: ImmutableImage) {
img1.width shouldBe img2.width
img1.height shouldBe img2.height
img1.pixels() shouldBe img2.pixels()
}
val g2 = GraphicsContext { g2 ->
g2.composite = AlphaComposite.getInstance(AlphaComposite.SRC)
g2.color = Color.black
}
val blank = ImmutableImage.filled(300, 200, X11Colorlist.White.awt())
test("The lines are correctly drawn") {
val canvas = Canvas(blank).draw(
Line(10, 5, 20, 25, g2),
Line(30, 50, 30, 200, g2),
Line(100, 100, 120, 120, g2)
)
val img = canvas.image
val black = RGBColor(0, 0, 0, 255).toARGBInt()
img.pixel(10, 5).argb shouldBe black
img.pixel(20, 25).argb shouldBe black
img.pixel(30, 100).argb shouldBe black
img.pixel(110, 110).argb shouldBe black
}
test("The colors are correctly put") {
val canvas = Canvas(blank).draw(
Line(10, 5, 20, 25, g2),
Line(30, 50, 30, 200) { it.setPainter(ColorPainter(X11Colorlist.Red)) },
Line(100, 100, 120, 120, g2)
)
val img = canvas.image
val black = RGBColor(0, 0, 0, 255).toARGBInt()
val red = RGBColor(255, 0, 0, 255).toARGBInt()
img.pixel(20, 25).argb shouldBe black
img.pixel(30, 100).argb shouldBe red
img.pixel(110, 110).argb shouldBe black
}
test("Rectangles and polygons draw the same thing") {
val canvas1 = Canvas(blank).draw(
Rect(10, 20, 30, 30, g2),
Rect(100, 120, 50, 20, g2).toFilled()
)
val canvas2 = Canvas(blank).draw(
Polygon.rectangle(10, 20, 30, 30, g2),
Polygon.rectangle(100, 120, 50, 20, g2).toFilled()
)
val img1 = canvas1.image
val img2 = canvas2.image
assertSameImage(img1, img2)
}
})
| apache-2.0 | dcc75ab6c6fb6abff41b4bec2a50ced9 | 32.16 | 81 | 0.666667 | 3.52766 | false | true | false | false |
oehf/ipf | modules/hl7-kotlin/src/test/kotlin/org/openehealth/ipf/modules/hl7/kotlin/VariesTest.kt | 1 | 3336 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.modules.hl7.kotlin
import ca.uhn.hl7v2.DefaultHapiContext
import ca.uhn.hl7v2.model.Message
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* @author Christian Ohr
*/
class VariesTest {
val context = DefaultHapiContext()
private val msg1: Message = loadHl7(context, "/msg-05.hl7")
private val msg2: Message = loadHl7(context, "/msg-02.hl7")
@Test
fun testVariesUsage() {
assertTrue(msg1["QPD"]::class.java.name.contains("ca.uhn.hl7v2.model.v25.segment.QPD"))
//Test field explicitly defined as Varies: OBX-5
//-----------------------------------
val v = msg2["PATIENT_RESULT"]["ORDER_OBSERVATION"]["OBSERVATION"]["OBX"][5]
//Test a repeated Varies field
//Primitive value can be accessed either as element or as subelement #1
//Here QPD-3-1-1 returns the same as QPD-3-1
assertEquals("100", v(0).value)
val x = v(0)[1].value
assertEquals("100", x)
// Index out of bounds on accessing further (non-existing) subelements
// assertEquals("", v(0)[2].getValueOr(""))
//Test a field explicitly defined as Varies: PDQ-3
//-----------------------------------
//Access normally filled components
assertEquals("HIMSS2006", msg1["QPD"][3][4][1].value)
assertEquals("1.3.6.1.4.1.21367.2005.1.1", msg1["QPD"][3][4][2].value)
assertEquals("ISO", msg1["QPD"][3][4][3].value)
//Primitive value can be accessed either as element or as subelement #1
//Here QPD-3-1-1 returns the same as QPD-3-1
assertEquals("123456", msg1["QPD"][3][1].value)
assertEquals("123456", msg1["QPD"][3][1][1].value)
// Index out of bounds on accessing further (non-existing) subelements
// assertNull(msg1["QPD"][3][1][2].value)
//Access empty Varies component
assertNull(msg1["QPD"][3][2].value)
assertNull(msg1["QPD"][3][2][1].value)
//Test undefined field => field implicitly defined as Varies: PDQ-4
//-----------------------------------
//Test repetition
assertNull(msg1["QPD"][4](0)[1].value)
//Primitive value can be accessed either as element or as subelement 1
//Here QPD-4(0)-4 returns the same as QPD-4(0)-4-1
assertEquals("HIMSS2006", msg1["QPD"][4](0)[4].value)
assertEquals("HIMSS2006", msg1["QPD"][4](0)[4][1].value)
// Index out of bounds on accessing further (non-existing) subelements
// assertNull(msg1["QPD"][4](0)[4][2].value)
// assertNull(msg1["QPD"][4](3)[4].value)
assertNull(msg1["QPD"][4](3)[1].value)
}
} | apache-2.0 | 34a51df420311e6f81ecc0a72724792d | 36.920455 | 95 | 0.617806 | 3.526427 | false | true | false | false |
yzbzz/beautifullife | icore/src/main/java/com/ddu/icore/flow/workflow/WorkNode.kt | 2 | 695 | package com.ddu.icore.flow.workflow
import com.ddu.icore.callback.Consumer
/**
* Created by yzbzz on 2019/11/27.
*/
class WorkNode(private val nodeId: Int, val worker: Worker) : Node {
private var mConsumer: Consumer? = null
override fun getId() = nodeId
override fun onCompleted() {
mConsumer?.accept()
}
fun doWork(consumer: Consumer) {
this.mConsumer = consumer
worker.doWork(this)
}
fun removeCallback() {
this.mConsumer = null;
}
override fun toString(): String {
return "nodeId: ${getId()}"
}
companion object {
fun build(nodeId: Int, worker: Worker) = WorkNode(nodeId, worker)
}
} | apache-2.0 | cf35097c03eb69773f8e9435d40757ff | 18.885714 | 73 | 0.618705 | 3.971429 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/util/Parametros.kt | 1 | 5254 | package com.quijotelui.electronico.util
import com.quijotelui.electronico.correo.ConfiguracionCorreo
import com.quijotelui.model.Parametro
import java.text.ParseException
import java.util.*
import java.text.SimpleDateFormat
import java.util.Calendar
class Parametros{
companion object {
fun getAmbiente(parametro: MutableList<Parametro>): String {
if (parametro.isEmpty()) {
return "No existe valor para el parámetro: Ambiente"
} else if (parametro.size > 1) {
return "Existen más de un valor para el parámetro: Ambiente"
} else {
println("Ambiente " + parametro[0].valor)
if (parametro[0].valor == "Pruebas") {
return "1"
} else if (parametro[0].valor == "Producción") {
return "2"
}
}
return "El parámetro Ambiente no fue encontrado"
}
fun getEmision(parametro: MutableList<Parametro>) : String {
if (parametro.isEmpty()) {
return "No existe valor para el parámetro: Emisión"
} else if (parametro.size > 1) {
return "Existen más de un valor para el parámetro: Emisión"
} else {
println("Emisión " + parametro[0].valor)
if (parametro[0].valor == "Normal") {
return "1"
}
}
return "El parámetro Emisión no fue encontrado"
}
fun getRuta(parametro: MutableList<Parametro>) : String {
if (parametro.isEmpty()) {
return "No existe valor para el parámetro: Ruta"
} else if (parametro.size > 1) {
return "Existen más de un valor para el parámetro: Ruta"
} else {
println("Ruta ${parametro[0].nombre} ${parametro[0].valor}" )
return parametro[0].valor.toString()
}
return "El parámetro Ruta no fue encontrado"
}
fun getClaveElectronica(parametro: MutableList<Parametro>, key: String) : String {
if (parametro.isEmpty()) {
return "No existe valor para el parámetro: Clave Firma Electrónica"
} else if (parametro.size > 1) {
return "Existen más de un valor para el parámetro: Clave Firma Electrónica"
} else {
// println("Clave Firma Electrónica ${parametro[0].nombre} ${parametro[0].valor}" )
val claveFirmaElectronica : String = parametro[0].valor.toString()
Encriptar.setKey(key)
return Encriptar.decrypt(claveFirmaElectronica)
}
return "El parámetro Clave Firma Electrónica no fue encontrado"
}
fun getDatosCorreo(parametro: MutableList<Parametro>, key: String) : ConfiguracionCorreo {
var servidor = ""
var puerto = 0
var correo = ""
var clave = ""
if (parametro.isEmpty()) {
return ConfiguracionCorreo(servidor, puerto, correo, clave)
}
else {
for (i in parametro.indices) {
if (parametro[i].nombre.toString() == "Servidor Correo"){
servidor = parametro[i].valor.toString()
}
if (parametro[i].nombre.equals("Puerto Servidor Correo")){
puerto = parametro[i].valor!!.toInt()
}
if (parametro[i].nombre.equals("Correo")){
correo = parametro[i].valor.toString()
}
if (parametro[i].nombre.equals("Clave Correo")){
clave = parametro[i].valor.toString()
}
}
println("Configuración Correo: $servidor $puerto $correo $clave")
Encriptar.setKey(key)
return ConfiguracionCorreo(servidor, puerto, correo, Encriptar.decrypt(clave))
}
}
fun getSuscripcion(parametro: MutableList<Parametro>, key: String) : Date {
println("Suscripción: ${parametro[0].nombre.toString()} -> ${parametro[0].valor.toString()}")
return if (parametro.isEmpty()) {
errorDate()
} else {
val suscripcionEncryptedData : String = parametro[0].valor.toString()
toDate(suscripcionEncryptedData, key)
}
}
fun toDate(suscripcionEncryptedData : String, key :String) : Date {
val formatter = SimpleDateFormat("yyyy-MM-dd")
return try {
Encriptar.setKey(key)
val suscripcion = Encriptar.decrypt(suscripcionEncryptedData)
formatter.parse(suscripcion)
} catch (e : ParseException) {
errorDate()
} catch (e : Exception) {
errorDate()
}
}
fun errorDate() : Date {
val cal = Calendar.getInstance()
cal.time = Date()
cal.add(Calendar.DATE, -1)
return cal.time
}
}
}
| gpl-3.0 | cc34d1c7362444b0673e3cbe8d3b9eee | 38.007463 | 105 | 0.52688 | 4.093187 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/local/implementation/RealmBaseLocalRepository.kt | 1 | 3810 | package com.habitrpg.android.habitica.data.local.implementation
import com.habitrpg.android.habitica.data.local.BaseLocalRepository
import com.habitrpg.android.habitica.models.BaseMainObject
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.android.habitica.models.user.User
import hu.akarnokd.rxjava3.bridge.RxJavaBridge
import io.reactivex.rxjava3.core.Flowable
import io.realm.Realm
import io.realm.RealmObject
import io.realm.kotlin.deleteFromRealm
abstract class RealmBaseLocalRepository internal constructor(override var realm: Realm) : BaseLocalRepository {
override val isClosed: Boolean
get() = realm.isClosed
override fun close() {
realm.close()
}
override fun executeTransaction(transaction: (Realm) -> Unit) {
if (isClosed) { return }
realm.executeTransaction {
transaction(it)
}
}
override fun executeTransactionAsync(transaction: (Realm) -> Unit) {
if (isClosed) { return }
realm.executeTransactionAsync {
transaction(it)
}
}
override fun <T : BaseObject> getUnmanagedCopy(managedObject: T): T {
return if (managedObject is RealmObject && managedObject.isManaged && managedObject.isValid) {
realm.copyFromRealm(managedObject)
} else {
managedObject
}
}
override fun <T : BaseObject> getUnmanagedCopy(list: List<T>): List<T> {
if (isClosed) { return emptyList() }
return realm.copyFromRealm(list)
}
override fun <T : BaseObject> save(`object`: T) {
if (isClosed) { return }
realm.executeTransactionAsync { realm1 -> realm1.insertOrUpdate(`object`) }
}
override fun <T : BaseObject> save(objects: List<T>) {
if (isClosed) { return }
realm.executeTransactionAsync { realm1 -> realm1.insertOrUpdate(objects) }
}
override fun <T : BaseObject> saveSyncronous(`object`: T) {
if (isClosed) { return }
realm.executeTransaction { realm1 -> realm1.insertOrUpdate(`object`) }
}
override fun <T : BaseMainObject> modify(obj: T, transaction: (T) -> Unit) {
if (isClosed) { return }
val liveObject = getLiveObject(obj) ?: return
realm.executeTransaction {
transaction(liveObject)
}
}
override fun <T : BaseMainObject> modifyWithRealm(obj: T, transaction: (Realm, T) -> Unit) {
if (isClosed) { return }
val liveObject = getLiveObject(obj) ?: return
realm.executeTransaction {
transaction(it, liveObject)
}
}
override fun <T : BaseMainObject> delete(obj: T) {
if (isClosed) { return }
val liveObject = getLiveObject(obj) ?: return
realm.executeTransaction {
liveObject.deleteFromRealm()
}
}
override fun getLiveUser(id: String): User? {
return realm.where(User::class.java).equalTo("id", id).findFirst()
}
override fun <T : BaseObject> getLiveObject(obj: T): T? {
if (isClosed) return null
if (obj !is RealmObject || !obj.isManaged) return obj
val baseObject = obj as? BaseMainObject ?: return null
return realm.where(baseObject.realmClass).equalTo(baseObject.primaryIdentifierName, baseObject.primaryIdentifier).findFirst() as? T
}
fun queryUser(userID: String): Flowable<User> {
return RxJavaBridge.toV3Flowable(
realm.where(User::class.java)
.equalTo("id", userID)
.findAll()
.asFlowable()
)
.filter { it.isLoaded && it.isValid && !it.isEmpty() }
.map { it.first() }
}
}
| gpl-3.0 | 14b3f5ebd7a044bdda558f055952cbb4 | 32.954128 | 139 | 0.618898 | 4.445741 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/account/AccountSettingsViewModel.kt | 4 | 861 | package org.thoughtcrime.securesms.components.settings.app.account
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.livedata.Store
class AccountSettingsViewModel : ViewModel() {
private val store: Store<AccountSettingsState> = Store(getCurrentState())
val state: LiveData<AccountSettingsState> = store.stateLiveData
fun refreshState() {
store.update { getCurrentState() }
}
private fun getCurrentState(): AccountSettingsState {
return AccountSettingsState(
hasPin = SignalStore.kbsValues().hasPin() && !SignalStore.kbsValues().hasOptedOut(),
pinRemindersEnabled = SignalStore.pinValues().arePinRemindersEnabled(),
registrationLockEnabled = SignalStore.kbsValues().isV2RegistrationLockEnabled
)
}
}
| gpl-3.0 | e5249e8e03f7bb951092f64f5e0f8731 | 34.875 | 90 | 0.785134 | 4.756906 | false | false | false | false |
pyamsoft/power-manager | powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/BluetoothAdapterWrapperImpl.kt | 1 | 3849 | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.states
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.Context
import com.pyamsoft.powermanager.base.logger.Logger
import com.pyamsoft.powermanager.model.Connections
import com.pyamsoft.powermanager.model.States
import timber.log.Timber
import javax.inject.Inject
internal class BluetoothAdapterWrapperImpl @Inject internal constructor(context: Context,
private val logger: Logger) : ConnectedDeviceFunctionWrapper {
private val adapter: BluetoothAdapter?
private val bluetoothManager: BluetoothManager = context.applicationContext.getSystemService(
Context.BLUETOOTH_SERVICE) as BluetoothManager
init {
this.adapter = bluetoothManager.adapter
}
private fun toggle(state: Boolean) {
if (adapter != null) {
logger.i("Bluetooth: %s", if (state) "enable" else "disable")
if (state) {
adapter.enable()
} else {
adapter.disable()
}
}
}
override fun enable() {
toggle(true)
}
override fun disable() {
toggle(false)
}
override val state: States
get() {
if (adapter == null) {
Timber.w("Bluetooth state unknown")
return States.UNKNOWN
} else {
return if (adapter.isEnabled) States.ENABLED else States.DISABLED
}
}
override // Check if we are connected to any profiles
// Connected to profile
// Check if we are connected to any devices
// Get a list of devices that are connected/connecting
// Docs say list will be empty, null check just to be safe
// Connected to device
// We are not connected to anything
val connectionState: Connections
get() {
if (adapter == null) {
Timber.w("Bluetooth connection state unknown")
return Connections.UNKNOWN
} else {
for (profile in BLUETOOTH_ADAPTER_PROFILES) {
val connectionState = adapter.getProfileConnectionState(profile)
if (connectionState == BluetoothAdapter.STATE_CONNECTED || connectionState == BluetoothAdapter.STATE_CONNECTING) {
Timber.d("Connected to bluetooth adapter profile: %d", profile)
return Connections.CONNECTED
}
}
for (profile in BLUETOOTH_MANAGER_PROFILES) {
val devices = bluetoothManager.getDevicesMatchingConnectionStates(profile,
BLUETOOTH_CONNECTED_STATES)
if (devices != null) {
if (devices.size > 0) {
Timber.d("Connected to bluetooth manager device: %s (%d)", devices[0].name, profile)
return Connections.CONNECTED
}
}
}
Timber.d("Bluetooth not connected")
return Connections.DISCONNECTED
}
}
companion object {
private val BLUETOOTH_ADAPTER_PROFILES = intArrayOf(BluetoothProfile.A2DP,
BluetoothProfile.HEADSET, BluetoothProfile.HEALTH)
private val BLUETOOTH_MANAGER_PROFILES = intArrayOf(BluetoothProfile.GATT,
BluetoothProfile.GATT_SERVER)
private val BLUETOOTH_CONNECTED_STATES = intArrayOf(BluetoothAdapter.STATE_CONNECTED,
BluetoothAdapter.STATE_CONNECTING)
}
}
| apache-2.0 | 5d6381872f51e6e3c80241598f3d2396 | 33.990909 | 124 | 0.691089 | 4.705379 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/watchers/event/sequence/known/space/API25InWordSpaceInsertionEvent.kt | 1 | 4837 | package org.wordpress.aztec.watchers.event.sequence.known.space
import org.apache.commons.lang3.StringUtils
import org.wordpress.aztec.watchers.event.sequence.EventSequence
import org.wordpress.aztec.watchers.event.sequence.UserOperationEvent
import org.wordpress.aztec.watchers.event.sequence.known.space.steps.TextWatcherEventDeleteText
import org.wordpress.aztec.watchers.event.sequence.known.space.steps.TextWatcherEventInsertText
import org.wordpress.aztec.watchers.event.text.AfterTextChangedEventData
import org.wordpress.aztec.watchers.event.text.TextWatcherEvent
/*
This case implements the behavior observed in https://github.com/wordpress-mobile/AztecEditor-Android/issues/555
*/
class API25InWordSpaceInsertionEvent : UserOperationEvent() {
private val SPACE = ' '
private val SPACE_STRING = "" + SPACE
init {
// here we populate our model of reference (which is the sequence of events we expect to find)
// note we don' populate the TextWatcherEvents with actual data, but rather we just want
// to instantiate them so we can populate them later and test whether data holds true to their
// validation.
// 2 generic deletes, followed by 2 generic inserts
val builder = TextWatcherEventDeleteText.Builder()
val step1 = builder.build()
val builderStep2 = TextWatcherEventDeleteText.Builder()
val step2 = builderStep2.build()
val builderStep3 = TextWatcherEventInsertText.Builder()
val step3 = builderStep3.build()
val builderStep4 = TextWatcherEventInsertText.Builder()
val step4 = builderStep4.build()
// add each of the steps that make up for the identified API25InWordSpaceInsertionEvent here
clear()
addSequenceStep(step1)
addSequenceStep(step2)
addSequenceStep(step3)
addSequenceStep(step4)
}
override fun isUserOperationObservedInSequence(sequence: EventSequence<TextWatcherEvent>): ObservedOperationResultType {
/* here check:
If we have 2 deletes followed by 2 inserts AND:
1) checking the first BEFORETEXTCHANGED and
2) checking the LAST AFTERTEXTCHANGED
text length is longer by 1, and the item that is now located at the first BEFORETEXTCHANGED is a SPACE character.
*/
if (this.sequence.size == sequence.size) {
// populate data in our own sequence to be able to run the comparator checks
if (!isUserOperationPartiallyObservedInSequence(sequence)) {
return ObservedOperationResultType.SEQUENCE_NOT_FOUND
}
// ok all events are good individually and match the sequence we want to compare against.
// now let's make sure the BEFORE / AFTER situation is what we are trying to identify
val firstEvent = sequence.first()
val lastEvent = sequence.last()
// if new text length is longer than original text by 1
if (firstEvent.beforeEventData.textBefore?.length == lastEvent.afterEventData.textAfter!!.length - 1) {
// now check that the inserted character is actually a space
val data = firstEvent.beforeEventData
if (lastEvent.afterEventData.textAfter!![data.start + data.count] == SPACE) {
// okay sequence has been observed completely, let's make sure we are not within a Block
if (!isEventFoundWithinABlock(data)) {
return ObservedOperationResultType.SEQUENCE_FOUND
} else {
// we're within a Block, things are going to be handled by the BlockHandler so let's just request
// a queue clear only
return ObservedOperationResultType.SEQUENCE_FOUND_CLEAR_QUEUE
}
}
}
}
return ObservedOperationResultType.SEQUENCE_NOT_FOUND
}
override fun buildReplacementEventWithSequenceData(sequence: EventSequence<TextWatcherEvent>): TextWatcherEvent {
val builder = TextWatcherEventInsertText.Builder()
// here make it all up as a unique event that does the insert as usual, as we'd get it on older APIs
val firstEvent = sequence.first()
val lastEvent = sequence[sequence.size - 1]
val (oldText) = firstEvent.beforeEventData
val differenceIndex = StringUtils.indexOfDifference(oldText, lastEvent.afterEventData.textAfter)
oldText?.insert(differenceIndex, SPACE_STRING)
builder.afterEventData = AfterTextChangedEventData(oldText)
val replacementEvent = builder.build()
replacementEvent.insertionStart = differenceIndex
replacementEvent.insertionLength = 1
return replacementEvent
}
}
| mpl-2.0 | b52cf0bf824e09c054bc93180b3f8c6c | 45.509615 | 124 | 0.686996 | 4.880928 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/WorkAuthorsViewHolder.kt | 2 | 1639 | package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.author_row_item.view.*
import ru.fantlab.android.App
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Work
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.ui.modules.author.AuthorPagerActivity
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class WorkAuthorsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<Work.Author, WorkAuthorsViewHolder>)
: BaseViewHolder<Work.Author>(itemView, adapter) {
override fun bind(author: Work.Author) {
itemView.authorAvatar.setUrl("https://${LinkParserHelper.HOST_DATA}/images/autors/${author.id}")
if (!InputHelper.isEmpty(author.name)){
itemView.authorName.text = author.name
itemView.authorName.visibility = View.VISIBLE
} else itemView.authorName.visibility = View.GONE
if (!InputHelper.isEmpty(author.nameOrig)) {
itemView.authorOrigName.text = author.nameOrig
itemView.authorOrigName.visibility = View.VISIBLE
} else itemView.authorOrigName.visibility = View.GONE
itemView.setOnClickListener {
AuthorPagerActivity.startActivity(App.instance, author.id, author.name, 0)
}
}
companion object {
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<Work.Author, WorkAuthorsViewHolder>
): WorkAuthorsViewHolder =
WorkAuthorsViewHolder(getView(viewGroup, R.layout.author_row_item), adapter)
}
} | gpl-3.0 | b2d6af37dfb2e4b1a5d43e1b358fbee8 | 36.272727 | 109 | 0.799268 | 3.911695 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/psi/ModuleName.kt | 1 | 3082 | package org.jetbrains.haskell.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiElement
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.psi.search.FileTypeIndex
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.haskell.fileType.HaskellFileType
import org.jetbrains.haskell.psi.reference.ModuleReference
import com.intellij.psi.PsiFile
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.psi.PsiManager
import org.jetbrains.haskell.fileType.HaskellFile
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.jetbrains.cabal.CabalInterface
import org.jetbrains.cabal.CabalFileType
import org.jetbrains.cabal.CabalFile
import org.jetbrains.haskell.util.joinPath
import java.io.File
import org.jetbrains.haskell.vfs.TarGzFile
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.application.PathManager
import java.net.URL
import java.io.FileOutputStream
import java.io.IOException
import java.util.Arrays
import org.jetbrains.haskell.scope.GlobalScope
/**
* Created by atsky on 3/29/14.
*/
public class ModuleName(node: ASTNode) : ASTWrapperPsiElement(node) {
override fun getReference(): PsiReference? {
return ModuleReference(this)
}
public fun findModuleFile(): HaskellFile? {
val nameToFind = getText()!!
val module = ModuleUtilCore.findModuleForPsiElement(this);
if (module == null) {
return null
}
val sourceRoots = ModuleRootManager.getInstance(module)!!.getSourceRoots(true)
var result: VirtualFile? = null
for (root in sourceRoots) {
trace("", root) { name, file ->
if (nameToFind == name) {
result = file
false
} else {
true
}
}
}
if (result != null) {
val psiFile = PsiManager.getInstance(getProject()).findFile(result!!)
return psiFile as HaskellFile
}
val haskellFile = GlobalScope.getModule(getProject(), nameToFind)
if (haskellFile != null) {
return haskellFile
}
return null
}
fun trace(suffix: String, dir: VirtualFile, function: (String, VirtualFile) -> Boolean): Boolean {
for (file in dir.getChildren()!!) {
if (file.isDirectory()) {
if (!trace(suffix + file.getName() + ".", file, function)) {
return false;
}
} else {
if (file.getFileType() == HaskellFileType.INSTANCE) {
if (!function(suffix + file.getNameWithoutExtension(), file)) {
return false;
}
}
}
}
return true;
}
} | apache-2.0 | 5461b6959c2b546b54c569f0f1937836 | 30.783505 | 102 | 0.652823 | 4.705344 | false | false | false | false |
felipebz/sonar-plsql | zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/matchers/MethodMatcherWithTypesTest.kt | 1 | 3852 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.matchers
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.plsqlopen.getSemanticNode
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.RuleTest
import org.sonar.plugins.plsqlopen.api.squid.SemanticAstNode
import org.sonar.plugins.plsqlopen.api.symbols.PlSqlType
class MethodMatcherWithTypesTest : RuleTest() {
@BeforeEach
fun init() {
setRootRule(PlSqlGrammar.EXPRESSION)
}
@Test
fun matchesMethodWhenTheTypeIsNotSpecifiedInTheMatcher() {
val matcher = MethodMatcher.create().name("func").addParameter()
val node = getAstNodeWithArguments("func(x)", PlSqlType.NUMERIC)
assertThat(matcher.matches(node)).isTrue
}
@Test
fun matchesMethodWhenTheTypeIsSpecifiedAsUnknownInTheMatcher() {
val matcher = MethodMatcher.create().name("func").addParameter(PlSqlType.UNKNOWN)
val node = getAstNodeWithArguments("func(x)", PlSqlType.NUMERIC)
assertThat(matcher.matches(node)).isTrue
}
@Test
fun matchesMethodWhenTheTypeIsSpecifiedInTheMatcher() {
val matcher = MethodMatcher.create().name("func").addParameter(PlSqlType.NUMERIC)
val node = getAstNodeWithArguments("func(x)", PlSqlType.NUMERIC)
assertThat(matcher.matches(node)).isTrue
}
@Test
fun notMatchesMethodWhenTheTypeIsDifferentFromExpectation() {
val matcher = MethodMatcher.create().name("func").addParameter(PlSqlType.CHARACTER)
val node = getAstNodeWithArguments("func(x)", PlSqlType.NUMERIC)
assertThat(matcher.matches(node)).isFalse
}
@Test
fun matchesMethodWithMultipleParametersWhenTheTypeIsSpecifiedInTheMatcher() {
val matcher = MethodMatcher.create().name("func")
.addParameters(PlSqlType.NUMERIC, PlSqlType.CHARACTER, PlSqlType.DATE)
val node = getAstNodeWithArguments("func(x, y, z)", PlSqlType.NUMERIC, PlSqlType.CHARACTER, PlSqlType.DATE)
assertThat(matcher.matches(node)).isTrue
}
@Test
fun noMatchesMethodWithMultipleParametersWhenTheAnyTypeIsDifferentFromExpectation() {
val matcher = MethodMatcher.create().name("func")
.addParameters(PlSqlType.NUMERIC, PlSqlType.CHARACTER, PlSqlType.DATE)
val node = getAstNodeWithArguments("func(x, y, z)", PlSqlType.NUMERIC, PlSqlType.CHARACTER, PlSqlType.CHARACTER)
assertThat(matcher.matches(node)).isFalse
}
private fun getAstNodeWithArguments(text: String, vararg types: PlSqlType): SemanticAstNode {
val node = getSemanticNode(p.parse(text).firstChild)
val arguments = node.getDescendants(PlSqlGrammar.ARGUMENT)
for (i in types.indices) {
val actualArgument = arguments[i].firstChild
MethodMatcher.semantic(actualArgument).plSqlType = types[i]
}
return node
}
}
| lgpl-3.0 | b483e8eb09cbb8a081caa8e1a358ee8b | 39.978723 | 120 | 0.727934 | 4.362401 | false | true | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/implementation/TaskRepositoryImpl.kt | 1 | 14868 | package com.habitrpg.android.habitica.data.implementation
import androidx.core.os.bundleOf
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.local.TaskLocalRepository
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.interactors.ScoreTaskLocallyInteractor
import com.habitrpg.android.habitica.models.BaseMainObject
import com.habitrpg.android.habitica.models.responses.BulkTaskScoringData
import com.habitrpg.shared.habitica.models.responses.TaskDirection
import com.habitrpg.shared.habitica.models.responses.TaskDirectionData
import com.habitrpg.shared.habitica.models.responses.TaskScoringResult
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskList
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.habitrpg.shared.habitica.models.tasks.TasksOrder
import com.habitrpg.android.habitica.models.user.OwnedItem
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
class TaskRepositoryImpl(
localRepository: TaskLocalRepository,
apiClient: ApiClient,
userID: String,
val appConfigManager: AppConfigManager,
val analyticsManager: AnalyticsManager
) : BaseRepositoryImpl<TaskLocalRepository>(localRepository, apiClient, userID), TaskRepository {
private var lastTaskAction: Long = 0
override fun getTasks(taskType: TaskType, userID: String?, includedGroupIDs: Array<String>): Flow<List<Task>> =
this.localRepository.getTasks(taskType, userID ?: this.userID, includedGroupIDs)
override fun getTasksFlowable(taskType: TaskType, userID: String?, includedGroupIDs: Array<String>): Flowable<out List<Task>> =
this.localRepository.getTasksFlowable(taskType, userID ?: this.userID, includedGroupIDs)
override fun saveTasks(userId: String, order: TasksOrder, tasks: TaskList) {
localRepository.saveTasks(userId, order, tasks)
}
override suspend fun retrieveTasks(userId: String, tasksOrder: TasksOrder): TaskList? {
val tasks = apiClient.getTasks() ?: return null
this.localRepository.saveTasks(userId, tasksOrder, tasks)
return tasks
}
override fun retrieveCompletedTodos(userId: String?): Flowable<TaskList> {
return this.apiClient.getTasks("completedTodos")
.doOnNext { taskList ->
val tasks = taskList.tasks
this.localRepository.saveCompletedTodos(userId ?: this.userID, tasks.values)
}
}
override fun retrieveTasks(userId: String, tasksOrder: TasksOrder, dueDate: Date): Flowable<TaskList> {
val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.US)
return this.apiClient.getTasks("dailys", formatter.format(dueDate))
.doOnNext { res -> this.localRepository.saveTasks(userId, tasksOrder, res) }
}
@Suppress("ReturnCount")
override fun taskChecked(
user: User?,
task: Task,
up: Boolean,
force: Boolean,
notifyFunc: ((TaskScoringResult) -> Unit)?
): Flowable<TaskScoringResult> {
val localData = if (user != null && appConfigManager.enableLocalTaskScoring()) {
ScoreTaskLocallyInteractor.score(user, task, if (up) TaskDirection.UP else TaskDirection.DOWN)
} else null
if (user != null && localData != null) {
val stats = user.stats
val result = TaskScoringResult(localData, stats)
notifyFunc?.invoke(result)
handleTaskResponse(user, localData, task, up, 0f)
}
val now = Date().time
val id = task.id
if (lastTaskAction > now - 500 && !force || id == null) {
return Flowable.empty()
}
lastTaskAction = now
return this.apiClient.postTaskDirection(id, (if (up) TaskDirection.UP else TaskDirection.DOWN).text)
.flatMapMaybe {
// There are cases where the user object is not set correctly. So the app refetches it as a fallback
if (user == null) {
localRepository.getUser(userID).firstElement()
} else {
Maybe.just(user)
}.map { user -> Pair(it, user) }
}
.map { (res, user): Pair<TaskDirectionData, User> ->
// save local task changes
analyticsManager.logEvent(
"task_scored",
bundleOf(
Pair("type", task.type),
Pair("scored_up", up),
Pair("value", task.value)
)
)
if (res.lvl == 0) {
// Team tasks that require approval have weird data that we should just ignore.
return@map TaskScoringResult()
}
val result = TaskScoringResult(res, user.stats)
if (localData == null) {
notifyFunc?.invoke(result)
}
handleTaskResponse(user, res, task, up, localData?.delta ?: 0f)
result
}
}
override fun bulkScoreTasks(data: List<Map<String, String>>): Flowable<BulkTaskScoringData> {
return apiClient.bulkScoreTasks(data)
}
private fun handleTaskResponse(
user: User,
res: TaskDirectionData,
task: Task,
up: Boolean,
localDelta: Float
) {
this.localRepository.executeTransaction {
val bgTask = localRepository.getLiveObject(task) ?: return@executeTransaction
val bgUser = localRepository.getLiveObject(user) ?: return@executeTransaction
if (bgTask.type != TaskType.REWARD && (bgTask.value - localDelta) + res.delta != bgTask.value) {
bgTask.value = (bgTask.value - localDelta) + res.delta
if (TaskType.DAILY == bgTask.type || TaskType.TODO == bgTask.type) {
bgTask.completed = up
if (TaskType.DAILY == bgTask.type) {
if (up) {
bgTask.streak = (bgTask.streak ?: 0) + 1
} else {
bgTask.streak = (bgTask.streak ?: 0) - 1
}
}
} else if (TaskType.HABIT == bgTask.type) {
if (up) {
bgTask.counterUp = (bgTask.counterUp ?: 0) + 1
} else {
bgTask.counterDown = (bgTask.counterDown ?: 0) + 1
}
}
}
res._tmp?.drop?.key?.let { key ->
val type = when (res._tmp?.drop?.type?.lowercase(Locale.US)) {
"hatchingpotion" -> "hatchingPotions"
"egg" -> "eggs"
else -> res._tmp?.drop?.type?.lowercase(Locale.US)
}
var item = it.where(OwnedItem::class.java).equalTo("itemType", type).equalTo("key", key).findFirst()
if (item == null) {
item = OwnedItem()
item.key = key
item.itemType = type
item.userID = user.id
}
item.numberOwned += 1
when (type) {
"eggs" -> bgUser.items?.eggs?.add(item)
"food" -> bgUser.items?.food?.add(item)
"hatchingPotions" -> bgUser.items?.hatchingPotions?.add(item)
"quests" -> bgUser.items?.quests?.add(item)
else -> ""
}
}
bgUser.stats?.hp = res.hp
bgUser.stats?.exp = res.exp
bgUser.stats?.mp = res.mp
bgUser.stats?.gp = res.gp
bgUser.stats?.lvl = res.lvl
bgUser.party?.quest?.progress?.up = (
bgUser.party?.quest?.progress?.up
?: 0F
) + (res._tmp?.quest?.progressDelta?.toFloat() ?: 0F)
}
}
override fun taskChecked(
user: User?,
taskId: String,
up: Boolean,
force: Boolean,
notifyFunc: ((TaskScoringResult) -> Unit)?
): Maybe<TaskScoringResult> {
return localRepository.getTask(taskId).firstElement()
.flatMap { task -> taskChecked(user, task, up, force, notifyFunc).singleElement() }
}
override fun scoreChecklistItem(taskId: String, itemId: String): Flowable<Task> {
return apiClient.scoreChecklistItem(taskId, itemId)
.flatMapMaybe { localRepository.getTask(taskId).firstElement() }
.doOnNext { task ->
val updatedItem: ChecklistItem? = task.checklist?.lastOrNull { itemId == it.id }
if (updatedItem != null) {
localRepository.modify(updatedItem) { liveItem -> liveItem.completed = !liveItem.completed }
}
}
}
override fun getTask(taskId: String): Flowable<Task> = localRepository.getTask(taskId)
override fun getTaskCopy(taskId: String): Flowable<Task> = localRepository.getTaskCopy(taskId)
override fun createTask(task: Task, force: Boolean): Flowable<Task> {
val now = Date().time
if (lastTaskAction > now - 500 && !force) {
return Flowable.empty()
}
lastTaskAction = now
task.isSaving = true
task.isCreating = true
task.hasErrored = false
task.userId = userID
if (task.id == null) {
task.id = UUID.randomUUID().toString()
}
localRepository.saveSyncronous(task)
return apiClient.createTask(task)
.map { task1 ->
task1.dateCreated = Date()
task1
}
.doOnNext {
it.tags = task.tags
localRepository.save(it)
}
.doOnError {
task.hasErrored = true
task.isSaving = false
localRepository.saveSyncronous(task)
}
}
@Suppress("ReturnCount")
override fun updateTask(task: Task, force: Boolean): Maybe<Task> {
val now = Date().time
if ((lastTaskAction > now - 500 && !force) || !task.isValid) {
return Maybe.just(task)
}
lastTaskAction = now
val id = task.id ?: return Maybe.just(task)
val unmanagedTask = localRepository.getUnmanagedCopy(task)
unmanagedTask.isSaving = true
unmanagedTask.hasErrored = false
localRepository.saveSyncronous(unmanagedTask)
return apiClient.updateTask(id, unmanagedTask).singleElement()
.map { task1 ->
task1.position = task.position
task1.id = task.id
task1
}
.doOnSuccess {
it.tags = task.tags
localRepository.save(it)
}
.doOnError {
unmanagedTask.hasErrored = true
unmanagedTask.isSaving = false
localRepository.saveSyncronous(unmanagedTask)
}
}
override fun deleteTask(taskId: String): Flowable<Void> {
return apiClient.deleteTask(taskId)
.doOnNext { localRepository.deleteTask(taskId) }
}
override fun saveTask(task: Task) {
localRepository.save(task)
}
override fun createTasks(newTasks: List<Task>): Flowable<List<Task>> = apiClient.createTasks(newTasks)
override fun markTaskCompleted(taskId: String, isCompleted: Boolean) {
localRepository.markTaskCompleted(taskId, isCompleted)
}
override fun <T : BaseMainObject> modify(obj: T, transaction: (T) -> Unit) {
localRepository.modify(obj, transaction)
}
override fun swapTaskPosition(firstPosition: Int, secondPosition: Int) {
localRepository.swapTaskPosition(firstPosition, secondPosition)
}
override fun updateTaskPosition(taskType: TaskType, taskID: String, newPosition: Int): Maybe<List<String>> {
return apiClient.postTaskNewPosition(taskID, newPosition).firstElement()
.doOnSuccess { localRepository.updateTaskPositions(it) }
}
override fun getUnmanagedTask(taskid: String): Flowable<Task> =
getTask(taskid).map { localRepository.getUnmanagedCopy(it) }
override fun updateTaskInBackground(task: Task) {
updateTask(task).subscribe({ }, ExceptionHandler.rx())
}
override fun createTaskInBackground(task: Task) {
createTask(task).subscribe({ }, ExceptionHandler.rx())
}
override fun getTaskCopies(userId: String): Flow<List<Task>> =
localRepository.getTasks(userId).map { localRepository.getUnmanagedCopy(it) }
override fun getTaskCopies(tasks: List<Task>): List<Task> = localRepository.getUnmanagedCopy(tasks)
override fun retrieveDailiesFromDate(date: Date): Flowable<TaskList> {
val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.US)
return apiClient.getTasks("dailys", formatter.format(date))
}
override fun syncErroredTasks(): Single<List<Task>> {
return localRepository.getErroredTasks(userID).firstElement()
.flatMapPublisher { Flowable.fromIterable(it) }
.map { localRepository.getUnmanagedCopy(it) }
.flatMap {
return@flatMap if (it.isCreating) {
createTask(it, true)
} else {
updateTask(it, true).toFlowable()
}
}.toList()
}
override fun unlinkAllTasks(challengeID: String?, keepOption: String): Flowable<Void> {
return apiClient.unlinkAllTasks(challengeID, keepOption)
}
override fun getTasksForChallenge(challengeID: String?): Flowable<out List<Task>> {
return localRepository.getTasksForChallenge(challengeID, userID)
}
}
| gpl-3.0 | 3ee9aba90bdc8dce6072cfccd26453e6 | 40 | 131 | 0.590194 | 4.729008 | false | false | false | false |
InsertKoinIO/koin | core/koin-core/src/commonTest/kotlin/org/koin/perfs/PerfsTest.kt | 1 | 1442 | package org.koin.perfs
import kotlin.test.Test
import org.koin.core.A
import org.koin.core.time.measureDurationForResult
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.assertDefinitionsCount
class PerfsTest {
@Test
fun `empty module perfs`() {
val app = measureDurationForResult("empty - start ") {
koinApplication()
}
app.assertDefinitionsCount(0)
app.close()
}
private fun useDSL() {
measureDurationForResult("dsl ") {
val app = koinApplication {
modules(module {
single { A() }
})
}
app.close()
}
}
@Test
fun `perfModule400 module perfs`() {
runPerfs()
runPerfs()
}
private fun runPerfs() {
val app = measureDurationForResult("perf400 - start ") {
koinApplication {
modules(perfModule400())
}
}
val koin = app.koin
measureDurationForResult("perf400 - executed") {
koin.get<Perfs.A27>()
koin.get<Perfs.B31>()
koin.get<Perfs.C12>()
koin.get<Perfs.D42>()
}
app.close()
}
}
fun <T> measureDurationForResult(msg: String, code: () -> T): T {
val result = measureDurationForResult(code)
println("$msg in ${result.second} ms")
return result.first
} | apache-2.0 | 33e49ed7fb3fbe5f4afc69473d886513 | 22.274194 | 65 | 0.553398 | 4.19186 | false | true | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectMySwitch/app/src/main/java/me/liuqingwen/android/projectmyswitch/MySwitch.kt | 1 | 13885 | package me.liuqingwen.android.projectmyswitch
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import kotlin.math.roundToInt
/**
* Created by Qingwen on 2018-2018-1-16, project: ProjectMySwitch.
*
* @Author: Qingwen
* @DateTime: 2018-1-16
* @Package: me.liuqingwen.android.projectmyswitch in project: ProjectMySwitch
*
* Notice: If you are using this class or file, check it and do some modification.
*/
class MySwitch:View, AnkoLogger
{
companion object
{
private const val DEFAULT_WIDTH = 160
private const val DEFAULT_HEIGHT = 80
private const val ANIMATION_DISTANCE_TOLERANCE = 0.1
}
constructor(context: Context):super(context)
constructor(context: Context, attrs:AttributeSet):this(context, attrs, 0)
constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int):super(context, attrs, defStyleAttr)
{
this.setUp(attrs, defStyleAttr, 0)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int):super(context, attrs, defStyleAttr, defStyleRes)
{
this.setUp(attrs, defStyleAttr, defStyleRes)
}
private fun setUp(attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int)
{
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MySwitch, defStyleAttr, defStyleRes)
this.isOn = typedArray.getBoolean(R.styleable.MySwitch_on, false)
this.maxAnimationDuration = typedArray.getInt(R.styleable.MySwitch_maxAnimationDuration, 100).toLong()
this.contentOnBackgroundColor = typedArray.getColor(R.styleable.MySwitch_backgroundColor_switch_enabled_on, Color.GREEN)
this.contentOffBackgroundColor = typedArray.getColor(R.styleable.MySwitch_backgroundColor_switch_enabled_off, Color.GRAY)
this.contentDisabledBackgroundColor = typedArray.getColor(R.styleable.MySwitch_backgroundColor_switch_disabled, Color.GRAY)
this.contentStrokeColor = typedArray.getColor(R.styleable.MySwitch_strokeColor_switch_enabled, Color.BLACK)
this.contentDisabledStrokeColor = typedArray.getColor(R.styleable.MySwitch_strokeColor_switch_disabled, Color.GRAY)
this.buttonColor = typedArray.getColor(R.styleable.MySwitch_buttonColor_switch_enabled, Color.RED)
this.buttonDisabledColor = typedArray.getColor(R.styleable.MySwitch_buttonColor_switch_disabled, Color.BLACK)
this.contentStrokeWidth = typedArray.getFloat(R.styleable.MySwitch_contentStrokeWidth_In_Pixel, 4.0f)
this.buttonRadiusSizeDelta = typedArray.getFloat(R.styleable.MySwitch_buttonSpaceSize_In_Pixel, 4.0f)
typedArray.recycle()
}
var maxAnimationDuration = 100L
private var onSwitchValueChangedHandler:((MySwitch, Boolean) -> Unit)? = null
private var isWillOn = false
var isOn = false
set(value)
{
field = value
if (this.animator.isRunning)
{
this.animator.cancel()
}
this.buttonLocationX = if (this.isOn) this.rightEndPosition else this.leftStartPosition
this.invalidate()
}
var contentOnBackgroundColor = Color.GREEN
set(value)
{
field = value
if (this.isEnabled && this.isOn)
{
this.invalidate()
}
}
var contentOffBackgroundColor = Color.GRAY
set(value)
{
field = value
if (this.isEnabled && ! this.isOn)
{
this.invalidate()
}
}
var contentDisabledBackgroundColor = Color.GRAY
set(value)
{
field = value
if (! this.isEnabled)
{
this.invalidate()
}
}
var contentStrokeColor = Color.BLACK
set(value)
{
field = value
if (this.isEnabled)
{
this.invalidate()
}
}
var contentDisabledStrokeColor = Color.GRAY
set(value)
{
field = value
if (! this.isEnabled)
{
this.invalidate()
}
}
var buttonColor = Color.RED
set(value)
{
field = value
if (this.isEnabled)
{
this.invalidate()
}
}
var buttonDisabledColor = Color.BLACK
set(value)
{
field = value
if (! this.isEnabled)
{
this.invalidate()
}
}
var contentStrokeWidth = 4.0f
set(value)
{
field = value
this.invalidate()
}
private var buttonRadiusSizeDelta = 4.0f
set(value)
{
field = value
this.invalidate()
}
private var buttonRadius = 0.0f
private var drawingRectWidth = 0.0f
private var drawingRectHeight = 0.0f
private var isClickNotDrag = false
private var buttonLocationX = 0.0f
private var leftStartPosition = 0.0f
private var rightEndPosition = 0.0f
private var centerPosition = 0.0f
private val rect = RectF()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val animator by lazy(LazyThreadSafetyMode.NONE) { ValueAnimator().also {
it.interpolator = DecelerateInterpolator()
it.addUpdateListener {
this.buttonLocationX = it.animatedValue as Float
this.invalidate()
}
it.addListener(object:AnimatorListenerAdapter(){
override fun onAnimationEnd(animation: Animator?)
{
super.onAnimationEnd(animation)
if ([email protected] <= [email protected] || [email protected] >= [email protected])
{
[email protected] = [email protected]
[email protected]?.run { this(this@MySwitch, [email protected]) }
}
}
})
} }
fun setOnSwitchValueChangedListener(listener:((MySwitch, Boolean) -> Unit)? = null)
{
this.onSwitchValueChangedHandler = listener
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val widthMeasureMode = MeasureSpec.getMode(widthMeasureSpec)
val heightMeasureMode = MeasureSpec.getMode(heightMeasureSpec)
val widthMeasureSize = MeasureSpec.getSize(widthMeasureSpec)
val heightMeasureSize = MeasureSpec.getSize(heightMeasureSpec)
if (widthMeasureMode == MeasureSpec.AT_MOST && heightMeasureMode == MeasureSpec.AT_MOST)
{
this.setMeasuredDimension(MySwitch.DEFAULT_WIDTH, MySwitch.DEFAULT_HEIGHT)
}else if (widthMeasureMode == MeasureSpec.AT_MOST)
{
this.setMeasuredDimension((heightMeasureSize * 3.0f / 2.0f).roundToInt(), heightMeasureSize)
}else if (heightMeasureMode == MeasureSpec.AT_MOST)
{
this.setMeasuredDimension(widthMeasureSize, (widthMeasureSize * 2.0f / 3.0f).roundToInt())
}
}
override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int)
{
super.onSizeChanged(w, h, oldW, oldH)
this.drawingRectWidth = w - this.paddingLeft - this.paddingRight - this.contentStrokeWidth * 2
this.drawingRectHeight = h - this.paddingTop - this.paddingBottom - this.contentStrokeWidth * 2
this.recalculateSizeAndRadius()
info("----------------------->Get the drawing canvas rect, width: $drawingRectWidth, height: $drawingRectHeight")
}
private fun recalculateSizeAndRadius()
{
if (this.drawingRectWidth < this.drawingRectHeight)
{
this.drawingRectHeight = this.drawingRectWidth / 3 * 2
}
this.leftStartPosition = this.paddingLeft + this.contentStrokeWidth + this.drawingRectHeight / 2
this.rightEndPosition = this.paddingLeft + this.contentStrokeWidth + this.drawingRectWidth - this.drawingRectHeight / 2
this.centerPosition = this.paddingLeft + this.contentStrokeWidth + this.drawingRectWidth / 2
this.buttonRadius = this.drawingRectHeight / 2 - this.buttonRadiusSizeDelta
this.buttonLocationX = if (this.isOn) this.rightEndPosition else this.leftStartPosition
}
private fun startButtonAnimation()
{
val endPointX = when
{
this.isClickNotDrag && this.isWillOn -> this.rightEndPosition
this.isClickNotDrag && ! this.isWillOn -> this.leftStartPosition
this.buttonLocationX >= this.centerPosition -> {this.isWillOn = true; this.rightEndPosition
}
else -> {this.isWillOn = false; this.leftStartPosition
}
}
this.animator.setFloatValues(this.buttonLocationX, endPointX)
val delta = if (endPointX > this.buttonLocationX) endPointX - this.buttonLocationX else this.buttonLocationX - endPointX
this.animator.duration = if (delta <= MySwitch.ANIMATION_DISTANCE_TOLERANCE) 0L else (delta * this.maxAnimationDuration / (this.rightEndPosition - this.leftStartPosition)).toLong()
this.animator.start()
}
private fun getMovementButtonX(x:Float) = when
{
x <= this.leftStartPosition -> this.leftStartPosition
x >= this.rightEndPosition -> this.rightEndPosition
else -> x
}
override fun performClick(): Boolean
{
super.performClick()
return true
}
override fun onTouchEvent(event: MotionEvent?): Boolean
{
if (! this.isEnabled)
{
return false
}
when(event?.action)
{
MotionEvent.ACTION_DOWN -> {
if (this.animator.isRunning) { this.animator.cancel() }
this.isClickNotDrag = ! this.isClickOnButton(this.buttonLocationX, event.x, event.y)
if (this.isClickNotDrag)
{
this.isWillOn = event.x >= this.buttonLocationX
}
return true
}
MotionEvent.ACTION_MOVE -> {
if (! this.isClickNotDrag)
{
this.buttonLocationX = this.getMovementButtonX(event.x)
this.invalidate()
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (event.action == MotionEvent.ACTION_UP && this.isClickNotDrag)
{
this.performClick()
}
this.startButtonAnimation()
}
else -> { info("Not handled touch event: ${event.toString()}") }
}
return super.onTouchEvent(event)
}
private fun isClickOnButton(buttonX:Float, x: Float, y: Float) = (x - buttonX) * (x - buttonX) +
(y - this.paddingTop - this.contentStrokeWidth - this.drawingRectHeight / 2) * (y - this.paddingTop - this.contentStrokeWidth - this.drawingRectHeight / 2) <
this.buttonRadius * this.buttonRadius
override fun onDraw(canvas: Canvas?)
{
super.onDraw(canvas)
canvas?.save()
canvas?.translate(this.paddingLeft + this.contentStrokeWidth, this.paddingTop + this.contentStrokeWidth)
this.drawBackground(canvas)
this.drawButton(canvas)
canvas?.restore()
}
private fun drawBackground(canvas: Canvas?)
{
this.drawBackgroundStroke(canvas)
this.drawBackgroundContent(canvas)
}
private fun drawButton(canvas: Canvas?)
{
this.paint.color = if (this.isEnabled) this.buttonColor else this.buttonDisabledColor
this.paint.style = Paint.Style.FILL
canvas?.drawCircle(this.buttonLocationX - this.paddingLeft - this.contentStrokeWidth, this.drawingRectHeight / 2, this.buttonRadius, this.paint)
}
private fun drawBackgroundStroke(canvas: Canvas?)
{
this.paint.color = if (this.isEnabled) this.contentStrokeColor else this.contentDisabledStrokeColor
this.paint.style = Paint.Style.STROKE
this.paint.strokeWidth = this.contentStrokeWidth * 2 //important!
this.rect.top = 0.0f
this.rect.bottom = this.drawingRectHeight
this.rect.left = 0.0f
this.rect.right = this.drawingRectWidth
canvas?.drawRoundRect(this.rect, this.drawingRectHeight / 2, this.drawingRectHeight / 2, this.paint)
}
private fun drawBackgroundContent(canvas: Canvas?)
{
this.paint.color = when{
this.isOn && this.isEnabled -> this.contentOnBackgroundColor
! this.isOn && this.isEnabled -> this.contentOffBackgroundColor
else -> this.contentDisabledBackgroundColor
}
this.paint.style = Paint.Style.FILL
canvas?.drawRoundRect(this.rect, this.drawingRectHeight / 2, this.drawingRectHeight / 2, this.paint)
}
} | mit | e897bc5fcb31dbdab7e13dcd6cc420a3 | 37.148352 | 211 | 0.622326 | 4.631421 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectPhotoWall/app/src/main/java/me/liuqingwen/android/projectphotowall/MainActivity.kt | 1 | 4069 | package me.liuqingwen.android.projectphotowall
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.view.View
import kotlinx.android.synthetic.main.layout_activity_main.*
import kotlinx.android.synthetic.main.layout_empty_content_holder.view.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
class MainActivity : AppCompatActivity()
{
companion object
{
private const val LOADING_TIME_OUT = 5000
const val VIEW_IMAGE_REQUEST_CODE = 1001
const val ADD_IMAGE_REQUEST_CODE = 1002
}
private val viewLoader by lazy(LazyThreadSafetyMode.NONE) { this.viewStubHolder.inflate() }
private val adapter by lazy(LazyThreadSafetyMode.NONE) { MyAdapter(this, this.dataList){
val index = this.recyclerView.getChildAdapterPosition(it)
val photo = this.dataList[index]
val intent = DetailActivity.getIntent(this, true, photo)
this.startActivityForResult(intent, MainActivity.VIEW_IMAGE_REQUEST_CODE)
} }
private val dataList by lazy(LazyThreadSafetyMode.NONE) { arrayListOf<Photo>() }
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.init()
}
private fun init()
{
setSupportActionBar(this.toolbar)
this.supportActionBar?.title = "Photo Wall"
this.layoutSwipeRefresh.setOnRefreshListener {
if (this.viewLoader.labelInfo.visibility == View.VISIBLE)
{
this.viewLoader.labelInfo.text = this.getString(R.string.load_data_info)
}
this.loadData()
}
this.floatingActionButton.setOnClickListener {
val intent = DetailActivity.getIntent(this, isView = false)
this.startActivityForResult(intent, MainActivity.ADD_IMAGE_REQUEST_CODE)
}
this.recyclerView.adapter = this.adapter
this.recyclerView.layoutManager = GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false)
this.layoutSwipeRefresh.isRefreshing = true
this.viewLoader.labelInfo.text = this.getString(R.string.load_data_info)
this.loadData()
}
private fun loadData()
{
doAsync {
val photos = AppDatabaseHelper.getInstance(this@MainActivity).getAllPhotos()
uiThread {
[email protected] = false
if (photos.isEmpty())
{
[email protected] = [email protected](R.string.no_data_info)
[email protected] = View.VISIBLE
}
else if ([email protected] == View.VISIBLE)
{
[email protected] = View.INVISIBLE
}
[email protected]()
[email protected](photos)
[email protected]()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == AppCompatActivity.RESULT_OK)
{
when(requestCode)
{
MainActivity.VIEW_IMAGE_REQUEST_CODE, MainActivity.ADD_IMAGE_REQUEST_CODE -> {
this.loadData()
this.toast("Photos updated!")
}
else -> {this.toast("Not handled result!")}
}
}
else if (requestCode == MainActivity.ADD_IMAGE_REQUEST_CODE)
{
this.toast("Action canceled.")
}
}
}
| mit | 433f006f03a33861dfb0b9e1d2f117dc | 36.330275 | 116 | 0.6348 | 4.873054 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/recent/history/HistoryPresenter.kt | 1 | 5276 | package eu.kanade.tachiyomi.ui.recent.history
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import eu.kanade.core.util.insertSeparators
import eu.kanade.domain.base.BasePreferences
import eu.kanade.domain.chapter.model.Chapter
import eu.kanade.domain.history.interactor.DeleteAllHistory
import eu.kanade.domain.history.interactor.GetHistory
import eu.kanade.domain.history.interactor.GetNextChapter
import eu.kanade.domain.history.interactor.RemoveHistoryById
import eu.kanade.domain.history.interactor.RemoveHistoryByMangaId
import eu.kanade.domain.history.model.HistoryWithRelations
import eu.kanade.presentation.history.HistoryUiModel
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.toDateKey
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Date
class HistoryPresenter(
private val state: HistoryStateImpl = HistoryState() as HistoryStateImpl,
private val getHistory: GetHistory = Injekt.get(),
private val getNextChapter: GetNextChapter = Injekt.get(),
private val deleteAllHistory: DeleteAllHistory = Injekt.get(),
private val removeHistoryById: RemoveHistoryById = Injekt.get(),
private val removeHistoryByMangaId: RemoveHistoryByMangaId = Injekt.get(),
preferences: BasePreferences = Injekt.get(),
) : BasePresenter<HistoryController>(), HistoryState by state {
private val _events: Channel<Event> = Channel(Int.MAX_VALUE)
val events: Flow<Event> = _events.receiveAsFlow()
val isDownloadOnly: Boolean by preferences.downloadedOnly().asState()
val isIncognitoMode: Boolean by preferences.incognitoMode().asState()
@Composable
fun getHistory(): Flow<List<HistoryUiModel>> {
val query = searchQuery ?: ""
return remember(query) {
getHistory.subscribe(query)
.distinctUntilChanged()
.catch { error ->
logcat(LogPriority.ERROR, error)
_events.send(Event.InternalError)
}
.map { pagingData ->
pagingData.toHistoryUiModels()
}
}
}
private fun List<HistoryWithRelations>.toHistoryUiModels(): List<HistoryUiModel> {
return map { HistoryUiModel.Item(it) }
.insertSeparators { before, after ->
val beforeDate = before?.item?.readAt?.time?.toDateKey() ?: Date(0)
val afterDate = after?.item?.readAt?.time?.toDateKey() ?: Date(0)
when {
beforeDate.time != afterDate.time && afterDate.time != 0L -> HistoryUiModel.Header(afterDate)
// Return null to avoid adding a separator between two items.
else -> null
}
}
}
fun removeFromHistory(history: HistoryWithRelations) {
presenterScope.launchIO {
removeHistoryById.await(history)
}
}
fun removeAllFromHistory(mangaId: Long) {
presenterScope.launchIO {
removeHistoryByMangaId.await(mangaId)
}
}
fun getNextChapterForManga(mangaId: Long, chapterId: Long) {
presenterScope.launchIO {
val chapter = getNextChapter.await(mangaId, chapterId)
_events.send(if (chapter != null) Event.OpenChapter(chapter) else Event.NoNextChapterFound)
}
}
fun deleteAllHistory() {
presenterScope.launchIO {
val result = deleteAllHistory.await()
if (!result) return@launchIO
withUIContext {
view?.activity?.toast(R.string.clear_history_completed)
}
}
}
fun resumeLastChapterRead() {
presenterScope.launchIO {
val chapter = getNextChapter.await()
_events.send(if (chapter != null) Event.OpenChapter(chapter) else Event.NoNextChapterFound)
}
}
sealed class Dialog {
object DeleteAll : Dialog()
data class Delete(val history: HistoryWithRelations) : Dialog()
}
sealed class Event {
object InternalError : Event()
object NoNextChapterFound : Event()
data class OpenChapter(val chapter: Chapter) : Event()
}
}
@Stable
interface HistoryState {
var searchQuery: String?
var dialog: HistoryPresenter.Dialog?
}
fun HistoryState(): HistoryState {
return HistoryStateImpl()
}
class HistoryStateImpl : HistoryState {
override var searchQuery: String? by mutableStateOf(null)
override var dialog: HistoryPresenter.Dialog? by mutableStateOf(null)
}
| apache-2.0 | d2d306258b925a93b5f47bfc13276b28 | 35.638889 | 113 | 0.695792 | 4.509402 | false | false | false | false |
gurleensethi/LiteUtilities | liteutils/src/main/java/com/thetechnocafe/gurleensethi/liteutils/ValidatorUtils.kt | 1 | 6307 | package com.thetechnocafe.gurleensethi.liteutils
import android.support.design.widget.TextInputEditText
import android.widget.EditText
/**
* Created by gurleensethi on 08/09/17.
* Add easy validations on edit text
*
* Motivation : Easily validate the text from the edit text based on different parameters
*/
public fun EditText.validator(): Validator = Validator(text.toString())
public fun TextInputEditText.validator(): Validator = Validator(text.toString())
/*
* Class to process all the filters provided by the user
* */
class Validator(val text: String) {
/*
* Boolean to determine whether all the validations has passed successfully.
* If any validation fails the state is changed to false.
* Final result is returned to the user
* */
private var isValidated = true
/*
* If validation fails then this callback is invoked to notify the user about
* and error
* */
private var errorCallback: ((ValidationError?) -> Unit)? = null
/*
* If validation is passes then this callback is invoked to notify the user
* for the same
* */
private var successCallback: (() -> Unit)? = null
/*
* User settable limits for the numbers of characters that the string can contain
* */
private var MINIMUM_LENGTH = 0
private var MAXIMUM_LENGTH = Int.MAX_VALUE
private var VALIDATION_ERROR_TYPE: ValidationError? = null
public fun validate(): Boolean {
//Check if the string characters count is in limits
if (text.length < MINIMUM_LENGTH) {
isValidated = false
setErrorType(ValidationError.MINIMUM_LENGTH)
} else if (text.length > MAXIMUM_LENGTH) {
isValidated = false
setErrorType(ValidationError.MAXIMUM_LENGTH)
}
//Invoke the error callback if supplied by the user
if (isValidated) {
successCallback?.invoke()
} else {
errorCallback?.invoke(VALIDATION_ERROR_TYPE)
}
return isValidated
}
public fun email(): Validator {
if (!text.matches(Regex("^[A-Za-z0-9+_.-]+@(.+)\$"))) {
setErrorType(ValidationError.EMAIL)
}
return this
}
public fun noNumbers(): Validator {
if (text.matches(Regex(".*\\d.*"))) {
setErrorType(ValidationError.NO_NUMBERS)
}
return this
}
public fun nonEmpty(): Validator {
if (text.isEmpty()) {
setErrorType(ValidationError.NON_EMPTY)
}
return this
}
public fun onlyNumbers(): Validator {
if (!text.matches(Regex("\\d+"))) {
setErrorType(ValidationError.ONLY_NUMBERS)
}
return this;
}
public fun allUpperCase(): Validator {
if (text.toUpperCase() != text) {
setErrorType(ValidationError.ALL_UPPER_CASE)
}
return this
}
public fun allLowerCase(): Validator {
if (text.toLowerCase() != text) {
setErrorType(ValidationError.ALL_LOWER_CASE)
}
return this
}
public fun atLeastOneLowerCase(): Validator {
if (text.matches(Regex("[A-Z0-9]+"))) {
setErrorType(ValidationError.AT_LEAST_ONE_LOWER_CASE)
}
return this
}
public fun atLeastOneUpperCase(): Validator {
if (text.matches(Regex("[a-z0-9]+"))) {
setErrorType(ValidationError.AT_LEAST_ONE_UPPER_CASE)
}
return this
}
public fun maximumLength(length: Int): Validator {
MAXIMUM_LENGTH = length
return this
}
public fun minimumLength(length: Int): Validator {
MINIMUM_LENGTH = length
return this
}
public fun addErrorCallback(callback: (ValidationError?) -> Unit): Validator {
errorCallback = callback
return this
}
public fun addSuccessCallback(callback: () -> Unit): Validator {
successCallback = callback
return this
}
public fun atLeastOneNumber(): Validator {
if (!text.matches(Regex(".*\\d.*"))) {
setErrorType(ValidationError.AT_LEAST_ONE_NUMBER)
}
return this
}
public fun startsWithNonNumber(): Validator {
if (Character.isDigit(text[0])) {
setErrorType(ValidationError.STARTS_WITH_NON_NUMBER)
}
return this
}
public fun noSpecialCharacter(): Validator {
if (!text.matches(Regex("[A-Za-z0-9]+"))) {
setErrorType(ValidationError.NO_SPECIAL_CHARACTER)
}
return this
}
public fun atLeastOneSpecialCharacter(): Validator {
if (text.matches(Regex("[A-Za-z0-9]+"))) {
setErrorType(ValidationError.AT_LEAST_ONE_SPECIAL_CHARACTER)
}
return this
}
public fun contains(string: String): Validator {
if (!text.contains(string)) {
setErrorType(ValidationError.CONTAINS)
}
return this
}
public fun doesNotContains(string: String): Validator {
if (text.contains(string)) {
setErrorType(ValidationError.DOES_NOT_CONTAINS)
}
return this
}
public fun startsWith(string: String): Validator {
if (!text.startsWith(string)) {
setErrorType(ValidationError.STARTS_WITH)
}
return this
}
public fun endsWith(string: String): Validator {
if (!text.endsWith(string)) {
setErrorType(ValidationError.ENDS_WITH)
}
return this
}
private fun setErrorType(validationError: ValidationError) {
isValidated = false
if (VALIDATION_ERROR_TYPE == null) {
VALIDATION_ERROR_TYPE = validationError
}
}
}
/*
* Enums that serve for identification of error while validation text.
* Every enum is the name of a function with the corresponding validation
* */
enum class ValidationError {
MINIMUM_LENGTH,
MAXIMUM_LENGTH,
AT_LEAST_ONE_UPPER_CASE,
AT_LEAST_ONE_LOWER_CASE,
ALL_LOWER_CASE,
ALL_UPPER_CASE,
ONLY_NUMBERS,
NON_EMPTY,
NO_NUMBERS,
EMAIL,
AT_LEAST_ONE_NUMBER,
STARTS_WITH_NON_NUMBER,
NO_SPECIAL_CHARACTER,
AT_LEAST_ONE_SPECIAL_CHARACTER,
CONTAINS,
DOES_NOT_CONTAINS,
STARTS_WITH,
ENDS_WITH
} | mit | 1da52029dd5d1b68c8566401ba29ccf6 | 26.307359 | 89 | 0.613445 | 4.450953 | false | false | false | false |
paslavsky/music-sync-manager | msm-server/src/main/kotlin/net/paslavsky/msm/setting/PropertyDescriptionFactory.kt | 1 | 3120 | package net.paslavsky.msm.setting
import net.paslavsky.msm.setting.description.XmlPropertiesDescriptionHolder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.ArrayList
import net.paslavsky.msm.setting.description.XmlProperty
import net.paslavsky.msm.hasText
import org.springframework.beans.BeanUtils
import org.springframework.util.Assert
import net.paslavsky.msm.setting.description.XmlPropertyGroup
import kotlin.properties.Delegates
import java.util.Collections
/**
* This factory using to build PropertyDescription's
*
* @author Andrey Paslavsky
* @version 1.0
*/
Component
public class PropertyDescriptionFactory() : Iterable<PropertyDescription> {
private var xmlDescriptionHolder: XmlPropertiesDescriptionHolder by Delegates.notNull()
private val propertyDescriptions: Collection<PropertyDescription> by Delegates.lazy {
var parentName = ""
val description = xmlDescriptionHolder.description
val descriptions = ArrayList<PropertyDescription>()
for (p in description.properties) {
descriptions.add(buildPropertyDescription(p, parentName))
}
for (g in description.groups) {
descriptions.addAll(buildPropertyDescriptionsInGroup(g, parentName))
}
Collections.unmodifiableCollection(descriptions)
}
Autowired fun init(descriptionHolder: XmlPropertiesDescriptionHolder) {
xmlDescriptionHolder = descriptionHolder
}
private fun buildPropertyDescriptionsInGroup(group: XmlPropertyGroup, parentName: String): Collection<PropertyDescription> {
val subName = if (parentName.hasText()) "${parentName}.${group.name}" else group.name
val descriptions = ArrayList<PropertyDescription>()
for (p in group.properties) {
descriptions.add(buildPropertyDescription(p, subName))
}
for (g in group.groups) {
descriptions.addAll(buildPropertyDescriptionsInGroup(g, subName))
}
return descriptions
}
suppress("unchecked") fun buildPropertyDescription(xmlDescription: XmlProperty, parentName: String): PropertyDescription {
val validators = ArrayList<PropertyValidator>()
if (xmlDescription.validate.hasText()) {
validators.add(SpELPropertyValidator(xmlDescription.validate!!))
}
for (`class` in xmlDescription.validators) {
Assert.isAssignable(javaClass<PropertyValidator>(), `class`)
validators.add(BeanUtils.instantiate(`class`))
}
val validator = if (validators.size() == 1) validators[0] else CompositePropertyValidator(validators)
return PropertyDescription(
name = if (parentName.hasText()) "${parentName}.${xmlDescription.name}" else xmlDescription.name,
scope = xmlDescription.scope,
`type` = xmlDescription.`type`,
validator = validator
)
}
override fun iterator(): Iterator<PropertyDescription> {
return propertyDescriptions.iterator()
}
} | apache-2.0 | 1b727ba76ae322bb0ff57365f9ab3303 | 38.0125 | 128 | 0.715064 | 5.032258 | false | false | false | false |
Heiner1/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt | 1 | 4510 | package info.nightscout.androidaps.plugins.insulin
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Iob
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.Insulin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.shared.logging.AAPSLogger
import org.json.JSONObject
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
class InsulinOrefBasePluginTest {
var testPeak = 0
var testUserDefinedDia = 0.0
var shortDiaNotificationSend = false
inner class InsulinBaseTest(
injector: HasAndroidInjector,
rh: ResourceHelper,
profileFunction: ProfileFunction,
rxBus: RxBus,
aapsLogger: AAPSLogger,
config: Config,
hardLimits: HardLimits
) : InsulinOrefBasePlugin(injector, rh, profileFunction, rxBus, aapsLogger, config, hardLimits) {
override fun sendShortDiaNotification(dia: Double) {
shortDiaNotificationSend = true
}
override val userDefinedDia: Double
get() = testUserDefinedDia
override val peak: Int
get() = testPeak
override fun commentStandardText(): String = ""
override val id get(): Insulin.InsulinType = Insulin.InsulinType.UNKNOWN
override val friendlyName get(): String = ""
override fun configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: JSONObject) {}
}
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
private lateinit var sut: InsulinBaseTest
@Mock lateinit var rh: ResourceHelper
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var rxBus: RxBus
@Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var activePlugin: ActivePlugin
@Mock lateinit var config: Config
@Mock lateinit var hardLimits: HardLimits
private var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector {
}
}
@Before
fun setUp() {
sut = InsulinBaseTest(injector, rh, profileFunction, rxBus, aapsLogger, config, hardLimits)
`when`(hardLimits.minDia()).thenReturn(5.0)
}
@Test
fun testGetDia() {
Assert.assertEquals(5.0, sut.dia, 0.0)
testUserDefinedDia = 5.0 + 1
Assert.assertEquals(5.0 + 1, sut.dia, 0.0)
testUserDefinedDia = 5.0 - 1
Assert.assertEquals(5.0, sut.dia, 0.0)
Assert.assertTrue(shortDiaNotificationSend)
}
@Test
fun testIobCalcForTreatment() {
val treatment = Bolus(timestamp = 0, amount = 10.0, type = Bolus.Type.NORMAL)
testPeak = 30
testUserDefinedDia = 4.0
val time = System.currentTimeMillis()
// check directly after bolus
treatment.timestamp = time
treatment.amount = 10.0
Assert.assertEquals(10.0, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1)
// check after 1 hour
treatment.timestamp = time - 1 * 60 * 60 * 1000 // 1 hour
treatment.amount = 10.0
Assert.assertEquals(3.92, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1)
// check after 2 hour
treatment.timestamp = time - 2 * 60 * 60 * 1000 // 2 hours
treatment.amount = 10.0
Assert.assertEquals(0.77, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1)
// check after 3 hour
treatment.timestamp = time - 3 * 60 * 60 * 1000 // 3 hours
treatment.amount = 10.0
Assert.assertEquals(0.10, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1)
// check after dia
treatment.timestamp = time - 4 * 60 * 60 * 1000 // 4 hours
treatment.amount = 10.0
Assert.assertEquals(0.0, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1)
}
} | agpl-3.0 | 3aba329edca3276fa5be4b324cc3b18c | 36.591667 | 113 | 0.70133 | 4.365924 | false | true | false | false |
geeteshk/Hyper | app/src/main/java/io/geeteshk/hyper/ui/activity/WebActivity.kt | 1 | 12218 | /*
* Copyright 2016 Geetesh Kalakoti <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.geeteshk.hyper.ui.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.*
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import io.geeteshk.hyper.R
import io.geeteshk.hyper.ui.adapter.LogsAdapter
import io.geeteshk.hyper.util.Constants
import io.geeteshk.hyper.util.Prefs.defaultPrefs
import io.geeteshk.hyper.util.Prefs.get
import io.geeteshk.hyper.util.net.HyperServer
import io.geeteshk.hyper.util.net.NetworkUtils
import io.geeteshk.hyper.util.project.ProjectManager
import kotlinx.android.synthetic.main.activity_web.*
import kotlinx.android.synthetic.main.dialog_input_single.view.*
import kotlinx.android.synthetic.main.sheet_logs.view.*
import kotlinx.android.synthetic.main.sheet_web_settings.view.*
import kotlinx.android.synthetic.main.widget_toolbar.*
import timber.log.Timber
import java.io.IOException
import java.util.*
class WebActivity : ThemedActivity() {
private var jsLogs = ArrayList<ConsoleMessage>()
private lateinit var localUrl: String
private lateinit var localWithoutIndex: String
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
val project = intent.getStringExtra("name")
NetworkUtils.server = HyperServer(project)
super.onCreate(savedInstanceState)
try {
NetworkUtils.server!!.start()
} catch (e: IOException) {
Timber.e(e)
}
setContentView(R.layout.activity_web)
val indexFile = ProjectManager.getIndexFile(project)
val indexPath = ProjectManager.getRelativePath(indexFile!!, project)
toolbar.title = project
setSupportActionBar(toolbar)
webView.settings.javaScriptEnabled = true
localUrl = if (NetworkUtils.server!!.wasStarted() && NetworkUtils.server!!.isAlive && NetworkUtils.ipAddress != null)
"http://${NetworkUtils.ipAddress}:${HyperServer.PORT_NUMBER}/$indexPath"
else
intent.getStringExtra("localUrl")
localWithoutIndex = localUrl.substring(0, localUrl.length - 10)
webView.loadUrl(localUrl)
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
loadingProgress.progress = newProgress
}
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
jsLogs.add(consoleMessage)
return true
}
override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
AlertDialog.Builder(this@WebActivity)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK") { _, _ -> result.confirm() }
.setCancelable(false)
.show()
return true
}
override fun onJsConfirm(view: WebView, url: String, message: String, result: JsResult): Boolean {
AlertDialog.Builder(this@WebActivity)
.setTitle("Confirm")
.setMessage(message)
.setPositiveButton("OK") { _, _ -> result.confirm() }
.setNegativeButton("CANCEL") { _, _ -> result.cancel() }
.setCancelable(false)
.show()
return true
}
}
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, localUrl: String) {
super.onPageFinished(view, localUrl)
webView.animate().alpha(1F)
}
}
toolbar.subtitle = localUrl
}
override fun onDestroy() {
super.onDestroy()
NetworkUtils.server!!.stop()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_web, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val prefs = defaultPrefs(this)
when (item.itemId) {
R.id.refresh -> {
webView.animate().alpha(0F)
webView.reload()
return true
}
R.id.user_agent -> {
val selectedI = IntArray(1)
val current = webView.settings.userAgentString
val agents = LinkedList(Arrays.asList(*Constants.USER_AGENTS))
if (!agents.contains(current)) agents.add(0, current)
val parsedAgents = NetworkUtils.parseUAList(agents)
AlertDialog.Builder(this)
.setTitle("Change User Agent")
.setSingleChoiceItems(parsedAgents.toTypedArray(), parsedAgents.indexOf(NetworkUtils.parseUA(current))) { _, i -> selectedI[0] = i }
.setPositiveButton("UPDATE") { _, _ -> webView.settings.userAgentString = agents[selectedI[0]] }
.setNeutralButton("RESET") { _, _ -> webView.settings.userAgentString = null }
.setNegativeButton("CUSTOM") { _, _ ->
val rootView = View.inflate(this@WebActivity, R.layout.dialog_input_single, null)
rootView.inputText.hint = "Custom agent string"
rootView.inputText.setText(current)
AlertDialog.Builder(this@WebActivity)
.setTitle("Custom User Agent")
.setView(rootView)
.setPositiveButton("UPDATE") { _, _ -> webView.settings.userAgentString = rootView.inputText.text.toString() }
.setNegativeButton(R.string.cancel, null)
.show()
}
.show()
return true
}
R.id.web_browser -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(localUrl))
startActivity(intent)
return true
}
R.id.web_logs -> {
val layoutLog = View.inflate(this, R.layout.sheet_logs, null)
val darkTheme = prefs["dark_theme", false]!!
if (darkTheme) {
layoutLog.setBackgroundColor(-0xcccccd)
}
val manager = LinearLayoutManager(this)
val adapter = LogsAdapter(localWithoutIndex, jsLogs, darkTheme)
layoutLog.logsList.layoutManager = manager
layoutLog.logsList.addItemDecoration(DividerItemDecoration(this@WebActivity, manager.orientation))
layoutLog.logsList.adapter = adapter
val dialogLog = BottomSheetDialog(this)
dialogLog.setContentView(layoutLog)
dialogLog.show()
return true
}
R.id.web_settings -> {
val layout = View.inflate(this, R.layout.sheet_web_settings, null)
if (prefs["dark_theme", false]!!) {
layout.setBackgroundColor(-0xcccccd)
}
layout.allowContentAccess.isChecked = webView.settings.allowContentAccess
layout.allowFileAccess.isChecked = webView.settings.allowFileAccess
layout.blockNetworkImage.isChecked = webView.settings.blockNetworkImage
layout.blockNetworkLoads.isChecked = webView.settings.blockNetworkLoads
layout.builtInZoomControls.isChecked = webView.settings.builtInZoomControls
layout.database.isChecked = webView.settings.databaseEnabled
layout.displayZoomControls.isChecked = webView.settings.displayZoomControls
layout.domStorage.isChecked = webView.settings.domStorageEnabled
layout.jsCanOpenWindows.isChecked = webView.settings.javaScriptCanOpenWindowsAutomatically
layout.jsEnabled.isChecked = webView.settings.javaScriptEnabled
layout.loadOverview.isChecked = webView.settings.loadWithOverviewMode
layout.imageLoad.isChecked = webView.settings.loadsImagesAutomatically
layout.wideView.isChecked = webView.settings.useWideViewPort
layout.allowContentAccess.setOnCheckedChangeListener { _, isChecked -> webView.settings.allowContentAccess = isChecked }
layout.allowFileAccess.setOnCheckedChangeListener { _, isChecked -> webView.settings.allowFileAccess = isChecked }
layout.blockNetworkImage.setOnCheckedChangeListener { _, isChecked -> webView.settings.blockNetworkImage = isChecked }
layout.blockNetworkLoads.setOnCheckedChangeListener { _, isChecked -> webView.settings.blockNetworkLoads = isChecked }
layout.builtInZoomControls.setOnCheckedChangeListener { _, isChecked -> webView.settings.builtInZoomControls = isChecked }
layout.database.setOnCheckedChangeListener { _, isChecked -> webView.settings.databaseEnabled = isChecked }
layout.displayZoomControls.setOnCheckedChangeListener { _, isChecked -> webView.settings.displayZoomControls = isChecked }
layout.domStorage.setOnCheckedChangeListener { _, isChecked -> webView.settings.domStorageEnabled = isChecked }
layout.jsCanOpenWindows.setOnCheckedChangeListener { _, isChecked -> webView.settings.javaScriptCanOpenWindowsAutomatically = isChecked }
layout.jsEnabled.setOnCheckedChangeListener { _, isChecked -> webView.settings.javaScriptEnabled = isChecked }
layout.loadOverview.setOnCheckedChangeListener { _, isChecked -> webView.settings.loadWithOverviewMode = isChecked }
layout.imageLoad.setOnCheckedChangeListener { _, isChecked -> webView.settings.loadsImagesAutomatically = isChecked }
layout.wideView.setOnCheckedChangeListener { _, isChecked -> webView.settings.useWideViewPort = isChecked }
if (Build.VERSION.SDK_INT >= 16) {
layout.allowFileAccessFromFileUrls.isChecked = webView.settings.allowFileAccessFromFileURLs
layout.allowUniversalAccessFromFileUrls.isChecked = webView.settings.allowUniversalAccessFromFileURLs
layout.allowFileAccessFromFileUrls.setOnCheckedChangeListener { _, isChecked -> webView.settings.allowFileAccessFromFileURLs = isChecked }
layout.allowUniversalAccessFromFileUrls.setOnCheckedChangeListener { _, isChecked -> webView.settings.allowUniversalAccessFromFileURLs = isChecked }
} else {
layout.allowFileAccessFromFileUrls.visibility = View.GONE
layout.allowUniversalAccessFromFileUrls.visibility = View.GONE
}
val dialog = BottomSheetDialog(this)
dialog.setContentView(layout)
dialog.show()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | e5120d24cf0f2965fa6954f743fb2f1e | 48.068273 | 168 | 0.633246 | 5.354075 | false | false | false | false |
hgschmie/jdbi | kotlin-sqlobject/src/test/kotlin/org/jdbi/v3/sqlobject/kotlin/Issue1944Test.kt | 2 | 4080 | /*
* 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.jdbi.v3.sqlobject.kotlin
import org.jdbi.v3.core.HandleCallback
import org.jdbi.v3.core.Jdbi
import org.jdbi.v3.core.kotlin.KotlinMapper
import org.jdbi.v3.core.kotlin.KotlinPlugin
import org.jdbi.v3.core.kotlin.mapTo
import org.jdbi.v3.core.mapper.JoinRow
import org.jdbi.v3.core.mapper.JoinRowMapper
import org.jdbi.v3.sqlobject.SqlObjectPlugin
import org.jdbi.v3.testing.junit5.JdbiExtension
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
class Issue1944Test {
@JvmField
@RegisterExtension
var h2Extension: JdbiExtension = JdbiExtension.h2()
.withPlugins(SqlObjectPlugin(), KotlinSqlObjectPlugin())
.withInitializer { _, handle ->
handle.inTransaction(
HandleCallback<Any?, RuntimeException> { h ->
h.execute("CREATE TABLE Tag (id integer primary key, name VARCHAR(50))")
h.execute("CREATE TABLE Product (id integer primary key, primaryName varchar(50), tagId integer)")
h.execute("INSERT INTO Tag (id, name) VALUES (1, 'foo')")
h.execute("INSERT INTO Product (id, primaryName, tagId) VALUES (2, 'stuff', 1)")
}
)
}
data class Tag(
val id: Int?,
val name: String?
)
data class Product(
val id: Int?,
val primaryName: String?,
val tagId: Int?
)
@Test
fun testWithKotlinMapperFactory(jdbi: Jdbi) {
jdbi.installPlugin(KotlinPlugin())
// the required mapper for Tag is implicit and will be created on the fly without a prefix by the KotlinMapperFactory
.registerRowMapper(KotlinMapper(Product::class.java, "p"))
.registerRowMapper(JoinRowMapper.forTypes(Tag::class.java, Product::class.java))
doTest(jdbi)
}
@Test
fun testWithoutKotlinMapperFactory(jdbi: Jdbi) {
jdbi.installPlugin(KotlinPlugin(false))
.registerRowMapper(KotlinMapper(Product::class.java, "p"))
.registerRowMapper(KotlinMapper(Tag::class.java))
.registerRowMapper(JoinRowMapper.forTypes(Tag::class.java, Product::class.java))
doTest(jdbi)
}
@Test
fun testNativeKotlin(jdbi: Jdbi) {
jdbi.installPlugin(KotlinPlugin(false))
.registerRowMapper(KotlinMapper(Product::class, "p"))
.registerRowMapper(KotlinMapper(Tag::class))
.registerRowMapper(JoinRowMapper.forTypes(Tag::class.java, Product::class.java))
doTest(jdbi)
}
fun doTest(jdbi: Jdbi) {
val sql = """
SELECT
t.id, t.name,
p.id pid, p.tagId ptagId, p.primaryName pprimaryName
FROM Tag t JOIN Product P ON t.id = p.TagId
""".trimIndent()
val rows = jdbi.withHandle(
HandleCallback<List<JoinRow>, RuntimeException> { handle -> handle.createQuery(sql).mapTo<JoinRow>().list() }
)
assertNotNull(rows)
assertEquals(1, rows.size)
val joinRow = rows[0]
assertEquals(1, joinRow[Tag::class.java].id)
assertEquals("foo", joinRow[Tag::class.java].name)
assertEquals(2, joinRow[Product::class.java].id, "Product::id mismatch")
assertEquals("stuff", joinRow[Product::class.java].primaryName)
assertEquals(1, joinRow[Product::class.java].tagId)
}
}
| apache-2.0 | 599a04953023e8c19a9f02fb503db77e | 35.756757 | 129 | 0.659804 | 4.092277 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.