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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kue-framework/generator-kue | app/templates/src/main/kotlin/com/widgets/controllers/WidgetController.kt | 1 | 871 | package <%= basePackage %>.controllers
import com.fasterxml.jackson.databind.ObjectMapper
import <%= basePackage %>.models.dto.CreateWidgetRequest
import <%= basePackage %>.models.dto.widgetResponse
import <%= basePackage %>.services.WidgetService
import com.kue.route.json
import spark.Route
import javax.inject.Inject
class WidgetController @Inject constructor (val objectMapper: ObjectMapper, val widgetService: WidgetService) {
val create = json(Route() { req, res ->
val widgetRequest = objectMapper.readValue(req.body(), CreateWidgetRequest::class.java)
val widget = widgetService.create(widgetRequest)
widgetResponse(widget)
})
val list = json(Route() { req, res ->
widgetService.list().map { widgetResponse(it) }
})
val secureCreate = securedPolitely(create)
val secureList = securedPolitely(list)
}
| mit | cc81d16896c06fc678f94c080f5554a5 | 31.259259 | 111 | 0.727899 | 4.333333 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/listener/IRCMessageListener.kt | 1 | 2267 | /*
* Copyright 2016 Ross 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.chat.bukkit.irc.listener
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider
import com.rpkit.chat.bukkit.chatchannel.undirected.IRCComponent
import com.rpkit.players.bukkit.profile.RPKIRCProfileProvider
import org.pircbotx.hooks.ListenerAdapter
import org.pircbotx.hooks.events.MessageEvent
/**
* IRC message listener.
* Sends messages to chat channels when received in IRC.
*/
class IRCMessageListener(private val plugin: RPKChatBukkit): ListenerAdapter() {
override fun onMessage(event: MessageEvent) {
// Commands all extend ListenerAdapter as well, and have their own handling.
// This stops commands from being sent to chat.
if (event.message.startsWith("!")) return
val ircProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKIRCProfileProvider::class)
val user = event.user
// According to PircBotX documentation, user can be null if the hostmask doesn't match a user at creation time.
if (user != null) {
val senderIRCProfile = ircProfileProvider.getIRCProfile(user)
if (senderIRCProfile != null) {
val senderProfile = senderIRCProfile.profile
val chatChannelProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class)
val chatChannel = chatChannelProvider.getChatChannelFromIRCChannel(event.channel.name)
chatChannel?.sendMessage(senderProfile, null, event.message, chatChannel.directedPipeline, chatChannel.undirectedPipeline.filter { it !is IRCComponent })
}
}
}
} | apache-2.0 | c5a9c4d58aedbb69e68b3004152db594 | 43.470588 | 169 | 0.734892 | 4.693582 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/ui/SimpleButton.kt | 1 | 1108 | package com.soywiz.kpspemu.ui
import com.soywiz.korge.input.*
import com.soywiz.korge.scene.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
import com.soywiz.korim.font.*
fun Views.simpleButton(text: String, width: Int = 80, height: Int = 18, font: BitmapFont = debugBmpFont): View {
val colorOver = RGBA(0xA0, 0xA0, 0xA0, 0xFF)
val colorOut = RGBA(0x90, 0x90, 0x90, 0xFF)
return Container().apply {
val bg = solidRect(width, height, colorOut)
text(text, font = font, textSize = height.toDouble() - 2.0) {
this.name = "label"
this.x = 4.0
this.y = 2.0
//this.bgcolor = Colors.GREEN
this.autoSize = true
//this.autoSize = false
//this.textBounds.setBounds(0, 0, width - 8, height - 8)
//this.width = width - 8.0
//this.height = height - 8.0
//this.enabled = false
//this.mouseEnabled = false
//this.enabled = false
}
onOut { bg.colorMul = colorOut }
onOver { bg.colorMul = colorOver }
}
}
| mit | fa6776199384017c1c62300a3567cb03 | 33.625 | 112 | 0.577617 | 3.473354 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/ch/ethz/vppserver/ippclient/IppTag.kt | 1 | 16559 | package ch.ethz.vppserver.ippclient
import java.io.UnsupportedEncodingException
import java.nio.ByteBuffer
/**
* Copyright (C) 2008 ITS of ETH Zurich, Switzerland, Sarah Windler Burri
*
* 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, see
* <http:></http:>//www.gnu.org/licenses/>.
*/
object IppTag {
private const val MAJOR_VERSION: Byte = 0x01
private const val MINOR_VERSION: Byte = 0x01
private const val ATTRIBUTES_CHARSET = "attributes-charset"
private const val ATTRIBUTES_NATURAL_LANGUAGE = "attributes-natural-language"
private const val ATTRIBUTES_CHARSET_VALUE = "utf-8"
private const val ATTRIBUTES_NATURAL_LANGUAGE_VALUE = "en-us"
private const val ATTRIBUTES_INTEGER_VALUE_LENGTH: Short = 0x0004
private const val ATTRIBUTES_RANGE_OF_INT_VALUE_LENGTH: Short = 0x0008
private const val ATTRIBUTES_BOOLEAN_VALUE_LENGTH: Short = 0x0001
private const val ATTRIBUTES_RESOLUTION_VALUE_LENGTH: Short = 0x0009
private const val ATTRIBUTES_BOOLEAN_FALSE_VALUE: Byte = 0x00
private const val ATTRIBUTES_BOOLEAN_TRUE_VALUE: Byte = 0x01
private const val OPERATION_ATTRIBUTES_TAG: Byte = 0x01
private const val JOB_ATTRIBUTES_TAG: Byte = 0x02
private const val END_OF_ATTRIBUTES_TAG: Byte = 0x03
private const val PRINTER_ATTRIBUTES_TAG: Byte = 0x04
private const val UNSUPPORTED_ATTRIBUTES_TAG: Byte = 0x05
private const val SUBSCRIPTION_ATTRIBUTES_TAG: Byte = 0x06
private const val EVENT_NOTIFICATION_ATTRIBUTES_TAG: Byte = 0x07
private const val INTEGER_TAG: Byte = 0x21
private const val BOOLEAN_TAG: Byte = 0x22
private const val ENUM_TAG: Byte = 0x23
private const val RESOLUTION_TAG: Byte = 0x32
private const val RANGE_OF_INTEGER_TAG: Byte = 0x33
private const val TEXT_WITHOUT_LANGUAGE_TAG: Byte = 0x41
private const val NAME_WITHOUT_LANGUAGE_TAG: Byte = 0x42
private const val KEYWORD_TAG: Byte = 0x44
private const val URI_TAG: Byte = 0x45
private const val URI_SCHEME_TAG: Byte = 0x46
private const val CHARSET_TAG: Byte = 0x47
private const val NATURAL_LANGUAGE_TAG: Byte = 0x48
private const val MIME_MEDIA_TYPE_TAG: Byte = 0x49
private const val NULL_LENGTH: Short = 0
private var requestID = 0 // required attribute within operations (will increase with
/**
*
* @param ippBuf
* @param operation
* @param charset
* @param naturalLanguage
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getOperation(ippBuf: ByteBuffer, operation: Short, charset: String? = null, naturalLanguage: String? = null): ByteBuffer {
ippBuf.put(MAJOR_VERSION)
ippBuf.put(MINOR_VERSION)
ippBuf.putShort(operation)
ippBuf.putInt(++requestID)
ippBuf.put(OPERATION_ATTRIBUTES_TAG)
val outputIppBuf = getCharset(ippBuf, ATTRIBUTES_CHARSET, charset ?: ATTRIBUTES_CHARSET_VALUE)
return getNaturalLanguage(outputIppBuf, ATTRIBUTES_NATURAL_LANGUAGE, naturalLanguage ?: ATTRIBUTES_NATURAL_LANGUAGE_VALUE)
}
/**
*
* @param ippBuf
* @return
*/
fun getOperationAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(OPERATION_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @return
*/
fun getJobAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(JOB_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @return
*/
fun getSubscriptionAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(SUBSCRIPTION_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @return
*/
fun getEventNotificationAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(EVENT_NOTIFICATION_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @return
*/
fun getUnsupportedAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(UNSUPPORTED_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @return
*/
fun getPrinterAttributesTag(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(PRINTER_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getCharset(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, CHARSET_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getNaturalLanguage(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, NATURAL_LANGUAGE_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getUri(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, URI_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getUriScheme(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, URI_SCHEME_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getNameWithoutLanguage(ippBuf: ByteBuffer, attributeName: String?, value: String?): ByteBuffer {
ippBuf.put(NAME_WITHOUT_LANGUAGE_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
if (value != null) {
ippBuf.putShort(value.length.toShort())
ippBuf.put(IppUtil.toBytes(value))
} else {
ippBuf.putShort(NULL_LENGTH)
}
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getTextWithoutLanguage(ippBuf: ByteBuffer, attributeName: String?, value: String?): ByteBuffer {
ippBuf.put(TEXT_WITHOUT_LANGUAGE_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
if (value != null) {
ippBuf.putShort(value.length.toShort())
ippBuf.put(IppUtil.toBytes(value))
} else {
ippBuf.putShort(NULL_LENGTH)
}
return ippBuf
}
/**
* @param ippBuf
* @param attributeName
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getInteger(ippBuf: ByteBuffer, attributeName: String? = null): ByteBuffer {
ippBuf.put(INTEGER_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(NULL_LENGTH)
return ippBuf
}
/**
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getInteger(ippBuf: ByteBuffer, attributeName: String?, value: Int): ByteBuffer {
ippBuf.put(INTEGER_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(ATTRIBUTES_INTEGER_VALUE_LENGTH)
ippBuf.putInt(value)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getBoolean(ippBuf: ByteBuffer, attributeName: String? = null): ByteBuffer {
ippBuf.put(BOOLEAN_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(NULL_LENGTH)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getBoolean(ippBuf: ByteBuffer, attributeName: String?, value: Boolean): ByteBuffer {
ippBuf.put(BOOLEAN_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(ATTRIBUTES_BOOLEAN_VALUE_LENGTH)
if (value) {
ippBuf.put(ATTRIBUTES_BOOLEAN_TRUE_VALUE)
} else {
ippBuf.put(ATTRIBUTES_BOOLEAN_FALSE_VALUE)
}
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getEnum(ippBuf: ByteBuffer, attributeName: String? = null): ByteBuffer {
ippBuf.put(ENUM_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(NULL_LENGTH)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getEnum(ippBuf: ByteBuffer, attributeName: String?, value: Int): ByteBuffer {
ippBuf.put(ENUM_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(ATTRIBUTES_INTEGER_VALUE_LENGTH)
ippBuf.putInt(value)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getResolution(ippBuf: ByteBuffer, attributeName: String? = null): ByteBuffer{
ippBuf.put(RESOLUTION_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(NULL_LENGTH)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value1
* @param value2
* @param value3
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getResolution(ippBuf: ByteBuffer, attributeName: String?, value1: Int, value2: Int, value3: Byte): ByteBuffer {
ippBuf.put(RESOLUTION_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(ATTRIBUTES_RESOLUTION_VALUE_LENGTH)
ippBuf.putInt(value1)
ippBuf.putInt(value2)
ippBuf.put(value3)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getRangeOfInteger(ippBuf: ByteBuffer, attributeName: String? = null): ByteBuffer {
ippBuf.put(RANGE_OF_INTEGER_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(NULL_LENGTH)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value1
* @param value2
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
fun getRangeOfInteger(ippBuf: ByteBuffer, attributeName: String?, value1: Int, value2: Int): ByteBuffer {
ippBuf.put(RANGE_OF_INTEGER_TAG)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
ippBuf.putShort(ATTRIBUTES_RANGE_OF_INT_VALUE_LENGTH)
ippBuf.putInt(value1)
ippBuf.putInt(value2)
return ippBuf
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getMimeMediaType(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, MIME_MEDIA_TYPE_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
@JvmOverloads
fun getKeyword(ippBuf: ByteBuffer, attributeName: String? = null, value: String? = null): ByteBuffer {
return getUsAscii(ippBuf, KEYWORD_TAG, attributeName, value)
}
/**
*
* @param ippBuf
* @return
*/
fun getEnd(ippBuf: ByteBuffer): ByteBuffer {
ippBuf.put(END_OF_ATTRIBUTES_TAG)
return ippBuf
}
/**
*
* @param ippBuf
* @param tag
* @param attributeName
* @param value
* @return
* @throws UnsupportedEncodingException
*/
@Throws(UnsupportedEncodingException::class)
private fun getUsAscii(ippBuf: ByteBuffer, tag: Byte, attributeName: String?, value: String?): ByteBuffer {
ippBuf.put(tag)
if (attributeName != null) {
ippBuf.putShort(attributeName.length.toShort())
ippBuf.put(IppUtil.toBytes(attributeName))
} else {
ippBuf.putShort(NULL_LENGTH)
}
if (value != null) {
ippBuf.putShort(value.length.toShort())
ippBuf.put(IppUtil.toBytes(value))
} else {
ippBuf.putShort(NULL_LENGTH)
}
return ippBuf
}
}
| lgpl-3.0 | 68cf960507fe07099f59cb2fd14b3df9 | 29.217153 | 130 | 0.630352 | 4.193213 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/test/kotlin/com/almasb/fxgl/texture/AnimatedTextureTest.kt | 1 | 4972 | /*
* 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.texture
import javafx.geometry.HorizontalDirection
import javafx.geometry.Rectangle2D
import javafx.scene.image.Image
import javafx.scene.paint.Color
import javafx.util.Duration
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
class AnimatedTextureTest {
private lateinit var texture: AnimatedTexture
companion object {
// BLACK | WHITE
private val image: Image = ColoredTexture(320, 320, Color.BLACK)
.superTexture(ColoredTexture(320, 320, Color.WHITE), HorizontalDirection.RIGHT).image
}
@BeforeEach
fun setUp() {
texture = Texture(image).toAnimatedTexture(2, Duration.seconds(1.0))
}
@Test
fun `Next frame updates after counter reaches frame duration`() {
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
texture.play()
texture.onUpdate(0.1)
texture.onUpdate(0.1)
texture.onUpdate(0.1)
texture.onUpdate(0.1)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// should now move one frame
texture.onUpdate(0.1)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
}
@Test
fun `Play animation ends with last frame`() {
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
texture.play()
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// move single frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
// animation is complete with play() we stop on last frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
texture.onUpdate(2.0)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
}
@Test
fun `Loop animation repeats from 1st frame`() {
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
texture.loop()
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// move single frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
// animation is complete with loop() we move to 1st frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
}
@Test
fun `Loop with no override`() {
val channel = AnimationChannel(image, Duration.seconds(1.0), 2)
texture.loopNoOverride(channel)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// move single frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
// this overrides channel
texture.loopAnimationChannel(channel)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// move single frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
// this does not
texture.loopNoOverride(channel)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
}
@Test
fun `Stop animation ends with 1st frame`() {
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
texture.loop()
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// move single frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(320.0, 0.0, 320.0, 320.0)))
// animation is complete with loop() we move to 1st frame
texture.onUpdate(0.5)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
// we stop so 1st frame
texture.stop()
texture.onUpdate(2.0)
assertThat(texture.viewport, `is`(Rectangle2D(0.0, 0.0, 320.0, 320.0)))
}
@Test
fun `Run code on cycle finished`() {
var count = 0
texture.loop()
texture.onUpdate(0.5)
texture.onUpdate(0.5)
assertThat(count, `is`(0))
texture.onCycleFinished = Runnable { count++ }
texture.onUpdate(0.5)
texture.onUpdate(0.5)
assertThat(count, `is`(1))
// we only advance 1 frame at a time, so
texture.onUpdate(0.5)
assertThat(count, `is`(1))
texture.onUpdate(0.5)
assertThat(count, `is`(2))
}
} | mit | a3d77d3ec055854595d55834d5f15845 | 26.938202 | 101 | 0.619469 | 3.424242 | false | false | false | false |
xfmax/BasePedo | app/src/main/java/com/base/basepedo/service/StepService.kt | 1 | 10511 | package com.base.basepedo.service
import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.os.RemoteException
import android.support.v4.app.NotificationCompat
import android.util.Log
import com.base.basepedo.R
import com.base.basepedo.base.StepMode
import com.base.basepedo.callback.StepCallBack
import com.base.basepedo.config.Constant
import com.base.basepedo.pojo.StepData
import com.base.basepedo.ui.MainActivity
import com.base.basepedo.utils.CountDownTimer
import com.base.basepedo.utils.DbUtils
import java.text.SimpleDateFormat
import java.util.*
@TargetApi(Build.VERSION_CODES.CUPCAKE)
class StepService : Service(), StepCallBack {
private val TAG = "StepService"
private val DB_NAME = "basepedo"
private var nm: NotificationManager? = null
private var builder: NotificationCompat.Builder? = null
private val messenger = Messenger(MessenerHandler())
private var mBatInfoReceiver: BroadcastReceiver? = null
private var mWakeLock: WakeLock? = null
private var time: TimeCount? = null
//当天的日期
private var CURRENTDATE = ""
private val todayDate: String
private get() {
val date = Date(System.currentTimeMillis())
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(date)
}
override fun onCreate() {
super.onCreate()
Log.v(TAG, "onCreate")
initBroadcastReceiver()
startStep()
startTimeCount()
}
private fun initBroadcastReceiver() {
Log.v(TAG, "initBroadcastReceiver")
val filter = IntentFilter()
// 屏幕灭屏广播
filter.addAction(Intent.ACTION_SCREEN_OFF)
//日期修改
filter.addAction(Intent.ACTION_DATE_CHANGED)
//关机广播
filter.addAction(Intent.ACTION_SHUTDOWN)
// 屏幕亮屏广播
filter.addAction(Intent.ACTION_SCREEN_ON)
// 屏幕解锁广播
filter.addAction(Intent.ACTION_USER_PRESENT)
// 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
// example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
// 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
mBatInfoReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (Intent.ACTION_SCREEN_ON == action) {
Log.v(TAG, "screen on")
} else if (Intent.ACTION_SCREEN_OFF == action) {
Log.v(TAG, "screen off")
//改为60秒一存储
duration = 60000
//解决某些厂商的rom在锁屏后收不到sensor的回调
val runnable = Runnable { startStep() }
Handler().postDelayed(runnable, SCREEN_OFF_RECEIVER_DELAY)
} else if (Intent.ACTION_USER_PRESENT == action) {
Log.v(TAG, "screen unlock")
save()
//改为30秒一存储
duration = 30000
} else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS == intent.action) {
Log.v(TAG, " receive Intent.ACTION_CLOSE_SYSTEM_DIALOGS")
//保存一次
save()
} else if (Intent.ACTION_SHUTDOWN == intent.action) {
Log.v(TAG, " receive ACTION_SHUTDOWN")
save()
} else if (Intent.ACTION_DATE_CHANGED == intent.action) {
Log.v(TAG, " receive ACTION_DATE_CHANGED")
initTodayData()
clearStepData()
Log.v(TAG, "归零数据:" + StepMode.CURRENT_SETP)
Step(StepMode.CURRENT_SETP)
}
}
}
registerReceiver(mBatInfoReceiver, filter)
}
private fun startStep() {
var mode: StepMode = StepInPedometer(this, this)
var isAvailable = mode.step
if (!isAvailable) {
mode = StepInAcceleration(this, this)
isAvailable = mode.step
if (isAvailable) {
Log.v(TAG, "acceleration can execute!")
}
}
}
private fun startTimeCount() {
time = TimeCount(duration.toLong(), 1000)
time!!.start()
}
override fun Step(stepNum: Int) {
StepMode.CURRENT_SETP = stepNum
Log.v(TAG, "Step:$stepNum")
updateNotification("今日步数:$stepNum 步")
}
override fun onStart(intent: Intent, startId: Int) {
super.onStart(intent, startId)
}
override fun onBind(intent: Intent): IBinder {
return messenger.binder
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
initTodayData()
updateNotification("今日步数:" + StepMode.CURRENT_SETP + " 步")
return START_STICKY
}
private fun initTodayData() {
CURRENTDATE = todayDate
DbUtils.createDb(this, DB_NAME)
//获取当天的数据,用于展示
val list = DbUtils.getQueryByWhere(StepData::class.java, "today", arrayOf(CURRENTDATE))
if (list.size == 0 || list.isEmpty()) {
StepMode.CURRENT_SETP = 0
} else if (list.size == 1) {
StepMode.CURRENT_SETP = list[0].step!!.toInt()
} else {
Log.v(TAG, "It's wrong!")
}
}
/**
* update notification
*/
private fun updateNotification(content: String) {
builder = NotificationCompat.Builder(this)
builder!!.priority = Notification.PRIORITY_MIN
val contentIntent = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java), 0)
builder!!.setContentIntent(contentIntent)
builder!!.setSmallIcon(R.mipmap.ic_launcher)
builder!!.setTicker("BasePedo")
builder!!.setContentTitle("BasePedo")
//设置不可清除
builder!!.setOngoing(true)
builder!!.setContentText(content)
val notification = builder!!.build()
startForeground(0, notification)
nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm!!.notify(R.string.app_name, notification)
}
override fun onUnbind(intent: Intent): Boolean {
return super.onUnbind(intent)
}
private fun save() {
val tempStep = StepMode.CURRENT_SETP
val list = DbUtils.getQueryByWhere(StepData::class.java, "today", arrayOf(CURRENTDATE))
if (list.size == 0 || list.isEmpty()) {
val data = StepData()
data.today = CURRENTDATE
data.step = tempStep.toString() + ""
DbUtils.insert(data)
} else if (list.size == 1) {
val data = list[0]
data.step = tempStep.toString() + ""
DbUtils.update(data)
} else {
}
}
private fun clearStepData() {
StepMode.CURRENT_SETP = 0
}
override fun onDestroy() {
//取消前台进程
stopForeground(true)
DbUtils.closeDb()
unregisterReceiver(mBatInfoReceiver)
val intent = Intent(this, StepService::class.java)
startService(intent)
super.onDestroy()
}
// private void unlock(){
// setLockPatternEnabled(android.provider.Settings.Secure.LOCK_PATTERN_ENABLED,false);
// }
//
// private void setLockPatternEnabled(String systemSettingKey, boolean enabled) {
// //推荐使用
// android.provider.Settings.Secure.putInt(getContentResolver(), systemSettingKey,enabled ? 1 : 0);
// }
@Synchronized
private fun getLock(context: Context): WakeLock? {
if (mWakeLock != null) {
if (mWakeLock?.isHeld!!) mWakeLock?.release()
mWakeLock = null
}
if (mWakeLock == null) {
val mgr = context
.getSystemService(Context.POWER_SERVICE) as PowerManager
mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
StepService::class.java.name)
mWakeLock?.setReferenceCounted(true)
val c = Calendar.getInstance()
c.timeInMillis = System.currentTimeMillis()
val hour = c[Calendar.HOUR_OF_DAY]
if (hour >= 23 || hour <= 6) {
mWakeLock?.acquire(5000)
} else {
mWakeLock?.acquire(300000)
}
}
return mWakeLock
}
private class MessenerHandler : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
Constant.MSG_FROM_CLIENT -> try {
val messenger = msg.replyTo
val replyMsg = Message.obtain(null, Constant.MSG_FROM_SERVER)
val bundle = Bundle()
bundle.putInt("step", StepMode.CURRENT_SETP)
replyMsg.data = bundle
messenger.send(replyMsg)
} catch (e: RemoteException) {
e.printStackTrace()
}
else -> super.handleMessage(msg)
}
}
}
internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onFinish() {
// 如果计时器正常结束,则开始计步
time!!.cancel()
save()
startTimeCount()
}
override fun onTick(millisUntilFinished: Long) {}
}
companion object {
private const val SCREEN_OFF_RECEIVER_DELAY = 500L
//默认为30秒进行一次存储
private var duration = 30000
}
}
| apache-2.0 | a7f51d93e47c0aa595d3018322129049 | 33.716263 | 135 | 0.592943 | 4.215546 | false | false | false | false |
dslomov/intellij-community | plugins/settings-repository/src/settings/IcsSettings.kt | 5 | 2853 | package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectWriter
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.Time
import java.io.File
private val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = DefaultPrettyPrinter.NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline()) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline()) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: File) {
val serialized = ObjectMapper().writer<ObjectWriter>(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size() <= 2) {
FileUtil.delete(settingsFile)
}
else {
FileUtil.writeToFile(settingsFile, serialized)
}
}
fun loadSettings(settingsFile: File): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile, javaClass<IcsSettings>())
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
class IcsSettings {
var shareProjectWorkspace = false
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
}
JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
JsonIgnore
val path: String?
get() {
if (url == null) {
return null
}
else {
var fileName = PathUtilRt.getFileName(url!!)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length() - suffix.length())
}
// the convention is that the .git extension should be used for bare repositories
return "${FileUtil.sanitizeName(fileName)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
} | apache-2.0 | e70ea5c8523eb1b3b74e803d07342293 | 28.729167 | 101 | 0.720995 | 4.270958 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/coroutine/select/FizzAndBuzzSelect.kt | 1 | 1229 | package tutorial.coroutine.select
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
fun CoroutineScope.fizz() = produce {
while (true) {
// 每 300 毫秒发送一个 "Fizz"
delay(300)
send("Fizz")
}
}
fun CoroutineScope.buzz() = produce {
while (true) {
// 每 300 毫秒发送一个 "Fizz"
delay(500)
send("Buzz")
}
}
suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
select<Unit> { // 意味着该 select 表达式不返回任何结果
fizz.onReceive { value -> // 这是第一个 select 子句
println("fizz -> '$value'")
}
buzz.onReceive { value -> // 这是第二个 select 子句
println("buzz -> '$value'")
}
}
}
fun main() = runBlocking {
val fizz = fizz()
val buzz = buzz()
repeat(7) {
selectFizzBuzz(fizz, buzz)
}
coroutineContext.cancelChildren() // 取消 fizz 和 buzz 协程
}
| bsd-2-clause | 9d331b95481d82443ba53bbe9841962f | 24.222222 | 88 | 0.640529 | 3.795987 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFavoritePutResolver.kt | 4 | 1254 | package eu.kanade.tachiyomi.data.database.resolvers
import android.content.ContentValues
import com.pushtorefresh.storio.sqlite.StorIOSQLite
import com.pushtorefresh.storio.sqlite.operations.put.PutResolver
import com.pushtorefresh.storio.sqlite.operations.put.PutResult
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import eu.kanade.tachiyomi.data.database.inTransactionReturn
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.tables.MangaTable
class MangaFavoritePutResolver : PutResolver<Manga>() {
override fun performPut(db: StorIOSQLite, manga: Manga) = db.inTransactionReturn {
val updateQuery = mapToUpdateQuery(manga)
val contentValues = mapToContentValues(manga)
val numberOfRowsUpdated = db.lowLevel().update(updateQuery, contentValues)
PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table())
}
fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder()
.table(MangaTable.TABLE)
.where("${MangaTable.COL_ID} = ?")
.whereArgs(manga.id)
.build()
fun mapToContentValues(manga: Manga) = ContentValues(1).apply {
put(MangaTable.COL_FAVORITE, manga.favorite)
}
}
| apache-2.0 | f80ae9b326bb86cac9077fc140c46e5b | 37 | 86 | 0.751196 | 4.354167 | false | false | false | false |
madtcsa/AppManager | app/src/main/java/com/md/appmanager/utils/AppPreferences.kt | 1 | 3369 | package com.md.appmanager.utils
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.md.appmanager.R
import java.util.HashSet
class AppPreferences(private val context: Context) {
private val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
private val editor: SharedPreferences.Editor
init {
this.editor = sharedPreferences.edit()
}
var rootStatus: Int
get() = sharedPreferences.getInt(KeyIsRooted, 0)
set(rootStatus) {
editor.putInt(KeyIsRooted, rootStatus)
editor.commit()
}
val primaryColorPref: Int
get() = sharedPreferences.getInt(KeyPrimaryColor, context.resources.getColor(R.color.primary))
fun setPrimaryColorPref(res: Int?) {
editor.putInt(KeyPrimaryColor, res!!)
editor.commit()
}
val fabColorPref: Int
get() = sharedPreferences.getInt(KeyFABColor, context.resources.getColor(R.color.fab))
fun setFABColorPref(res: Int?) {
editor.putInt(KeyFABColor, res!!)
editor.commit()
}
var navigationBlackPref: Boolean?
get() = sharedPreferences.getBoolean(KeyNavigationBlack, false)
set(res) {
editor.putBoolean(KeyNavigationBlack, res!!)
editor.commit()
}
var fabShowPref: Boolean?
get() = sharedPreferences.getBoolean(KeyFABShow, false)
set(res) {
editor.putBoolean(KeyFABShow, res!!)
editor.commit()
}
var customFilename: String
get() = sharedPreferences.getString(KeyCustomFilename, "1")
set(res) {
editor.putString(KeyCustomFilename, res)
editor.commit()
}
var sortMode: String
get() = sharedPreferences.getString(KeySortMode, "1")
set(res) {
editor.putString(KeySortMode, res)
editor.commit()
}
var customPath: String
get() = sharedPreferences.getString(KeyCustomPath, UtilsApp.defaultAppFolder.getPath())
set(path) {
editor.putString(KeyCustomPath, path)
editor.commit()
}
var favoriteApps: MutableSet<String>
get() = sharedPreferences.getStringSet(KeyFavoriteApps, HashSet<String>())
set(favoriteApps) {
editor.remove(KeyFavoriteApps)
editor.commit()
editor.putStringSet(KeyFavoriteApps, favoriteApps)
editor.commit()
}
var hiddenApps: MutableSet<String>
get() = sharedPreferences.getStringSet(KeyHiddenApps, HashSet<String>())
set(hiddenApps) {
editor.remove(KeyHiddenApps)
editor.commit()
editor.putStringSet(KeyHiddenApps, hiddenApps)
editor.commit()
}
companion object {
val KeyPrimaryColor = "prefPrimaryColor"
val KeyFABColor = "prefFABColor"
val KeyFABShow = "prefFABShow"
val KeyNavigationBlack = "prefNavigationBlack"
val KeyCustomFilename = "prefCustomFilename"
val KeySortMode = "prefSortMode"
val KeyIsRooted = "prefIsRooted"
val KeyCustomPath = "prefCustomPath"
// List
val KeyFavoriteApps = "prefFavoriteApps"
val KeyHiddenApps = "prefHiddenApps"
}
}
| gpl-3.0 | 7631a21fc17a78dc8fcc7a9d2b0b54b0 | 29.351351 | 109 | 0.640546 | 4.583673 | false | false | false | false |
nguyenhoanglam/ImagePicker | imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/ui/imagepicker/FolderFragment.kt | 1 | 4772 | /*
* Copyright (C) 2021 Image Picker
* Author: Nguyen Hoang Lam <[email protected]>
*/
package com.nguyenhoanglam.imagepicker.ui.imagepicker
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.nguyenhoanglam.imagepicker.R
import com.nguyenhoanglam.imagepicker.databinding.ImagepickerFragmentBinding
import com.nguyenhoanglam.imagepicker.helper.ImageHelper
import com.nguyenhoanglam.imagepicker.helper.LayoutManagerHelper
import com.nguyenhoanglam.imagepicker.listener.OnFolderClickListener
import com.nguyenhoanglam.imagepicker.model.CallbackStatus
import com.nguyenhoanglam.imagepicker.model.GridCount
import com.nguyenhoanglam.imagepicker.model.Result
import com.nguyenhoanglam.imagepicker.ui.adapter.FolderPickerAdapter
import com.nguyenhoanglam.imagepicker.widget.GridSpacingItemDecoration
class FolderFragment : BaseFragment() {
private var _binding: ImagepickerFragmentBinding? = null
private val binding get() = _binding!!
private lateinit var gridCount: GridCount
private var viewModel: ImagePickerViewModel? = null
private lateinit var folderAdapter: FolderPickerAdapter
private lateinit var gridLayoutManager: GridLayoutManager
private lateinit var itemDecoration: GridSpacingItemDecoration
companion object {
const val GRID_COUNT = "GridCount"
fun newInstance(gridCount: GridCount): FolderFragment {
val fragment = FolderFragment()
val args = Bundle()
args.putParcelable(ImageFragment.GRID_COUNT, gridCount)
fragment.arguments = args
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
gridCount = arguments?.getParcelable(GRID_COUNT)!!
viewModel = activity?.run {
ViewModelProvider(this, ImagePickerViewModelFactory(requireActivity().application)).get(
ImagePickerViewModel::class.java
)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val config = viewModel!!.getConfig()
folderAdapter = FolderPickerAdapter(requireActivity(), activity as OnFolderClickListener)
gridLayoutManager = LayoutManagerHelper.newInstance(requireContext(), gridCount)
itemDecoration = GridSpacingItemDecoration(
gridLayoutManager.spanCount,
resources.getDimension(R.dimen.imagepicker_grid_spacing).toInt()
)
_binding = ImagepickerFragmentBinding.inflate(inflater, container, false)
binding.apply {
root.setBackgroundColor(Color.parseColor(config.backgroundColor))
progressIndicator.setIndicatorColor(Color.parseColor(config.progressIndicatorColor))
recyclerView.apply {
setHasFixedSize(true)
layoutManager = gridLayoutManager
addItemDecoration(itemDecoration)
adapter = folderAdapter
}
}
viewModel?.result?.observe(viewLifecycleOwner, {
handleResult(it)
})
return binding.root
}
private fun handleResult(result: Result) {
if (result.status is CallbackStatus.SUCCESS && result.images.isNotEmpty()) {
val folders = ImageHelper.folderListFromImages(result.images)
folderAdapter.setData(folders)
binding.recyclerView.visibility = View.VISIBLE
} else {
binding.recyclerView.visibility = View.GONE
}
binding.apply {
emptyText.visibility =
if (result.status is CallbackStatus.SUCCESS && result.images.isEmpty()) View.VISIBLE else View.GONE
progressIndicator.visibility =
if (result.status is CallbackStatus.FETCHING) View.VISIBLE else View.GONE
}
}
override fun handleOnConfigurationChanged() {
binding.recyclerView.removeItemDecoration(itemDecoration)
val newSpanCount =
LayoutManagerHelper.getSpanCountForCurrentConfiguration(requireContext(), gridCount)
itemDecoration =
GridSpacingItemDecoration(
gridLayoutManager.spanCount,
resources.getDimension(R.dimen.imagepicker_grid_spacing).toInt()
)
gridLayoutManager.spanCount = newSpanCount
binding.recyclerView.addItemDecoration(itemDecoration)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | apache-2.0 | 618e3e0f9899578859729c6f1159b1af | 35.435115 | 115 | 0.701593 | 5.203926 | false | false | false | false |
shyiko/ktlint | ktlint/src/main/kotlin/com/pinterest/ktlint/internal/ApplyToIDEAProjectSubCommand.kt | 1 | 1064 | package com.pinterest.ktlint.internal
import com.pinterest.ktlint.KtlintCommandLine
import picocli.CommandLine
@CommandLine.Command(
description = [
"Update Intellij IDEA project settings"
],
aliases = ["--apply-to-idea-project"],
mixinStandardHelpOptions = true,
versionProvider = KtlintVersionProvider::class
)
class ApplyToIDEAProjectSubCommand : Runnable {
@CommandLine.ParentCommand
private lateinit var ktlintCommand: KtlintCommandLine
@CommandLine.Spec
private lateinit var commandSpec: CommandLine.Model.CommandSpec
@CommandLine.Option(
names = ["-y"],
description = ["Overwrite existing Kotlin codestyle settings without asking"]
)
private var forceApply: Boolean = false
override fun run() {
commandSpec.commandLine().printHelpOrVersionUsage()
ApplyToIDEACommandHelper(
true,
forceApply,
ktlintCommand.android
).apply()
}
companion object {
const val COMMAND_NAME = "applyToIDEAProject"
}
}
| mit | e51d56cb9e75c16cf2e652988d042921 | 25.6 | 85 | 0.68703 | 4.995305 | false | false | false | false |
eugeis/ee | ee-lang_gen/src/main/kotlin/ee/lang/gen/kt/KotlinLangGen.kt | 1 | 7583 | package ee.lang.gen.kt
import ee.common.ext.ifElse
import ee.common.ext.joinSurroundIfNotEmptyToString
import ee.common.ext.then
import ee.common.ext.toUnderscoredUpperCase
import ee.lang.*
import ee.lang.gen.DerivedNames
import ee.lang.gen.isNative
fun <T : ItemI<*>> T.toKotlinEMPTY(c: GenerationContext, derived: String): String {
return (this.parent() == n).ifElse("\"\"", { "${c.n(this, derived)}.EMPTY" })
}
fun <T : AttributeI> T.toKotlinEMPTY(c: GenerationContext, derived: String): String {
return type().toKotlinEMPTY(c, derived)
}
fun <T : AttributeI> T.toKotlinTypeSingle(c: GenerationContext, api: String): String {
return type().isNative().ifElse({ c.n(type(), api) }, { "${c.n(type(), api)}<*>" })
}
fun <T : AttributeI> T.toKotlinDslTypeDef(c: GenerationContext, api: String): String {
return """${isMulti().ifElse({ "ListMultiHolder<${toKotlinTypeSingle(c, api)}>" },
{ toKotlinTypeSingle(c, api) })}${isNullable().then("?")}"""
}
fun <T : AttributeI> T.toKotlinTypeSingleNoGeneric(c: GenerationContext, api: String): String {
return type().isNative().ifElse({ c.n(type(), api) }, { c.n(type(), api) })
}
fun <T : AttributeI> T.toKotlinTypeSingleClass(c: GenerationContext, api: String): String {
return type().isNative().ifElse({ c.n(type(), api) }, { c.n(type(), api) })
}
fun <T : AttributeI> T.toKotlinDslTypeDefNoGeneric(c: GenerationContext, api: String): String {
return """${isMulti().ifElse({ "ListMultiHolder<${toKotlinTypeSingleNoGeneric(c, api)}>" },
{ toKotlinTypeSingleNoGeneric(c, api) })}${isNullable().then("?")}"""
}
fun <T : AttributeI> T.toKotlinDslBuilderMethodsIB(c: GenerationContext, api: String): String {
val value = (name() == "value").ifElse("aValue", "value")
val bool = type() == n.Boolean
return isMulti().ifElse({
"""
fun ${name()}(vararg $value: ${toKotlinTypeSingle(c, api)}): B"""
}, {
"""
fun ${name()}($value: ${toKotlinDslTypeDef(c, api)}): B${bool.then {
"""
fun ${name()}(): B = ${name()}(true)
fun not${name().capitalize()}(): B = ${name()}(false)"""
}}"""
})
}
fun <T : AttributeI> T.toKotlinDslBuilderMethodsI(c: GenerationContext, api: String): String {
val value = (name() == "value").ifElse("aValue", "value")
return """
fun ${(type() == n.Boolean && !isMulti()).ifElse({ "is${name().capitalize()}" },
{ name() })}(): ${toKotlinDslTypeDef(c, api)}${nonFluent().isNotBlank().then {
"""
fun ${nonFluent()}($value: ${toKotlinTypeSingle(c, api)}): ${toKotlinTypeSingle(c, api)}
fun ${nonFluent()}($value: ${toKotlinTypeSingle(c, api)}.() -> Unit = {}): ${toKotlinTypeSingle(c, api)}"""
}}"""
}
fun <T : AttributeI> T.toKotlinDslBuilderMethods(c: GenerationContext, derived: String, api: String): String {
val value = (name() == "value").ifElse("aValue", "value")
val override = (derived != api).ifElse("override ", "")
return """${isMulti().ifElse({
"""
${override}fun ${name()}(): ${toKotlinDslTypeDef(c,
api)} = itemAsList(${name().toUnderscoredUpperCase()}, ${toKotlinTypeSingleNoGeneric(c,
api)}::class.java, true)
${override}fun ${name()}(vararg $value: ${toKotlinTypeSingle(c,
api)}): B = apply { ${name()}().addItems(value.asList()) }"""
}, {
"""
${override}fun ${(type() == n.Boolean).ifElse({ "is${name().capitalize()}" }, { name() })}(): ${toKotlinDslTypeDef(
c,
api)} = attr(${name().toUnderscoredUpperCase()}${isNullable().not().then {
", { ${value().toString().isEmpty().ifElse(toKotlinEMPTY(c, derived), value())} }"
}})
${override}fun ${name()}($value: ${toKotlinDslTypeDef(c,
api)}): B = apply { attr(${name().toUnderscoredUpperCase()}, $value) }"""
})}${nonFluent().isNotBlank().then {
"""
${override}fun ${nonFluent()}($value: ${toKotlinTypeSingle(c, api)}): ${toKotlinTypeSingle(c,
api)} = applyAndReturn { ${isMulti().ifElse({
"""${name()}().addItem($value); value"""
}, { """${name()}().addItem($value)""" })} }
${override}fun ${nonFluent()}($value: ${toKotlinTypeSingle(c, api)}.() -> Unit): ${toKotlinTypeSingle(c,
api)} = ${nonFluent()}(${toKotlinTypeSingleClass(c, derived)}($value))"""
}}"""
}
val specialEmptyObjects = setOf("CompilationUnit", "LogicUnit")
// isMulti holder for general types (like 'superUnitFor') must not be used as target for dynamic DSL objects,
// like "object commands : Command... {..}"
val generalTypes = setOf("Item", "Composite", "CompilationUnit", "LogicUnit", "Type", "Command", "Controller")
fun <T : AttributeI> T.toKotlinCompanionObjectName(): String {
return """ val ${name().toUnderscoredUpperCase()} = "${generalTypes.contains(type().name()).then(
"_")}_${name()}""""
}
fun <T : CompositeI<*>> T.toKotlinDslBuilderI(c: GenerationContext, api: String = DerivedNames.API): String {
val props = items().filterIsInstance(AttributeI::class.java)
return """
interface ${c.n(this, api)}<B : ${c.n(this, api)}<B>> : ${c.n(derivedFrom(),
api)}<B> {${props.joinSurroundIfNotEmptyToString(nL) {
it.toKotlinDslBuilderMethodsIB(c, api)
}}${props.joinSurroundIfNotEmptyToString(nL) { it.toKotlinDslBuilderMethodsI(c, api) }}
}"""
}
fun <T : CompositeI<*>> T.toKotlinDslBuilder(c: GenerationContext, derived: String = DerivedNames.IMPL,
api: String = DerivedNames.API): String {
val props = items().filterIsInstance(AttributeI::class.java)
val multiProps = props.filter { it.isMulti() }
val target = c.n(this, derived)
return """
open class ${c.n(this, derived)}(adapt: ${c.n(this, derived)}.() -> Unit = {}) : ${
c.n(this, derived)}B<${c.n(this,
derived)}>(adapt) {
companion object {
val EMPTY = ${specialEmptyObjects.contains(target).ifElse({ "${target}Empty" }, {
"$target { name(ItemEmpty.name()) }.apply<$target> { init() }"
})}
}
}
open class ${c.n(this, derived)}B<B : ${c.n(this, api)}<B>>(adapt: B.() -> Unit = {}) : ${c.n(derivedFrom(),
derived)}B<B>(adapt)${(derived != api).then { ", ${c.n(this, DerivedNames.API)}<B>" }} {${
props.joinSurroundIfNotEmptyToString(nL,
prefix = nL) { it.toKotlinDslBuilderMethods(c, derived, api) }}${multiProps.isNotEmpty().then {
"""
override fun fillSupportsItems() {${multiProps.joinSurroundIfNotEmptyToString(nL,
prefix = nL) { " ${it.name()}()" }}
super.fillSupportsItems()
}"""
}}${props.isNotEmpty().then {
"""
companion object {${props.joinSurroundIfNotEmptyToString(nL, prefix = nL) { it.toKotlinCompanionObjectName() }}
}"""
}}
}
"""
}
fun <T : ItemI<*>> T.toKotlinObjectTreeCompilationUnit(c: GenerationContext,
derived: String = DerivedNames.DSL_TYPE): String {
return """ val ${c.n(this, derived)} = ${c.n(l.CompilationUnit, derived)}${
derivedFrom().isNotEMPTY().then {
" { derivedFrom(${c.n(derivedFrom(), derived)}) }"
}}"""
}
fun <T : CompositeI<*>> T.toKotlinDslObjectTree(c: GenerationContext, derived: String = DerivedNames.DSL_TYPE): String {
return """
object ${c.n(this)} : ${c.n(l.StructureUnit)}({ namespace("${namespace()}") }) {
${items().filter { !(it.name() == "MultiHolder") }.joinSurroundIfNotEmptyToString(nL) {
it.toKotlinObjectTreeCompilationUnit(c, derived)
}}
object MultiHolder : CompilationUnit({ derivedFrom(Item) }) {
val T = G { type(Item) }
}
}"""
} | apache-2.0 | 6e37f1960739e813f3e9f5dc91b666fb | 42.090909 | 120 | 0.608598 | 3.642171 | false | false | false | false |
EmmanuelMess/Simple-Accounting | SimpleAccounting/app/src/test/java/com/emmanuelmess/simpleaccounting/MainActivityTest.kt | 1 | 2884 | package com.emmanuelmess.simpleaccounting
import android.content.Context
import android.content.SharedPreferences
import com.emmanuelmess.simpleaccounting.activities.MainActivity
import com.emmanuelmess.simpleaccounting.activities.views.LedgerView
import com.emmanuelmess.simpleaccounting.fragments.EditRowFragment
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.junit.Before
import org.junit.Ignore
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.android.controller.ActivityController
@RunWith(RobolectricTestRunner::class)
@Ignore
open class MainActivityTest {
protected lateinit var context: Context
protected lateinit var sharedPreferences: SharedPreferences
protected lateinit var activityController: ActivityController<MainActivity>
protected lateinit var activity: MainActivity
protected lateinit var table: LedgerView
protected lateinit var fab: FloatingActionButton
private var useFragmentExceptionHack = true
@Before
fun setUp() {
startSetUp()
/*
* All SharedPreferences editing calls must be done before this point.
* @see #endSetUp()
*/
endSetUp()
}
protected open fun startSetUp() {
context = RuntimeEnvironment.application.applicationContext
sharedPreferences = context.getSharedPreferences(MainActivity.PREFS_NAME, Context.MODE_PRIVATE)
if (useFragmentExceptionHack) {
Robolectric.getForegroundThreadScheduler().pause()//Fragment throws IllegalStateException, this hack fixes Robolectric issue#4021
}
setShowTutorial(false)
}
/**
* This is a hack, used to circumvent a call to park() that never ends.
* In this method go all calls for creating and after creating an Activity.
*/
protected open fun endSetUp() {
activityController = Robolectric.buildActivity(MainActivity::class.java)
.create().start().resume().visible()
activity = activityController.get()
table = activity.findViewById(R.id.table)
fab = activity.findViewById(R.id.fab)
}
/**
* This hack fixes a IllegalStateException thrown by Fragments, but breaks AsyncTasks
*/
protected fun useFragmentExceptionHack(useFragmentExceptionHack: Boolean) {
this.useFragmentExceptionHack = useFragmentExceptionHack
}
protected fun createNewRow() {
fab.callOnClick()
shadowOf(activity).clickMenuItem(R.id.action_done)
}
protected fun createNewRow(credit: String, debit: String) {
fab.callOnClick()
val fragment = activity.supportFragmentManager
.findFragmentById(R.id.fragmentContainer) as EditRowFragment
shadowOf(activity).clickMenuItem(R.id.action_done)
}
private fun setShowTutorial(show: Boolean) {
sharedPreferences.edit().putBoolean(MainActivity.PREFS_FIRST_RUN, show).commit()
}
} | gpl-3.0 | 36c4410fec13b3ea51816c9aa1a0d00e | 31.41573 | 132 | 0.797157 | 4.430108 | false | false | false | false |
prengifo/VEF-Exchange-Android-App | mobile/src/main/java/melquelolea/vefexchange/widget/VefExchangeWidget.kt | 1 | 1741 | package melquelolea.vefexchange.widget
import android.app.AlarmManager
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.util.Log
import melquelolea.vefexchange.services.UpdateDataService
/**
* Implementation of App Widget functionality.
*/
class VefExchangeWidget : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
//Start the background service to update the widgets
ContextCompat.startForegroundService(context, Intent(context, UpdateDataService::class.java))
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES
val job = JobInfo.Builder(JOB_ID,
ComponentName(context.packageName,
UpdateDataService::class.java.name))
.setPersisted(true)
.setPeriodic(interval)
.build()
jobScheduler.schedule(job)
Log.d(TAG, "setting scheduled job for: " + interval)
}
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
}
override fun onDisabled(context: Context) {
// Enter relevant functionality for when the last widget is disabled
}
companion object {
private val TAG = VefExchangeWidget::class.java.simpleName
private val JOB_ID = 44
}
}
| mit | 05ee2775f449c6a21c6418afd301b02b | 32.480769 | 105 | 0.72085 | 4.756831 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidosqlite/src/androidTest/java/com/izeni/rapidosqlite/util/PetToToy.kt | 1 | 888 | package com.izeni.rapidosqlite.util
import android.content.ContentValues
import com.izeni.rapidosqlite.addAll
import com.izeni.rapidosqlite.table.Column
import com.izeni.rapidosqlite.table.DataTable
/**
* Created by ner on 2/8/17.
*/
data class PetToToy(val petUuid: String, val toyUuid: String, val uuid: String = java.util.UUID.randomUUID().toString().replace("-", "")) : DataTable {
companion object {
val TABLE_NAME = "PetToToy"
val PET_UUID = Column(String::class.java, "PetId")
val TOY_UUID = Column(String::class.java, "ToyId")
val UUID = Column(String::class.java, "Uuid")
val COLUMNS = arrayOf(PET_UUID, TOY_UUID, UUID)
}
override fun tableName() = TABLE_NAME
override fun id() = uuid
override fun idColumn() = UUID
override fun contentValues() = ContentValues().addAll(COLUMNS, petUuid, toyUuid, uuid)
} | mit | 83edbbaaa6dc3c07a45a33a57fe0286a | 28.633333 | 151 | 0.686937 | 3.762712 | false | false | false | false |
jiangkang/KTools | vpn/src/main/java/com/jiangkang/vpn/ToyVpnService.kt | 1 | 4129 | package com.jiangkang.vpn
import android.app.*
import android.content.Intent
import android.net.VpnService
import android.os.Handler
import android.os.Message
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.core.util.Pair
import com.jiangkang.tools.extend.notificationManager
import com.jiangkang.tools.utils.ToastUtils
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.DatagramChannel
import kotlin.concurrent.thread
class ToyVpnService : VpnService(), Handler.Callback {
private val mHandler = Handler(this)
/**
* 用于点击通知栏的时候启动VPN Activity
*/
private var mConfigIntent: PendingIntent? = null
override fun onCreate() {
super.onCreate()
mConfigIntent = PendingIntent.getActivity(
this,
0,
Intent(this, ToyVpnClientActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return when (intent.action) {
ACTION_DISCONNECT -> {
disconnect()
Service.START_NOT_STICKY
}
else -> {
connect()
Service.START_STICKY
}
}
}
override fun onDestroy() {
super.onDestroy()
disconnect()
}
private var server = "127.0.0.1"
private val port = 8888
private val proxyHost = ""
private val proxyPort = 8888
private fun connect() {
// 更新通知栏信息
updateForegroundNotification(R.string.connecting)
mHandler.sendEmptyMessage(R.string.connecting)
thread {
val serverAddress = InetSocketAddress(server,port)
val tunnel = DatagramChannel.open()
if (!protect(tunnel.socket())){
ToastUtils.showShortToast("Cannot protect the tunnel")
}
tunnel.connect(serverAddress)
tunnel.configureBlocking(false)
val pfd = Builder()
.apply {
addAddress(server,port)
addRoute("0:0:0:0",0)
setSession(server)
setConfigureIntent(mConfigIntent!!)
}.establish()
val fis = FileInputStream(pfd?.fileDescriptor)
val fos = FileOutputStream(pfd?.fileDescriptor)
val packet = ByteBuffer.allocate(Short.MAX_VALUE.toInt())
while (true){
val len = fis.read(packet.array())
if (len > 0){
packet.limit(len)
tunnel.write(packet)
packet.clear()
Log.d("Toy",packet.toString())
}
}
}
}
private fun disconnect() {
mHandler.sendEmptyMessage(R.string.disconnected)
stopForeground(true)
}
override fun handleMessage(msg: Message): Boolean {
ToastUtils.showShortToast(msg.what.toString())
if (msg.what != R.string.disconnected) {
updateForegroundNotification(msg.what)
}
return true
}
private fun updateForegroundNotification(msg: Int) {
val channelId = "ToyVpn"
val channel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
val notification = Notification.Builder(this, channelId)
.setContentText(getString(msg))
.setContentIntent(mConfigIntent)
.build()
startForeground(0, notification)
}
companion object {
const val ACTION_CONNECT = "com.jiangkang.toyvpn.start"
const val ACTION_DISCONNECT = "com.jiangkang.toyvpn.stop"
}
class Connection(thread: Thread, parcelFileDescriptor: ParcelFileDescriptor) : Pair<Thread, ParcelFileDescriptor>(thread, parcelFileDescriptor)
} | mit | c78d2df05f117f242402723f93f79af0 | 29.766917 | 147 | 0.602542 | 5.063119 | false | false | false | false |
Nyubis/Pomfshare | app/src/main/kotlin/science/itaintrocket/pomfshare/RequestAuthenticationDialog.kt | 1 | 2302 | package science.itaintrocket.pomfshare
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
class RequestAuthenticationDialog : DialogFragment(), TextView.OnEditorActionListener {
private lateinit var listener: RequestAuthenticationDialogListener
private lateinit var dialogView: View
private lateinit var passwordField: EditText
interface RequestAuthenticationDialogListener {
fun onDialogSubmit(dialog: DialogFragment, text: String?)
fun onDialogCancel(dialog: DialogFragment)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialogView = inflater.inflate(R.layout.fragment_request_authentication, container)
passwordField = dialogView.findViewById(R.id.password) as EditText
dialog.setTitle("Authentication Required")
dialog.setContentView(dialogView)
passwordField.requestFocus();
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
passwordField.setOnEditorActionListener(this);
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = context as RequestAuthenticationDialogListener
} catch (e: ClassCastException) {
// The activity doesn't implement the interface, throw exception
throw ClassCastException("$context must implement NoticeDialogListener")
}
}
override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
val activity: RequestAuthenticationDialogListener = activity as RequestAuthenticationDialogListener;
activity.onDialogSubmit(this, passwordField.text.toString());
this.dismiss();
return true;
}
return false;
}
}
| gpl-2.0 | 38fe7a0d66b74308c48f008d0b1e93f7 | 40.107143 | 116 | 0.721112 | 5.546988 | false | false | false | false |
tom-kita/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/scroll_listener/TimelineScrollListener.kt | 3 | 1007 | package com.bl_lia.kirakiratter.presentation.scroll_listener
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
abstract class TimelineScrollListener(
private val layoutManger: LinearLayoutManager
) : RecyclerView.OnScrollListener() {
companion object {
const val VISIBLE_THRESHOLD: Int = 5
}
abstract fun onLoadMore()
private var firstVisibleItem: Int = 0
private var visibleItemCount: Int = 0
private var totalItemCount: Int = 0
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
recyclerView?.let {
visibleItemCount = recyclerView.childCount
totalItemCount = layoutManger.itemCount
firstVisibleItem = layoutManger.findFirstVisibleItemPosition()
}
if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) {
onLoadMore()
}
}
} | mit | 530314209bc5fa73c62a0256a172570b | 28.647059 | 92 | 0.695134 | 5.443243 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepShowSimUnpauseUi.kt | 1 | 1252 | package io.particle.mesh.setup.flow.setupsteps
import io.particle.mesh.common.android.livedata.awaitUpdate
import io.particle.mesh.common.android.livedata.nonNull
import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate
import io.particle.mesh.setup.flow.FlowUiDelegate
import io.particle.mesh.setup.flow.MeshSetupStep
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.TerminateFlowException
import io.particle.mesh.setup.flow.context.SetupContexts
class StepShowSimUnpauseUi(private val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
flowUi.showControlPanelSimUnpauseUi()
val newLimit: Int? = ctxs.cellular.newSelectedDataLimitLD
.nonNull(scopes)
.awaitUpdate(scopes)
if (newLimit == null || newLimit < 1) {
throw TerminateFlowException("No new data limit selected (value=$newLimit)")
}
val clicked = ctxs.cellular.changeSimStatusButtonClickedLD
.nonNull(scopes)
.awaitUpdate(scopes)
if (clicked != true) {
throw TerminateFlowException("User did not click 'unpause' button")
}
}
}
| apache-2.0 | a951ba931ee4eadcb5c9a59888dce1ce | 35.823529 | 88 | 0.722045 | 4.33218 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/openapiext/AsyncTasks.kt | 3 | 1414 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.openapiext
import com.intellij.openapi.progress.BackgroundTaskQueue
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import java.util.concurrent.CompletableFuture
@kotlin.Suppress("unused")
sealed class TaskResult<out T> {
class Ok<out T>(val value: T) : TaskResult<T>()
class Err<out T>(val reason: String) : TaskResult<T>()
}
interface AsyncTaskCtx<T> {
val progress: ProgressIndicator
fun err(presentableMessage: String) = TaskResult.Err<T>(presentableMessage)
fun ok(value: T) = TaskResult.Ok(value)
}
fun <T> runAsyncTask(project: Project, queue: BackgroundTaskQueue, title: String,
task: AsyncTaskCtx<T>.() -> TaskResult<T>): CompletableFuture<TaskResult<T>> {
val fut = CompletableFuture<TaskResult<T>>()
queue.run(object : Task.Backgroundable(project, title) {
override fun run(indicator: ProgressIndicator) {
val ctx = object : AsyncTaskCtx<T> {
override val progress: ProgressIndicator get() = indicator
}
fut.complete(ctx.task())
}
override fun onThrowable(error: Throwable) {
fut.completeExceptionally(error)
}
})
return fut
}
| mit | 8974846c2738599fc2ce639f2f72dabe | 32.666667 | 99 | 0.686704 | 4.183432 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/cs/ClientState.kt | 1 | 1262 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.cs
import org.xena.offsets.offsets.EngineOffsets.dwViewAngles
import org.xena.plugin.utils.Vector
import org.xena.process
import org.xena.utils.SignOnState
class ClientState : GameObject() {
var localPlayerIndex: Long = 0
var inGame: Long = 0
var maxPlayer: Long = 0
var state: SignOnState = SignOnState.MAIN_MENU
private val angleVector = Vector()
fun angle(): Vector {
angleVector.x = process.readFloat(address() + dwViewAngles)
angleVector.y = process.readFloat(address() + dwViewAngles + 4)
angleVector.z = process.readFloat(address() + dwViewAngles + 8)
return angleVector
}
}
| apache-2.0 | e947069223ca6e33382bf1ccb5016a39 | 28.348837 | 78 | 0.722662 | 3.690058 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt | 1 | 25000 | package eu.kanade.tachiyomi.ui.main
import android.animation.ValueAnimator
import android.app.SearchManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.widget.Toast
import androidx.appcompat.view.ActionMode
import androidx.core.animation.doOnEnd
import androidx.core.graphics.ColorUtils
import androidx.core.splashscreen.SplashScreen
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceDialogController
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.Router
import com.google.android.material.navigation.NavigationBarView
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.Migrations
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.notification.NotificationReceiver
import eu.kanade.tachiyomi.data.updater.AppUpdateChecker
import eu.kanade.tachiyomi.data.updater.AppUpdateResult
import eu.kanade.tachiyomi.databinding.MainActivityBinding
import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi
import eu.kanade.tachiyomi.ui.base.activity.BaseViewBindingActivity
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.base.controller.FabController
import eu.kanade.tachiyomi.ui.base.controller.NoAppBarElevationController
import eu.kanade.tachiyomi.ui.base.controller.RootController
import eu.kanade.tachiyomi.ui.base.controller.TabbedController
import eu.kanade.tachiyomi.ui.base.controller.setRoot
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.browse.BrowseController
import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourceController
import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchController
import eu.kanade.tachiyomi.ui.download.DownloadController
import eu.kanade.tachiyomi.ui.library.LibraryController
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.more.MoreController
import eu.kanade.tachiyomi.ui.more.NewUpdateDialogController
import eu.kanade.tachiyomi.ui.recent.history.HistoryController
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesController
import eu.kanade.tachiyomi.ui.setting.SettingsMainController
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.launchUI
import eu.kanade.tachiyomi.util.preference.asImmediateFlow
import eu.kanade.tachiyomi.util.system.dpToPx
import eu.kanade.tachiyomi.util.system.getThemeColor
import eu.kanade.tachiyomi.util.system.isTablet
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.util.view.setNavigationBarTransparentCompat
import eu.kanade.tachiyomi.widget.ActionModeWithToolbar
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import logcat.LogPriority
import uy.kohesive.injekt.injectLazy
class MainActivity : BaseViewBindingActivity<MainActivityBinding>() {
private lateinit var router: Router
private val startScreenId by lazy {
when (preferences.startScreen()) {
2 -> R.id.nav_history
3 -> R.id.nav_updates
4 -> R.id.nav_browse
else -> R.id.nav_library
}
}
private var isConfirmingExit: Boolean = false
private var isHandlingShortcut: Boolean = false
/**
* App bar lift state for backstack
*/
private val backstackLiftState = mutableMapOf<String, Boolean>()
private val chapterCache: ChapterCache by injectLazy()
// To be checked by splash screen. If true then splash screen will be removed.
var ready = false
override fun onCreate(savedInstanceState: Bundle?) {
// Prevent splash screen showing up on configuration changes
val splashScreen = if (savedInstanceState == null) installSplashScreen() else null
// Set up shared element transition and disable overlay so views don't show above system bars
window.requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS)
setExitSharedElementCallback(MaterialContainerTransformSharedElementCallback())
window.sharedElementsUseOverlay = false
super.onCreate(savedInstanceState)
val didMigration = if (savedInstanceState == null) Migrations.upgrade(preferences) else false
binding = MainActivityBinding.inflate(layoutInflater)
// Do not let the launcher create a new activity http://stackoverflow.com/questions/16283079
if (!isTaskRoot) {
finish()
return
}
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
// Draw edge-to-edge
WindowCompat.setDecorFitsSystemWindows(window, false)
binding.fabLayout.rootFab.applyInsetter {
ignoreVisibility(true)
type(navigationBars = true) {
margin()
}
}
binding.bottomNav?.applyInsetter {
type(navigationBars = true) {
padding()
}
}
val startTime = System.currentTimeMillis()
splashScreen?.setKeepVisibleCondition {
val elapsed = System.currentTimeMillis() - startTime
elapsed <= SPLASH_MIN_DURATION || (!ready && elapsed <= SPLASH_MAX_DURATION)
}
setSplashScreenExitAnimation(splashScreen)
if (binding.sideNav != null) {
preferences.sideNavIconAlignment()
.asImmediateFlow {
binding.sideNav?.menuGravity = when (it) {
1 -> Gravity.CENTER
2 -> Gravity.BOTTOM
else -> Gravity.TOP
}
}
.launchIn(lifecycleScope)
}
nav.setOnItemSelectedListener { item ->
val id = item.itemId
val currentRoot = router.backstack.firstOrNull()
if (currentRoot?.tag()?.toIntOrNull() != id) {
when (id) {
R.id.nav_library -> router.setRoot(LibraryController(), id)
R.id.nav_updates -> router.setRoot(UpdatesController(), id)
R.id.nav_history -> router.setRoot(HistoryController(), id)
R.id.nav_browse -> router.setRoot(BrowseController(), id)
R.id.nav_more -> router.setRoot(MoreController(), id)
}
} else if (!isHandlingShortcut) {
when (id) {
R.id.nav_library -> {
val controller = router.getControllerWithTag(id.toString()) as? LibraryController
controller?.showSettingsSheet()
}
R.id.nav_updates -> {
if (router.backstackSize == 1) {
router.pushController(DownloadController().withFadeTransaction())
}
}
R.id.nav_more -> {
if (router.backstackSize == 1) {
router.pushController(SettingsMainController().withFadeTransaction())
}
}
}
}
true
}
val container: ViewGroup = binding.controllerContainer
router = Conductor.attachRouter(this, container, savedInstanceState)
if (!router.hasRootController()) {
// Set start screen
if (!handleIntentAction(intent)) {
setSelectedNavItem(startScreenId)
}
}
binding.toolbar.setNavigationOnClickListener {
onBackPressed()
}
router.addChangeListener(
object : ControllerChangeHandler.ControllerChangeListener {
override fun onChangeStarted(
to: Controller?,
from: Controller?,
isPush: Boolean,
container: ViewGroup,
handler: ControllerChangeHandler
) {
syncActivityViewWithController(to, from, isPush)
}
override fun onChangeCompleted(
to: Controller?,
from: Controller?,
isPush: Boolean,
container: ViewGroup,
handler: ControllerChangeHandler
) {
}
}
)
syncActivityViewWithController()
if (savedInstanceState == null) {
// Reset Incognito Mode on relaunch
preferences.incognitoMode().set(false)
// Show changelog prompt on update
if (didMigration && !BuildConfig.DEBUG) {
WhatsNewDialogController().showDialog(router)
}
}
merge(preferences.showUpdatesNavBadge().asFlow(), preferences.unreadUpdatesCount().asFlow())
.onEach { setUnreadUpdatesBadge() }
.launchIn(lifecycleScope)
preferences.extensionUpdatesCount()
.asImmediateFlow { setExtensionsBadge() }
.launchIn(lifecycleScope)
preferences.downloadedOnly()
.asImmediateFlow { binding.downloadedOnly.isVisible = it }
.launchIn(lifecycleScope)
binding.incognitoMode.isVisible = preferences.incognitoMode().get()
preferences.incognitoMode().asFlow()
.drop(1)
.onEach {
binding.incognitoMode.isVisible = it
// Close BrowseSourceController and its MangaController child when incognito mode is disabled
if (!it) {
val fg = router.backstack.lastOrNull()?.controller
if (fg is BrowseSourceController || fg is MangaController && fg.fromSource) {
router.popToRoot()
}
}
}
.launchIn(lifecycleScope)
}
/**
* Sets custom splash screen exit animation on devices prior to Android 12.
*
* When custom animation is used, status and navigation bar color will be set to transparent and will be restored
* after the animation is finished.
*/
private fun setSplashScreenExitAnimation(splashScreen: SplashScreen?) {
val setNavbarScrim = {
// Make sure navigation bar is on bottom before we modify it
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->
if (insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom > 0) {
val elevation = binding.bottomNav?.elevation ?: 0F
window.setNavigationBarTransparentCompat(this@MainActivity, elevation)
}
insets
}
ViewCompat.requestApplyInsets(binding.root)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S && splashScreen != null) {
val oldStatusColor = window.statusBarColor
val oldNavigationColor = window.navigationBarColor
window.statusBarColor = Color.TRANSPARENT
window.navigationBarColor = Color.TRANSPARENT
splashScreen.setOnExitAnimationListener { splashProvider ->
// For some reason the SplashScreen applies (incorrect) Y translation to the iconView
splashProvider.iconView.translationY = 0F
val activityAnim = ValueAnimator.ofFloat(1F, 0F).apply {
interpolator = LinearOutSlowInInterpolator()
duration = SPLASH_EXIT_ANIM_DURATION
addUpdateListener { va ->
val value = va.animatedValue as Float
binding.root.translationY = value * 16.dpToPx
}
}
val splashAnim = ValueAnimator.ofFloat(1F, 0F).apply {
interpolator = FastOutSlowInInterpolator()
duration = SPLASH_EXIT_ANIM_DURATION
addUpdateListener { va ->
val value = va.animatedValue as Float
splashProvider.view.alpha = value
}
doOnEnd {
splashProvider.remove()
window.statusBarColor = oldStatusColor
window.navigationBarColor = oldNavigationColor
setNavbarScrim()
}
}
activityAnim.start()
splashAnim.start()
}
} else {
setNavbarScrim()
}
}
override fun onNewIntent(intent: Intent) {
if (!handleIntentAction(intent)) {
super.onNewIntent(intent)
}
}
override fun onResume() {
super.onResume()
checkForUpdates()
}
private fun checkForUpdates() {
lifecycleScope.launchIO {
// App updates
if (BuildConfig.INCLUDE_UPDATER) {
try {
val result = AppUpdateChecker().checkForUpdate(this@MainActivity)
if (result is AppUpdateResult.NewUpdate) {
NewUpdateDialogController(result).showDialog(router)
}
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
}
}
// Extension updates
try {
val pendingUpdates = ExtensionGithubApi().checkForUpdates(this@MainActivity)
preferences.extensionUpdatesCount().set(pendingUpdates.size)
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
}
}
}
private fun setUnreadUpdatesBadge() {
val updates = if (preferences.showUpdatesNavBadge().get()) preferences.unreadUpdatesCount().get() else 0
if (updates > 0) {
nav.getOrCreateBadge(R.id.nav_updates).number = updates
} else {
nav.removeBadge(R.id.nav_updates)
}
}
private fun setExtensionsBadge() {
val updates = preferences.extensionUpdatesCount().get()
if (updates > 0) {
nav.getOrCreateBadge(R.id.nav_browse).number = updates
} else {
nav.removeBadge(R.id.nav_browse)
}
}
private fun handleIntentAction(intent: Intent): Boolean {
val notificationId = intent.getIntExtra("notificationId", -1)
if (notificationId > -1) {
NotificationReceiver.dismissNotification(applicationContext, notificationId, intent.getIntExtra("groupId", 0))
}
isHandlingShortcut = true
when (intent.action) {
SHORTCUT_LIBRARY -> setSelectedNavItem(R.id.nav_library)
SHORTCUT_RECENTLY_UPDATED -> setSelectedNavItem(R.id.nav_updates)
SHORTCUT_RECENTLY_READ -> setSelectedNavItem(R.id.nav_history)
SHORTCUT_CATALOGUES -> setSelectedNavItem(R.id.nav_browse)
SHORTCUT_EXTENSIONS -> {
if (router.backstackSize > 1) {
router.popToRoot()
}
setSelectedNavItem(R.id.nav_browse)
router.pushController(BrowseController(toExtensions = true).withFadeTransaction())
}
SHORTCUT_MANGA -> {
val extras = intent.extras ?: return false
if (router.backstackSize > 1) {
router.popToRoot()
}
setSelectedNavItem(R.id.nav_library)
router.pushController(MangaController(extras).withFadeTransaction())
}
SHORTCUT_DOWNLOADS -> {
if (router.backstackSize > 1) {
router.popToRoot()
}
setSelectedNavItem(R.id.nav_more)
router.pushController(DownloadController().withFadeTransaction())
}
Intent.ACTION_SEARCH, Intent.ACTION_SEND, "com.google.android.gms.actions.SEARCH_ACTION" -> {
// If the intent match the "standard" Android search intent
// or the Google-specific search intent (triggered by saying or typing "search *query* on *Tachiyomi*" in Google Search/Google Assistant)
// Get the search query provided in extras, and if not null, perform a global search with it.
val query = intent.getStringExtra(SearchManager.QUERY) ?: intent.getStringExtra(Intent.EXTRA_TEXT)
if (query != null && query.isNotEmpty()) {
if (router.backstackSize > 1) {
router.popToRoot()
}
router.pushController(GlobalSearchController(query).withFadeTransaction())
}
}
INTENT_SEARCH -> {
val query = intent.getStringExtra(INTENT_SEARCH_QUERY)
if (query != null && query.isNotEmpty()) {
val filter = intent.getStringExtra(INTENT_SEARCH_FILTER)
if (router.backstackSize > 1) {
router.popToRoot()
}
router.pushController(GlobalSearchController(query, filter).withFadeTransaction())
}
}
else -> {
isHandlingShortcut = false
return false
}
}
ready = true
isHandlingShortcut = false
return true
}
@Suppress("UNNECESSARY_SAFE_CALL")
override fun onDestroy() {
super.onDestroy()
// Binding sometimes isn't actually instantiated yet somehow
nav?.setOnItemSelectedListener(null)
binding?.toolbar.setNavigationOnClickListener(null)
}
override fun onBackPressed() {
val backstackSize = router.backstackSize
if (backstackSize == 1 && router.getControllerWithTag("$startScreenId") == null) {
// Return to start screen
setSelectedNavItem(startScreenId)
} else if (shouldHandleExitConfirmation()) {
// Exit confirmation (resets after 2 seconds)
lifecycleScope.launchUI { resetExitConfirmation() }
} else if (backstackSize == 1 || !router.handleBack()) {
// Regular back (i.e. closing the app)
if (preferences.autoClearChapterCache()) {
chapterCache.clear()
}
super.onBackPressed()
}
}
override fun onSupportActionModeStarted(mode: ActionMode) {
binding.appbar.apply {
tag = isTransparentWhenNotLifted
isTransparentWhenNotLifted = false
}
// Color taken from m3_appbar_background
window.statusBarColor = ColorUtils.compositeColors(
getColor(R.color.m3_appbar_overlay_color),
getThemeColor(R.attr.colorSurface)
)
super.onSupportActionModeStarted(mode)
}
override fun onSupportActionModeFinished(mode: ActionMode) {
binding.appbar.apply {
isTransparentWhenNotLifted = (tag as? Boolean) ?: false
tag = null
}
window.statusBarColor = getThemeColor(android.R.attr.statusBarColor)
super.onSupportActionModeFinished(mode)
}
fun startActionModeAndToolbar(modeCallback: ActionModeWithToolbar.Callback): ActionModeWithToolbar {
binding.actionToolbar.start(modeCallback)
return binding.actionToolbar
}
private suspend fun resetExitConfirmation() {
isConfirmingExit = true
val toast = toast(R.string.confirm_exit, Toast.LENGTH_LONG)
delay(2000)
toast.cancel()
isConfirmingExit = false
}
private fun shouldHandleExitConfirmation(): Boolean {
return router.backstackSize == 1 &&
router.getControllerWithTag("$startScreenId") != null &&
preferences.confirmExit() &&
!isConfirmingExit
}
fun setSelectedNavItem(itemId: Int) {
if (!isFinishing) {
nav.selectedItemId = itemId
}
}
private fun syncActivityViewWithController(
to: Controller? = router.backstack.lastOrNull()?.controller,
from: Controller? = null,
isPush: Boolean = true,
) {
if (from is DialogController || to is DialogController) {
return
}
if (from is PreferenceDialogController || to is PreferenceDialogController) {
return
}
supportActionBar?.setDisplayHomeAsUpEnabled(router.backstackSize != 1)
// Always show appbar again when changing controllers
binding.appbar.setExpanded(true)
if ((from == null || from is RootController) && to !is RootController) {
showNav(false)
}
if (to is RootController) {
// Always show bottom nav again when returning to a RootController
showNav(true)
}
if (from is TabbedController) {
from.cleanupTabs(binding.tabs)
}
if (to is TabbedController) {
to.configureTabs(binding.tabs)
} else {
binding.tabs.setupWithViewPager(null)
}
binding.tabs.isVisible = to is TabbedController
if (from is FabController) {
from.cleanupFab(binding.fabLayout.rootFab)
}
if (to is FabController) {
binding.fabLayout.rootFab.show()
to.configureFab(binding.fabLayout.rootFab)
} else {
binding.fabLayout.rootFab.hide()
}
if (!isTablet()) {
// Save lift state
if (isPush) {
if (router.backstackSize > 1) {
// Save lift state
from?.let {
backstackLiftState[it.instanceId] = binding.appbar.isLifted
}
} else {
backstackLiftState.clear()
}
binding.appbar.isLifted = false
} else {
to?.let {
binding.appbar.isLifted = backstackLiftState.getOrElse(it.instanceId) { false }
}
from?.let {
backstackLiftState.remove(it.instanceId)
}
}
binding.root.isLiftAppBarOnScroll = to !is NoAppBarElevationController
binding.appbar.isTransparentWhenNotLifted = to is MangaController
binding.controllerContainer.overlapHeader = to is MangaController
}
}
private fun showNav(visible: Boolean) {
showBottomNav(visible)
showSideNav(visible)
}
// Also used from some controllers to swap bottom nav with action toolbar
fun showBottomNav(visible: Boolean) {
if (visible) {
binding.bottomNav?.slideUp()
} else {
binding.bottomNav?.slideDown()
}
}
private fun showSideNav(visible: Boolean) {
binding.sideNav?.isVisible = visible
}
private val nav: NavigationBarView
get() = binding.bottomNav ?: binding.sideNav!!
companion object {
// Splash screen
private const val SPLASH_MIN_DURATION = 500 // ms
private const val SPLASH_MAX_DURATION = 5000 // ms
private const val SPLASH_EXIT_ANIM_DURATION = 400L // ms
// Shortcut actions
const val SHORTCUT_LIBRARY = "eu.kanade.tachiyomi.SHOW_LIBRARY"
const val SHORTCUT_RECENTLY_UPDATED = "eu.kanade.tachiyomi.SHOW_RECENTLY_UPDATED"
const val SHORTCUT_RECENTLY_READ = "eu.kanade.tachiyomi.SHOW_RECENTLY_READ"
const val SHORTCUT_CATALOGUES = "eu.kanade.tachiyomi.SHOW_CATALOGUES"
const val SHORTCUT_DOWNLOADS = "eu.kanade.tachiyomi.SHOW_DOWNLOADS"
const val SHORTCUT_MANGA = "eu.kanade.tachiyomi.SHOW_MANGA"
const val SHORTCUT_EXTENSIONS = "eu.kanade.tachiyomi.EXTENSIONS"
const val INTENT_SEARCH = "eu.kanade.tachiyomi.SEARCH"
const val INTENT_SEARCH_QUERY = "query"
const val INTENT_SEARCH_FILTER = "filter"
}
}
| apache-2.0 | 67c605639b489369386d10ffa4904424 | 37.94081 | 153 | 0.61308 | 5.13347 | false | false | false | false |
google/horologist | base-ui/src/debug/java/com/google/android/horologist/base/ui/components/AlertDialogAlertPreview.kt | 1 | 2028 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistBaseUiApi::class)
package com.google.android.horologist.base.ui.components
import androidx.compose.runtime.Composable
import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi
import com.google.android.horologist.compose.tools.WearPreviewDevices
@WearPreviewDevices
@Composable
fun AlertDialogAlertPreview() {
AlertDialogAlert(
title = "Title",
body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
onCancelButtonClick = { },
onOKButtonClick = { },
okButtonContentDescription = "Ok",
cancelButtonContentDescription = "Cancel"
)
}
@WearPreviewDevices
@Composable
fun AlertDialogAlertWithLongBodyPreview() {
AlertDialogAlert(
title = "Title",
body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
onCancelButtonClick = { },
onOKButtonClick = { },
okButtonContentDescription = "Ok",
cancelButtonContentDescription = "Cancel"
)
}
| apache-2.0 | 9150ef4c4897747e8b62bed501596fd0 | 40.387755 | 463 | 0.745562 | 4.251572 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/appdata/local/StorIOExtensions.kt | 1 | 661 | package net.yslibrary.monotweety.appdata.local
import com.pushtorefresh.storio3.sqlite.operations.delete.PreparedDelete
import com.pushtorefresh.storio3.sqlite.operations.get.PreparedGet
import com.pushtorefresh.storio3.sqlite.operations.put.PreparedPut
fun <T> PreparedPut.Builder.withObject(entity: T) = `object`(entity)
fun <T> PreparedPut.Builder.withObjects(entities: Collection<T>) = objects(entities)
fun <T> PreparedGet.Builder.singleObject(entityClass: Class<T>) = `object`(entityClass)
fun <T> PreparedDelete.Builder.withObject(entity: T) = `object`(entity)
fun <T> PreparedDelete.Builder.withObjects(entities: Collection<T>) = objects(entities) | apache-2.0 | d9a04d5022bee733f126f3d204ad7a24 | 43.133333 | 87 | 0.807867 | 3.553763 | false | false | false | false |
trevjonez/AndroidGithubReleasePlugin | plugin/src/main/kotlin/com/trevjonez/agrp/CreateReleaseTask.kt | 1 | 2543 | /*
* Copyright (c) 2019. Trevor Jones
*
* 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.trevjonez.agrp
import com.trevjonez.github.releases.Release
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction
abstract class CreateReleaseTask : AgrpTask() {
lateinit var response: Release
@TaskAction
fun createRelease() {
val createRequest = Release.Request(
config.modifiedTagName,
config.targetCommitish.orNull,
config.releaseName.orNull,
config.releaseBody.orNull,
config.draft.orNull,
config.preRelease.orNull
)
val releaseLookupResponse = releaseApi.byTag(
owner.get(),
repo.get(),
config.modifiedTagName,
"token ${authToken.get()}"
).execute()
if (releaseLookupResponse.isSuccessful && !config.overwrite.get()) {
throw GradleException("A release with the specified tag name already exists.\n" +
"You can configure this task to overwrite the release @ that tag name with `overwrite = true`\n" +
releaseLookupResponse.body().toString())
}
val existingRelease = releaseLookupResponse.body()
val postPatchCall = if (releaseLookupResponse.isSuccessful) {
releaseApi.edit(
owner.get(),
repo.get(),
existingRelease!!.id,
"token ${authToken.get()}",
createRequest)
} else {
releaseApi.create(
owner.get(),
repo.get(),
"token ${authToken.get()}",
createRequest
)
}
val postPatchResponse = postPatchCall.execute()
if (!postPatchResponse.isSuccessful) {
val method = postPatchCall.request().method()
project.logger.lifecycle("$method github release api call failed with code: ${postPatchResponse.code()}")
throw GradleException("$method github release api call failed:\n${postPatchResponse.errorBody()!!.string()}\n")
}
response = postPatchResponse.body()!!
project.logger.lifecycle("Github release created: ${response.html_url}")
}
} | apache-2.0 | 8a29203bdd9a776cdbde31b432110415 | 31.202532 | 117 | 0.684624 | 4.361921 | false | true | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/transformers/documentables/ReportUndocumentedTransformer.kt | 1 | 6133 | package org.jetbrains.dokka.base.transformers.documentables
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet
import org.jetbrains.dokka.analysis.DescriptorDocumentableSource
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.transformers.documentation.DocumentableTransformer
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.FAKE_OVERRIDE
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class ReportUndocumentedTransformer : DocumentableTransformer {
override fun invoke(original: DModule, context: DokkaContext): DModule = original.apply {
withDescendants().forEach { documentable -> invoke(documentable, context) }
}
private fun invoke(documentable: Documentable, context: DokkaContext) {
documentable.sourceSets.forEach { sourceSet ->
if (shouldBeReportedIfNotDocumented(documentable, sourceSet)) {
reportIfUndocumented(context, documentable, sourceSet)
}
}
}
private fun shouldBeReportedIfNotDocumented(
documentable: Documentable, sourceSet: DokkaSourceSet
): Boolean {
val packageOptionsOrNull = packageOptionsOrNull(sourceSet, documentable)
if (!(packageOptionsOrNull?.reportUndocumented ?: sourceSet.reportUndocumented)) {
return false
}
if (documentable is DParameter || documentable is DPackage || documentable is DModule) {
return false
}
if (isConstructor(documentable)) {
return false
}
if (isFakeOverride(documentable, sourceSet)) {
return false
}
if (isSynthesized(documentable, sourceSet)) {
return false
}
if (isPrivateOrInternalApi(documentable, sourceSet)) {
return false
}
return true
}
private fun reportIfUndocumented(
context: DokkaContext,
documentable: Documentable,
sourceSet: DokkaSourceSet
) {
if (isUndocumented(documentable, sourceSet)) {
val documentableDescription = with(documentable) {
buildString {
dri.packageName?.run {
append(this)
append("/")
}
dri.classNames?.run {
append(this)
append("/")
}
dri.callable?.run {
append(name)
append("/")
append(signature())
append("/")
}
val sourceSetName = sourceSet.displayName
if (sourceSetName != null.toString()) {
append(" ($sourceSetName)")
}
}
}
context.logger.warn("Undocumented: $documentableDescription")
}
}
private fun isUndocumented(documentable: Documentable, sourceSet: DokkaSourceSet): Boolean {
fun resolveDependentSourceSets(sourceSet: DokkaSourceSet): List<DokkaSourceSet> {
return sourceSet.dependentSourceSets.mapNotNull { sourceSetID ->
documentable.sourceSets.singleOrNull { it.sourceSetID == sourceSetID }
}
}
fun withAllDependentSourceSets(sourceSet: DokkaSourceSet): Sequence<DokkaSourceSet> = sequence {
yield(sourceSet)
for (dependentSourceSet in resolveDependentSourceSets(sourceSet)) {
yieldAll(withAllDependentSourceSets(dependentSourceSet))
}
}
return withAllDependentSourceSets(sourceSet).all { sourceSetOrDependentSourceSet ->
documentable.documentation[sourceSetOrDependentSourceSet]?.children?.isEmpty() ?: true
}
}
private fun isConstructor(documentable: Documentable): Boolean {
if (documentable !is DFunction) return false
return documentable.isConstructor
}
private fun isFakeOverride(documentable: Documentable, sourceSet: DokkaSourceSet): Boolean {
return callableMemberDescriptorOrNull(documentable, sourceSet)?.kind == FAKE_OVERRIDE
}
private fun isSynthesized(documentable: Documentable, sourceSet: DokkaSourceSet): Boolean {
return callableMemberDescriptorOrNull(documentable, sourceSet)?.kind == SYNTHESIZED
}
private fun callableMemberDescriptorOrNull(
documentable: Documentable, sourceSet: DokkaSourceSet
): CallableMemberDescriptor? {
if (documentable is WithSources) {
return documentable.sources[sourceSet]
.safeAs<DescriptorDocumentableSource>()?.descriptor
.safeAs<CallableMemberDescriptor>()
}
return null
}
private fun isPrivateOrInternalApi(documentable: Documentable, sourceSet: DokkaSourceSet): Boolean {
return when (documentable.safeAs<WithVisibility>()?.visibility?.get(sourceSet)) {
KotlinVisibility.Public -> false
KotlinVisibility.Private -> true
KotlinVisibility.Protected -> true
KotlinVisibility.Internal -> true
JavaVisibility.Public -> false
JavaVisibility.Private -> true
JavaVisibility.Protected -> true
JavaVisibility.Default -> true
null -> false
}
}
private fun packageOptionsOrNull(
dokkaSourceSet: DokkaSourceSet,
documentable: Documentable
): DokkaConfiguration.PackageOptions? {
val packageName = documentable.dri.packageName ?: return null
return dokkaSourceSet.perPackageOptions
.filter { packageOptions -> Regex(packageOptions.matchingRegex).matches(packageName) }
.maxByOrNull { packageOptions -> packageOptions.matchingRegex.length }
}
}
| apache-2.0 | 280b493a9edf5f6e43409b387c1a4410 | 36.396341 | 104 | 0.643078 | 5.919884 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/activities/IntroActivity.kt | 1 | 7999 | /*
* Copyright 2018 Allan Wang
*
* 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.pitchedapps.frost.activities
import android.animation.ValueAnimator
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import ca.allanwang.kau.internal.KauBaseActivity
import ca.allanwang.kau.kotlin.lazyUi
import ca.allanwang.kau.utils.blendWith
import ca.allanwang.kau.utils.color
import ca.allanwang.kau.utils.fadeScaleTransition
import ca.allanwang.kau.utils.navigationBarColor
import ca.allanwang.kau.utils.postDelayed
import ca.allanwang.kau.utils.scaleXY
import ca.allanwang.kau.utils.setIcon
import ca.allanwang.kau.utils.statusBarColor
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial
import com.pitchedapps.frost.R
import com.pitchedapps.frost.databinding.ActivityIntroBinding
import com.pitchedapps.frost.injectors.ThemeProvider
import com.pitchedapps.frost.intro.BaseIntroFragment
import com.pitchedapps.frost.intro.IntroAccountFragment
import com.pitchedapps.frost.intro.IntroFragmentEnd
import com.pitchedapps.frost.intro.IntroFragmentTheme
import com.pitchedapps.frost.intro.IntroFragmentWelcome
import com.pitchedapps.frost.intro.IntroTabContextFragment
import com.pitchedapps.frost.intro.IntroTabTouchFragment
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.ActivityThemer
import com.pitchedapps.frost.utils.cookies
import com.pitchedapps.frost.utils.launchNewTask
import com.pitchedapps.frost.utils.loadAssets
import com.pitchedapps.frost.widgets.NotificationWidget
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
/**
* Created by Allan Wang on 2017-07-25.
*
* A beautiful intro activity Phone showcases are drawn via layers
*/
@AndroidEntryPoint
class IntroActivity : KauBaseActivity(), ViewPager.PageTransformer, ViewPager.OnPageChangeListener {
@Inject lateinit var prefs: Prefs
@Inject lateinit var themeProvider: ThemeProvider
@Inject lateinit var activityThemer: ActivityThemer
lateinit var binding: ActivityIntroBinding
private var barHasNext = true
private val fragments by lazyUi {
listOf(
IntroFragmentWelcome(),
IntroFragmentTheme(),
IntroAccountFragment(),
IntroTabTouchFragment(),
IntroTabContextFragment(),
IntroFragmentEnd()
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityIntroBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.init()
}
private fun ActivityIntroBinding.init() {
viewpager.apply {
setPageTransformer(true, this@IntroActivity)
addOnPageChangeListener(this@IntroActivity)
adapter = IntroPageAdapter(supportFragmentManager, fragments)
}
indicator.setViewPager(viewpager)
next.setIcon(GoogleMaterial.Icon.gmd_navigate_next)
next.setOnClickListener {
if (barHasNext) viewpager.setCurrentItem(viewpager.currentItem + 1, true)
else finish(next.x + next.pivotX, next.y + next.pivotY)
}
skip.setOnClickListener { finish() }
ripple.set(themeProvider.bgColor)
theme()
}
fun theme() {
statusBarColor = themeProvider.headerColor
navigationBarColor = themeProvider.headerColor
with(binding) {
skip.setTextColor(themeProvider.textColor)
next.imageTintList = ColorStateList.valueOf(themeProvider.textColor)
indicator.setColour(themeProvider.textColor)
indicator.invalidate()
}
fragments.forEach { it.themeFragment() }
activityThemer.setFrostTheme(forceTransparent = true)
}
/**
* Transformations are mainly handled on a per view basis This makes the first fragment fade out
* as the second fragment comes in All fragments are locked in position
*/
override fun transformPage(page: View, position: Float) {
// only apply to adjacent pages
if ((position < 0 && position > -1) || (position > 0 && position < 1)) {
val pageWidth = page.width
val translateValue = position * -pageWidth
page.translationX = (if (translateValue > -pageWidth) translateValue else 0f)
page.alpha = if (position < 0) 1 + position else 1f
} else {
page.alpha = 1f
page.translationX = 0f
}
}
fun finish(x: Float, y: Float) {
val blue = color(R.color.facebook_blue)
window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
)
binding.ripple.ripple(blue, x, y, 600) { postDelayed(1000) { finish() } }
val lastView: View? = fragments.last().view
arrayOf<View?>(
binding.skip,
binding.indicator,
binding.next,
lastView?.findViewById(R.id.intro_title),
lastView?.findViewById(R.id.intro_desc)
)
.forEach { it?.animate()?.alpha(0f)?.setDuration(600)?.start() }
if (themeProvider.textColor != Color.WHITE) {
val f = lastView?.findViewById<ImageView>(R.id.intro_image)?.drawable
if (f != null)
ValueAnimator.ofFloat(0f, 1f).apply {
addUpdateListener {
f.setTint(themeProvider.textColor.blendWith(Color.WHITE, it.animatedValue as Float))
}
duration = 600
start()
}
}
if (themeProvider.headerColor != blue) {
ValueAnimator.ofFloat(0f, 1f).apply {
addUpdateListener {
val c = themeProvider.headerColor.blendWith(blue, it.animatedValue as Float)
statusBarColor = c
navigationBarColor = c
}
duration = 600
start()
}
}
}
override fun finish() {
launch(NonCancellable) {
loadAssets(themeProvider)
NotificationWidget.forceUpdate(this@IntroActivity)
launchNewTask<MainActivity>(cookies(), false)
super.finish()
}
}
override fun onBackPressed() {
with(binding) {
if (viewpager.currentItem > 0) viewpager.setCurrentItem(viewpager.currentItem - 1, true)
else finish()
}
}
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
fragments[position].onPageScrolled(positionOffset)
if (position + 1 < fragments.size) fragments[position + 1].onPageScrolled(positionOffset - 1)
}
override fun onPageSelected(position: Int) {
fragments[position].onPageSelected()
val hasNext = position != fragments.size - 1
if (barHasNext == hasNext) return
barHasNext = hasNext
binding.next.fadeScaleTransition {
setIcon(
if (barHasNext) GoogleMaterial.Icon.gmd_navigate_next else GoogleMaterial.Icon.gmd_done,
color = themeProvider.textColor
)
}
binding.skip.animate().scaleXY(if (barHasNext) 1f else 0f)
}
class IntroPageAdapter(fm: FragmentManager, private val fragments: List<BaseIntroFragment>) :
FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment = fragments[position]
override fun getCount(): Int = fragments.size
}
}
| gpl-3.0 | 452e04134812ae6d9d83df602f2e30c7 | 34.083333 | 100 | 0.734217 | 4.344921 | false | false | false | false |
UweTrottmann/wp-display-android | app/src/main/java/com/uwetrottmann/wpdisplay/settings/SettingsListAdapter.kt | 1 | 2287 | /*
* Copyright 2018 Uwe Trottmann
*
* 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.uwetrottmann.wpdisplay.settings
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.uwetrottmann.wpdisplay.databinding.ItemSelectableBinding
import com.uwetrottmann.wpdisplay.model.DisplayItem
class SettingsListAdapter :
ListAdapter<DisplayItem, SettingsListAdapter.SettingsViewHolder>(object :
DiffUtil.ItemCallback<DisplayItem>() {
override fun areItemsTheSame(oldItem: DisplayItem, newItem: DisplayItem): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: DisplayItem, newItem: DisplayItem): Boolean =
oldItem.enabled == newItem.enabled
}) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder {
val binding =
ItemSelectableBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return SettingsViewHolder(binding)
}
override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) {
holder.bindTo(getItem(position))
}
class SettingsViewHolder(private val binding: ItemSelectableBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bindTo(item: DisplayItem) {
binding.checkBoxItemSelectable.apply {
setOnCheckedChangeListener(null) // disable while binding
isChecked = item.enabled
setOnCheckedChangeListener { _, isChecked -> item.enabled = isChecked }
setText(item.type.labelResId)
}
}
}
} | apache-2.0 | b3cbdacd9bcfaca7c094c0c487aa6e8d | 37.779661 | 94 | 0.722781 | 4.928879 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/collections/processors/AddPairToEntityTypeCollectionTemplateProcessor.kt | 1 | 1151 | package com.openlattice.collections.processors
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.collections.CollectionTemplateType
import com.openlattice.collections.EntityTypeCollection
import java.util.*
class AddPairToEntityTypeCollectionTemplateProcessor(
val collectionTemplateType: CollectionTemplateType
) : AbstractRhizomeEntryProcessor<UUID, EntityTypeCollection, EntityTypeCollection?>() {
override fun process(entry: MutableMap.MutableEntry<UUID, EntityTypeCollection>): EntityTypeCollection? {
val collection = entry.value
collection.addTypeToTemplate(collectionTemplateType)
entry.setValue(collection)
return null
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AddPairToEntityTypeCollectionTemplateProcessor
if (collectionTemplateType != other.collectionTemplateType) return false
return true
}
override fun hashCode(): Int {
return collectionTemplateType.hashCode()
}
} | gpl-3.0 | e19c3811b56405aed9cb210a613f87b7 | 30.135135 | 109 | 0.757602 | 5.93299 | false | false | false | false |
JimSeker/ui | Dialogs/DialogDemo_kt/app/src/main/java/edu/cs4730/dialogdemo_kt/MultiInputDialogFragment.kt | 1 | 4421 | package edu.cs4730.dialogdemo_kt
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ContextThemeWrapper
import androidx.fragment.app.DialogFragment
import java.lang.RuntimeException
/**
* This is a dialogfragment that has two text boxes.
* The program can start it up with data or just have start with blanks.
*
* It will return a string array via the listener that that needs to be implemented by the activity (or fragment?)
*/
class MultiInputDialogFragment : DialogFragment() {
private var name: String? = null
private var amount: String? = null
private var mListener: OnDialogFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
name = requireArguments().getString(ARG_PARAM1, null)
amount = requireArguments().getString(ARG_PARAM2, null)
}
}
lateinit var et_name: EditText
lateinit var et_amount: EditText
override fun onCreateDialog(SavedIntanceState: Bundle?): Dialog {
val inflater = LayoutInflater.from(requireActivity())
val myView = inflater.inflate(R.layout.fragment_multi_input_dialog, null)
et_name = myView.findViewById<View>(R.id.et_name) as EditText
if (name != null) et_name.setText(name)
et_amount = myView.findViewById<View>(R.id.et_amount) as EditText
if (amount != null) et_amount.setText(amount)
val builder = AlertDialog.Builder(
ContextThemeWrapper(
requireActivity(),
R.style.ThemeOverlay_AppCompat_Dialog
)
)
builder.setView(myView).setTitle("Multi Input Dialog")
builder.setPositiveButton(
"Save"
) { dialog, id ->
val returnlist = arrayOf(
et_name.text.toString(),
et_amount.text.toString()
)
//send the list back to the MainActivity to process.
mListener!!.onMultiInputInteraction(returnlist)
dismiss()
}
.setNegativeButton(
"Cancel"
) { dialog, id -> dialog.cancel() }
return builder.create()
}
override fun onAttach(context: Context) {
super.onAttach(context)
mListener = if (context is OnDialogFragmentInteractionListener) {
context
} else {
throw RuntimeException(
context.toString()
+ " must implement OnFragmentInteractionListener"
)
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
internal interface OnDialogFragmentInteractionListener {
fun onMultiInputInteraction(items: Array<String>)
}
companion object {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1. //name
* @param param2 Parameter 2. //amount
* @return A new instance of fragment MultiInputDialogFragment.
*/
fun newInstance(param1: String?, param2: String?): MultiInputDialogFragment {
val fragment = MultiInputDialogFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1) //name
args.putString(ARG_PARAM2, param2) //amount
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 965b1d07e9dc5ead8d166d0c4ae9337c | 35.53719 | 172 | 0.646686 | 4.852909 | false | false | false | false |
wisnia/Videooo | app/src/main/kotlin/com/wisnia/videooo/authentication/AuthenticationWebViewClient.kt | 2 | 1789 | package com.wisnia.videooo.authentication
import android.annotation.TargetApi
import android.net.Uri
import android.os.Build
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import com.wisnia.videooo.authentication.permission.PermissionInterceptor
import com.wisnia.videooo.authentication.permission.PermissionState
import com.wisnia.videooo.authentication.permission.PermissionUrl
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.subjects.PublishSubject
class AuthenticationWebViewClient(token: String) : WebViewClient() {
private val interceptor: PermissionInterceptor = PermissionInterceptor(token) // todo: use DI here.
private val permissionSubject: PublishSubject<PermissionState> = PublishSubject.create()
val permissionEvent: Flowable<PermissionState>
get() = permissionSubject.toFlowable(BackpressureStrategy.LATEST).distinctUntilChanged()
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
providePermissionEvent(Uri.parse(url))
return super.shouldInterceptRequest(view, url)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
providePermissionEvent(request.url)
return super.shouldInterceptRequest(view, request)
}
private fun providePermissionEvent(uri: Uri) {
val permissionUrl = PermissionUrl(uri.encodedPath, uri.lastPathSegment)
val state = interceptor.interceptPermissionState(permissionUrl)
permissionSubject.onNext(state)
}
}
| apache-2.0 | 35cdbc40aebd5129535373f59efe52d0 | 41.595238 | 107 | 0.799329 | 4.969444 | false | false | false | false |
ShevaBrothers/easylib | src/core/maps/test/HashMapTest.kt | 1 | 742 | import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
/**
* @Author is Alex Syrotenko (@flystyle)
* Created on 30.05.17.
*/
class HashMapTest {
val map = HashMap<Int, Int>();
val rand = Random()
@Test fun putAndGetFromHashMap() {
for (i in 1..100) {
map.put(i, i + 100)
}
var index = rand.nextInt(100)
assertEquals(index + 100, map[index])
index = rand.nextInt(100)
assertEquals(index + 100, map[index])
}
@Test fun sizeAndClearTest() {
val size = 100
for (i in 1..size) {
map.put(i, i + 100)
}
assertEquals(size, map.size)
map.clear()
assertEquals(0, map.size)
}
}
| mit | 3962b9626346425b0024b6ceae0c2086 | 18.526316 | 45 | 0.543127 | 3.483568 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/ui/CardBrowserSearchView.kt | 1 | 2005 | /*
* Copyright (c) 2021 David Allison <[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 com.ichi2.ui
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.SearchView
class CardBrowserSearchView : SearchView {
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
/** Whether an action to set text should be ignored */
private var mIgnoreValueChange = false
/** Whether an action to set text should be ignored */
fun shouldIgnoreValueChange(): Boolean {
return mIgnoreValueChange
}
override fun onActionViewCollapsed() {
try {
mIgnoreValueChange = true
super.onActionViewCollapsed()
} finally {
mIgnoreValueChange = false
}
}
override fun onActionViewExpanded() {
try {
mIgnoreValueChange = true
super.onActionViewExpanded()
} finally {
mIgnoreValueChange = false
}
}
override fun setQuery(query: CharSequence, submit: Boolean) {
if (mIgnoreValueChange) {
return
}
super.setQuery(query, submit)
}
}
| gpl-3.0 | 6c3bf1a1a541d2c8bab650c9d9063fd7 | 32.416667 | 114 | 0.677805 | 4.567198 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/schema/SchemaActivity.kt | 1 | 4238 | package com.infinum.dbinspector.ui.schema
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import com.google.android.material.tabs.TabLayoutMediator
import com.infinum.dbinspector.R
import com.infinum.dbinspector.databinding.DbinspectorActivitySchemaBinding
import com.infinum.dbinspector.domain.schema.shared.models.SchemaType
import com.infinum.dbinspector.extensions.searchView
import com.infinum.dbinspector.extensions.setup
import com.infinum.dbinspector.extensions.uppercase
import com.infinum.dbinspector.ui.schema.shared.SchemaFragment
import com.infinum.dbinspector.ui.schema.shared.SchemaTypeAdapter
import com.infinum.dbinspector.ui.shared.base.BaseActivity
import com.infinum.dbinspector.ui.shared.base.lifecycle.LifecycleConnection
import com.infinum.dbinspector.ui.shared.contracts.EditContract
import com.infinum.dbinspector.ui.shared.delegates.lifecycleConnection
import com.infinum.dbinspector.ui.shared.delegates.viewBinding
import com.infinum.dbinspector.ui.shared.searchable.Searchable
import org.koin.androidx.viewmodel.ext.android.viewModel
internal class SchemaActivity : BaseActivity<Any, Any>(), Searchable {
override val binding by viewBinding(DbinspectorActivitySchemaBinding::inflate)
override val viewModel: SchemaViewModel by viewModel()
private val connection: LifecycleConnection by lifecycleConnection()
private lateinit var contract: ActivityResultLauncher<EditContract.Input>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.toolbar.setNavigationOnClickListener { finish() }
if (connection.hasDatabaseData) {
viewModel.databasePath = connection.databasePath!!
viewModel.open()
setupUi(connection.databaseName!!, connection.databasePath!!)
} else {
showDatabaseParametersError()
}
contract = registerForActivityResult(EditContract()) { shouldRefresh ->
if (shouldRefresh) {
supportFragmentManager.fragments
.filterIsInstance<SchemaFragment>()
.forEach { it.refresh() }
}
}
}
override fun onDestroy() {
contract.unregister()
viewModel.close()
super.onDestroy()
}
override fun onState(state: Any) = Unit
override fun onEvent(event: Any) = Unit
override fun onSearchOpened() = Unit
override fun search(query: String?) =
supportFragmentManager
.fragments
.filterIsInstance<Searchable>()
.forEach { it.search(query) }
override fun searchQuery(): String? =
binding.toolbar.menu.searchView?.query?.toString()
override fun onSearchClosed() = Unit
private fun setupUi(databaseName: String, databasePath: String) {
with(binding) {
toolbar.subtitle = databaseName
toolbar.menu.searchView?.setup(
hint = getString(R.string.dbinspector_search_by_name),
onSearchClosed = { onSearchClosed() },
onQueryTextChanged = { search(it) }
)
toolbar.setOnMenuItemClickListener {
when (it.itemId) {
R.id.search -> {
onSearchOpened()
true
}
R.id.edit -> {
showEdit(databasePath, databaseName)
true
}
else -> false
}
}
viewPager.adapter = SchemaTypeAdapter(
fragmentActivity = this@SchemaActivity,
databasePath = databasePath,
databaseName = databaseName
)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = getString(SchemaType.values()[position].nameRes).uppercase()
}.attach()
}
}
private fun showEdit(databasePath: String, databaseName: String) =
contract.launch(
EditContract.Input(
databasePath = databasePath,
databaseName = databaseName
)
)
}
| apache-2.0 | c9e3352bbb766fb728f1cbb28013ac14 | 35.222222 | 87 | 0.647947 | 5.412516 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/building_underground/AddIsBuildingUnderground.kt | 1 | 1294 | package de.westnordost.streetcomplete.quests.building_underground
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddIsBuildingUnderground : OsmFilterQuestType<Boolean>() {
override val elementFilter = "ways, relations with building and !location and layer~-[0-9]+"
override val commitMessage = "Determine whether building is fully underground"
override val wikiLink = "Key:location"
override val icon = R.drawable.ic_quest_building_underground
override val questTypeAchievements = listOf(BUILDING)
override fun getTitle(tags: Map<String, String>): Int =
if (tags.containsKey("name"))
R.string.quest_building_underground_name_title
else
R.string.quest_building_underground_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("location", if (answer) "underground" else "surface")
}
}
| gpl-3.0 | 2636460ee7d027064bc48b684bb2483f | 43.62069 | 96 | 0.772798 | 4.864662 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/MakefileFileChooserDescriptor.kt | 1 | 639 | package name.kropp.intellij.makefile
import com.intellij.openapi.fileChooser.*
import com.intellij.openapi.vfs.*
class MakefileFileChooserDescriptor : FileChooserDescriptor(true, false, false, false, false, false) {
init {
title = "Makefile"
}
override fun isFileVisible(file: VirtualFile, showHiddenFiles: Boolean) = when {
!showHiddenFiles && FileElement.isFileHidden(file) -> false
file.isDirectory -> true
else -> file.fileType == MakefileFileType // file.name.endsWith(".mk") || file.name == "Makefile"
}
override fun isFileSelectable(file: VirtualFile) = !file.isDirectory && isFileVisible(file, true)
} | mit | 45492329e5b395df8906d5408c57e6e0 | 34.555556 | 102 | 0.735524 | 4.231788 | false | false | false | false |
wtopolski/testing-workshop-app | app/src/main/java/com/github/wtopolski/testingworkshopapp/binding/TextViewBinder.kt | 1 | 753 | package com.github.wtopolski.testingworkshopapp.binding
import android.databinding.Bindable
import com.github.wtopolski.testingworkshopapp.BR
open class TextViewBinder(enabled: Boolean, visibility: Boolean) : BaseBinder(enabled, visibility) {
@get:Bindable
var value: CharSequence? = null
set(value) {
field = value
notifyPropertyChanged(BR.value)
}
@get:Bindable
var textColor: Int? = null
set(textColor) {
field = textColor
notifyPropertyChanged(BR.textColor)
}
@get:Bindable
var backgroundColor: Int? = null
set(backgroundColor) {
field = backgroundColor
notifyPropertyChanged(BR.backgroundColor)
}
}
| apache-2.0 | 8e7886823ff468c65e429fc0b7bbc780 | 25.892857 | 100 | 0.648074 | 4.648148 | false | true | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/PreferenceSet.kt | 1 | 4897 | package pyxis.uzuki.live.richutilskt.demo.set
import android.content.Context
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem
import pyxis.uzuki.live.richutilskt.utils.RPreference
import pyxis.uzuki.live.richutilskt.utils.toast
/**
* RichUtilsKt
* Class: PreferenceSet
* Created by Pyxis on 2017-11-09.
*
* Description:
*/
fun Context.getPreferenceSet() : ArrayList<ExecuteItem> {
val list = arrayListOf<ExecuteItem>()
val key = "PREF_KEY"
val put = generateExecuteItem(CategoryItem.PREFERENCE, "put",
"Put any value to SharedPreference",
"RPreference.getInstance(this).put(key to editPref.text.toString())",
"RPreference.getInstance(this).put(key, editPref.getText().toString());") {
RPreference.getInstance(this).put("${key}String" to "abc")
RPreference.getInstance(this).put("${key}CharSequence" to "abc")
RPreference.getInstance(this).put("${key}Boolean" to true)
RPreference.getInstance(this).put("${key}Int" to 1)
RPreference.getInstance(this).put("${key}Long" to 2L)
RPreference.getInstance(this).put("${key}Float" to 3f)
RPreference.getInstance(this).put("${key}Double" to 4.0)
RPreference.getInstance(this).put("${key}Char" to 'a')
}
list.add(put)
val getString = generateExecuteItem(CategoryItem.PREFERENCE, "getString",
"get String value from SharedPreference",
"RPreference.getInstance(this).getString(key)",
"RPreference.getInstance(this).getString(key);") {
toast("$key = ${RPreference.getInstance(this).getString("${key}String")}")
}
list.add(getString)
val getChar = generateExecuteItem(CategoryItem.PREFERENCE, "getChar",
"get Char value from SharedPreference",
"RPreference.getInstance(this).getChar(key)",
"RPreference.getInstance(this).getChar(key);") {
toast("$key = ${RPreference.getInstance(this).getChar("${key}Char")}")
}
list.add(getChar)
val getCharSequence = generateExecuteItem(CategoryItem.PREFERENCE, "getCharSequence",
"get CharSequence value from SharedPreference",
"RPreference.getInstance(this).getCharSequence(key)",
"RPreference.getInstance(this).getCharSequence(key);") {
toast("$key = ${RPreference.getInstance(this).getCharSequence("${key}CharSequence")}")
}
list.add(getCharSequence)
val getInt = generateExecuteItem(CategoryItem.PREFERENCE, "getInt",
"get Int value from SharedPreference",
"RPreference.getInstance(this).getInt(key)",
"RPreference.getInstance(this).getInt(key);") {
toast("$key = ${RPreference.getInstance(this).getInt("${key}Int")}")
}
list.add(getInt)
val getLong = generateExecuteItem(CategoryItem.PREFERENCE, "getLong",
"get Long value from SharedPreference",
"RPreference.getInstance(this).getLong(key)",
"RPreference.getInstance(this).getLong(key);") {
toast("$key = ${RPreference.getInstance(this).getLong("${key}Long")}")
}
list.add(getLong)
val getFloat = generateExecuteItem(CategoryItem.PREFERENCE, "getFloat",
"get Float value from SharedPreference",
"RPreference.getInstance(this).getFloat(key)",
"RPreference.getInstance(this).getFloat(key);") {
toast("$key = ${RPreference.getInstance(this).getFloat("${key}Float")}")
}
list.add(getFloat)
val getDouble = generateExecuteItem(CategoryItem.PREFERENCE, "getDouble",
"get Double value from SharedPreference",
"RPreference.getInstance(this).getDouble(key)",
"RPreference.getInstance(this).getDouble(key);") {
toast("$key = ${RPreference.getInstance(this).getDouble("${key}Double")}")
}
list.add(getDouble)
val getBoolean = generateExecuteItem(CategoryItem.PREFERENCE, "getBoolean",
"get Boolean value from SharedPreference",
"RPreference.getInstance(this).getBoolean(key)",
"RPreference.getInstance(this).getBoolean(key);") {
toast("$key = ${RPreference.getInstance(this).getBoolean("${key}Boolean")}")
}
list.add(getBoolean)
val delete = generateExecuteItem(CategoryItem.PREFERENCE, "delete",
"delete key-value from SharedPreference",
"RPreference.getInstance(this).delete(key)",
"RPreference.getInstance(this).delete(key);")
list.add(delete)
val clear = generateExecuteItem(CategoryItem.PREFERENCE, "clear",
"clear all of preferences",
"RPreference.getInstance(this).clear()",
"RPreference.getInstance(this).clear();")
list.add(clear)
return list
} | apache-2.0 | 2985370515f2a33aeb44c75b044159a2 | 37.566929 | 94 | 0.662446 | 4.451818 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/Guardx.kt | 1 | 4259 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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.
*
*/
@file:JvmName("Guardx")
package debop4k.core
import java.lang.IllegalArgumentException
fun <T> firstNotNull(first: T, second: T): T {
if (!areEquals(first, null)) return first
else if (!areEquals(second, null)) return second
else throw IllegalArgumentException("all parameter is null.")
}
fun shouldBe(cond: Boolean): Unit = assert(cond)
inline fun shouldBe(cond: Boolean, msg: () -> Any): Unit = assert(cond, msg)
fun shouldBe(cond: Boolean, fmt: String, vararg args: Any): Unit {
assert(cond) { fmt.format(*args) }
}
fun Any.shouldBeEquals(expected: Any, actualName: String): Unit {
shouldBe(areEquals(this, expected), ShouldBeEquals, actualName, this, expected)
}
fun Any?.shouldBeNull(argName: String): Any? {
shouldBe(this == null, ShouldBeNull, argName)
return this
}
fun Any?.shouldNotBeNull(argName: String): Any? {
shouldBe(this != null, ShouldNotBeNull, argName)
return this
}
fun String?.shouldBeEmpty(argName: String): String? {
shouldBe(this.isNullOrEmpty(), ShouldBeEmptyString, argName)
return this
}
fun String?.shouldNotBeEmpty(argName: String): String? {
shouldBe(!this.isNullOrEmpty(), ShouldBeEmptyString, argName)
return this
}
fun String?.shouldBeWhitespace(argName: String): String? {
shouldBe(this.isNullOrBlank(), ShouldBeWhiteSpace, argName)
return this
}
fun String?.shouldNotBeWhitespace(argName: String): String? {
shouldBe(!this.isNullOrBlank(), ShouldNotBeWhiteSpace, argName)
return this
}
fun <T : Number> T.shouldBePositiveNumber(argName: String): T {
shouldBe(this.toDouble() > 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBePositiveOrZeroNumber(argName: String): T {
shouldBe(this.toDouble() >= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNotPositiveNumber(argName: String): T {
shouldBe(this.toDouble() <= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNegativeNumber(argName: String): T {
shouldBe(this.toDouble() < 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNegativeOrZeroNumber(argName: String): T {
shouldBe(this.toDouble() <= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldNotBeNegativeNumber(argName: String): T {
shouldBe(this.toDouble() >= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> shouldBeInRange(value: T, fromInclude: T, toExclude: T, argName: String): Unit {
val v = value.toDouble()
shouldBe(v >= fromInclude.toDouble() && v < toExclude.toDouble(),
ShouldBeInRangeInt, argName, value, fromInclude, toExclude)
}
fun Int.shouldBeInRange(range: IntProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun Long.shouldBeInRange(range: LongProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun <T : Number> T.shouldBeBetween(fromInclude: T, toInclude: T, argName: String): Unit {
val v = this.toDouble()
shouldBe(v >= fromInclude.toDouble() && v <= toInclude.toDouble(),
ShouldBeInRangeDouble, argName, this, fromInclude, toInclude)
}
fun Int.shouldBeBetween(range: IntProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun Long.shouldBeBetween(range: LongProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
} | apache-2.0 | 544bb8455c08db9c67685057ed64492e | 31.030075 | 97 | 0.727636 | 3.769027 | false | false | false | false |
PaulWoitaschek/Voice | folderPicker/src/main/kotlin/voice/folderPicker/folderPicker/FolderPickerViewModel.kt | 1 | 2217 | package voice.folderPicker.folderPicker
import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.documentfile.provider.DocumentFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import voice.common.navigation.Destination
import voice.common.navigation.Navigator
import voice.data.folders.AudiobookFolders
import voice.data.folders.FolderType
import javax.inject.Inject
class FolderPickerViewModel
@Inject constructor(
private val audiobookFolders: AudiobookFolders,
private val navigator: Navigator,
) {
@Composable
fun viewState(): FolderPickerViewState {
val folders: List<FolderPickerViewState.Item> by remember {
items()
}.collectAsState(initial = emptyList())
return FolderPickerViewState(folders)
}
private fun items(): Flow<List<FolderPickerViewState.Item>> {
return audiobookFolders.all().map { folders ->
withContext(Dispatchers.IO) {
folders.flatMap { (folderType, folders) ->
folders.map { (documentFile, uri) ->
FolderPickerViewState.Item(
name = documentFile.displayName(),
id = uri,
folderType = folderType,
)
}
}.sortedDescending()
}
}
}
internal fun add(uri: Uri, type: FileTypeSelection) {
when (type) {
FileTypeSelection.File -> {
audiobookFolders.add(uri, FolderType.SingleFile)
}
FileTypeSelection.Folder -> {
navigator.goTo(Destination.SelectFolderType(uri))
}
}
}
fun removeFolder(item: FolderPickerViewState.Item) {
audiobookFolders.remove(item.id, item.folderType)
}
}
private fun DocumentFile.displayName(): String {
val name = name
return if (name == null) {
uri.pathSegments.lastOrNull()
?.dropWhile { it != ':' }
?.removePrefix(":")
?.takeUnless { it.isBlank() }
?: uri.toString()
} else {
name.substringBeforeLast(".")
.takeUnless { it.isEmpty() }
?: name
}
}
| gpl-3.0 | daed601138fddb66e195037649a8b54c | 27.423077 | 63 | 0.693279 | 4.496957 | false | false | false | false |
hanks-zyh/KotlinExample | src/LearnProperties.kt | 1 | 1008 | /**
* Created by hanks on 15-11-25.
*/
public class Address {
public var name: String ? = ""
public var street: String = ""
public var city: String = ""
public var state: String = ""
// getter setter
var zip: String = ""
get() = field
set(value) {
if (value.length > 0) {
field = "$value.zip"
}
}
// getter
val isEmpty: Boolean
get() = this.name.isNullOrEmpty()
}
fun cpoyAddress(address: Address): Address {
val result = Address()
result.name = address.name
result.street = address.street
result.city = address.city
result.state = address.state
result.zip = address.zip
return result
}
fun main(args: Array<String>) {
val address = Address()
println(address.isEmpty) // true
// address.isEmpty = false // compile error
address.name = "hanks"
println(address.isEmpty) // false
address.zip = "info"
println(address.zip) //info.zip
} | apache-2.0 | 17303d65e6357466577a705deaa1b33a | 19.591837 | 50 | 0.575397 | 3.847328 | false | false | false | false |
henrikfroehling/timekeeper | models/src/main/kotlin/de/froehling/henrik/timekeeper/models/Email.kt | 1 | 603 | package de.froehling.henrik.timekeeper.models
import android.support.annotation.IntDef
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
class Email : RealmObject() {
companion object {
final const val TYPE_WORK : Int = 0
final const val TYPE_PRIVATE : Int = 1
}
@IntDef(TYPE_WORK.toLong(), TYPE_PRIVATE.toLong())
@Retention(AnnotationRetention.SOURCE)
annotation class EmailType
@PrimaryKey var uuid: String? = null
@Required var address: String? = null
@EmailType var type: Int = TYPE_WORK
}
| gpl-3.0 | 0943849236d00353a0e56dd982d73a50 | 24.125 | 54 | 0.716418 | 4.04698 | false | false | false | false |
apollo-rsps/apollo | game/plugin-testing/src/main/kotlin/org/apollo/game/plugin/testing/junit/stubs/PlayerStubInfo.kt | 1 | 711 | package org.apollo.game.plugin.testing.junit.stubs
import org.apollo.game.model.Position
import org.apollo.game.plugin.testing.junit.api.annotations.Name
import org.apollo.game.plugin.testing.junit.api.annotations.Pos
class PlayerStubInfo {
companion object {
fun create(annotations: Collection<Annotation>): PlayerStubInfo {
val info = PlayerStubInfo()
annotations.forEach {
when (it) {
is Name -> info.name = it.value
is Pos -> info.position = Position(it.x, it.y, it.height)
}
}
return info
}
}
var position = Position(3222, 3222)
var name = "test"
}
| isc | 771d342c2a6c54d0c75bf52646ec348d | 27.44 | 77 | 0.59775 | 4.109827 | false | true | false | false |
jraska/github-client | feature/users/src/main/java/com/jraska/github/client/users/model/UserDetailWithReposConverter.kt | 1 | 1615 | package com.jraska.github.client.users.model
import org.threeten.bp.Instant
internal class UserDetailWithReposConverter {
fun translateUserDetail(gitHubUserDetail: GitHubUserDetail, gitHubRepos: List<GitHubUserRepo>, reposToDisplay: Int): UserDetail {
val joined = Instant.parse(gitHubUserDetail.createdAt)
val stats = UserStats(
gitHubUserDetail.followers!!, gitHubUserDetail.following!!,
gitHubUserDetail.publicRepos!!, joined
)
val sortedRepos = gitHubRepos.sortedWith(compareByDescending { it.stargazersCount })
val usersRepos = ArrayList<RepoHeader>()
val contributedRepos = ArrayList<RepoHeader>()
for (gitHubRepo in sortedRepos) {
if (usersRepos.size < reposToDisplay && gitHubUserDetail.login == gitHubRepo.owner!!.login) {
val repo = convert(gitHubRepo)
usersRepos.add(repo)
} else if (contributedRepos.size < reposToDisplay) {
val repo = convert(gitHubRepo)
contributedRepos.add(repo)
}
}
val user = convert(gitHubUserDetail)
return UserDetail(user, stats, usersRepos, contributedRepos)
}
private fun convert(gitHubRepo: GitHubUserRepo): RepoHeader {
return RepoHeader(
gitHubRepo.owner!!.login!!,
gitHubRepo.name!!, gitHubRepo.description ?: "",
gitHubRepo.stargazersCount!!, gitHubRepo.forks!!
)
}
private fun convert(gitHubUser: GitHubUserDetail): User {
val isAdmin = gitHubUser.siteAdmin ?: false
return User(gitHubUser.login!!, gitHubUser.avatarUrl!!, isAdmin)
}
companion object {
val INSTANCE = UserDetailWithReposConverter()
}
}
| apache-2.0 | 173bbd01dfd69ceb524ea550f00af2a5 | 31.3 | 131 | 0.715789 | 4.272487 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsConstant.kt | 1 | 1762 | package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.DEFAULT
import org.rust.lang.core.stubs.RsConstantStub
enum class RsConstantKind {
STATIC,
MUT_STATIC,
CONST
}
val RsConstant.kind: RsConstantKind get() = when {
mut != null -> RsConstantKind.MUT_STATIC
const != null -> RsConstantKind.CONST
else -> RsConstantKind.STATIC
}
enum class RsConstantRole {
FREE,
TRAIT_CONSTANT,
IMPL_CONSTANT,
FOREIGN
}
val RsConstant.role: RsConstantRole get() {
return when (parent) {
is RsItemsOwner -> RsConstantRole.FREE
is RsTraitItem -> RsConstantRole.TRAIT_CONSTANT
is RsImplItem -> RsConstantRole.IMPL_CONSTANT
is RsForeignModItem -> RsConstantRole.FOREIGN
else -> error("Unexpected constant parent: $parent")
}
}
val RsConstant.default: PsiElement?
get() = node.findChildByType(DEFAULT)?.psi
val RsConstant.isMut: Boolean
get() = mut != null
abstract class RsConstantImplMixin : RsStubbedNamedElementImpl<RsConstantStub>, RsConstant {
constructor(node: ASTNode) : super(node)
constructor(stub: RsConstantStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int) = iconWithVisibility(flags, when (kind) {
RsConstantKind.CONST -> RsIcons.CONSTANT
RsConstantKind.MUT_STATIC -> RsIcons.MUT_STATIC
RsConstantKind.STATIC -> RsIcons.STATIC
})
override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub)
override val isAbstract: Boolean get() = expr == null
}
| mit | 10e22876215f9d74806c1070c178502e | 28.366667 | 95 | 0.717934 | 4.15566 | false | false | false | false |
daviddenton/databob.kotlin | src/main/kotlin/io/github/databob/Databob.kt | 1 | 1514 | package io.github.databob
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.full.defaultType
import kotlin.reflect.jvm.javaType
class Databob(vararg overrides: Generator) {
private val defaults = listOf(
LanguageConstructsGenerator(),
DateTimeGenerator.instances.random,
CollectionGenerator.instances.random,
PrimitiveGenerator(),
JdkCommonsGenerator(),
CoinToss.generators.even)
private val generator = defaults.plus(overrides.toList()).fold(CompositeGenerator(), CompositeGenerator::with)
inline fun <reified R : Any> mk(): R {
return mk(R::class)
}
@Suppress("UNCHECKED_CAST")
fun <R : Any> mk(c: KClass<R>): R = (generator.mk(c.defaultType.javaType, this) ?: fallback(c)) as R
private fun <R : Any> fallback(c: KClass<R>): R {
val constructor = c.constructors.iterator().next()
val generatedParameters = constructor.parameters
.map {
if (it.type.isMarkedNullable) {
if (mk<CoinToss>().toss()) {
convert(it)
} else {
null
}
} else {
convert(it)
}
}
return constructor.call(*generatedParameters.toTypedArray())
}
private fun convert(it: KParameter) = generator.mk(it.type.javaType, this) ?: mk(Class.forName(it.type.toString().replace("?", "")).kotlin)
}
| apache-2.0 | e6016c5cbe4af5f5a5bdfee95ce27b80 | 33.409091 | 143 | 0.595773 | 4.47929 | false | false | false | false |
masahide318/Croudia-for-Android | app/src/main/kotlin/t/masahide/android/croudia/adapter/TimeLineAdapter.kt | 1 | 4899 | package t.masahide.android.croudia.adapter
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.annotation.ColorRes
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import com.squareup.picasso.Picasso
import t.masahide.android.croudia.R
import t.masahide.android.croudia.databinding.TimeLineRowBinding
import t.masahide.android.croudia.databinding.TimeLineRowShareBinding
import t.masahide.android.croudia.entitiy.Status
import t.masahide.android.croudia.entitiy.User
import t.masahide.android.croudia.service.PreferenceService
/**
* Created by Masahide on 2016/05/05.
*/
class TimeLineAdapter(context: Context, resource: Int, statusList: MutableList<Status>) : ArrayAdapter<Status>(context, resource, statusList) {
lateinit var user: User
init {
val preferenceService = PreferenceService()
user = preferenceService.getUser()
}
enum class ViewType() {
NORMAL,
SHARE
}
override fun getItemViewType(position: Int): Int {
getItem(position).spreadStatus?.let {
return ViewType.SHARE.ordinal
}
return ViewType.NORMAL.ordinal
}
override fun getViewTypeCount(): Int {
return ViewType.values().size
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
if (getItemViewType(position) == ViewType.NORMAL.ordinal) {
return getNormalView(convertView, parent, position)
} else {
return getShareView(convertView, parent, position)
}
}
private fun getNormalView(convertView: View?, parent: ViewGroup?, position: Int): View {
val view: View
val dataBinding: TimeLineRowBinding
if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
dataBinding = DataBindingUtil.inflate(inflater, R.layout.time_line_row, parent, false)
view = dataBinding.root
view.tag = dataBinding
} else {
dataBinding = convertView.tag as TimeLineRowBinding
view = convertView
}
val status = getItem(position)
Picasso.with(context).load(status.user.profileImageUrl).into(dataBinding.userIcon)
Picasso.with(context).load(status.entities?.media?.mediaUrl).into(dataBinding.imgMedia)
dataBinding.txtShare.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
dataBinding.favorite.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
dataBinding.imgReply.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
dataBinding.imgDelete.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
dataBinding.status = status
dataBinding.imgDelete.visibility = if (status.user.id == user.id) View.VISIBLE else View.INVISIBLE
dataBinding.parentLayout.setBackgroundResource(if (status.inReplyToUserId == user.id) R.color.reply_bg else R.color.translate)
return view
}
private fun getShareView(convertView: View?, parent: ViewGroup?, position: Int): View {
val shareDataBinding: TimeLineRowShareBinding
val view: View
if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
shareDataBinding = DataBindingUtil.inflate(inflater, R.layout.time_line_row_share, parent, false)
view = shareDataBinding.root
view.tag = shareDataBinding
} else {
shareDataBinding = convertView.tag as TimeLineRowShareBinding
view = convertView
}
val status = getItem(position)
status.spreadStatus?.let {
Picasso.with(context).load(it.user.profileImageUrl).into(shareDataBinding.userIcon)
Picasso.with(context).load(it.entities?.media?.mediaUrl).into(shareDataBinding.imgMedia)
}
shareDataBinding.txtShare.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
shareDataBinding.favorite.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
shareDataBinding.imgReply.setOnClickListener {
(parent as ListView).performItemClick(parent, position, it.id.toLong())
}
shareDataBinding.imgDelete.visibility = View.INVISIBLE
shareDataBinding.status = status
return view
}
} | apache-2.0 | b9f9fc68f0d7b041922f64255b643c02 | 38.837398 | 143 | 0.687079 | 4.710577 | false | false | false | false |
isuPatches/WiseFy | wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/SearchStore.kt | 1 | 3316 | /*
* Copyright 2019 Patches Klinefelter
*
* 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.isupatches.wisefysample.internal.preferences
import android.content.SharedPreferences
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import com.isupatches.wisefysample.internal.models.SearchType
@VisibleForTesting internal const val PREF_SEARCH_TYPE = "search type"
@VisibleForTesting internal const val PREF_RETURN_FULL_LIST = "return full list"
@VisibleForTesting internal const val PREF_FILTER_DUPLICATES = "filter duplicates"
@VisibleForTesting internal const val PREF_TIMEOUT = "timeout"
internal interface SearchStore {
fun clear()
fun getLastUsedRegex(): String
fun getSearchType(): SearchType
fun shouldReturnFullList(): Boolean
fun shouldFilterDuplicates(): Boolean
fun getTimeout(): Int
fun setLastUsedRegex(lastUsedRegex: String)
fun setSearchType(searchType: SearchType)
fun setReturnFullList(returnFullList: Boolean)
fun setFilterDuplicates(filterDuplicates: Boolean)
fun setTimeout(timeout: Int)
}
internal class SharedPreferencesSearchStore(
private val sharedPreferences: SharedPreferences
) : SearchStore {
override fun clear() {
sharedPreferences.edit { clear() }
}
/*
* Last used Regex
*/
override fun getLastUsedRegex() = sharedPreferences.getLastUsedRegex()
override fun setLastUsedRegex(lastUsedRegex: String) {
sharedPreferences.setLastUsedRegex(lastUsedRegex)
}
/*
* Search type
*/
override fun getSearchType(): SearchType = SearchType.of(
sharedPreferences.getInt(PREF_SEARCH_TYPE, SearchType.ACCESS_POINT.intVal)
)
override fun setSearchType(searchType: SearchType) {
sharedPreferences.edit {
putInt(PREF_SEARCH_TYPE, searchType.intVal)
}
}
/*
* Return full list
*/
override fun shouldReturnFullList() = sharedPreferences.getBoolean(
PREF_RETURN_FULL_LIST,
true
)
override fun setReturnFullList(returnFullList: Boolean) {
sharedPreferences.edit {
putBoolean(PREF_RETURN_FULL_LIST, returnFullList)
}
}
/*
* Filter duplicates
*/
override fun shouldFilterDuplicates() = sharedPreferences.getBoolean(
PREF_FILTER_DUPLICATES,
true
)
override fun setFilterDuplicates(filterDuplicates: Boolean) {
sharedPreferences.edit {
putBoolean(PREF_FILTER_DUPLICATES, filterDuplicates)
}
}
/*
* Timeout
*/
override fun getTimeout() = sharedPreferences.getInt(PREF_TIMEOUT, 1)
override fun setTimeout(timeout: Int) {
sharedPreferences.edit {
putInt(PREF_TIMEOUT, timeout)
}
}
}
| apache-2.0 | a65df0150f544df4b60f8a6aebb495ee | 27.34188 | 82 | 0.705368 | 4.798842 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/navigation/Drawer.kt | 1 | 6044 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthconnectsample.presentation.navigation
import android.content.Intent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ScaffoldState
import androidx.compose.material.Text
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.healthconnectsample.R
import com.example.healthconnectsample.presentation.theme.HealthConnectTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
const val HEALTH_CONNECT_SETTINGS_ACTION = "androidx.health.ACTION_HEALTH_CONNECT_SETTINGS"
/**
* The side navigation drawer used to explore each Health Connect feature.
*/
@Composable
fun Drawer(
scope: CoroutineScope,
scaffoldState: ScaffoldState,
navController: NavController
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
val activity = LocalContext.current
Column {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Image(
modifier = Modifier
.width(96.dp)
.clickable {
navController.navigate(Screen.WelcomeScreen.route) {
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
scope.launch {
scaffoldState.drawerState.close()
}
},
painter = painterResource(id = R.drawable.ic_health_connect_logo),
contentDescription = stringResource(id = R.string.health_connect_logo)
)
}
Spacer(modifier = Modifier.height(16.dp))
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
text = stringResource(id = R.string.app_name)
)
Spacer(modifier = Modifier.height(16.dp))
Screen.values().filter { it.hasMenuItem }.forEach { item ->
DrawerItem(
item = item,
selected = item.route == currentRoute,
onItemClick = {
navController.navigate(item.route) {
// See: https://developer.android.com/jetpack/compose/navigation#nav-to-composable
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
scope.launch {
scaffoldState.drawerState.close()
}
}
)
}
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(
onClick = {
val settingsIntent = Intent()
settingsIntent.action = HEALTH_CONNECT_SETTINGS_ACTION
activity.startActivity(settingsIntent)
}
)
.height(48.dp)
.padding(start = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.settings),
style = MaterialTheme.typography.h5,
color = MaterialTheme.colors.onBackground
)
}
}
}
@Preview
@Composable
fun DrawerPreview() {
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
val navController = rememberNavController()
HealthConnectTheme {
Drawer(
scope = scope,
scaffoldState = scaffoldState,
navController = navController
)
}
}
| apache-2.0 | 403cd68b431984cd0ef61410d1b4d5e6 | 37.496815 | 106 | 0.61863 | 5.494545 | false | false | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/main/java/dWallet/core/bitcoin/protocol/messages/Version.kt | 1 | 2040 | package dwallet.core.bitcoin.protocol.messages
import dwallet.core.bitcoin.protocol.structures.*
import dwallet.core.extensions.*
/**
* Created by unsignedint8 on 8/15/17.
*/
class Version(val version: Int = number, val services: ByteArray = ByteArray(8), val timestamp: Long = System.currentTimeMillis() / 1000, val toAddr: NetworkAddress, val fromAddr: NetworkAddress, val nonce: Long, val ua: String, val startHeight: Int, val relay: Boolean = false) {
companion object {
fun fromBytes(bytes: ByteArray): Version {
val version = bytes.readInt32LE(0)
val services = bytes.sliceArray(4, 12)
val timestamp = bytes.readInt64LE(12)
val toAddr = NetworkAddress.fromBytes(bytes.sliceArray(16, 16 + NetworkAddress.standardSize - 4), false)
val fromAddr = NetworkAddress.fromBytes(bytes.sliceArray(42, 46 + NetworkAddress.standardSize - 4), false)
val nonce = bytes.readInt64LE(72)
val uaSize = bytes.sliceArray(80).readVarStringOffsetLength()
val ua = bytes.sliceArray(80).readVarString()
val startHeight = bytes.readInt32LE((80 + uaSize.first + uaSize.second).toInt())
val relay = if (version >= 70001) bytes[bytes.lastIndex] == 1.toByte() else false
return Version(version, services, timestamp, toAddr, fromAddr, nonce, ua, startHeight, relay)
}
val text = "version"
val verack = "verack"
val number = 70001
}
fun toBytes() = version.toInt32LEBytes() +
services +
timestamp.toInt64LEBytes() +
toAddr.toBytes() +
fromAddr.toBytes() +
nonce.toInt64LEBytes() +
ua.toVarBytes() +
startHeight.toInt32LEBytes() +
(if (version >= 70001) byteArrayOf(if (relay) 1 else 0) else ByteArray(0))
val isFullNode: Boolean = services[0] == 1.toByte()
val canGetUTXO: Boolean = services[1] == 1.toByte()
val canSetBloom: Boolean = services[2] == 1.toByte()
} | gpl-3.0 | 7e2a5a8520ee7774bb89a4917299d46f | 42.425532 | 280 | 0.639706 | 4.031621 | false | false | false | false |
mswift42/apg | Workout/app/src/main/java/mswift42/com/github/workout/WorkoutListFragment.kt | 1 | 1400 | package mswift42.com.github.workout
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.ListFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import java.text.FieldPosition
/**
* A simple [Fragment] subclass.
*/
class WorkoutListFragment : ListFragment () {
internal interface WorkoutListListener {
fun itemClicked(id: Long) : Unit
}
private var listener: WorkoutListListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val names = Workout.workouts.map { it.name }
val adapter = ArrayAdapter<String>(inflater!!.context, android.R.layout.simple_list_item_1,names)
listAdapter = adapter
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
this.listener = context as WorkoutListListener?
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
if (listener != null) {
listener!!.itemClicked(id);
}
}
}// Required empty public constructor
| gpl-3.0 | a42fafe0a8897549a6eeeb8d192af2cf | 30.111111 | 105 | 0.707143 | 4.516129 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ButtonSample.kt | 3 | 3770 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.CompactButton
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.OutlinedButton
import androidx.wear.compose.material.OutlinedCompactButton
import androidx.wear.compose.material.Text
@Sampled
@Composable
fun ButtonWithIcon() {
Button(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier
.size(ButtonDefaults.DefaultIconSize).wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun OutlinedButtonWithIcon() {
OutlinedButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier
.size(ButtonDefaults.DefaultIconSize).wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun LargeButtonWithIcon() {
Button(
onClick = { /* Do something */ },
enabled = true,
modifier = Modifier.size(ButtonDefaults.LargeButtonSize)
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier
.size(ButtonDefaults.LargeIconSize).wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun ButtonWithText() {
Button(
onClick = { /* Do something */ },
enabled = true,
modifier = Modifier.size(ButtonDefaults.LargeButtonSize)
) {
Text("Big")
}
}
@Sampled
@Composable
fun CompactButtonWithIcon() {
CompactButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier
.size(ButtonDefaults.SmallIconSize).wrapContentSize(align = Alignment.Center),
)
}
}
@Sampled
@Composable
fun OutlinedCompactButtonWithIcon() {
OutlinedCompactButton(
onClick = { /* Do something */ },
enabled = true,
) {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier
.size(ButtonDefaults.SmallIconSize).wrapContentSize(align = Alignment.Center),
)
}
}
| apache-2.0 | 7fb5f6d7d794a908dd5cabc9b2e5b63c | 29.16 | 96 | 0.663926 | 4.558646 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/DefaultInventoryImpl.kt | 1 | 3690 | package com.teamwizardry.librarianlib.facade.container
import net.minecraft.inventory.Inventory
import net.minecraft.util.collection.DefaultedList
import net.minecraft.item.ItemStack
import net.minecraft.inventory.Inventories
import net.minecraft.entity.player.PlayerEntity
/**
* A simple `Inventory` implementation with only default methods + an item list getter.
*
*
* Originally by Juuz
*/
public interface DefaultInventoryImpl : Inventory {
/**
* Retrieves the item list of this inventory.
* Must return the same instance every time it's called.
*/
public val items: DefaultedList<ItemStack>
/**
* Returns the inventory size.
*/
override fun size(): Int {
return items.size
}
/**
* Checks if the inventory is empty.
*
* @return true if this inventory has only empty stacks, false otherwise.
*/
override fun isEmpty(): Boolean {
for (i in 0 until size()) {
val stack = getStack(i)
if (!stack.isEmpty) {
return false
}
}
return true
}
/**
* Retrieves the item in the slot.
*/
override fun getStack(slot: Int): ItemStack {
return items[slot]
}
/**
* Removes items from an inventory slot.
*
* @param slot The slot to remove from.
* @param count How many items to remove. If there are less items in the slot than what are requested,
* takes all items in that slot.
*/
override fun removeStack(slot: Int, count: Int): ItemStack {
val result = Inventories.splitStack(items, slot, count)
if (!result.isEmpty) {
markDirty()
}
return result
}
/**
* Removes all items from an inventory slot.
*
* @param slot The slot to remove from.
*/
override fun removeStack(slot: Int): ItemStack {
return Inventories.removeStack(items, slot)
}
/**
* Replaces the current stack in an inventory slot with the provided stack.
*
* @param slot The inventory slot of which to replace the itemstack.
* @param stack The replacing itemstack. If the stack is too big for
* this inventory ([Inventory.getMaxCountPerStack]),
* it gets resized to this inventory's maximum amount.
*/
override fun setStack(slot: Int, stack: ItemStack) {
items[slot] = stack
if (stack.count > maxCountPerStack) {
stack.count = maxCountPerStack
}
}
/**
* Clears the inventory.
*/
override fun clear() {
items.clear()
}
/**
* Marks the state as dirty.
* Must be called after changes in the inventory, so that the game can properly save
* the inventory contents and notify neighboring blocks of inventory changes.
*/
override fun markDirty() {
// Override if you want behavior.
}
/**
* @return true if the player can use the inventory, false otherwise.
*/
override fun canPlayerUse(player: PlayerEntity): Boolean {
return true
}
public companion object {
/**
* Creates an inventory from the item list.
*/
@JvmStatic
public fun of(items: DefaultedList<ItemStack>): DefaultInventoryImpl {
return object : DefaultInventoryImpl {
override val items: DefaultedList<ItemStack> = items
}
}
/**
* Creates a new inventory with the specified size.
*/
@JvmStatic
public fun ofSize(size: Int): DefaultInventoryImpl {
return of(DefaultedList.ofSize(size, ItemStack.EMPTY))
}
}
} | lgpl-3.0 | d1c12c7fdc7791fdcddfe3c2dbe3e677 | 26.962121 | 106 | 0.610298 | 4.566832 | false | false | false | false |
mickele/DBFlow | dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/BaseDefinition.kt | 1 | 5406 | package com.raizlabs.android.dbflow.processor.definition
import com.raizlabs.android.dbflow.processor.ProcessorManager
import com.raizlabs.android.dbflow.processor.utils.ElementUtility
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.util.*
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
/**
* Description: Holds onto a common-set of fields and provides a common-set of methods to output class files.
*/
abstract class BaseDefinition : TypeDefinition {
val manager: ProcessorManager
var elementClassName: ClassName? = null
var elementTypeName: TypeName? = null
lateinit var outputClassName: ClassName
var erasedTypeName: TypeName? = null
var element: Element
var typeElement: TypeElement? = null
var elementName: String
var packageName: String
constructor(element: ExecutableElement, processorManager: ProcessorManager) {
this.manager = processorManager
this.element = element
packageName = manager.elements.getPackageOf(element).toString()
elementName = element.simpleName.toString()
try {
val typeMirror = element.asType()
elementTypeName = TypeName.get(typeMirror)
elementTypeName?.let {
if (!it.isPrimitive) {
elementClassName = getElementClassName(element)
}
}
val erasedType = processorManager.typeUtils.erasure(typeMirror)
erasedTypeName = TypeName.get(erasedType)
} catch (e: Exception) {
}
}
constructor(element: Element, processorManager: ProcessorManager) {
this.manager = processorManager
this.element = element
packageName = manager.elements.getPackageOf(element).toString()
try {
val typeMirror: TypeMirror
if (element is ExecutableElement) {
typeMirror = element.returnType
elementTypeName = TypeName.get(typeMirror)
} else {
typeMirror = element.asType()
elementTypeName = TypeName.get(typeMirror)
}
val erasedType = processorManager.typeUtils.erasure(typeMirror)
erasedTypeName = TypeName.get(erasedType)
} catch (i: IllegalArgumentException) {
manager.logError("Found illegal type:" + element.asType() + " for " + element.simpleName.toString())
manager.logError("Exception here:" + i.toString())
}
elementName = element.simpleName.toString()
elementTypeName?.let {
if (!it.isPrimitive) elementClassName = getElementClassName(element)
}
if (element is TypeElement) {
typeElement = element
}
}
constructor(element: TypeElement, processorManager: ProcessorManager) {
this.manager = processorManager
this.typeElement = element
this.element = element
elementClassName = ClassName.get(typeElement)
elementTypeName = TypeName.get(element.asType())
elementName = element.simpleName.toString()
packageName = manager.elements.getPackageOf(element).toString()
}
protected open fun getElementClassName(element: Element): ClassName? {
try {
return ElementUtility.getClassName(element.asType().toString(), manager)
} catch (e: Exception) {
return null
}
}
protected fun setOutputClassName(postfix: String) {
val outputName: String
if (elementClassName == null) {
if (elementTypeName is ClassName) {
outputName = (elementTypeName as ClassName).simpleName()
} else if (elementTypeName is ParameterizedTypeName) {
outputName = (elementTypeName as ParameterizedTypeName).rawType.simpleName()
elementClassName = (elementTypeName as ParameterizedTypeName).rawType
} else {
outputName = elementTypeName.toString()
}
} else {
outputName = elementClassName!!.simpleName()
}
outputClassName = ClassName.get(packageName, outputName + postfix)
}
protected fun setOutputClassNameFull(fullName: String) {
outputClassName = ClassName.get(packageName, fullName)
}
override val typeSpec: TypeSpec
get() {
val typeBuilder = TypeSpec.classBuilder(outputClassName.simpleName())
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addSuperinterfaces(Arrays.asList(*implementsClasses))
val extendsClass = extendsClass
if (extendsClass != null) {
typeBuilder.superclass(extendsClass)
}
typeBuilder.addJavadoc("This is generated code. Please do not modify")
onWriteDefinition(typeBuilder)
return typeBuilder.build()
}
protected open val extendsClass: TypeName?
get() = null
protected val implementsClasses: Array<TypeName>
get() = arrayOf()
open fun onWriteDefinition(typeBuilder: TypeSpec.Builder) {
}
}
| mit | aeeab42c7c7e62d2b7999b801c99aa0d | 35.527027 | 112 | 0.653718 | 5.253644 | false | false | false | false |
kotlinx/kotlinx.html | src/commonMain/kotlin/generated/gen-tags-n.kt | 1 | 1139 | package kotlinx.html
import kotlinx.html.*
import kotlinx.html.impl.*
import kotlinx.html.attributes.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
@Suppress("unused")
open class NAV(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("nav", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowSectioningContent {
}
val NAV.asFlowContent : FlowContent
get() = this
val NAV.asSectioningContent : SectioningContent
get() = this
@Suppress("unused")
open class NOSCRIPT(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("noscript", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowMetaDataPhrasingContent {
}
val NOSCRIPT.asFlowContent : FlowContent
get() = this
val NOSCRIPT.asMetaDataContent : MetaDataContent
get() = this
val NOSCRIPT.asPhrasingContent : PhrasingContent
get() = this
| apache-2.0 | 8d9495756d7825b984c6fe8015064392 | 30.638889 | 228 | 0.649693 | 4.867521 | false | false | false | false |
MaTriXy/android-topeka | app/src/main/java/com/google/samples/apps/topeka/adapter/OptionsQuizAdapter.kt | 1 | 2741 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.adapter
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.helper.inflate
/**
* A simple adapter to display a options of a quiz.
*
* @param options The options to add to the adapter.
*
* @param layoutId Must consist of a single [TextView].
*
* @param context The context for the adapter.
*
* @param withPrefix True if a prefix should be given to all items.
*/
class OptionsQuizAdapter(
private val options: Array<String>,
private val layoutId: Int,
context: Context? = null,
withPrefix: Boolean = false
) : BaseAdapter() {
private val alphabet: Array<String> = if (withPrefix && context != null) {
context.resources.getStringArray(R.array.alphabet)
} else {
emptyArray()
}
override fun getCount() = options.size
override fun getItem(position: Int) = options[position]
override fun getItemId(position: Int) = position.toLong()
/* Important to return true in order to get checked items from this adapter correctly */
override fun hasStableIds(): Boolean = true
override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
((convertView ?: parent.context.inflate(layoutId, parent, false)) as TextView)
.apply {
text = getText(position)
}
private fun getText(position: Int): String {
return if (alphabet.isNotEmpty()) "${getPrefix(position)}${getItem(position)}"
else getItem(position)
}
private fun getPrefix(position: Int): String {
/* Only ever to be called in case alphabet != null */
val length = alphabet.size
if (position >= length || 0 > position) {
throw IllegalArgumentException("Only positions between 0 and $length are supported")
}
return if (position < length) "${alphabet[position]}."
else "${getPrefix(position % length)}."
}
}
| apache-2.0 | fabd0b2e005a14eb904bb294d1b96c8f | 33.2625 | 96 | 0.676395 | 4.449675 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/HaskellDebuggerEditorsProvider.kt | 1 | 1916 | package org.jetbrains.haskell.debugger
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.openapi.fileTypes.FileType
import org.jetbrains.haskell.fileType.HaskellFileType
import org.jetbrains.haskell.fileType.HaskellFile
import org.jetbrains.haskell.HaskellViewProvider
import com.intellij.psi.impl.PsiManagerImpl
import com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.haskell.fileType.HaskellFileViewProviderFactory
import com.intellij.psi.PsiFileFactory
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.psi.impl.source.PsiExpressionCodeFragmentImpl
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.EvaluationMode
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory
import com.intellij.psi.PsiDocumentManager
public class HaskellDebuggerEditorsProvider : XDebuggerEditorsProvider() {
override fun createDocument(project: Project,
text: String,
sourcePosition: XSourcePosition?,
mode: EvaluationMode): Document {
if(sourcePosition != null) {
val hsPsiFile = PsiFileFactory.getInstance(project)!!.createFileFromText(sourcePosition.getFile().getName(),
HaskellFileType.INSTANCE,
text)
val hsDocument = PsiDocumentManager.getInstance(project)!!.getDocument(hsPsiFile)
if(hsDocument != null) {
return hsDocument
}
}
return EditorFactory.getInstance()!!.createDocument(text)
}
override fun getFileType(): FileType = HaskellFileType.INSTANCE
} | apache-2.0 | 9b609ebefdd3452a075cc62e9500b4af | 43.581395 | 120 | 0.75 | 5.292818 | false | false | false | false |
czyzby/ktx | scene2d/src/test/kotlin/ktx/scene2d/TooltipTest.kt | 2 | 1681 | package ktx.scene2d
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Tooltip
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Tests extension methods that allow to add [Tooltip] instances to all actors.
*/
class TooltipTest : ApplicationTest() {
@Test
fun `should add TextTooltip`() {
val actor = Actor()
val tooltip = actor.textTooltip("Test.")
assertNotNull(tooltip)
assertTrue(tooltip in actor.listeners)
assertEquals("Test.", tooltip.actor.text.toString())
}
@Test
fun `should add TextTooltip with init block`() {
val actor = Actor()
val variable: Int
val tooltip = actor.textTooltip("Test.") {
// Changing Label color:
color = Color.BLUE
variable = 42
}
assertNotNull(tooltip)
assertTrue(tooltip in actor.listeners)
assertEquals("Test.", tooltip.actor.text.toString())
assertEquals(Color.BLUE, tooltip.actor.color)
assertEquals(42, variable)
}
@Test
fun `should add Tooltip with init block`() {
val actor = Actor()
val variable: Int
val tooltip = actor.tooltip {
// Changing Table color:
color = Color.BLUE
// Adding child to Table content:
label("Test.")
variable = 42
}
assertNotNull(tooltip)
assertTrue(tooltip in actor.listeners)
assertEquals("Test.", (tooltip.actor.children.first() as Label).text.toString())
assertEquals(Color.BLUE, tooltip.actor.color)
assertEquals(42, variable)
}
}
| cc0-1.0 | b7187039fe34a8c3f17a72964a65f881 | 25.265625 | 84 | 0.69304 | 4.021531 | false | true | false | false |
EmpowerOperations/getoptk | src/test/kotlin/com/empowerops/getoptk/HelpOptionFixture.kt | 1 | 10410 | package com.empowerops.getoptk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* Created by Geoff on 2017-04-17.
*/
class HelpOptionFixture {
val ` ` = " "
@Test fun `when asking for --help on simple class should produce good message by default`(){
val ex = assertThrows<HelpException> { arrayOf("--help").parsedAs("prog.exe") { SimpleHelpableOptionSet() } }
//TBD: how do we specify what to do with outputs?
// more importantly, if we dont use exception flow then we need a valid instance of the object
// without having hit any options, required or not.
// This means that every single option regardless of its required-status must have a valid default.
//TBD: the exact format. some to consider below.
assertThat(ex.message).isEqualTo("""
|usage: prog.exe
| -f,--first <decimal> the first value that is to be tested
| -sec,--second <int> Lorem ipsum dolor sit amet, consectetur adipiscing${` `}
| elit, sed do eiusmod tempor incididunt ut labore${` `}
| et dolore magna aliqua. Ut enim ad minim veniam,${` `}
| quis nostrud exercitation ullamco laboris nisi ut
""".trimMargin().replace("\n", System.lineSeparator()).trim()
)
}
class SimpleHelpableOptionSet: CLI(){
val first: Double by getValueOpt {
description = "the first value that is to be tested"
}
val second: Int by getValueOpt {
description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut"
shortName = "sec"
}
}
@Test fun `when dealing with boolean options should still properly format`(){
val ex = assertThrows<HelpException> { arrayOf("--help").parsedAs("prog.exe") { SimpleHelpableOptionSetWithBoolean() } }
assertThat(ex.message).isEqualTo("""
|usage: prog.exe
| -f,--first <decimal> the first value that is to be tested
| -sec,--second Lorem ipsum dolor sit amet, consectetur adipiscing${` `}
| elit, sed do eiusmod tempor incididunt ut labore${` `}
| et dolore magna aliqua. Ut enim ad minim veniam,${` `}
| quis nostrud exercitation ullamco laboris nisi ut
""".trimMargin().replace("\n", System.lineSeparator()).trim()
)
}
class SimpleHelpableOptionSetWithBoolean: CLI(){
val first: Double by getValueOpt {
description = "the first value that is to be tested"
}
val second: Boolean by getFlagOpt {
description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut"
shortName = "sec"
}
}
@Test fun `when dealing with long names should still properly format`(){
val ex = assertThrows<HelpException> { arrayOf("--help").parsedAs("prog.exe") { HelpableOptionSetWithLongName() } }
assertThat(ex.message).isEqualTo("""
|usage: prog.exe
| -f,--first <decimal> the first value that is to be tested
| -blargwargl, Lorem ipsum dolor sit amet, consectetur adipiscing${` `}
| --super-deduper-long-name elit, sed do eiusmod tempor incididunt ut labore${` `}
| <decimal> et dolore magna aliqua. Ut enim ad minim veniam,${` `}
| quis nostrud exercitation ullamco laboris nisi ut${` `}
| -b, Surprisingly short description${` `}
| --super-deduper-deduper-real
| ly-long-name
| <decimal>
| -a,--a <int>
""".trimMargin().replace("\n", System.lineSeparator()).trim()
)
}
class HelpableOptionSetWithLongName: CLI(){
val first: Double by getValueOpt {
description = "the first value that is to be tested"
}
val superDeduperLongName: Double by getValueOpt {
description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut"
longName = "super-deduper-long-name"
shortName = "blargwargl"
}
val anotherSuperDeduperLongName: Int by getValueOpt {
description = "Surprisingly short description"
shortName = "b"
longName = "super-deduper-deduper-really-long-name"
}
val a: Int by getValueOpt()
}
}
/*
[ Apache CLI: https://commons.apache.org/proper/commons-cli/ ]
usage: prog.exe
-A,--almost-all do not list implied . and ..
-a,--all do not hide entries starting with .
-B,--ignore-backups do not list implied entried ending with ~
-b,--escape print octal escapes for nongraphic characters
--block-size <SIZE> use SIZE-byte blocks
-c with -lt: sort by, and show, ctime (time of last
modification of file status information) with
-l:show ctime and sort by name otherwise: sort
by ctime
-C list entries by columns
[ GNU ]
ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort.
Mandatory arguments to long options are mandatory for short options too.
-a, --all do not ignore entries starting with .
-A, --almost-all do not list implied . and ..
--author with -l, print the author of each file
-b, --escape print octal escapes for nongraphic characters
--block-size=SIZE use SIZE-byte blocks. See SIZE format below
-B, --ignore-backups do not list implied entries ending with ~
-c with -lt: sort by, and show, ctime (time of last
modification of file status information)
with -l: show ctime and sort by name
otherwise: sort by ctime
-C list entries by columns
--color[=WHEN] colorize the output. WHEN defaults to `always'
or can be `never' or `auto'. More info below
-d, --directory list directory entries instead of contents,
and do not dereference symbolic links
-D, --dired generate output designed for Emacs' dired mode
-f do not sort, enable -aU, disable -ls --color
-F, --classify append indicator (one of *=>@|) to entries
[ powershell ]
> powershell /?
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
[ JCommander ]
> kobaltw --help
_ __ _ _ _
| |/ / ___ | |__ __ _ | | | |_
| ' / / _ \ | '_ \ / _` | | | | __|
| . \ | (_) | | |_) | | (_| | | | | |_
|_|\_\ \___/ |_.__/ \__,_| |_| \__| 1.0.68
Usage: <main class> [options]
Options:
-bf, --buildFile
The build file
Default: kobalt/src/Build.kt
--checkVersions
Check if there are any newer versions of the dependencies
Default: false
--client
Default: false
--dev
Turn on dev mode, resulting in a more verbose log output
Default: false
--download
Force a download from the downloadUrl in the wrapper
Default: false
[ msbuild ]
> msbuild /?
Microsoft (R) Build Engine version 12.0.31101.0
[Microsoft .NET Framework, version 4.0.30319.42000]
Copyright (C) Microsoft Corporation. All rights reserved.
Syntax: MSBuild.exe [options] [project file]
Description: Builds the specified targets in the project file. If
a project file is not specified, MSBuild searches the
current working directory for a file that has a file
extension that ends in "proj" and uses that file.
Switches:
/target:<targets> Build these targets in this project. Use a semicolon or a
comma to separate multiple targets, or specify each
target separately. (Short form: /t)
Example:
/target:Resources;Compile
/property:<n>=<v> Set or override these project-level properties. <n> is
the property name, and <v> is the property value. Use a
semicolon or a comma to separate multiple properties, or
specify each property separately. (Short form: /p)
Example:
/property:WarningLevel=2;OutDir=bin\Debug\
*/ | apache-2.0 | 0d581a299239c5e0c04af1e903d4fa8c | 40.478088 | 128 | 0.566186 | 4.32309 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Outfit.kt | 1 | 721 | package com.habitrpg.android.habitica.models.user
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.shared.habitica.models.AvatarOutfit
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class Outfit : RealmObject(), BaseObject, AvatarOutfit {
override var armor: String = ""
override var back: String = ""
override var body: String = ""
override var head: String = ""
override var shield: String = ""
override var weapon: String = ""
@SerializedName("eyewear")
override var eyeWear: String = ""
override var headAccessory: String = ""
}
| gpl-3.0 | 749f0efa514bd7330391d42601434772 | 34.05 | 61 | 0.718447 | 4.19186 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/sequences/PsiElement.kt | 1 | 5175 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.sequences
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.elementType
import java.util.*
private class PsiElementTreeIterator(node: PsiElement?) : Iterator<PsiElement> {
private val stack: Stack<PsiElement> = Stack()
init {
stack.push(node)
}
override fun hasNext(): Boolean = !stack.isEmpty()
override fun next(): PsiElement {
val current = stack.pop()
// An element (file) with a directory as a parent may be part of a
// resource JAR file. This can cause the file to have a different
// object location to the child in the parent directory, which will
// result in nextSibling logging a "Cannot find element among its
// parent' children." error.
if (current?.parent !is PsiDirectory) {
val right = current?.nextSibling
if (right != null) {
stack.push(right)
}
}
val left = current?.firstChild
if (left != null) {
stack.push(left)
}
return current
}
}
private class PsiElementIterator(
private var node: PsiElement?,
private val end: PsiElement?,
private var walk: (PsiElement) -> PsiElement?
) : Iterator<PsiElement> {
constructor(node: PsiElement?, walk: (PsiElement) -> PsiElement?) : this(node, null, walk)
override fun hasNext(): Boolean = node != end
override fun next(): PsiElement {
val ret = node!!
node = walk(ret)
return ret
}
}
class PsiElementReversibleSequence(
internal var node: PsiElement,
internal var gen: (PsiElement) -> Iterator<PsiElement>,
internal var rgen: (PsiElement) -> Iterator<PsiElement>
) : Sequence<PsiElement> {
override fun iterator(): Iterator<PsiElement> = gen(node)
}
fun reverse(s: PsiElementReversibleSequence): PsiElementReversibleSequence {
return PsiElementReversibleSequence(s.node, s.rgen, s.gen)
}
fun PsiElement.contexts(strict: Boolean): Sequence<PsiElement> = when (strict) {
true -> PsiElementIterator(context, PsiElement::getContext).asSequence()
else -> PsiElementIterator(this, PsiElement::getContext).asSequence()
}
fun PsiElement.ancestors(): Sequence<PsiElement> {
return PsiElementIterator(parent, PsiElement::getParent).asSequence()
}
fun PsiElement.ancestorsAndSelf(): Sequence<PsiElement> {
return PsiElementIterator(this, PsiElement::getParent).asSequence()
}
fun PsiElement.descendants(): Sequence<PsiElement> {
return PsiElementIterator(firstChild, PsiElement::getFirstChild).asSequence()
}
fun PsiElement.children(): PsiElementReversibleSequence = PsiElementReversibleSequence(this,
{ e -> PsiElementIterator(e.firstChild, PsiElement::getNextSibling) },
{ e -> PsiElementIterator(e.lastChild, PsiElement::getPrevSibling) }
)
fun PsiElement.siblings(end: PsiElement? = null): PsiElementReversibleSequence = PsiElementReversibleSequence(this,
{ e -> PsiElementIterator(e.nextSibling, end, PsiElement::getNextSibling) },
{ e -> PsiElementIterator(e.prevSibling, end, PsiElement::getPrevSibling) }
)
fun PsiElement.walkTree(): PsiElementReversibleSequence = PsiElementReversibleSequence(this,
{ element -> PsiElementTreeIterator(element) },
{ element ->
PsiElementIterator(element) { e ->
val parent = e.parent
// An element (file) with a directory as a parent may be part of a
// resource JAR file. This can cause the file to have a different
// object location to the child in the parent directory, which will
// result in prevSibling logging a "Cannot find element among its
// parent' children." error.
(if (parent is PsiDirectory) null else e.prevSibling) ?: parent
}
}
)
fun Sequence<PsiElement>.filterIsElementType(elementType: IElementType): Sequence<PsiElement> = filter {
it.elementType === elementType
}
@Suppress("unused")
fun Sequence<PsiElement>.filterIsElementType(tokens: TokenSet): Sequence<PsiElement> = filter {
tokens.contains(it.elementType)
}
@Suppress("unused")
fun Sequence<PsiElement>.filterIsNotElementType(elementType: IElementType): Sequence<PsiElement> = filter {
it.elementType !== elementType
}
@Suppress("unused")
fun Sequence<PsiElement>.filterIsNotElementType(tokens: TokenSet): Sequence<PsiElement> = filter {
!tokens.contains(it.elementType)
}
| apache-2.0 | 0cdf3192c2c83d5cc73db9d569b4295e | 34.689655 | 115 | 0.702995 | 4.38188 | false | false | false | false |
jiaminglu/kotlin-native | samples/csvparser/src/main/kotlin/CsvParser.kt | 1 | 2275 | /*
* 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.
*/
import kotlinx.cinterop.*
import stdio.*
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
val builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder.length = 0
}
else -> builder.append(ch)
}
}
return result
}
fun main(args: Array<String>) {
if (args.size != 3) {
println("usage: csvparser.kexe file.csv column count")
return
}
val fileName = args[0]
val column = args[1].toInt()
val count = args[2].toInt()
val file = fopen(fileName, "r")
if (file == null) {
perror("cannot open input file $fileName")
return
}
val keyValue = mutableMapOf<String, Int>()
try {
memScoped {
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)
for (i in 1..count) {
val nextLine = fgets(buffer, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
val records = parseLine(nextLine, ',')
val key = records[column]
val current = keyValue[key] ?: 0
keyValue[key] = current + 1
}
}
} finally {
fclose(file)
}
keyValue.forEach {
println("${it.key} -> ${it.value}")
}
}
| apache-2.0 | 1d73f7dc036da2529a8c9b54c697c587 | 27.4375 | 77 | 0.551209 | 4.159049 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/activity/UserActivity.kt | 2 | 3596 | package com.commit451.gitlab.activity
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.palette.graphics.Palette
import coil.api.load
import com.commit451.addendum.themeAttrColor
import com.commit451.alakazam.navigationBarColorAnimator
import com.commit451.gitlab.R
import com.commit451.gitlab.extension.feedUrl
import com.commit451.gitlab.fragment.FeedFragment
import com.commit451.gitlab.image.PaletteImageViewTarget
import com.commit451.gitlab.model.api.User
import com.commit451.gitlab.util.ImageUtil
import kotlinx.android.synthetic.main.activity_user.*
/**
* User activity, which shows the user!
*/
class UserActivity : BaseActivity() {
companion object {
private const val KEY_USER = "user"
fun newIntent(context: Context, user: User): Intent {
val intent = Intent(context, UserActivity::class.java)
intent.putExtra(KEY_USER, user)
return intent
}
}
private lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user)
user = intent.getParcelableExtra(KEY_USER)!!
// Default content and scrim colors
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE)
collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE)
toolbar.setNavigationIcon(R.drawable.ic_back_24dp)
toolbar.setNavigationOnClickListener { onBackPressed() }
toolbar.title = user.username
val url = ImageUtil.getAvatarUrl(user, resources.getDimensionPixelSize(R.dimen.user_header_image_size))
val paletteImageViewTarget = PaletteImageViewTarget(backdrop) {
bindPalette(it)
}
backdrop.load(url) {
allowHardware(false)
target(paletteImageViewTarget)
}
if (savedInstanceState == null) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction
.add(R.id.user_feed, FeedFragment.newInstance(user.feedUrl))
.commit()
}
}
override fun onBackPressed() {
supportFinishAfterTransition()
}
override fun hasBrowsableLinks(): Boolean {
return true
}
private fun bindPalette(palette: Palette) {
val animationTime = 1000
val vibrantColor = palette.getVibrantColor(this.themeAttrColor(R.attr.colorPrimary))
val darkerColor = this.themeAttrColor(vibrantColor)
window.navigationBarColorAnimator(darkerColor)
.setDuration(animationTime.toLong())
.start()
window.statusBarColor = darkerColor
ObjectAnimator.ofObject(collapsingToolbarLayout, "contentScrimColor", ArgbEvaluator(),
this.themeAttrColor(R.attr.colorPrimary), vibrantColor)
.setDuration(animationTime.toLong())
.start()
ObjectAnimator.ofObject(collapsingToolbarLayout, "statusBarScrimColor", ArgbEvaluator(),
this.themeAttrColor(R.attr.colorPrimaryDark), darkerColor)
.setDuration(animationTime.toLong())
.start()
ObjectAnimator.ofObject(toolbar, "titleTextColor", ArgbEvaluator(),
Color.WHITE, palette.getDarkMutedColor(Color.BLACK))
.setDuration(animationTime.toLong())
.start()
}
}
| apache-2.0 | a4a2104e81059fac1ad393f20e9c34ce | 34.254902 | 111 | 0.687709 | 4.912568 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsGeneralScreen.kt | 1 | 4710 | package eu.kanade.presentation.more.settings.screen
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.os.LocaleListCompat
import eu.kanade.domain.base.BasePreferences
import eu.kanade.domain.library.service.LibraryPreferences
import eu.kanade.presentation.more.settings.Preference
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.LocaleHelper
import org.xmlpull.v1.XmlPullParser
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class SettingsGeneralScreen : SearchableSettings {
@Composable
@ReadOnlyComposable
@StringRes
override fun getTitleRes() = R.string.pref_category_general
@Composable
override fun getPreferences(): List<Preference> {
val prefs = remember { Injekt.get<BasePreferences>() }
val libraryPrefs = remember { Injekt.get<LibraryPreferences>() }
return mutableListOf<Preference>().apply {
add(
Preference.PreferenceItem.SwitchPreference(
pref = libraryPrefs.showUpdatesNavBadge(),
title = stringResource(R.string.pref_library_update_show_tab_badge),
),
)
add(
Preference.PreferenceItem.SwitchPreference(
pref = prefs.confirmExit(),
title = stringResource(R.string.pref_confirm_exit),
),
)
val context = LocalContext.current
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
add(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.pref_manage_notifications),
onClick = {
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
}
context.startActivity(intent)
},
),
)
}
val langs = remember { getLangs(context) }
var currentLanguage by remember { mutableStateOf(AppCompatDelegate.getApplicationLocales().get(0)?.toLanguageTag() ?: "") }
add(
Preference.PreferenceItem.BasicListPreference(
value = currentLanguage,
title = stringResource(R.string.pref_app_language),
subtitle = "%s",
entries = langs,
onValueChanged = { newValue ->
currentLanguage = newValue
true
},
),
)
LaunchedEffect(currentLanguage) {
val locale = if (currentLanguage.isEmpty()) {
LocaleListCompat.getEmptyLocaleList()
} else {
LocaleListCompat.forLanguageTags(currentLanguage)
}
AppCompatDelegate.setApplicationLocales(locale)
}
}
}
private fun getLangs(context: Context): Map<String, String> {
val langs = mutableListOf<Pair<String, String>>()
val parser = context.resources.getXml(R.xml.locales_config)
var eventType = parser.eventType
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && parser.name == "locale") {
for (i in 0 until parser.attributeCount) {
if (parser.getAttributeName(i) == "name") {
val langTag = parser.getAttributeValue(i)
val displayName = LocaleHelper.getDisplayName(langTag)
if (displayName.isNotEmpty()) {
langs.add(Pair(langTag, displayName))
}
}
}
}
eventType = parser.next()
}
langs.sortBy { it.second }
langs.add(0, Pair("", context.getString(R.string.label_default)))
return langs.toMap()
}
}
| apache-2.0 | f65288c787d940f003e0f126c161d2df | 38.579832 | 135 | 0.591295 | 5.364465 | false | false | false | false |
Heiner1/AndroidAPS | insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt | 1 | 981 | package info.nightscout.androidaps.insight.database
class InsightDbHelper (val insightDatabaseDao: InsightDatabaseDao) {
fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? = insightDatabaseDao.getInsightBolusID(pumpSerial, bolusID, timestamp)
fun createOrUpdate(insightBolusID: InsightBolusID) = insightDatabaseDao.createOrUpdate(insightBolusID)
fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? = insightDatabaseDao.getInsightHistoryOffset(pumpSerial)
fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) = insightDatabaseDao.createOrUpdate(insightHistoryOffset)
fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = insightDatabaseDao.getPumpStoppedEvent(pumpSerial, timestamp, InsightPumpID.EventType.PumpStopped, InsightPumpID.EventType.PumpPaused)
fun createOrUpdate(insightPumpID: InsightPumpID) = insightDatabaseDao.createOrUpdate(insightPumpID)
} | agpl-3.0 | f6bd46f17f478d10ca2f0a1573fab069 | 56.764706 | 217 | 0.840979 | 4.520737 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/ExpoTurboPackage.kt | 2 | 4416 | // Copyright 2020-present 650 Industries. All rights reserved.
package abi43_0_0.host.exp.exponent
import abi43_0_0.com.facebook.react.TurboReactPackage
import abi43_0_0.com.facebook.react.bridge.NativeModule
import abi43_0_0.com.facebook.react.bridge.ReactApplicationContext
import abi43_0_0.com.facebook.react.module.annotations.ReactModule
import abi43_0_0.com.facebook.react.module.annotations.ReactModuleList
import abi43_0_0.com.facebook.react.module.model.ReactModuleInfo
import abi43_0_0.com.facebook.react.module.model.ReactModuleInfoProvider
import abi43_0_0.com.facebook.react.modules.intent.IntentModule
import abi43_0_0.com.facebook.react.modules.storage.AsyncStorageModule
import abi43_0_0.com.facebook.react.turbomodule.core.interfaces.TurboModule
import abi43_0_0.com.facebook.react.uimanager.ViewManager
import expo.modules.manifests.core.Manifest
import host.exp.exponent.kernel.KernelConstants
import abi43_0_0.host.exp.exponent.modules.internal.ExponentAsyncStorageModule
import abi43_0_0.host.exp.exponent.modules.internal.ExponentIntentModule
import abi43_0_0.host.exp.exponent.modules.internal.ExponentUnsignedAsyncStorageModule
/** Package defining basic modules and view managers. */
@ReactModuleList(
nativeModules = [
// TODO(Bacon): Do we need to support unsigned storage module here?
ExponentAsyncStorageModule::class,
ExponentIntentModule::class
]
)
class ExpoTurboPackage(
private val experienceProperties: Map<String, Any?>,
private val manifest: Manifest
) : TurboReactPackage() {
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return listOf()
}
override fun getModule(name: String, context: ReactApplicationContext): NativeModule? {
val isVerified = manifest.isVerified()
return when (name) {
AsyncStorageModule.NAME -> if (isVerified) {
ExponentAsyncStorageModule(context, manifest)
} else {
ExponentUnsignedAsyncStorageModule(context)
}
IntentModule.NAME -> ExponentIntentModule(
context,
experienceProperties
)
else -> null
}
}
override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
return try {
// TODO(Bacon): Does this need to reflect ExpoTurboPackage$$ReactModuleInfoProvider ?
val reactModuleInfoProviderClass = Class.forName("com.facebook.react.shell.MainReactPackage$\$ReactModuleInfoProvider")
reactModuleInfoProviderClass.newInstance() as ReactModuleInfoProvider
} catch (e: ClassNotFoundException) {
// In OSS case, the annotation processor does not run. We fall back on creating this by hand
val moduleList: Array<Class<out NativeModule?>> = arrayOf(
// TODO(Bacon): Do we need to support unsigned storage module here?
ExponentAsyncStorageModule::class.java,
ExponentIntentModule::class.java
)
val reactModuleInfoMap = mutableMapOf<String, ReactModuleInfo>()
for (moduleClass in moduleList) {
val reactModule = moduleClass.getAnnotation(ReactModule::class.java)!!
val isTurbo = TurboModule::class.java.isAssignableFrom(moduleClass)
reactModuleInfoMap[reactModule.name] = ReactModuleInfo(
reactModule.name,
moduleClass.name,
reactModule.canOverrideExistingModule,
reactModule.needsEagerInit,
reactModule.hasConstants,
reactModule.isCxxModule,
isTurbo
)
}
ReactModuleInfoProvider { reactModuleInfoMap }
} catch (e: InstantiationException) {
throw RuntimeException(
"No ReactModuleInfoProvider for CoreModulesPackage$\$ReactModuleInfoProvider", e
)
} catch (e: IllegalAccessException) {
throw RuntimeException(
"No ReactModuleInfoProvider for CoreModulesPackage$\$ReactModuleInfoProvider", e
)
}
}
companion object {
private val TAG = ExpoTurboPackage::class.java.simpleName
fun kernelExpoTurboPackage(manifest: Manifest, initialURL: String?): ExpoTurboPackage {
val kernelExperienceProperties = mutableMapOf(
KernelConstants.LINKING_URI_KEY to "exp://",
KernelConstants.IS_HEADLESS_KEY to false,
).apply {
if (initialURL != null) {
this[KernelConstants.INTENT_URI_KEY] = initialURL
}
}
return ExpoTurboPackage(kernelExperienceProperties, manifest)
}
}
}
| bsd-3-clause | 1311a5525157c382f36924ac63c78272 | 40.660377 | 125 | 0.737772 | 4.389662 | false | false | false | false |
Unpublished/AmazeFileManager | app/src/main/java/com/amaze/filemanager/ui/dialogs/DragAndDropDialog.kt | 2 | 8135 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.ui.dialogs
import android.app.Dialog
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import androidx.fragment.app.DialogFragment
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.Theme
import com.amaze.filemanager.R
import com.amaze.filemanager.asynchronous.asynctasks.PrepareCopyTask
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.fragments.preference_fragments.PreferencesConstants
import com.amaze.filemanager.utils.safeLet
class DragAndDropDialog : DialogFragment() {
var pasteLocation: String? = null
var operationFiles: ArrayList<HybridFileParcelable>? = null
var mainActivity: MainActivity? = null
companion object {
private const val KEY_PASTE_LOCATION = "pasteLocation"
private const val KEY_FILES = "files"
/**
* Show move / copy dialog on drop or perform the operation directly based on
* remember preference selected by user previously in this dialog
*/
fun showDialogOrPerformOperation(
pasteLocation: String,
files: ArrayList<HybridFileParcelable>,
activity: MainActivity
) {
val dragAndDropPref = activity.prefs
.getInt(
PreferencesConstants.PREFERENCE_DRAG_AND_DROP_PREFERENCE,
PreferencesConstants.PREFERENCE_DRAG_DEFAULT
)
if (dragAndDropPref == PreferencesConstants.PREFERENCE_DRAG_TO_MOVE_COPY) {
val dragAndDropCopy = activity.prefs
.getString(PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED, "")
if (dragAndDropCopy != "") {
startCopyOrMoveTask(
pasteLocation, files,
PreferencesConstants.PREFERENCE_DRAG_REMEMBER_MOVE
.equals(dragAndDropCopy, ignoreCase = true),
activity
)
} else {
val dragAndDropDialog = newInstance(pasteLocation, files)
dragAndDropDialog.show(
activity.supportFragmentManager,
javaClass.simpleName
)
}
} else {
Log.w(
javaClass.simpleName,
"Trying to drop for copy / move while setting " +
"is drag select"
)
}
}
private fun newInstance(pasteLocation: String, files: ArrayList<HybridFileParcelable>):
DragAndDropDialog {
val dragAndDropDialog = DragAndDropDialog()
val args = Bundle()
args.putString(KEY_PASTE_LOCATION, pasteLocation)
args.putParcelableArrayList(KEY_FILES, files)
dragAndDropDialog.arguments = args
return dragAndDropDialog
}
private fun startCopyOrMoveTask(
pasteLocation: String,
files: ArrayList<HybridFileParcelable>,
move: Boolean,
mainActivity: MainActivity
) {
PrepareCopyTask(
pasteLocation,
move,
mainActivity,
mainActivity.isRootExplorer,
mainActivity.currentMainFragment?.mainFragmentViewModel?.openMode
)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, files)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
mainActivity = context as MainActivity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pasteLocation = arguments?.getString(KEY_PASTE_LOCATION)
operationFiles = arguments?.getParcelableArrayList(KEY_FILES)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
safeLet(
context, mainActivity?.appTheme?.materialDialogTheme, mainActivity?.accent,
pasteLocation, operationFiles
) {
context, dialogTheme, accent, pasteLocation, operationFiles ->
val dialog: MaterialDialog = MaterialDialog.Builder(context)
.title(getString(R.string.choose_operation))
.customView(R.layout.dialog_drag_drop, true)
.theme(dialogTheme)
.negativeText(getString(R.string.cancel).toUpperCase())
.negativeColor(accent)
.cancelable(false)
.onNeutral { _: MaterialDialog?, _: DialogAction? ->
dismiss()
}
.build()
dialog.customView?.run {
// Get views from custom layout to set text values.
val rememberCheckbox = this.findViewById<CheckBox>(R.id.remember_drag)
val moveButton = this.findViewById<Button>(R.id.button_move)
moveButton.setOnClickListener {
mainActivity?.run {
if (rememberCheckbox.isChecked) {
rememberDragOperation(true)
}
startCopyOrMoveTask(pasteLocation, operationFiles, true, this)
dismiss()
}
}
val copyButton = this.findViewById<Button>(R.id.button_copy)
copyButton.setOnClickListener {
mainActivity?.run {
if (rememberCheckbox.isChecked) {
rememberDragOperation(false)
}
startCopyOrMoveTask(pasteLocation, operationFiles, false, this)
dismiss()
}
}
if (dialogTheme == Theme.LIGHT) {
moveButton.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_baseline_content_cut_24,
0, 0, 0
)
copyButton.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_baseline_content_copy_24,
0, 0, 0
)
}
}
return dialog
}
Log.w(javaClass.simpleName, "Failed to show drag drop dialog view")
return super.onCreateDialog(savedInstanceState)
}
override fun isCancelable(): Boolean {
return false
}
private fun rememberDragOperation(shouldMove: Boolean) {
mainActivity?.prefs?.edit()
?.putString(
PreferencesConstants.PREFERENCE_DRAG_AND_DROP_REMEMBERED,
if (shouldMove) PreferencesConstants.PREFERENCE_DRAG_REMEMBER_MOVE
else PreferencesConstants.PREFERENCE_DRAG_REMEMBER_COPY
)?.apply()
}
}
| gpl-3.0 | 2d8540e24c86ab4ae09674c4b0ec8798 | 39.879397 | 107 | 0.59496 | 5.430574 | false | false | false | false |
elsiff/MoreFish | src/main/kotlin/me/elsiff/morefish/configuration/loader/FishTypeMapLoader.kt | 1 | 2933 | package me.elsiff.morefish.configuration.loader
import me.elsiff.morefish.configuration.ConfigurationValueAccessor
import me.elsiff.morefish.configuration.translated
import me.elsiff.morefish.fishing.FishRarity
import me.elsiff.morefish.fishing.FishType
import me.elsiff.morefish.fishing.catchhandler.CatchCommandExecutor
import me.elsiff.morefish.fishing.catchhandler.CatchHandler
/**
* Created by elsiff on 2019-01-09.
*/
class FishTypeMapLoader(
private val fishRaritySetLoader: FishRaritySetLoader,
private val customItemStackLoader: CustomItemStackLoader,
private val fishConditionSetLoader: FishConditionSetLoader,
private val playerAnnouncementLoader: PlayerAnnouncementLoader
) : CustomLoader<Map<FishRarity, Set<FishType>>> {
override fun loadFrom(section: ConfigurationValueAccessor, path: String): Map<FishRarity, Set<FishType>> {
section[path].let { root ->
val rarities = fishRaritySetLoader.loadFrom(root, "rarity-list")
return root["fish-list"].children.map { groupByRarity ->
val rarity = findRarity(rarities, groupByRarity.name)
val fishTypes = groupByRarity.children.map {
val catchHandlers = mutableListOf<CatchHandler>()
catchHandlers.addAll(rarity.catchHandlers)
if (it.contains("commands")) {
val handler = CatchCommandExecutor(it.strings("commands").translated())
catchHandlers.add(handler)
}
FishType(
name = it.name,
displayName = it.string("display-name").translated(),
rarity = rarity,
lengthMin = it.double("length-min"),
lengthMax = it.double("length-max"),
icon = customItemStackLoader.loadFrom(it, "icon"),
catchHandlers = catchHandlers,
catchAnnouncement = playerAnnouncementLoader.loadIfExists(it, "catch-announce")
?: rarity.catchAnnouncement,
conditions = fishConditionSetLoader.loadFrom(it, "conditions"),
hasNotFishItemFormat = it.boolean("skip-item-format", rarity.hasNotFishItemFormat),
noDisplay = it.boolean("no-display", rarity.noDisplay),
hasCatchFirework = it.boolean("firework", rarity.hasCatchFirework),
additionalPrice = rarity.additionalPrice + it.double("additional-price", 0.0)
)
}.toSet()
Pair(rarity, fishTypes)
}.toMap()
}
}
private fun findRarity(rarities: Set<FishRarity>, name: String): FishRarity {
return rarities.find { it.name == name } ?: throw IllegalStateException("Rarity '$name' doesn't exist")
}
} | mit | d1cb273bcd74bcfe6af5233fd3679867 | 50.473684 | 111 | 0.617797 | 5.013675 | false | true | false | false |
k9mail/k-9 | backend/imap/src/main/java/com/fsck/k9/backend/imap/CommandRefreshFolderList.kt | 2 | 1777 | package com.fsck.k9.backend.imap
import com.fsck.k9.backend.api.BackendStorage
import com.fsck.k9.backend.api.FolderInfo
import com.fsck.k9.backend.api.updateFolders
import com.fsck.k9.mail.FolderType
import com.fsck.k9.mail.store.imap.FolderListItem
import com.fsck.k9.mail.store.imap.ImapStore
internal class CommandRefreshFolderList(
private val backendStorage: BackendStorage,
private val imapStore: ImapStore
) {
fun refreshFolderList() {
// TODO: Start using the proper server ID.
// For now we still use the old server ID format (decoded, with prefix removed).
val foldersOnServer = imapStore.getFolders().toLegacyFolderList()
val oldFolderServerIds = backendStorage.getFolderServerIds()
backendStorage.updateFolders {
val foldersToCreate = mutableListOf<FolderInfo>()
for (folder in foldersOnServer) {
if (folder.serverId !in oldFolderServerIds) {
foldersToCreate.add(FolderInfo(folder.serverId, folder.name, folder.type))
} else {
changeFolder(folder.serverId, folder.name, folder.type)
}
}
createFolders(foldersToCreate)
val newFolderServerIds = foldersOnServer.map { it.serverId }
val removedFolderServerIds = oldFolderServerIds - newFolderServerIds
deleteFolders(removedFolderServerIds)
}
}
}
private fun List<FolderListItem>.toLegacyFolderList(): List<LegacyFolderListItem> {
return this.filterNot { it.oldServerId == null }
.map { LegacyFolderListItem(it.oldServerId!!, it.name, it.type) }
}
private data class LegacyFolderListItem(
val serverId: String,
val name: String,
val type: FolderType
)
| apache-2.0 | 975e01cc498efe74ba0ddd955b4622c8 | 36.808511 | 94 | 0.687113 | 4.302663 | false | false | false | false |
DiUS/pact-jvm | core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonValue.kt | 1 | 7562 | package au.com.dius.pact.core.support.json
import au.com.dius.pact.core.support.Json
sealed class JsonValue {
class Integer(val value: JsonToken.Integer) : JsonValue() {
constructor(value: CharArray) : this(JsonToken.Integer(value))
fun toBigInteger() = String(this.value.chars).toBigInteger()
}
class Decimal(val value: JsonToken.Decimal) : JsonValue() {
constructor(value: CharArray) : this(JsonToken.Decimal(value))
fun toBigDecimal() = String(this.value.chars).toBigDecimal()
}
class StringValue(val value: JsonToken.StringValue) : JsonValue() {
constructor(value: CharArray) : this(JsonToken.StringValue(value))
override fun toString() = String(value.chars)
}
object True : JsonValue()
object False : JsonValue()
object Null : JsonValue()
class Array(val values: MutableList<JsonValue> = mutableListOf()) : JsonValue() {
fun find(function: (JsonValue) -> Boolean) = values.find(function)
operator fun set(i: Int, value: JsonValue) {
values[i] = value
}
val size: Int
get() = values.size
fun addAll(jsonValue: JsonValue) {
when (jsonValue) {
is Array -> values.addAll(jsonValue.values)
else -> values.add(jsonValue)
}
}
fun last() = values.last()
}
class Object(val entries: MutableMap<String, JsonValue>) : JsonValue() {
constructor(vararg values: Pair<String, JsonValue>) : this(values.associate { it }.toMutableMap())
operator fun get(name: String) = entries[name] ?: Null
override fun has(field: String) = entries.containsKey(field)
operator fun set(key: String, value: Any?) {
entries[key] = Json.toJson(value)
}
fun isEmpty() = entries.isEmpty()
fun isNotEmpty() = entries.isNotEmpty()
val size: Int
get() = entries.size
fun add(key: String, value: JsonValue) {
entries[key] = value
}
}
fun asObject(): Object {
if (this is Object) {
return this
} else {
throw UnsupportedOperationException("Expected an Object, but found a $this")
}
}
fun asArray(): Array {
if (this is Array) {
return this
} else {
throw UnsupportedOperationException("Expected an Array, but found a $this")
}
}
fun asString(): String {
return if (this is StringValue) {
String(value.chars)
} else {
serialise()
}
}
fun asBoolean() = when (this) {
is True -> true
is False -> false
else -> throw UnsupportedOperationException("Expected a Boolean, but found a $this")
}
fun asNumber(): Number = when (this) {
is Integer -> this.toBigInteger()
is Decimal -> this.toBigDecimal()
else -> throw UnsupportedOperationException("Expected a Number, but found a $this")
}
operator fun get(field: Any): JsonValue = when {
this is Object -> this.asObject()[field.toString()]
this is Array && field is Int -> this.values[field]
else -> throw UnsupportedOperationException("Indexed lookups only work on Arrays and Objects, not $this")
}
open fun has(field: String) = when (this) {
is Object -> this.entries.containsKey(field)
else -> false
}
fun serialise(): String {
return when (this) {
is Null -> "null"
is Decimal -> String(this.value.chars)
is Integer -> String(this.value.chars)
is StringValue -> "\"${Json.escape(this.asString())}\""
is True -> "true"
is False -> "false"
is Array -> "[${this.values.joinToString(",") { it.serialise() }}]"
is Object -> "{${this.entries.entries.sortedBy { it.key }.joinToString(",") { "\"${it.key}\":" + it.value.serialise() }}}"
}
}
fun add(value: JsonValue) {
if (this is Array) {
this.values.add(value)
} else {
throw UnsupportedOperationException("You can only add single values to Arrays, not $this")
}
}
fun size() = when (this) {
is Array -> this.values.size
is Object -> this.entries.size
else -> 1
}
fun type(): String {
return when (this) {
is StringValue -> "String"
else -> this::class.java.simpleName
}
}
fun unwrap(): Any? {
return when (this) {
is Null -> null
is Decimal -> this.toBigDecimal()
is Integer -> this.toBigInteger()
is StringValue -> this.asString()
is True -> true
is False -> false
is Array -> this.values
is Object -> this.entries
}
}
override fun equals(other: Any?): Boolean {
if (other !is JsonValue) return false
return when (this) {
is Null -> other is Null
is Decimal -> other is Decimal && this.toBigDecimal() == other.toBigDecimal()
is Integer -> other is Integer && this.toBigInteger() == other.toBigInteger()
is StringValue -> other is StringValue && this.asString() == other.asString()
is True -> other is True
is False -> other is False
is Array -> other is Array && this.values == other.values
is Object -> other is Object && this.entries == other.entries
}
}
override fun hashCode() = when (this) {
is Null -> 0.hashCode()
is Decimal -> this.toBigDecimal().hashCode()
is Integer -> this.toBigInteger().hashCode()
is StringValue -> this.asString().hashCode()
is True -> true.hashCode()
is False -> false.hashCode()
is Array -> this.values.hashCode()
is Object -> this.entries.hashCode()
}
fun prettyPrint(indent: Int = 0, skipIndent: Boolean = false): String {
val indentStr = "".padStart(indent)
val indentStr2 = "".padStart(indent + 2)
return if (skipIndent) {
when (this) {
is Array -> "[\n" + this.values.joinToString(",\n") {
it.prettyPrint(indent + 2) } + "\n$indentStr]"
is Object -> "{\n" + this.entries.entries.joinToString(",\n") {
"$indentStr2\"${it.key}\": ${it.value.prettyPrint(indent + 2, true)}"
} + "\n$indentStr}"
else -> this.serialise()
}
} else {
when (this) {
is Array -> "$indentStr$indentStr[\n" + this.values.joinToString(",\n") {
it.prettyPrint(indent + 2) } + "\n$indentStr]"
is Object -> "$indentStr{\n" + this.entries.entries.joinToString(",\n") {
"$indentStr2\"${it.key}\": ${it.value.prettyPrint(indent + 2, true)}"
} + "\n$indentStr}"
else -> indentStr + this.serialise()
}
}
}
val name: String
get() {
return when (this) {
is Null -> "Null"
is Decimal -> "Decimal"
is Integer -> "Integer"
is StringValue -> "String"
is True -> "True"
is False -> "False"
is Array -> "Array"
is Object -> "Object"
}
}
val isBoolean: Boolean
get() = when (this) {
is True, is False -> true
else -> false
}
val isNumber: Boolean
get() = when (this) {
is Integer, is Decimal -> true
else -> false
}
val isString: Boolean
get() = when (this) {
is StringValue -> true
else -> false
}
val isNull: Boolean
get() = when (this) {
is Null -> true
else -> false
}
}
fun <R> JsonValue?.map(transform: (JsonValue) -> R): List<R> = when {
this == null -> emptyList()
this is JsonValue.Array -> this.values.map(transform)
else -> emptyList()
}
operator fun JsonValue?.get(field: Any): JsonValue = when {
this == null -> JsonValue.Null
else -> this[field]
}
operator fun JsonValue.Object?.get(field: Any): JsonValue = when {
this == null -> JsonValue.Null
else -> this[field]
}
fun JsonValue?.orNull() = this ?: JsonValue.Null
| apache-2.0 | dc15b807a8eb05dcef97111301a0794d | 28.196911 | 128 | 0.603676 | 3.982096 | false | false | false | false |
mvysny/vaadin-on-kotlin | vok-rest-client/src/main/kotlin/eu/vaadinonkotlin/restclient/OkHttpClientUtils.kt | 1 | 5718 | package eu.vaadinonkotlin.restclient
import com.fatboyindustrial.gsonjavatime.Converters
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import eu.vaadinonkotlin.VOKPlugin
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.FileNotFoundException
import java.io.IOException
/**
* Destroys the [OkHttpClient] including the dispatcher, connection pool, everything. WARNING: THIS MAY AFFECT
* OTHER http clients if they share e.g. dispatcher executor service.
*/
public fun OkHttpClient.destroy() {
dispatcher.executorService.shutdown()
connectionPool.evictAll()
cache?.close()
}
/**
* Documents a HTTP failure.
* @property statusCode the HTTP status code, one of [javax.servlet.http.HttpServletResponse] `SC_*` constants.
* @property method the request method, e.g. `"GET"`
* @property requestUrl the URL requested from the server
* @property response the response body received from the server, may provide further information to the nature of the failure.
* May be blank.
*/
public class HttpResponseException(
public val statusCode: Int,
public val method: String,
public val requestUrl: String,
public val response: String,
cause: Throwable? = null
) : IOException("$statusCode: $response", cause) {
override fun toString(): String = "${javaClass.simpleName}: $message ($method $requestUrl)"
}
/**
* Fails if the response is not in 200..299 range; otherwise returns [this].
* @throws FileNotFoundException if the HTTP response was 404
* @throws HttpResponseException if the response is not in 200..299 ([Response.isSuccessful] returns false)
* @throws IOException on I/O error.
*/
public fun Response.checkOk(): Response {
if (!isSuccessful) {
val response = body!!.string()
if (code == 404) throw FileNotFoundException("$code: $response (${request.method} ${request.url})")
throw HttpResponseException(code, request.method, request.url.toString(), response)
}
return this
}
/**
* Makes sure that [okHttpClient] is properly destroyed.
*/
public class OkHttpClientVokPlugin : VOKPlugin {
override fun init() {
if (okHttpClient == null) {
okHttpClient = OkHttpClient()
}
}
override fun destroy() {
okHttpClient?.destroy()
okHttpClient = null
}
public companion object {
/**
* All REST client calls will reuse this client. Automatically destroyed in [destroy] (triggered by [com.github.vok.framework.VaadinOnKotlin.destroy]).
*/
public var okHttpClient: OkHttpClient? = null
/**
* The default [Gson] interface used by all serialization/deserialization methods. Simply reassign with another [Gson]
* instance to reconfigure. To be thread-safe, do the reassignment in your `ServletContextListener`.
*/
public var gson: Gson = GsonBuilder().registerJavaTimeAdapters().create()
}
}
private fun GsonBuilder.registerJavaTimeAdapters(): GsonBuilder = apply {
Converters.registerAll(this)
}
/**
* Parses the response as a JSON and converts it to a Java object with given [clazz] using [OkHttpClientVokPlugin.gson].
*/
public fun <T> ResponseBody.json(clazz: Class<T>): T = OkHttpClientVokPlugin.gson.fromJson(charStream(), clazz)
/**
* Parses the response as a JSON array and converts it into a list of Java object with given [clazz] using [OkHttpClientVokPlugin.gson].
*/
public fun <T> ResponseBody.jsonArray(clazz: Class<T>): List<T> = OkHttpClientVokPlugin.gson.fromJsonArray(charStream(), clazz)
/**
* Runs given [request] synchronously and then runs [responseBlock] with the response body.
* Everything including the [Response] and [ResponseBody] is properly closed afterwards.
*
* The [responseBlock] is only called on HTTP 200..299 SUCCESS. [checkOk] is used, to check for
* possible failure reported as HTTP status code, prior calling the block.
* @param responseBlock runs on success. Takes a [ResponseBody] and produces the object of type [T].
* You can use [json], [jsonArray] or other utility methods to convert JSON to a Java object.
* @return whatever has been returned by [responseBlock]
*/
public fun <T> OkHttpClient.exec(request: Request, responseBlock: (ResponseBody) -> T): T =
newCall(request).execute().use {
val body: ResponseBody = it.checkOk().body!!
body.use {
responseBlock(body)
}
}
/**
* Parses the response as a JSON map and converts it into a map of objects with given [valueClass] using [OkHttpClientVokPlugin.gson].
*/
public fun <V> ResponseBody.jsonMap(valueClass: Class<V>): Map<String, V> = OkHttpClientVokPlugin.gson.fromJsonMap(charStream(), valueClass)
/**
* Parses this string as a `http://` or `https://` URL. You can configure the URL
* (e.g. add further query parameters) in [block]. For example:
* ```
* val url: HttpUrl = baseUrl.buildUrl {
* if (range != 0..Long.MAX_VALUE) {
* addQueryParameter("offset", range.first.toString())
* addQueryParameter("limit", range.length.toString())
* }
* }
* ```
* @throws IllegalArgumentException if the URL is unparseable
*/
public inline fun String.buildUrl(block: HttpUrl.Builder.()->Unit = {}): HttpUrl = toHttpUrl().newBuilder().apply {
block()
}.build()
/**
* Builds a new OkHttp [Request] using given URL. You can optionally configure the request in [block]. Use [exec] to
* execute the request with given OkHttp client and obtain a response. By default the `GET` request gets built.
*/
public inline fun HttpUrl.buildRequest(block: Request.Builder.()->Unit = {}): Request = Request.Builder().url(this).apply {
block()
}.build()
| mit | 7c890ccb929ac0b42a8d976920a717e4 | 38.986014 | 159 | 0.705666 | 4.226164 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/ide/cds/CDSManager.kt | 9 | 13164 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cds
import com.intellij.diagnostic.VMOptions
import com.intellij.execution.CommandLineWrapperUtil
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.Pair.pair
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.TimeoutUtil
import com.intellij.util.system.CpuArch
import com.sun.management.OperatingSystemMXBean
import com.sun.tools.attach.VirtualMachine
import java.io.File
import java.io.IOException
import java.lang.management.ManagementFactory
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis
sealed class CDSTaskResult(val statusName: String) {
object Success : CDSTaskResult("success")
abstract class Cancelled(statusName: String) : CDSTaskResult(statusName)
object InterruptedForRetry : Cancelled("cancelled")
object TerminatedByUser : Cancelled("terminated-by-user")
object PluginsChanged : Cancelled("plugins-changed")
data class Failed(val error: String) : CDSTaskResult("failed")
}
object CDSManager {
private val LOG = Logger.getInstance(javaClass)
val isValidEnv: Boolean by lazy {
// AppCDS requires classes packed into JAR files, not from the out folder
if (PluginManagerCore.isRunningFromSources()) return@lazy false
// CDS features are only available on 64-bit JVMs
if (CpuArch.is32Bit()) return@lazy false
// AppCDS does not support Windows and macOS, but specific patches are included into JetBrains runtime
if (!(SystemInfo.isLinux || SystemInfo.isJetBrainsJvm)) return@lazy false
// we do not like to overload a potentially small computer with our process
val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
if (osBean.totalPhysicalMemorySize < 4L * 1024 * 1024 * 1024) return@lazy false
if (osBean.availableProcessors < 4) return@lazy false
if (!VMOptions.canWriteOptions()) return@lazy false
true
}
val currentCDSArchive: File? by lazy {
val arguments = ManagementFactory.getRuntimeMXBean().inputArguments
val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }
if (!xShare) return@lazy null
val key = "-XX:SharedArchiveFile="
return@lazy arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File)
}
fun cleanupStaleCDSFiles(isCDSEnabled: Boolean): CDSTaskResult {
val paths = CDSPaths.current
val currentCDSPath = currentCDSArchive
val files = paths.baseDir.listFiles() ?: arrayOf()
if (files.isEmpty()) return CDSTaskResult.Success
for (path in files) {
if (path == currentCDSPath) continue
if (isCDSEnabled && paths.isOurFile(path)) continue
FileUtil.delete(path)
}
return CDSTaskResult.Success
}
fun removeCDS() {
if (currentCDSArchive?.isFile != true) return
try {
// cannot remove "-XX:+UnlockDiagnosticVMOptions" for we do not know the reason it was included
VMOptions.setOptions(listOf(pair("-Xshare:", null), pair("-XX:SharedArchiveFile=", null)))
LOG.warn("Disabled CDS")
}
catch (e: IOException) {
LOG.warn(e)
}
}
private interface CDSProgressIndicator {
/// returns non-null value if cancelled
val cancelledStatus: CDSTaskResult.Cancelled?
var text2: String?
}
fun installCDS(canStillWork: () -> Boolean, onResult: (CDSTaskResult) -> Unit) {
CDSFUSCollector.logCDSBuildingStarted()
val startTime = System.nanoTime()
ProgressManager.getInstance().run(object : Task.Backgroundable(
null,
IdeBundle.message("progress.title.cds.optimize.startup"),
true,
PerformInBackgroundOption.ALWAYS_BACKGROUND
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val progress = object : CDSProgressIndicator {
override val cancelledStatus: CDSTaskResult.Cancelled?
get() {
if (!canStillWork()) return CDSTaskResult.InterruptedForRetry
if (indicator.isCanceled) return CDSTaskResult.TerminatedByUser
if (ApplicationManager.getApplication().isDisposed) return CDSTaskResult.InterruptedForRetry
return null
}
override var text2: String?
get() = indicator.text2
set(@NlsContexts.ProgressText value) {
indicator.text2 = value
}
}
val paths = CDSPaths.current
val result = try {
installCDSImpl(progress, paths)
} catch (t: Throwable) {
LOG.warn("Settings up CDS Archive crashed unexpectedly. ${t.message}", t)
val message = "Unexpected crash $t"
paths.markError(message)
CDSTaskResult.Failed(message)
}
val installTime = TimeoutUtil.getDurationMillis(startTime)
CDSFUSCollector.logCDSBuildingCompleted(installTime, result)
onResult(result)
}
})
}
private fun installCDSImpl(indicator: CDSProgressIndicator, paths: CDSPaths): CDSTaskResult {
if (paths.isSame(currentCDSArchive)) {
val message = "CDS archive is already generated and being used. Nothing to do"
LOG.debug(message)
return CDSTaskResult.Success
}
if (paths.classesErrorMarkerFile.isFile) {
return CDSTaskResult.Failed("CDS archive has already failed, skipping")
}
LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files")
paths.mkdirs()
val listResult = generateFileIfNeeded(indicator, paths, paths.classesListFile, ::generateClassList) { t ->
"Failed to attach CDS Java Agent to the running IDE instance. ${t.message}"
}
if (listResult != CDSTaskResult.Success) return listResult
val archiveResult = generateFileIfNeeded(indicator, paths, paths.classesArchiveFile, ::generateSharedArchive) { t ->
"Failed to generated CDS archive. ${t.message}"
}
if (archiveResult != CDSTaskResult.Success) return archiveResult
try {
VMOptions.setOptions(listOf(pair("-Xshare:", "auto"),
pair("-XX:+UnlockDiagnosticVMOptions", ""),
pair("-XX:SharedArchiveFile=", paths.classesArchiveFile.absolutePath)))
LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, VMOptions were updated")
return CDSTaskResult.Success
}
catch (e: IOException) {
LOG.warn(e)
return CDSTaskResult.Failed(e.message!!)
}
}
private val agentPath: File
get() {
val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar"
if (libPath.isFile) return libPath
LOG.warn("Failed to find bundled CDS classes agent in $libPath")
//consider local debug IDE case
val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar"
if (probe.isFile) return probe
error("Failed to resolve path to the CDS agent")
}
private fun generateClassList(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = IdeBundle.message("progress.text.collecting.classes")
val selfAttachKey = "jdk.attach.allowAttachSelf"
if (!System.getProperties().containsKey(selfAttachKey)) {
throw RuntimeException("Please make sure you have -D$selfAttachKey=true set in the VM options")
}
val duration = measureTimeMillis {
val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid())
try {
vm.loadAgent(agentPath.path, "${paths.classesListFile}")
}
finally {
vm.detach()
}
}
LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(duration)}")
}
private fun generateSharedArchive(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = IdeBundle.message("progress.text.generate.classes.archive")
val logLevel = if (LOG.isDebugEnabled) "=debug" else ""
val args = listOf(
"-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}",
"-Xlog:cds$logLevel",
"-Xlog:class+path$logLevel",
"-Xshare:dump",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:SharedClassListFile=${paths.classesListFile}",
"-XX:SharedArchiveFile=${paths.classesArchiveFile}"
)
CommandLineWrapperUtil.writeArgumentsFile(paths.classesPathFile, args, StandardCharsets.UTF_8)
val durationLink = measureTimeMillis {
val ext = if (SystemInfo.isWindows) ".exe" else ""
val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext"
val javaArgs = listOf(
javaExe.path,
"@${paths.classesPathFile}"
)
val cwd = File(".").canonicalFile
LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}")
//recreate files for sanity
FileUtil.delete(paths.dumpOutputFile)
FileUtil.delete(paths.classesArchiveFile)
val commandLine = object : GeneralCommandLine() {
override fun buildProcess(builder: ProcessBuilder) : ProcessBuilder {
return super.buildProcess(builder)
.redirectErrorStream(true)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(paths.dumpOutputFile)
}
}
commandLine.workDirectory = cwd
commandLine.exePath = javaExe.absolutePath
commandLine.addParameter("@${paths.classesPathFile}")
if (!SystemInfo.isWindows) {
// the utility does not recover process exit code from the call on Windows
ExecUtil.setupLowPriorityExecution(commandLine)
}
val timeToWaitFor = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
fun shouldWaitForProcessToComplete() = timeToWaitFor > System.currentTimeMillis()
val process = commandLine.createProcess()
try {
runCatching { process.outputStream.close() }
while (shouldWaitForProcessToComplete()) {
if (indicator.cancelledStatus != null) throw InterruptedException()
if (process.waitFor(200, TimeUnit.MILLISECONDS)) break
}
}
finally {
if (process.isAlive) {
process.destroyForcibly()
}
}
if (!shouldWaitForProcessToComplete()) {
throw RuntimeException("The process took too long and will be killed. See ${paths.dumpOutputFile} for details")
}
val exitValue = process.exitValue()
if (exitValue != 0) {
val outputLines = runCatching {
paths.dumpOutputFile.readLines().takeLast(30).joinToString("\n")
}.getOrElse { "" }
throw RuntimeException("The process existed with code $exitValue. See ${paths.dumpOutputFile} for details:\n$outputLines")
}
}
LOG.info("Generated CDS archive in ${paths.classesArchiveFile}, " +
"size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " +
"it took ${StringUtil.formatDuration(durationLink)}")
}
private operator fun File.div(s: String) = File(this, s)
private val File.isValidFile get() = isFile && length() > 42
private inline fun generateFileIfNeeded(indicator: CDSProgressIndicator,
paths: CDSPaths,
theOutputFile: File,
generate: (CDSProgressIndicator, CDSPaths) -> Unit,
errorMessage: (Throwable) -> String): CDSTaskResult {
try {
if (theOutputFile.isValidFile) return CDSTaskResult.Success
indicator.cancelledStatus?.let { return it }
if (!paths.hasSameEnvironmentToBuildCDSArchive()) return CDSTaskResult.PluginsChanged
generate(indicator, paths)
LOG.assertTrue(theOutputFile.isValidFile, "Result file must be generated and be valid")
return CDSTaskResult.Success
}
catch (t: Throwable) {
FileUtil.delete(theOutputFile)
indicator.cancelledStatus?.let { return it }
if (t is InterruptedException) {
return CDSTaskResult.InterruptedForRetry
}
val message = errorMessage(t)
LOG.warn(message, t)
paths.markError(message)
return CDSTaskResult.Failed(message)
}
}
}
| apache-2.0 | 3b29bd3201049678c49bf038971d8384 | 37.267442 | 158 | 0.690596 | 4.735252 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/signin/SignInActivity.kt | 1 | 5412 | package net.squanchy.signin
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.snackbar.Snackbar
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposables
import kotlinx.android.synthetic.main.activity_signin.*
import net.squanchy.R
import net.squanchy.analytics.Analytics
import net.squanchy.google.GoogleClientId
import net.squanchy.support.config.DialogLayoutParameters
import timber.log.Timber
class SignInActivity : AppCompatActivity() {
private lateinit var service: SignInService
private lateinit var analytics: Analytics
private lateinit var googleApiClient: GoogleApiClient
private var subscription = Disposables.disposed()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ensureSignInOriginIsSet()
googleApiClient = connectToGoogleApis()
with(signInComponent(this)) {
service = service()
analytics = analytics()
}
setContentView(R.layout.activity_signin)
signInButton.setOnClickListener { signIn() }
touchOutside.setOnClickListener { finish() }
setBottomSheetCallbackOn(bottomSheet)
setupWindowParameters()
setResult(Activity.RESULT_CANCELED)
}
private fun ensureSignInOriginIsSet() {
if (intent.extras?.containsKey(EXTRA_SIGN_IN_ORIGIN) == false) {
throw IllegalStateException("Sign in origin extra required but not set")
}
}
private fun connectToGoogleApis(): GoogleApiClient {
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
return GoogleApiClient.Builder(this)
.enableAutoManage(this, GoogleClientId.SIGN_IN_ACTIVITY.clientId()) { showSignInFailedError() }
.addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
.build()
}
private fun setBottomSheetCallbackOn(bottomSheet: View) {
BottomSheetBehavior.from(bottomSheet)
.setBottomSheetCallback(bottomSheetCallback)
}
private val bottomSheetCallback: BottomSheetBehavior.BottomSheetCallback
get() = object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
finish()
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) = Unit // No op
}
private fun setupWindowParameters() {
DialogLayoutParameters.wrapHeight(this)
.applyTo(window)
window.setGravity(Gravity.FILL_HORIZONTAL or Gravity.BOTTOM)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if (result != null && result.isSuccess) {
val account = result.signInAccount!!
firebaseAuthWithGoogle(account)
} else {
showSignInFailedError()
}
}
}
private fun firebaseAuthWithGoogle(account: GoogleSignInAccount) {
showProgress()
subscription = service.signInWithGoogle(account)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(
{
analytics.trackUserLoggedInFrom(getSignInOrigin())
setResult(RESULT_OK)
finish()
},
Timber::e
)
}
private fun getSignInOrigin() = intent.getSerializableExtra(EXTRA_SIGN_IN_ORIGIN) as SignInOrigin
private fun showProgress() {
signInContent.isEnabled = false
signInContent.alpha = ALPHA_DISABLED
progressView.isVisible = true
}
private fun showSignInFailedError() {
hideProgress()
Snackbar.make(signInContent, R.string.sign_in_error_please_retry, Snackbar.LENGTH_SHORT).show()
}
private fun hideProgress() {
signInContent.isEnabled = true
signInContent.alpha = ALPHA_ENABLED
progressView.isVisible = false
}
private fun signIn() {
val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onStop() {
super.onStop()
subscription.dispose()
}
companion object {
private const val RC_SIGN_IN = 9001
private const val ALPHA_DISABLED = .54f
private const val ALPHA_ENABLED = 1f
const val EXTRA_SIGN_IN_ORIGIN = "sign_in_origin"
}
}
| apache-2.0 | ed07837d245818838d96e38a126b3b95 | 32.407407 | 107 | 0.675166 | 5.02507 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/LegacyGroovydocGenerator.kt | 1 | 4887 | package com.eden.orchid.groovydoc
import com.caseyjbrooks.clog.Clog
import com.copperleaf.groovydoc.json.models.GroovydocPackageDoc
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.generators.PageCollection
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.groovydoc.helpers.OrchidGroovydocInvoker
import com.eden.orchid.groovydoc.models.GroovydocModel
import com.eden.orchid.groovydoc.pages.GroovydocClassPage
import com.eden.orchid.groovydoc.pages.GroovydocPackagePage
import com.eden.orchid.sourcedoc.SourcedocGenerator
import java.util.ArrayList
import java.util.HashMap
import javax.inject.Inject
@Description(
"Creates a page for each Class and Package in your project, displaying the expected Groovydoc information " +
"of methods, fields, etc. but in your site's theme.",
name = "Groovydoc"
)
@Deprecated(SourcedocGenerator.deprecationWarning)
class GroovydocGenerator
@Inject
constructor(
private val groovydocInvoker: OrchidGroovydocInvoker
) : OrchidGenerator<GroovydocModel>(GENERATOR_KEY, Stage.CONTENT) {
companion object {
const val GENERATOR_KEY = "groovydoc"
}
@Option
@StringDefault("../../main/groovy", "../../main/java")
@Description("The source directories with Kotlin files to document.")
lateinit var sourceDirs: List<String>
@Option
@Description("Arbitrary command line arguments to pass through directly to Groovydoc.")
lateinit var args: List<String>
override fun startIndexing(context: OrchidContext): GroovydocModel {
Clog.w(SourcedocGenerator.deprecationWarning)
groovydocInvoker.extractOptions(context, allData)
val rootDoc = groovydocInvoker.getRootDoc(sourceDirs, args)
if (rootDoc == null) return GroovydocModel(context, emptyList(), emptyList(), emptyList())
val allClasses = mutableListOf<GroovydocClassPage>()
val allPackages = mutableListOf<GroovydocPackagePage>()
for (classDoc in rootDoc.classes) {
allClasses.add(GroovydocClassPage(context, classDoc))
}
val packagePageMap = HashMap<String, GroovydocPackagePage>()
for (packageDoc in rootDoc.packages) {
val classesInPackage = ArrayList<GroovydocClassPage>()
for (classDocPage in allClasses) {
if (classDocPage.classDoc.`package` == packageDoc.name) {
classesInPackage.add(classDocPage)
}
}
classesInPackage.sortBy { it.title }
val packagePage = GroovydocPackagePage(context, packageDoc, classesInPackage)
allPackages.add(packagePage)
packagePageMap[packageDoc.name] = packagePage
}
for (packagePage in packagePageMap.values) {
for (possibleInnerPackage in packagePageMap.values) {
if (isInnerPackage(packagePage.packageDoc, possibleInnerPackage.packageDoc)) {
packagePage.innerPackages.add(possibleInnerPackage)
}
}
}
for (classDocPage in allClasses) {
classDocPage.packagePage = packagePageMap[classDocPage.classDoc.`package`]
}
val collections = getCollections(allClasses, allPackages)
return GroovydocModel(context, allClasses, allPackages, collections).also { createdModel ->
createdModel.allClasses.forEach { it.model = createdModel }
}
}
private fun getCollections(
allClasses: List<GroovydocClassPage>,
allPackages: List<GroovydocPackagePage>
): List<OrchidCollection<*>> {
return listOf(
PageCollection(this, "classes", allClasses),
PageCollection(this, "packages", allPackages)
)
}
private fun isInnerPackage(parent: GroovydocPackageDoc, possibleChild: GroovydocPackageDoc): Boolean {
// packages start the same...
if (possibleChild.name.startsWith(parent.name)) {
// packages are not the same...
if (possibleChild.name != parent.name) {
val parentSegmentCount =
parent.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size
val possibleChildSegmentCount =
possibleChild.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size
// child has one segment more than the parent, so is immediate child
if (possibleChildSegmentCount == parentSegmentCount + 1) {
return true
}
}
}
return false
}
}
| mit | 046746e5615b69a229f981fba4cd1be3 | 37.480315 | 113 | 0.680786 | 4.971516 | false | false | false | false |
mobilesolutionworks/works-controller-android | library/src/main/kotlin/com/mobilesolutionworks/android/app/controller/WorksControllerManager.kt | 1 | 5000 | package com.mobilesolutionworks.android.app.controller
import android.content.Context
import android.os.Bundle
import android.support.v4.app.LoaderManager
import android.support.v4.content.Loader
import android.util.SparseArray
//typealias ControllerCallbacks = (WorksControllerManager) -> WorksController
/**
* Controller manager where WorksController will be created and persisted.
*
*
* Created by yunarta on 18/11/15.
*/
class WorksControllerManager private constructor(context: Context) {
/**
* Collection of created controllers.
*/
internal val controllers = SparseArray<WorksController>()
/**
* Lifecycle hook.
*/
internal val lifecycleHook = WorksControllerLifecycleHook(this)
fun getLifecycleHook(): WorksControllerLifecycleHook = lifecycleHook
/**
* Main scheduler.
*/
/**
* Get main scheduler.
*/
internal val mainScheduler = WorksMainScheduler()
/**
* Get application context.
*/
internal val context: Context = context.applicationContext
/**
* Dispatch pause, called by lifecycle hook.
*/
internal fun dispatchPause() {
mainScheduler.pause()
}
/**
* Dispatch resume, called by lifecycle hook.
*/
internal fun dispatchResume() {
mainScheduler.resume()
}
// @FunctionalInterface
// interface ControllerCallbacks<out D : WorksController> {
//
// /**
// * Called by implementation to create a Loader.
// */
// fun onCreateController(id: Int, args: Bundle?): D
// }
/**
* Init a WorksController.
*
* @param id a unique identifier for this loader.
* *
* @param args optional arguments .
* *
* @param callback interface that controller manager will call to report about
* * changes in the state of the loader. Required.
* *
* @return returns controller implementation immediately, if one is already created before than it will be returned.
*/
fun initWorksController(id: Int, args: Bundle?, callback: CreateCallback2<out WorksController>): WorksController {
val controller: WorksController? = controllers.get(id)
if (controller == null) {
val newController = callback.create(this)
newController.onCreate(args)
controllers.put(id, newController)
return newController
} else {
return controller
}
}
fun <D : WorksController> initController(id: Int, args: Bundle?, callback: CreateCallback2<D>): D {
val controller = initWorksController(id, args, callback)
@Suppress("UNCHECKED_CAST")
val test = controller as? D
when {
test != null -> return test
else -> throw IllegalStateException("Controlled assigned with id $id is not created with this callback")
}
}
/**
* Get controller by id.
* @param id the id that controller was created
* *
* @return associated controller is exist.
*/
fun getController(id: Int): WorksController? {
return controllers.get(id)
}
/**
* Destroy associated controller.
*
*
* This will call onDestroy of controller.
*/
fun destroyController(id: Int) {
val controller = controllers.get(id)
if (controller != null) {
controllers.remove(id)
controller.onDestroy()
}
}
/**
* Loader implementation to create the WorksController.
*
*
* This can be used when developer requires to use activities that is not subclass of WorksActivity.
*/
class ControllerManager internal constructor(context: Context) : Loader<WorksControllerManager>(context) {
val controller = WorksControllerManager(context)
override fun onStartLoading() {
super.onStartLoading()
deliverResult(controller)
}
}
/**
* Loader callback implementation to create WorksController.
*
*
* This can be used when developer requires to use activities that is not subclass of WorksActivity.
*/
class ControllerManagerLoaderCallbacks(context: Context) : LoaderManager.LoaderCallbacks<WorksControllerManager> {
private val context = context.applicationContext
override fun onCreateLoader(id: Int, args: Bundle?): Loader<WorksControllerManager> {
return ControllerManager(context).apply {
startLoading()
}
}
override fun onLoadFinished(loader: Loader<WorksControllerManager>, data: WorksControllerManager) {
}
override fun onLoaderReset(loader: Loader<WorksControllerManager>) {
val controller = (loader as ControllerManager).controller
controller.lifecycleHook.dispatchDestroy()
controller.mainScheduler.release()
controller.controllers.clear()
}
}
}
| apache-2.0 | a11d710f4e82067fee8de8a4ee4e658b | 28.239766 | 120 | 0.6378 | 5.02008 | false | false | false | false |
jk1/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/TreeBasedEvaluator.kt | 2 | 28118 | /*
* 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.jetbrains.uast.evaluation
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.PsiVariable
import org.jetbrains.uast.*
import org.jetbrains.uast.values.*
import org.jetbrains.uast.values.UNothingValue.JumpKind.BREAK
import org.jetbrains.uast.values.UNothingValue.JumpKind.CONTINUE
import org.jetbrains.uast.visitor.UastTypedVisitor
class TreeBasedEvaluator(
override val context: UastContext,
val extensions: List<UEvaluatorExtension>
) : UastTypedVisitor<UEvaluationState, UEvaluationInfo>, UEvaluator {
override fun getDependents(dependency: UDependency): Set<UValue> {
return resultCache.values.map { it.value }.filter { dependency in it.dependencies }.toSet()
}
private val inputStateCache = mutableMapOf<UExpression, UEvaluationState>()
private val resultCache = mutableMapOf<UExpression, UEvaluationInfo>()
override fun visitElement(node: UElement, data: UEvaluationState): UEvaluationInfo {
return UEvaluationInfo(UUndeterminedValue, data).apply {
if (node is UExpression) {
this storeResultFor node
}
}
}
override fun analyze(method: UMethod, state: UEvaluationState) {
method.uastBody?.accept(this, state)
}
override fun analyze(field: UField, state: UEvaluationState) {
field.uastInitializer?.accept(this, state)
}
internal fun getCached(expression: UExpression): UValue? {
return resultCache[expression]?.value
}
override fun evaluate(expression: UExpression, state: UEvaluationState?): UValue {
if (state == null) {
val result = resultCache[expression]
if (result != null) return result.value
}
val inputState = state ?: inputStateCache[expression] ?: expression.createEmptyState()
return expression.accept(this, inputState).value
}
// ----------------------- //
private infix fun UValue.to(state: UEvaluationState) = UEvaluationInfo(this, state)
private infix fun UEvaluationInfo.storeResultFor(expression: UExpression) = apply {
resultCache[expression] = this
}
override fun visitLiteralExpression(node: ULiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val value = node.value
return value.toConstant(node) to data storeResultFor node
}
override fun visitClassLiteralExpression(node: UClassLiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return (node.type?.let { value -> UClassConstant(value, node) } ?: UUndeterminedValue) to data storeResultFor node
}
override fun visitReturnExpression(node: UReturnExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val argument = node.returnExpression
return UValue.UNREACHABLE to (argument?.accept(this, data)?.state ?: data) storeResultFor node
}
override fun visitBreakExpression(node: UBreakExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UNothingValue(node) to data storeResultFor node
}
override fun visitContinueExpression(node: UContinueExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UNothingValue(node) to data storeResultFor node
}
override fun visitThrowExpression(node: UThrowExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UValue.UNREACHABLE to data storeResultFor node
}
// ----------------------- //
override fun visitSimpleNameReferenceExpression(
node: USimpleNameReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
val resolvedElement = node.resolveToUElement()
return when (resolvedElement) {
is UEnumConstant -> UEnumEntryValueConstant(resolvedElement, node)
is UField -> if (resolvedElement.hasModifierProperty(PsiModifier.FINAL)) {
data[resolvedElement].ifUndetermined {
val helper = JavaPsiFacade.getInstance(resolvedElement.project).constantEvaluationHelper
val evaluated = helper.computeConstantExpression(resolvedElement.initializer)
evaluated?.toConstant() ?: UUndeterminedValue
}
}
else {
return super.visitSimpleNameReferenceExpression(node, data)
}
is UVariable -> data[resolvedElement].ifUndetermined {
node.evaluateViaExtensions { evaluateVariable(resolvedElement, data) }?.value ?: UUndeterminedValue
}
else -> return super.visitSimpleNameReferenceExpression(node, data)
} to data storeResultFor node
}
override fun visitReferenceExpression(
node: UReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
return UCallResultValue(node, emptyList()) to data storeResultFor node
}
// ----------------------- //
private fun UExpression.assign(
valueInfo: UEvaluationInfo,
operator: UastBinaryOperator.AssignOperator = UastBinaryOperator.ASSIGN
): UEvaluationInfo {
this.accept(this@TreeBasedEvaluator, valueInfo.state)
if (this is UResolvable) {
val resolvedElement = resolve()
if (resolvedElement is PsiVariable) {
val variable = context.getVariable(resolvedElement)
val currentValue = valueInfo.state[variable]
val result = when (operator) {
UastBinaryOperator.ASSIGN -> valueInfo.value
UastBinaryOperator.PLUS_ASSIGN -> currentValue + valueInfo.value
UastBinaryOperator.MINUS_ASSIGN -> currentValue - valueInfo.value
UastBinaryOperator.MULTIPLY_ASSIGN -> currentValue * valueInfo.value
UastBinaryOperator.DIVIDE_ASSIGN -> currentValue / valueInfo.value
UastBinaryOperator.REMAINDER_ASSIGN -> currentValue % valueInfo.value
UastBinaryOperator.AND_ASSIGN -> currentValue bitwiseAnd valueInfo.value
UastBinaryOperator.OR_ASSIGN -> currentValue bitwiseOr valueInfo.value
UastBinaryOperator.XOR_ASSIGN -> currentValue bitwiseXor valueInfo.value
UastBinaryOperator.SHIFT_LEFT_ASSIGN -> currentValue shl valueInfo.value
UastBinaryOperator.SHIFT_RIGHT_ASSIGN -> currentValue shr valueInfo.value
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN -> currentValue ushr valueInfo.value
else -> UUndeterminedValue
}
return result to valueInfo.state.assign(variable, result, this)
}
}
return UUndeterminedValue to valueInfo.state
}
private fun UExpression.assign(
operator: UastBinaryOperator.AssignOperator,
value: UExpression,
data: UEvaluationState
) = assign(value.accept(this@TreeBasedEvaluator, data), operator)
override fun visitPrefixExpression(node: UPrefixExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPrefixOperator.UNARY_PLUS -> operandValue
UastPrefixOperator.UNARY_MINUS -> -operandValue
UastPrefixOperator.LOGICAL_NOT -> !operandValue
UastPrefixOperator.INC -> {
val resultValue = operandValue.inc()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
UastPrefixOperator.DEC -> {
val resultValue = operandValue.dec()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
else -> {
return node.evaluateViaExtensions { evaluatePrefix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} to operandInfo.state storeResultFor node
}
inline fun UElement.evaluateViaExtensions(block: UEvaluatorExtension.() -> UEvaluationInfo): UEvaluationInfo? {
for (ext in extensions) {
val extResult = ext.block()
if (extResult.value != UUndeterminedValue) return extResult
}
languageExtension()?.block()?.let { if (it.value != UUndeterminedValue) return it }
return null
}
override fun visitPostfixExpression(node: UPostfixExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPostfixOperator.INC -> {
operandValue to node.operand.assign(operandValue.inc() to operandInfo.state).state
}
UastPostfixOperator.DEC -> {
operandValue to node.operand.assign(operandValue.dec() to operandInfo.state).state
}
else -> {
return node.evaluateViaExtensions { evaluatePostfix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} storeResultFor node
}
private fun UastBinaryOperator.evaluate(left: UValue, right: UValue): UValue? =
when (this) {
UastBinaryOperator.PLUS -> left + right
UastBinaryOperator.MINUS -> left - right
UastBinaryOperator.MULTIPLY -> left * right
UastBinaryOperator.DIV -> left / right
UastBinaryOperator.MOD -> left % right
UastBinaryOperator.EQUALS -> left valueEquals right
UastBinaryOperator.NOT_EQUALS -> left valueNotEquals right
UastBinaryOperator.IDENTITY_EQUALS -> left identityEquals right
UastBinaryOperator.IDENTITY_NOT_EQUALS -> left identityNotEquals right
UastBinaryOperator.GREATER -> left greater right
UastBinaryOperator.LESS -> left less right
UastBinaryOperator.GREATER_OR_EQUALS -> left greaterOrEquals right
UastBinaryOperator.LESS_OR_EQUALS -> left lessOrEquals right
UastBinaryOperator.LOGICAL_AND -> left and right
UastBinaryOperator.LOGICAL_OR -> left or right
UastBinaryOperator.BITWISE_AND -> left bitwiseAnd right
UastBinaryOperator.BITWISE_OR -> left bitwiseOr right
UastBinaryOperator.BITWISE_XOR -> left bitwiseXor right
UastBinaryOperator.SHIFT_LEFT -> left shl right
UastBinaryOperator.SHIFT_RIGHT -> left shr right
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT -> left ushr right
else -> null
}
override fun visitBinaryExpression(node: UBinaryExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operator = node.operator
if (operator is UastBinaryOperator.AssignOperator) {
return node.leftOperand.assign(operator, node.rightOperand, data) storeResultFor node
}
val leftInfo = node.leftOperand.accept(this, data)
if (!leftInfo.reachable) {
return leftInfo storeResultFor node
}
val rightInfo = node.rightOperand.accept(this, leftInfo.state)
operator.evaluate(leftInfo.value, rightInfo.value)?.let {
return it to rightInfo.state storeResultFor node
}
return node.evaluateViaExtensions { evaluateBinary(node, leftInfo.value, rightInfo.value, rightInfo.state) }
?: UUndeterminedValue to rightInfo.state storeResultFor node
}
override fun visitPolyadicExpression(node: UPolyadicExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operator = node.operator
val infos = node.operands.map {
it.accept(this, data).apply {
if (!reachable) {
return this storeResultFor node
}
}
}
val lastInfo = infos.last()
val firstValue = infos.first().value
val restInfos = infos.drop(1)
return restInfos.fold(firstValue) { accumulator, info ->
operator.evaluate(accumulator, info.value) ?: return UUndeterminedValue to info.state storeResultFor node
} to lastInfo.state storeResultFor node
}
private fun evaluateTypeCast(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val resultConstant = when (type) {
PsiType.BOOLEAN -> {
constant as? UBooleanConstant
}
PsiType.CHAR -> when (constant) {
// Join the following three in UNumericConstant
// when https://youtrack.jetbrains.com/issue/KT-14868 is fixed
is UIntConstant -> UCharConstant(constant.value.toChar())
is ULongConstant -> UCharConstant(constant.value.toChar())
is UFloatConstant -> UCharConstant(constant.value.toChar())
is UCharConstant -> constant
else -> null
}
PsiType.LONG -> {
(constant as? UNumericConstant)?.value?.toLong()?.let { value -> ULongConstant(value) }
}
PsiType.BYTE, PsiType.SHORT, PsiType.INT -> {
(constant as? UNumericConstant)?.value?.toInt()?.let { UIntConstant(it, type) }
}
PsiType.FLOAT, PsiType.DOUBLE -> {
(constant as? UNumericConstant)?.value?.toDouble()?.let { UFloatConstant.create(it, type) }
}
else -> when (type.name) {
"java.lang.String" -> UStringConstant(constant.asString())
else -> null
}
} ?: return UUndeterminedValue to operandInfo.state
return when (operandInfo.value) {
resultConstant -> return operandInfo
is UConstant -> resultConstant
is UDependentValue -> UDependentValue.create(resultConstant, operandInfo.value.dependencies)
else -> UUndeterminedValue
} to operandInfo.state
}
private fun evaluateTypeCheck(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val valid = when (type) {
PsiType.BOOLEAN -> constant is UBooleanConstant
PsiType.LONG -> constant is ULongConstant
PsiType.BYTE, PsiType.SHORT, PsiType.INT, PsiType.CHAR -> constant is UIntConstant
PsiType.FLOAT, PsiType.DOUBLE -> constant is UFloatConstant
else -> when (type.name) {
"java.lang.String" -> constant is UStringConstant
else -> false
}
}
return UBooleanConstant.valueOf(valid) to operandInfo.state
}
override fun visitBinaryExpressionWithType(
node: UBinaryExpressionWithType, data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
if (!operandInfo.reachable || operandInfo.value == UUndeterminedValue) {
return operandInfo storeResultFor node
}
return when (node.operationKind) {
UastBinaryExpressionWithTypeKind.TYPE_CAST -> evaluateTypeCast(operandInfo, node.type)
UastBinaryExpressionWithTypeKind.INSTANCE_CHECK -> evaluateTypeCheck(operandInfo, node.type)
else -> UUndeterminedValue to operandInfo.state
} storeResultFor node
}
override fun visitParenthesizedExpression(node: UParenthesizedExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return node.expression.accept(this, data) storeResultFor node
}
override fun visitLabeledExpression(node: ULabeledExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return node.expression.accept(this, data) storeResultFor node
}
override fun visitCallExpression(node: UCallExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver?.accept(this, currentInfo.state) ?: currentInfo
if (!currentInfo.reachable) return currentInfo storeResultFor node
val argumentValues = mutableListOf<UValue>()
for (valueArgument in node.valueArguments) {
currentInfo = valueArgument.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
argumentValues.add(currentInfo.value)
}
return (node.evaluateViaExtensions {
node.resolve()?.let { method -> evaluateMethodCall(method, argumentValues, currentInfo.state) }
?: UUndeterminedValue to currentInfo.state
} ?: UCallResultValue(node, argumentValues) to currentInfo.state) storeResultFor node
}
override fun visitQualifiedReferenceExpression(
node: UQualifiedReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
val selectorInfo = node.selector.accept(this, currentInfo.state)
return when (node.accessType) {
UastQualifiedExpressionAccessType.SIMPLE -> {
selectorInfo
}
else -> {
return node.evaluateViaExtensions { evaluateQualified(node.accessType, currentInfo, selectorInfo) }
?: UUndeterminedValue to selectorInfo.state storeResultFor node
}
} storeResultFor node
}
override fun visitDeclarationsExpression(
node: UDeclarationsExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
for (variable in node.declarations) {
currentInfo = variable.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitVariable(node: UVariable, data: UEvaluationState): UEvaluationInfo {
val initializer = node.uastInitializer
val initializerInfo = initializer?.accept(this, data) ?: UUndeterminedValue to data
if (!initializerInfo.reachable) return initializerInfo
return UUndeterminedValue to initializerInfo.state.assign(node, initializerInfo.value, node)
}
// ----------------------- //
override fun visitBlockExpression(node: UBlockExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
for (expression in node.expressions) {
currentInfo = expression.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitIfExpression(node: UIfExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val conditionInfo = node.condition.accept(this, data)
if (!conditionInfo.reachable) return conditionInfo storeResultFor node
val thenInfo = node.thenExpression?.accept(this, conditionInfo.state)
val elseInfo = node.elseExpression?.accept(this, conditionInfo.state)
val conditionValue = conditionInfo.value
val defaultInfo = UUndeterminedValue to conditionInfo.state
val constantConditionValue = conditionValue.toConstant()
return when (constantConditionValue) {
is UBooleanConstant -> {
if (constantConditionValue.value) thenInfo ?: defaultInfo
else elseInfo ?: defaultInfo
}
else -> when {
thenInfo == null -> elseInfo?.merge(defaultInfo) ?: defaultInfo
elseInfo == null -> thenInfo.merge(defaultInfo)
else -> thenInfo.merge(elseInfo)
}
} storeResultFor node
}
override fun visitSwitchExpression(node: USwitchExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val subjectInfo = node.expression?.accept(this, data) ?: UUndeterminedValue to data
if (!subjectInfo.reachable) return subjectInfo storeResultFor node
var resultInfo: UEvaluationInfo? = null
var clauseInfo = subjectInfo
var fallThroughCondition: UValue = UBooleanConstant.False
fun List<UExpression>.evaluateAndFold(): UValue =
this.map {
clauseInfo = it.accept(this@TreeBasedEvaluator, clauseInfo.state)
(clauseInfo.value valueEquals subjectInfo.value).toConstant() as? UValueBase ?: UUndeterminedValue
}.fold(UBooleanConstant.False) { previous: UValue, next -> previous or next }
clausesLoop@ for (expression in node.body.expressions) {
val switchClauseWithBody = expression as USwitchClauseExpressionWithBody
val caseCondition = switchClauseWithBody.caseValues.evaluateAndFold().or(fallThroughCondition)
if (caseCondition != UBooleanConstant.False) {
for (bodyExpression in switchClauseWithBody.body.expressions) {
clauseInfo = bodyExpression.accept(this, clauseInfo.state)
if (!clauseInfo.reachable) break
}
val clauseValue = clauseInfo.value
if (clauseValue is UNothingValue && clauseValue.containingLoopOrSwitch == node) {
// break from switch
resultInfo = resultInfo?.merge(clauseInfo) ?: clauseInfo
if (caseCondition == UBooleanConstant.True) break@clausesLoop
clauseInfo = subjectInfo
fallThroughCondition = UBooleanConstant.False
}
// TODO: jump out
else {
fallThroughCondition = caseCondition
clauseInfo = clauseInfo.merge(subjectInfo)
}
}
}
resultInfo = resultInfo ?: subjectInfo
val resultValue = resultInfo.value
if (resultValue is UNothingValue && resultValue.containingLoopOrSwitch == node) {
resultInfo = resultInfo.copy(UUndeterminedValue)
}
return resultInfo storeResultFor node
}
private fun evaluateLoop(
loop: ULoopExpression,
inputState: UEvaluationState,
condition: UExpression? = null,
infinite: Boolean = false,
update: UExpression? = null
): UEvaluationInfo {
fun evaluateCondition(inputState: UEvaluationState): UEvaluationInfo =
condition?.accept(this, inputState)
?: (if (infinite) UBooleanConstant.True else UUndeterminedValue) to inputState
ProgressManager.checkCanceled()
var resultInfo = UUndeterminedValue to inputState
do {
val previousInfo = resultInfo
resultInfo = evaluateCondition(resultInfo.state)
val conditionConstant = resultInfo.value.toConstant()
if (conditionConstant == UBooleanConstant.False) {
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
val bodyInfo = loop.body.accept(this, resultInfo.state)
val bodyValue = bodyInfo.value
if (bodyValue is UNothingValue) {
if (bodyValue.kind == BREAK && bodyValue.containingLoopOrSwitch == loop) {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo.copy(UUndeterminedValue)
}
else {
bodyInfo.copy(UUndeterminedValue).merge(previousInfo)
} storeResultFor loop
}
else if (bodyValue.kind == CONTINUE && bodyValue.containingLoopOrSwitch == loop) {
val updateInfo = update?.accept(this, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.copy(UUndeterminedValue).merge(previousInfo)
}
else {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo
}
else {
resultInfo.copy(UUndeterminedValue)
} storeResultFor loop
}
}
else {
val updateInfo = update?.accept(this, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.merge(previousInfo)
}
}
while (previousInfo != resultInfo)
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
override fun visitForEachExpression(node: UForEachExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val iterableInfo = node.iteratedValue.accept(this, data)
return evaluateLoop(node, iterableInfo.state)
}
override fun visitForExpression(node: UForExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val initialState = node.declaration?.accept(this, data)?.state ?: data
return evaluateLoop(node, initialState, node.condition, node.condition == null, node.update)
}
override fun visitWhileExpression(node: UWhileExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return evaluateLoop(node, data, node.condition)
}
override fun visitDoWhileExpression(node: UDoWhileExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val bodyInfo = node.body.accept(this, data)
return evaluateLoop(node, bodyInfo.state, node.condition)
}
override fun visitTryExpression(node: UTryExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val tryInfo = node.tryClause.accept(this, data)
val mergedTryInfo = tryInfo.merge(UUndeterminedValue to data)
val catchInfoList = node.catchClauses.map { it.accept(this, mergedTryInfo.state) }
val mergedTryCatchInfo = catchInfoList.fold(mergedTryInfo, UEvaluationInfo::merge)
val finallyInfo = node.finallyClause?.accept(this, mergedTryCatchInfo.state) ?: mergedTryCatchInfo
return finallyInfo storeResultFor node
}
// ----------------------- //
override fun visitObjectLiteralExpression(node: UObjectLiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val objectInfo = node.declaration.accept(this, data)
val resultState = data.merge(objectInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitLambdaExpression(node: ULambdaExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val lambdaInfo = node.body.accept(this, data)
val resultState = data.merge(lambdaInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitClass(node: UClass, data: UEvaluationState): UEvaluationInfo {
// fields / initializers / nested classes?
var resultState = data
for (method in node.methods) {
resultState = resultState.merge(method.accept(this, resultState).state)
}
return UUndeterminedValue to resultState
}
override fun visitMethod(node: UMethod, data: UEvaluationState): UEvaluationInfo {
return UUndeterminedValue to (node.uastBody?.accept(this, data)?.state ?: data)
}
}
fun Any?.toConstant(node: ULiteralExpression? = null): UValueBase = when (this) {
null -> UNullConstant
is Float -> UFloatConstant.create(this.toDouble(), UNumericType.FLOAT, node)
is Double -> UFloatConstant.create(this, UNumericType.DOUBLE, node)
is Long -> ULongConstant(this, node)
is Int -> UIntConstant(this, UNumericType.INT, node)
is Short -> UIntConstant(this.toInt(), UNumericType.SHORT, node)
is Byte -> UIntConstant(this.toInt(), UNumericType.BYTE, node)
is Char -> UCharConstant(this, node)
is Boolean -> UBooleanConstant.valueOf(this)
is String -> UStringConstant(this, node)
else -> UUndeterminedValue
}
| apache-2.0 | 2768b911243efda354160454e6c5bfa9 | 41.538578 | 120 | 0.707661 | 5.295292 | false | false | false | false |
andrewoma/dexx | collection/src/test/java/com/github/andrewoma/dexx/collection/performance/MapPerformanceTest.kt | 1 | 5771 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.dexx.collection.performance
import com.github.andrewoma.dexx.collection.Builder
import com.github.andrewoma.dexx.collection.HashMap
import com.github.andrewoma.dexx.collection.Pair
import com.github.andrewoma.dexx.collection.mutable.MutableHashMap
import com.github.andrewoma.dexx.collection.performance.PerformanceMeasurement.Result
import org.junit.Test
import kotlin.system.measureNanoTime
import com.github.andrewoma.dexx.collection.Map as DMap
open class MapPerformanceTest : PerformanceMeasurement {
@Test fun put() {
put(size = 100, operations = 10000, iterations = 1000)
put(size = 10000, operations = 10000, iterations = 1000)
put(size = 100000, operations = 10000, iterations = 100)
put(size = 1000000, operations = 10000, iterations = 10)
}
@Test fun containsKey() {
containsKey(size = 100, operations = 100, iterations = 1000)
containsKey(size = 10000, operations = 10000, iterations = 1000)
containsKey(size = 100000, operations = 100000, iterations = 100)
containsKey(size = 1000000, operations = 1000000, iterations = 10)
}
@Test fun remove() {
remove(size = 100, operations = 100, iterations = 1000)
remove(size = 10000, operations = 10000, iterations = 1000)
remove(size = 100000, operations = 100000, iterations = 100)
remove(size = 1000000, operations = 1000000, iterations = 10)
}
fun put(size: Int, operations: Int, iterations: Int) {
if (disabled()) return
val randomInts = uniqueRandomInts(size)
val operationInts = randomInts(operations)
compare("Put $operations random ints to map of size $size", operations, iterations = iterations) { builder ->
put(randomInts, operationInts, builder)
}
}
fun containsKey(size: Int, operations: Int, iterations: Int) {
if (disabled()) return
val randomInts = uniqueRandomInts(size)
val operationInts = randomAccesses(operations, randomInts, true)
compare("Check map of size $size contains element $operations times", operations, iterations = iterations) { builder ->
containsKey(randomInts, operationInts, builder)
}
}
fun remove(size: Int, operations: Int, iterations: Int) {
if (disabled()) return
val randomInts = uniqueRandomInts(size)
val operationInts = randomAccesses(operations, randomInts, true)
compare("Remove all items randomly from a map of size $size elements", operations, iterations = iterations) { builder ->
remove(randomInts, operationInts, builder)
}
}
fun put(randomInts: IntArray, operationInts: IntArray, builder: Builder<Pair<Int, Int>, out DMap<Int, Int>>): Result {
for (i in randomInts) {
builder.add(Pair(i, i))
}
var map = builder.build()
var result = 0L
val duration = measureNanoTime {
for (i in operationInts) {
map = map.put(i, i)
result += i
}
}
result += map.size()
return Result(duration, result)
}
fun containsKey(randomInts: IntArray, operationInts: IntArray, builder: Builder<Pair<Int, Int>, out DMap<Int, Int>>): Result {
for (i in randomInts) {
builder.add(Pair(i, i))
}
val map = builder.build()
var result = 0L
val duration = measureNanoTime {
for (i in operationInts) {
val found = map.containsKey(i)
result += if (found) 1 else 0
}
}
result += map.size()
return Result(duration, result)
}
fun remove(randomInts: IntArray, operationInts: IntArray, builder: Builder<Pair<Int, Int>, out DMap<Int, Int>>): Result {
for (i in randomInts) {
builder.add(Pair(i, i))
}
var map = builder.build()
var result = 0L
val duration = measureNanoTime {
for (i in operationInts) {
map = map.remove(i)
result += i
}
}
result += map.size()
return Result(duration, result)
}
open fun compare(description: String, operations: Int, iterations: Int, f: (builder: Builder<Pair<Int, Int>, out DMap<Int, Int>>) -> PerformanceMeasurement.Result) {
val java = time(iterations) { f(MutableHashMap.factory<Int, Int>().newBuilder()) }
val dexx = time(iterations) { f(HashMap.factory<Int, Int>().newBuilder()) }
compare("Map: $description", operations, java, dexx)
}
}
| mit | 585e0a821c1e6c4dd5b86b7ada98182e | 36.718954 | 169 | 0.649627 | 4.365356 | false | false | false | false |
eyneill777/SpacePirates | core/src/rustyice/game/tiles/WallTile.kt | 1 | 714 | package rustyice.game.tiles
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Sprite
import rustyengine.RustyEngine
import rustyice.Core
import rustyice.editor.annotations.ComponentProperty
import rustyice.game.physics.RectWallComponent
import rustyengine.resources.Resources
class WallTile() : Tile(true, true) {
@ComponentProperty
var color = Color.BLUE
set(value) {
field = value
sprite?.color = color
}
override fun init() {
super.init()
val sprite = Sprite(RustyEngine.resorces.box)
sprite.color = color
this.sprite = sprite
}
init {
tilePhysics = RectWallComponent()
}
}
| mit | 9eda0822de4513778d7f29b6debcbed3 | 21.3125 | 53 | 0.676471 | 4.224852 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/test/java/com/doctoror/particleswallpaper/userprefs/ConfigActivityMenuPresenterLollipopTest.kt | 1 | 3056 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.doctoror.particleswallpaper.userprefs
import android.view.Menu
import android.view.MenuItem
import com.doctoror.particleswallpaper.R
import com.doctoror.particleswallpaper.userprefs.preview.OpenChangeWallpaperIntentProvider
import com.doctoror.particleswallpaper.userprefs.preview.OpenChangeWallpaperIntentUseCase
import io.reactivex.Completable
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mockito.kotlin.*
class ConfigActivityMenuPresenterLollipopTest {
private val openChangeWallpaperIntentProvider: OpenChangeWallpaperIntentProvider = mock()
private val openChangeWallpaperIntentUseCase: OpenChangeWallpaperIntentUseCase = mock()
private val view: ConfigActivityMenuView = mock()
private val underTest = ConfigActivityMenuPresenterLollipop(
openChangeWallpaperIntentProvider,
openChangeWallpaperIntentUseCase,
view
)
@Test
fun setsUpToolbarOnCreate() {
// When
underTest.onCreate()
// Then
verify(view).setupToolbar()
}
@Test
fun inflatesOptionsMenuWhenHasWallpaperIntent() {
// Given
val menu: Menu = mock()
whenever(openChangeWallpaperIntentProvider.provideActionIntent()).thenReturn(mock())
// When
val result = underTest.onCreateOptionsMenu(menu)
// Then
assertTrue(result)
verify(view).inflateMenu(menu)
}
@Test
fun doesNotInflateOptionsMenuWhenHasNoWallpaperIntent() {
// When
val result = underTest.onCreateOptionsMenu(mock())
// Then
assertTrue(result)
verify(view, never()).inflateMenu(any())
}
@Test
fun finishesOnUpButton() {
// When
underTest.onOptionsItemSelected(mockMenuItemWithId(android.R.id.home))
// Then
verify(view).finish()
}
@Test
fun subscribesToChangeWallpaperUseCaseOnPreviewClick() {
// Given
val useCaseCompletable = spy(Completable.complete())
whenever(openChangeWallpaperIntentUseCase.action())
.thenReturn(useCaseCompletable)
// When
underTest.onOptionsItemSelected(mockMenuItemWithId(R.id.actionApply))
// Then
verify(openChangeWallpaperIntentUseCase).action()
verify(useCaseCompletable).subscribe()
}
private fun mockMenuItemWithId(id: Int): MenuItem = mock {
whenever(it.itemId).doReturn(id)
}
}
| apache-2.0 | 383160d6866b920ab00f9bdae82f1d27 | 29.56 | 93 | 0.70877 | 4.797488 | false | true | false | false |
jovr/imgui | core/src/main/kotlin/imgui/static/navigation.kt | 2 | 49659 | package imgui.static
import gli_.has
import gli_.hasnt
import glm_.glm
import glm_.i
import glm_.max
import glm_.vec2.Vec2
import imgui.*
import imgui.ImGui.begin
import imgui.ImGui.calcTextSize
import imgui.ImGui.clearActiveID
import imgui.ImGui.closePopupToLevel
import imgui.ImGui.closePopupsOverWindow
import imgui.ImGui.end
import imgui.ImGui.findRenderedTextEnd
import imgui.ImGui.findWindowByName
import imgui.ImGui.focusWindow
import imgui.ImGui.getForegroundDrawList
import imgui.ImGui.getNavInputAmount2d
import imgui.ImGui.io
import imgui.ImGui.isActiveIdUsingKey
import imgui.ImGui.isActiveIdUsingNavDir
import imgui.ImGui.isActiveIdUsingNavInput
import imgui.ImGui.isKeyDown
import imgui.ImGui.isMouseHoveringRect
import imgui.ImGui.isMousePosValid
import imgui.ImGui.navInitWindow
import imgui.ImGui.navMoveRequestButNoResultYet
import imgui.ImGui.navMoveRequestForward
import imgui.ImGui.popStyleVar
import imgui.ImGui.pushStyleVar
import imgui.ImGui.selectable
import imgui.ImGui.setNavIDWithRectRel
import imgui.ImGui.setNavID
import imgui.ImGui.setNextWindowPos
import imgui.ImGui.setNextWindowSizeConstraints
import imgui.ImGui.style
import imgui.ImGui.topMostPopupModal
import imgui.api.g
import imgui.internal.*
import imgui.internal.classes.NavMoveResult
import imgui.internal.classes.Rect
import imgui.internal.classes.Window
import imgui.internal.sections.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import imgui.WindowFlag as Wf
import imgui.internal.sections.ItemFlag as If
fun navUpdate() {
io.wantSetMousePos = false
// if (g.NavScoringCount > 0) printf("[%05d] NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g . NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest)
// Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
// (do it before we map Keyboard input!)
val navKeyboardActive = io.configFlags has ConfigFlag.NavEnableKeyboard
val navGamepadActive = io.configFlags has ConfigFlag.NavEnableGamepad && io.backendFlags has BackendFlag.HasGamepad
if (navGamepadActive && g.navInputSource != InputSource.NavGamepad)
io.navInputs.also {
if (it[NavInput.Activate] > 0f || it[NavInput.Input] > 0f || it[NavInput.Cancel] > 0f || it[NavInput.Menu] > 0f
|| it[NavInput.DpadLeft] > 0f || it[NavInput.DpadRight] > 0f || it[NavInput.DpadUp] > 0f || it[NavInput.DpadDown] > 0f
)
g.navInputSource = InputSource.NavGamepad
}
// Update Keyboard->Nav inputs mapping
if (navKeyboardActive) {
fun navMapKey(key: Key, navInput: NavInput) {
if (isKeyDown(io.keyMap[key])) {
io.navInputs[navInput] = 1f
g.navInputSource = InputSource.NavKeyboard
}
}
navMapKey(Key.Space, NavInput.Activate)
navMapKey(Key.Enter, NavInput.Input)
navMapKey(Key.Escape, NavInput.Cancel)
navMapKey(Key.LeftArrow, NavInput._KeyLeft)
navMapKey(Key.RightArrow, NavInput._KeyRight)
navMapKey(Key.UpArrow, NavInput._KeyUp)
navMapKey(Key.DownArrow, NavInput._KeyDown)
if (io.keyCtrl)
io.navInputs[NavInput.TweakSlow] = 1f
if (io.keyShift)
io.navInputs[NavInput.TweakFast] = 1f
if (io.keyAlt && !io.keyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
io.navInputs[NavInput._KeyMenu] = 1f
}
for (i in io.navInputsDownDuration.indices)
io.navInputsDownDurationPrev[i] = io.navInputsDownDuration[i]
for (i in io.navInputs.indices)
io.navInputsDownDuration[i] = when (io.navInputs[i] > 0f) {
true -> if (io.navInputsDownDuration[i] < 0f) 0f else io.navInputsDownDuration[i] + io.deltaTime
else -> -1f
}
// Process navigation init request (select first/default focus)
if (g.navInitResultId != 0 && (!g.navDisableHighlight || g.navInitRequestFromMove))
navUpdateInitResult()
g.navInitRequest = false
g.navInitRequestFromMove = false
g.navInitResultId = 0
g.navJustMovedToId = 0
// Process navigation move request
if (g.navMoveRequest)
navUpdateMoveResult()
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.navMoveRequestForward == NavForward.ForwardActive) {
assert(g.navMoveRequest)
if (g.navMoveResultLocal.id == 0 && g.navMoveResultOther.id == 0)
g.navDisableHighlight = false
g.navMoveRequestForward = NavForward.None
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.navMousePosDirty && g.navIdIsAlive) {
// Set mouse position given our knowledge of the navigated item position from last frame
if (io.configFlags has ConfigFlag.NavEnableSetMousePos && io.backendFlags has BackendFlag.HasSetMousePos)
if (!g.navDisableHighlight && g.navDisableMouseHover && g.navWindow != null) {
io.mousePos = navCalcPreferredRefPos()
io.mousePosPrev = Vec2(io.mousePos)
io.wantSetMousePos = true
}
g.navMousePosDirty = false
}
g.navIdIsAlive = false
g.navJustTabbedId = 0
// assert(g.navLayer == 0 || g.navLayer == 1) useless on jvm
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
g.navWindow?.let {
navSaveLastChildNavWindowIntoParent(it)
if (it.navLastChildNavWindow != null && g.navLayer == NavLayer.Main)
it.navLastChildNavWindow = null
}
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
navUpdateWindowing()
// Set output flags for user application
io.navActive = (navKeyboardActive || navGamepadActive) && g.navWindow?.flags?.hasnt(Wf.NoNavInputs) ?: false
io.navVisible = (io.navActive && g.navId != 0 && !g.navDisableHighlight) || g.navWindowingTarget != null
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (NavInput.Cancel.isTest(InputReadMode.Pressed)) {
IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel")
if (g.activeId != 0) {
if (!isActiveIdUsingNavInput(NavInput.Cancel))
clearActiveID()
} else if (g.navWindow != null && g.navWindow!!.flags has Wf._ChildWindow && g.navWindow!!.flags hasnt Wf._Popup && g.navWindow!!.parentWindow != null) {
// Exit child window
val childWindow = g.navWindow!!
val parentWindow = childWindow.parentWindow!!
assert(childWindow.childId != 0)
focusWindow(parentWindow)
setNavID(childWindow.childId, NavLayer.Main, 0)
// Reassigning with same value, we're being explicit here.
g.navIdIsAlive = false // -V1048
if (g.navDisableMouseHover)
g.navMousePosDirty = true
} else if (g.openPopupStack.isNotEmpty()) {
// Close open popup/menu
if (g.openPopupStack.last().window!!.flags hasnt Wf._Modal)
closePopupToLevel(g.openPopupStack.lastIndex, true)
} else if (g.navLayer != NavLayer.Main)
navRestoreLayer(NavLayer.Main) // Leave the "menu" layer
else {
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.navWindow != null && (g.navWindow!!.flags has Wf._Popup || g.navWindow!!.flags hasnt Wf._ChildWindow))
g.navWindow!!.navLastIds[0] = 0
g.navFocusScopeId = 0
g.navId = 0
}
}
// Process manual activation request
g.navActivateId = 0
g.navActivateDownId = 0
g.navActivatePressedId = 0
g.navInputId = 0
if (g.navId != 0 && !g.navDisableHighlight && g.navWindowingTarget == null && g.navWindow != null && g.navWindow!!.flags hasnt Wf.NoNavInputs) {
val activateDown = NavInput.Activate.isDown()
val activatePressed = activateDown && NavInput.Activate.isTest(InputReadMode.Pressed)
if (g.activeId == 0 && activatePressed)
g.navActivateId = g.navId
if ((g.activeId == 0 || g.activeId == g.navId) && activateDown)
g.navActivateDownId = g.navId
if ((g.activeId == 0 || g.activeId == g.navId) && activatePressed)
g.navActivatePressedId = g.navId
if ((g.activeId == 0 || g.activeId == g.navId) && NavInput.Input.isTest(InputReadMode.Pressed))
g.navInputId = g.navId
}
g.navWindow?.let { if (it.flags has Wf.NoNavInputs) g.navDisableHighlight = true }
if (g.navActivateId != 0)
assert(g.navActivateDownId == g.navActivateId)
g.navMoveRequest = false
// Process programmatic activation request
if (g.navNextActivateId != 0) {
g.navInputId = g.navNextActivateId
g.navActivatePressedId = g.navNextActivateId
g.navActivateDownId = g.navNextActivateId
g.navActivateId = g.navNextActivateId
}
g.navNextActivateId = 0
// Initiate directional inputs request
if (g.navMoveRequestForward == NavForward.None) {
g.navMoveDir = Dir.None
g.navMoveRequestFlags = NavMoveFlag.None.i
g.navWindow?.let {
if (g.navWindowingTarget == null && it.flags hasnt Wf.NoNavInputs) {
val readMode = InputReadMode.Repeat
if (!isActiveIdUsingNavDir(Dir.Left) && (NavInput.DpadLeft.isTest(readMode) || NavInput._KeyLeft.isTest(
readMode
))
) g.navMoveDir = Dir.Left
if (!isActiveIdUsingNavDir(Dir.Right) && (NavInput.DpadRight.isTest(readMode) || NavInput._KeyRight.isTest(
readMode
))
) g.navMoveDir = Dir.Right
if (!isActiveIdUsingNavDir(Dir.Up) && (NavInput.DpadUp.isTest(readMode) || NavInput._KeyUp.isTest(
readMode
))
) g.navMoveDir = Dir.Up
if (!isActiveIdUsingNavDir(Dir.Down) && (NavInput.DpadDown.isTest(readMode) || NavInput._KeyDown.isTest(
readMode
))
) g.navMoveDir = Dir.Down
}
}
g.navMoveDir = g.navMoveDir
} else {
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
assert(g.navMoveDir != Dir.None && g.navMoveDir != Dir.None)
assert(g.navMoveRequestForward == NavForward.ForwardQueued)
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward ${g.navMoveDir.i}")
g.navMoveRequestForward = NavForward.ForwardActive
}
// Update PageUp/PageDown/Home/End scroll
// FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
val navScoringRectOffsetY = when {
navKeyboardActive -> navUpdatePageUpPageDown()
else -> 0f
}
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.navMoveDir != Dir.None) {
g.navMoveRequest = true
g.navMoveRequestKeyMods = io.keyMods
g.navMoveDirLast = g.navMoveDir
}
if (g.navMoveRequest && g.navId == 0) {
IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"${g.navWindow!!.name}\", layer=${g.navLayer}")
g.navInitRequest = true
g.navInitRequestFromMove = true
// Reassigning with same value, we're being explicit here.
g.navInitResultId = 0 // -V1048
g.navDisableHighlight = false
}
navUpdateAnyRequestFlag()
// Scrolling
g.navWindow?.let {
if (it.flags hasnt Wf.NoNavInputs && g.navWindowingTarget == null) {
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
val scrollSpeed =
round(it.calcFontSize() * 100 * io.deltaTime) // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (it.dc.navLayerActiveMask == 0 && it.dc.navHasScroll && g.navMoveRequest) {
if (g.navMoveDir == Dir.Left || g.navMoveDir == Dir.Right)
it setScrollX floor(it.scroll.x + (if (g.navMoveDir == Dir.Left) -1f else 1f) * scrollSpeed)
if (g.navMoveDir == Dir.Up || g.navMoveDir == Dir.Down)
it setScrollY floor(it.scroll.y + (if (g.navMoveDir == Dir.Up) -1f else 1f) * scrollSpeed)
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
val scrollDir = getNavInputAmount2d(NavDirSourceFlag.PadLStick.i, InputReadMode.Down, 1f / 10f, 10f)
if (scrollDir.x != 0f && it.scrollbar.x)
it setScrollX floor(it.scroll.x + scrollDir.x * scrollSpeed)
if (scrollDir.y != 0f)
it setScrollY floor(it.scroll.y + scrollDir.y * scrollSpeed)
}
}
// Reset search results
g.navMoveResultLocal.clear()
g.navMoveResultLocalVisibleSet.clear()
g.navMoveResultOther.clear()
// When using gamepad, we project the reference nav bounding box into window visible area.
// This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
// (can't focus a visible object like we can with the mouse).
if (g.navMoveRequest && g.navInputSource == InputSource.NavGamepad && g.navLayer == NavLayer.Main) {
val window = g.navWindow!!
val windowRectRel = Rect(window.innerRect.min - window.pos - 1, window.innerRect.max - window.pos + 1)
if (window.navRectRel[g.navLayer] !in windowRectRel) {
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel")
val pad = window.calcFontSize() * 0.5f
windowRectRel expand Vec2(
-min(windowRectRel.width, pad),
-min(windowRectRel.height, pad)
) // Terrible approximation for the intent of starting navigation from first fully visible item
window.navRectRel[g.navLayer] clipWithFull windowRectRel
g.navFocusScopeId = 0
g.navId = 0
}
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
g.navWindow.let {
val navRectRel = it?.run { Rect(navRectRel[g.navLayer]) } ?: Rect()
g.navScoringRect.put(it?.run { Rect(navRectRel.min + it.pos, navRectRel.max + it.pos) } ?: viewportRect)
}
g.navScoringRect translateY navScoringRectOffsetY
g.navScoringRect.min.x = min(g.navScoringRect.min.x + 1f, g.navScoringRect.max.x)
g.navScoringRect.max.x = g.navScoringRect.min.x
// Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous abs() calls in navScoreItem().
assert(!g.navScoringRect.isInverted)
//g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.navScoringCount = 0
if (IMGUI_DEBUG_NAV_RECTS)
g.navWindow?.let { nav ->
for (layer in 0..1)
getForegroundDrawList(nav).addRect(
nav.pos + nav.navRectRel[layer].min,
nav.pos + nav.navRectRel[layer].max,
COL32(255, 200, 0, 255)
) // [DEBUG]
val col = if (!nav.hidden) COL32(255, 0, 255, 255) else COL32(255, 0, 0, 255)
val p = navCalcPreferredRefPos()
val buf = "${g.navLayer}".toByteArray()
getForegroundDrawList(nav).addCircleFilled(p, 3f, col)
getForegroundDrawList(nav).addText(null, 13f, p + Vec2(8, -4), col, buf)
}
}
/** Windowing management mode
* Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
* Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) */
fun navUpdateWindowing() {
var applyFocusWindow: Window? = null
var applyToggleLayer = false
val modalWindow = topMostPopupModal
val allowWindowing = modalWindow == null
if (!allowWindowing)
g.navWindowingTarget = null
// Fade out
if (g.navWindowingTargetAnim != null && g.navWindowingTarget == null) {
g.navWindowingHighlightAlpha = (g.navWindowingHighlightAlpha - io.deltaTime * 10f) max 0f
if (g.dimBgRatio <= 0f && g.navWindowingHighlightAlpha <= 0f)
g.navWindowingTargetAnim = null
}
// Start CTRL-TAB or Square+L/R window selection
val startWindowingWithGamepad = allowWindowing && g.navWindowingTarget == null && NavInput.Menu.isTest(InputReadMode.Pressed)
val startWindowingWithKeyboard = allowWindowing && g.navWindowingTarget == null && io.keyCtrl && Key.Tab.isPressed && io.configFlags has ConfigFlag.NavEnableKeyboard
if (startWindowingWithGamepad || startWindowingWithKeyboard)
(g.navWindow ?: findWindowNavFocusable(g.windowsFocusOrder.lastIndex, -Int.MAX_VALUE, -1))?.let {
g.navWindowingTarget = it.rootWindow // FIXME-DOCK: Will need to use RootWindowDockStop
g.navWindowingTargetAnim = it.rootWindow // FIXME-DOCK: Will need to use RootWindowDockStop
g.navWindowingHighlightAlpha = 0f
g.navWindowingTimer = 0f
g.navWindowingToggleLayer = !startWindowingWithKeyboard
g.navInputSource = if (startWindowingWithKeyboard) InputSource.NavKeyboard else InputSource.NavGamepad
}
// Gamepad update
g.navWindowingTimer += io.deltaTime
g.navWindowingTarget?.let {
if (g.navInputSource == InputSource.NavGamepad) {
/* Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu
(to toggle NavLayer) doesn't add visual noise */
g.navWindowingHighlightAlpha = max(
g.navWindowingHighlightAlpha,
saturate((g.navWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)
)
// Select window to focus
val focusChangeDir =
NavInput.FocusPrev.isTest(InputReadMode.RepeatSlow).i - NavInput.FocusNext.isTest(InputReadMode.RepeatSlow).i
if (focusChangeDir != 0) {
navUpdateWindowingHighlightWindow(focusChangeDir)
g.navWindowingHighlightAlpha = 1f
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!NavInput.Menu.isDown()) {
// Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
g.navWindowingToggleLayer = g.navWindowingToggleLayer and (g.navWindowingHighlightAlpha < 1f)
if (g.navWindowingToggleLayer && g.navWindow != null)
applyToggleLayer = true
else if (!g.navWindowingToggleLayer)
applyFocusWindow = it
g.navWindowingTarget = null
}
}
}
// Keyboard: Focus
g.navWindowingTarget?.let {
if (g.navInputSource == InputSource.NavKeyboard) {
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.navWindowingHighlightAlpha = max(
g.navWindowingHighlightAlpha,
saturate((g.navWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)
) // 1.0f
if (Key.Tab.isPressed(true))
navUpdateWindowingHighlightWindow(if (io.keyShift) 1 else -1)
if (!io.keyCtrl)
applyFocusWindow = g.navWindowingTarget
}
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of backend clearing releases all keys on ALT-TAB
if (NavInput._KeyMenu.isTest(InputReadMode.Pressed))
g.navWindowingToggleLayer = true
if ((g.activeId == 0 || g.activeIdAllowOverlap) && g.navWindowingToggleLayer && NavInput._KeyMenu.isTest(
InputReadMode.Released
)
)
if (isMousePosValid(io.mousePos) == isMousePosValid(io.mousePosPrev))
applyToggleLayer = true
// Move window
g.navWindowingTarget?.let {
if (it.flags hasnt Wf.NoMove) {
var moveDelta = Vec2()
if (g.navInputSource == InputSource.NavKeyboard && !io.keyShift)
moveDelta = getNavInputAmount2d(NavDirSourceFlag.Keyboard.i, InputReadMode.Down)
if (g.navInputSource == InputSource.NavGamepad)
moveDelta = getNavInputAmount2d(NavDirSourceFlag.PadLStick.i, InputReadMode.Down)
if (moveDelta.x != 0f || moveDelta.y != 0f) {
val NAV_MOVE_SPEED = 800f
val moveSpeed = floor(
NAV_MOVE_SPEED * io.deltaTime * min(
io.displayFramebufferScale.x,
io.displayFramebufferScale.y
)
) // FIXME: Doesn't handle variable framerate very well
it.rootWindow!!.apply { // movingWindow
setPos(pos + moveDelta * moveSpeed, Cond.Always)
markIniSettingsDirty()
}
g.navDisableMouseHover = true
}
}
}
// Apply final focus
if (applyFocusWindow != null && (g.navWindow == null || applyFocusWindow !== g.navWindow!!.rootWindow)) {
clearActiveID()
g.navDisableHighlight = false
g.navDisableMouseHover = true
applyFocusWindow = navRestoreLastChildNavWindow(applyFocusWindow!!)
closePopupsOverWindow(applyFocusWindow, false)
focusWindow(applyFocusWindow)
if (applyFocusWindow!!.navLastIds[0] == 0)
navInitWindow(applyFocusWindow!!, false)
// If the window only has a menu layer, select it directly
if (applyFocusWindow!!.dc.navLayerActiveMask == 1 shl NavLayer.Menu)
g.navLayer = NavLayer.Menu
}
applyFocusWindow?.let { g.navWindowingTarget = null }
// Apply menu/layer toggle
if (applyToggleLayer)
g.navWindow?.let {
// Move to parent menu if necessary
var newNavWindow = it
tailrec fun Window.getParent(): Window { // TODO, now we can use construct `parent?.`..
val parent = parentWindow
return when {
parent != null && dc.navLayerActiveMask hasnt (1 shl NavLayer.Menu) && flags has Wf._ChildWindow && flags hasnt (Wf._Popup or Wf._ChildMenu) -> parent.getParent()
else -> this
}
}
newNavWindow = newNavWindow.getParent()
if (newNavWindow !== it) {
val oldNavWindow = it
focusWindow(newNavWindow)
newNavWindow.navLastChildNavWindow = oldNavWindow
}
g.navDisableHighlight = false
g.navDisableMouseHover = true
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
val newNavLayer = when {
it.dc.navLayerActiveMask has (1 shl NavLayer.Menu) -> NavLayer of (g.navLayer xor 1)
else -> NavLayer.Main
}
navRestoreLayer(newNavLayer)
}
}
/** Overlay displayed when using CTRL+TAB. Called by EndFrame(). */
fun navUpdateWindowingOverlay() {
val target = g.navWindowingTarget!! // ~ assert
if (g.navWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return
if (g.navWindowingListWindow == null)
g.navWindowingListWindow = findWindowByName("###NavWindowingList")
setNextWindowSizeConstraints(Vec2(io.displaySize.x * 0.2f, io.displaySize.y * 0.2f), Vec2(Float.MAX_VALUE))
setNextWindowPos(Vec2(io.displaySize.x * 0.5f, io.displaySize.y * 0.5f), Cond.Always, Vec2(0.5f))
pushStyleVar(StyleVar.WindowPadding, style.windowPadding * 2f)
val flags =
Wf.NoTitleBar or Wf.NoFocusOnAppearing or Wf.NoResize or Wf.NoMove or Wf.NoInputs or Wf.AlwaysAutoResize or Wf.NoSavedSettings
begin("###NavWindowingList", null, flags)
for (n in g.windowsFocusOrder.lastIndex downTo 0) {
val window = g.windowsFocusOrder[n]
if (!window.isNavFocusable)
continue
var label = window.name
val labelEnd = findRenderedTextEnd(label)
if (labelEnd == -1)
label = window.fallbackWindowName
selectable(label, target == window)
}
end()
popStyleVar()
}
/** Apply result from previous frame navigation directional move request */
fun navUpdateMoveResult() {
if (g.navMoveResultLocal.id == 0 && g.navMoveResultOther.id == 0) {
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.navId != 0) {
g.navDisableHighlight = false
g.navDisableMouseHover = true
}
return
}
// Select which result to use
var result = if (g.navMoveResultLocal.id != 0) g.navMoveResultLocal else g.navMoveResultOther
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.navMoveRequestFlags has NavMoveFlag.AlsoScoreVisibleSet)
if (g.navMoveResultLocalVisibleSet.id != 0 && g.navMoveResultLocalVisibleSet.id != g.navId)
result = g.navMoveResultLocalVisibleSet
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != g.navMoveResultOther && g.navMoveResultOther.id != 0 && g.navMoveResultOther.window!!.parentWindow === g.navWindow)
if (g.navMoveResultOther.distBox < result.distBox || (g.navMoveResultOther.distBox == result.distBox && g.navMoveResultOther.distCenter < result.distCenter))
result = g.navMoveResultOther
val window = result.window!!
assert(g.navWindow != null)
// Scroll to keep newly navigated item fully into view.
if (g.navLayer == NavLayer.Main) {
val deltaScroll = Vec2()
if (g.navMoveRequestFlags has NavMoveFlag.ScrollToEdge) {
val scrollTarget = if (g.navMoveDir == Dir.Up) window.scrollMax.y else 0f
deltaScroll.y = window.scroll.y - scrollTarget
window setScrollY scrollTarget
} else {
val rectAbs = Rect(result.rectRel.min + window.pos, result.rectRel.max + window.pos)
deltaScroll put window.scrollToBringRectIntoView(rectAbs)
}
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result.rectRel translateX -deltaScroll.x
result.rectRel translateY -deltaScroll.y
}
clearActiveID()
g.navWindow = window
if (g.navId != result.id) {
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.navJustMovedToId = result.id
g.navJustMovedToFocusScopeId = result.focusScopeId
g.navJustMovedToKeyMods = g.navMoveRequestKeyMods
}
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer ${g.navLayer} Window \"${window.name}\"", result.id) // [JVM] window *is* g.navWindow!!
setNavIDWithRectRel(result.id, g.navLayer, result.focusScopeId, result.rectRel)
}
fun navUpdateInitResult() {
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
val nav = g.navWindow ?: return
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer ${g.navLayer} Window \"${nav.name}\"", g.navInitResultId)
if (g.navInitRequestFromMove)
setNavIDWithRectRel(g.navInitResultId, g.navLayer, 0, g.navInitResultRectRel)
else
setNavID(g.navInitResultId, g.navLayer, 0)
nav.navRectRel[g.navLayer] = g.navInitResultRectRel
}
/** Handle PageUp/PageDown/Home/End keys */
fun navUpdatePageUpPageDown(): Float {
val window = g.navWindow
if (g.navMoveDir != Dir.None || window == null)
return 0f
if (window.flags has Wf.NoNavInputs || g.navWindowingTarget != null || g.navLayer != NavLayer.Main)
return 0f
val pageUpHeld = Key.PageUp.isDown && !isActiveIdUsingKey(Key.PageUp)
val pageDownHeld = Key.PageDown.isDown && !isActiveIdUsingKey(Key.PageDown)
val homePressed = Key.Home.isPressed && !isActiveIdUsingKey(Key.Home)
val endPressed = Key.End.isPressed && !isActiveIdUsingKey(Key.End)
if (pageUpHeld != pageDownHeld || homePressed != endPressed) { // If either (not both) are pressed
if (window.dc.navLayerActiveMask == 0x00 && window.dc.navHasScroll) {
// Fallback manual-scroll when window has no navigable item
when {
Key.PageUp.isPressed(true) -> window.setScrollY(window.scroll.y - window.innerRect.height)
Key.PageDown.isPressed(true) -> window.setScrollY(window.scroll.y + window.innerRect.height)
homePressed -> window setScrollY 0f
endPressed -> window setScrollY window.scrollMax.y
}
} else {
val navRectRel = window.navRectRel[g.navLayer]
val pageOffsetY = 0f max (window.innerRect.height - window.calcFontSize() * 1f + navRectRel.height)
var navScoringRectOffsetY = 0f
if (Key.PageUp.isPressed(true)) {
navScoringRectOffsetY = -pageOffsetY
g.navMoveDir =
Dir.Down // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.navMoveClipDir = Dir.Up
g.navMoveRequestFlags = NavMoveFlag.AllowCurrentNavId or NavMoveFlag.AlsoScoreVisibleSet
} else if (Key.PageDown.isPressed(true)) {
navScoringRectOffsetY = +pageOffsetY
g.navMoveDir =
Dir.Up // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
g.navMoveClipDir = Dir.Down
g.navMoveRequestFlags = NavMoveFlag.AllowCurrentNavId or NavMoveFlag.AlsoScoreVisibleSet
} else if (homePressed) {
// FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
// Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
// Preserve current horizontal position if we have any.
navRectRel.min.y = -window.scroll.y
navRectRel.max.y = -window.scroll.y
if (navRectRel.isInverted) {
navRectRel.min.x = 0f
navRectRel.max.x = 0f
}
g.navMoveDir = Dir.Down
g.navMoveRequestFlags = NavMoveFlag.AllowCurrentNavId or NavMoveFlag.ScrollToEdge
} else if (endPressed) {
navRectRel.min.y = window.scrollMax.y + window.sizeFull.y - window.scroll.y
navRectRel.max.y = window.scrollMax.y + window.sizeFull.y - window.scroll.y
if (navRectRel.isInverted) {
navRectRel.min.x = 0f
navRectRel.max.x = 0f
}
g.navMoveDir = Dir.Up
g.navMoveRequestFlags = NavMoveFlag.AllowCurrentNavId or NavMoveFlag.ScrollToEdge
}
return navScoringRectOffsetY
}
}
return 0f
}
fun navUpdateAnyRequestFlag() {
g.navAnyRequest = g.navMoveRequest || g.navInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.navWindow != null)
if (g.navAnyRequest)
assert(g.navWindow != null)
}
fun navEndFrame() {
// Show CTRL+TAB list window
if (g.navWindowingTarget != null)
navUpdateWindowingOverlay()
// Perform wrap-around in menus
val window = g.navWrapRequestWindow
val moveFlags: NavMoveFlags = g.navWrapRequestFlags
if (window != null && g.navWindow === window && navMoveRequestButNoResultYet() &&
g.navMoveRequestForward == NavForward.None && g.navLayer == NavLayer.Main
) {
assert(moveFlags != 0) // No points calling this with no wrapping
val bbRel = Rect(window.navRectRel[0])
var clipDir = g.navMoveDir
if (g.navMoveDir == Dir.Left && moveFlags has (NavMoveFlag.WrapX or NavMoveFlag.LoopX)) {
bbRel.max.x = max(window.sizeFull.x, window.contentSize.x + window.windowPadding.x * 2f) - window.scroll.x
bbRel.min.x = bbRel.max.x
if (moveFlags has NavMoveFlag.WrapX) {
bbRel.translateY(-bbRel.height)
clipDir = Dir.Up
}
navMoveRequestForward(g.navMoveDir, clipDir, bbRel, moveFlags)
}
if (g.navMoveDir == Dir.Right && moveFlags has (NavMoveFlag.WrapX or NavMoveFlag.LoopX)) {
bbRel.max.x = -window.scroll.x
bbRel.min.x = bbRel.max.x
if (moveFlags has NavMoveFlag.WrapX) {
bbRel.translateY(+bbRel.height)
clipDir = Dir.Down
}
navMoveRequestForward(g.navMoveDir, clipDir, bbRel, moveFlags)
}
if (g.navMoveDir == Dir.Up && moveFlags has (NavMoveFlag.WrapY or NavMoveFlag.LoopY)) {
bbRel.max.y = max(window.sizeFull.y, window.contentSize.y + window.windowPadding.y * 2f) - window.scroll.y
bbRel.min.y = bbRel.max.y
if (moveFlags has NavMoveFlag.WrapY) {
bbRel.translateX(-bbRel.width)
clipDir = Dir.Left
}
navMoveRequestForward(g.navMoveDir, clipDir, bbRel, moveFlags)
}
if (g.navMoveDir == Dir.Down && moveFlags has (NavMoveFlag.WrapY or NavMoveFlag.LoopY)) {
bbRel.max.y = -window.scroll.y
bbRel.min.y = bbRel.max.y
if (moveFlags has NavMoveFlag.WrapY) {
bbRel.translateX(+bbRel.width)
clipDir = Dir.Right
}
navMoveRequestForward(g.navMoveDir, clipDir, bbRel, moveFlags)
}
}
}
/** Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057 */
fun navScoreItem(result: NavMoveResult, cand: Rect): Boolean {
val window = g.currentWindow!!
if (g.navLayer != window.dc.navLayerCurrent) return false
// Current modified source rect (NB: we've applied max.x = min.x in navUpdate() to inhibit the effect of having varied item width)
val curr = Rect(g.navScoringRect)
g.navScoringCount++
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window.parentWindow === g.navWindow) {
assert((window.flags or g.navWindow!!.flags) has Wf._NavFlattened)
if (!cand.overlaps(window.clipRect))
return false
cand clipWithFull window.clipRect // This allows the scored item to not overlap other candidates in the parent window
}
/* We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis
(clipping on our movement axis would give us equal scores for all clipped items)
For example, this ensure that items in one column are not reached when moving vertically from items in another column. */
navClampRectToVisibleAreaForMoveDir(g.navMoveDir, cand, window.clipRect)
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
var dbX = navScoreItemDistInterval(cand.min.x, cand.max.x, curr.min.x, curr.max.x)
// Scale down on Y to keep using box-distance for vertically touching items
val dbY = navScoreItemDistInterval(
lerp(cand.min.y, cand.max.y, 0.2f), lerp(cand.min.y, cand.max.y, 0.8f),
lerp(curr.min.y, curr.max.y, 0.2f), lerp(curr.min.y, curr.max.y, 0.8f)
)
if (dbY != 0f && dbX != 0f)
dbX = dbX / 1000f + if (dbX > 0f) 1f else -1f
val distBox = abs(dbX) + abs(dbY)
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
val dcX = (cand.min.x + cand.max.x) - (curr.min.x + curr.max.x)
val dcY = (cand.min.y + cand.max.y) - (curr.min.y + curr.max.y)
val distCenter = abs(dcX) + abs(dcY) // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
val quadrant: Dir
var dax = 0f
var day = 0f
var distAxial = 0f
if (dbX != 0f || dbY != 0f) {
// For non-overlapping boxes, use distance between boxes
dax = dbX
day = dbY
distAxial = distBox
quadrant = getDirQuadrantFromDelta(dbX, dbY)
} else if (dcX != 0f || dcY != 0f) {
// For overlapping boxes with different centers, use distance between centers
dax = dcX
day = dcY
distAxial = distCenter
quadrant = getDirQuadrantFromDelta(dcX, dcY)
}
/* Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that lastItemId here is
really the _previous_ item order, but it doesn't matter) */
else
quadrant = if (window.dc.lastItemId < g.navId) Dir.Left else Dir.Right
if (IMGUI_DEBUG_NAV_SCORING)
if (isMouseHoveringRect(cand)) {
val buf =
"dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav WENS${g.navMoveDir}, quadrant WENS$quadrant"
.format(style.locale, dbX, dbY, distBox, dcX, dcY, distCenter, dax, day, distAxial).toByteArray()
getForegroundDrawList(window).apply {
addRect(curr.min, curr.max, COL32(255, 200, 0, 100))
addRect(cand.min, cand.max, COL32(255, 255, 0, 200))
addRectFilled(cand.max - Vec2(4), cand.max + calcTextSize(buf, 0) + Vec2(4), COL32(40, 0, 0, 150))
addText(io.fontDefault, 13f, cand.max, 0.inv(), buf)
}
} else if (io.keyCtrl) { // Hold to preview score in matching quadrant. Press C to rotate.
if (Key.C.isPressed) {
g.navMoveDirLast = Dir.of((g.navMoveDirLast.i + 1) and 3)
io.keysDownDuration[io.keyMap[Key.C]] = 0.01f
}
if (quadrant == g.navMoveDir) {
val buf = "%.0f/%.0f".format(style.locale, distBox, distCenter).toByteArray()
getForegroundDrawList(window).apply {
addRectFilled(cand.min, cand.max, COL32(255, 0, 0, 200))
addText(io.fontDefault, 13f, cand.min, COL32(255), buf)
}
}
}
// Is it in the quadrant we're interesting in moving to?
var newBest = false
if (quadrant == g.navMoveDir) {
// Does it beat the current best candidate?
if (distBox < result.distBox) {
result.distBox = distBox
result.distCenter = distCenter
return true
}
if (distBox == result.distBox) {
// Try using distance between center points to break ties
if (distCenter < result.distCenter) {
result.distCenter = distCenter
newBest = true
} else if (distCenter == result.distCenter) {
/* Still tied! we need to be extra-careful to make sure everything gets linked properly.
We consistently break ties by symbolically moving "later" items (with higher index) to the
right/downwards by an infinitesimal amount since we the current "best" button already
(so it must have a lower index), this is fairly easy.
This rule ensures that all buttons with dx == dy == 0 will end up being linked in order
of appearance along the x axis. */
val db = if (g.navMoveDir == Dir.Up || g.navMoveDir == Dir.Down) dbY else dbX
if (db < 0f) // moving bj to the right/down decreases distance
newBest = true
}
}
}
/* Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction,
add a tentative link. This will only be kept if no "real" matches are found, so it only augments the graph
produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor.
You get good graphs without this too.
2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere.
Menus in particular need to catch failure. For general navigation it feels awkward.
Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis.
Perhaps consider offering this as an option? */
if (result.distBox == Float.MAX_VALUE && distAxial < result.distAxial) // Check axial match
if (g.navLayer == NavLayer.Menu && g.navWindow!!.flags hasnt Wf._ChildMenu)
if ((g.navMoveDir == Dir.Left && dax < 0f) || (g.navMoveDir == Dir.Right && dax > 0f) ||
(g.navMoveDir == Dir.Up && day < 0f) || (g.navMoveDir == Dir.Down && day > 0f)
) {
result.distAxial = distAxial
newBest = true
}
return newBest
}
fun navApplyItemToResult(result: NavMoveResult, window: Window, id: ID, navBbRel: Rect) {
result.window = window
result.id = id
result.focusScopeId = window.dc.navFocusScopeIdCurrent
result.rectRel put navBbRel
}
/** We get there when either navId == id, or when g.navAnyRequest is set (which is updated by navUpdateAnyRequestFlag above) */
fun navProcessItem(window: Window, navBb: Rect, id: ID) {
//if (!g.io.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
val itemFlags = window.dc.itemFlags
val navBbRel = Rect(navBb.min - window.pos, navBb.max - window.pos)
// Process Init Request
if (g.navInitRequest && g.navLayer == window.dc.navLayerCurrent) {
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (itemFlags hasnt If.NoNavDefaultFocus || g.navInitResultId == 0) {
g.navInitResultId = id
g.navInitResultRectRel = navBbRel
}
if (itemFlags hasnt If.NoNavDefaultFocus) {
g.navInitRequest = false // Found a match, clear request
navUpdateAnyRequestFlag()
}
}
/* Process Move Request (scoring for navigation)
FIXME-NAV: Consider policy for double scoring
(scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) */
if ((g.navId != id || g.navMoveRequestFlags has NavMoveFlag.AllowCurrentNavId) && itemFlags hasnt (If.Disabled or If.NoNav)) {
val result = if(window === g.navWindow) g.navMoveResultLocal else g.navMoveResultOther
val newBest = when {
IMGUI_DEBUG_NAV_SCORING -> { // [DEBUG] Score all items in NavWindow at all times
if (!g.navMoveRequest) g.navMoveDir = g.navMoveDirLast
navScoreItem(result, navBb) && g.navMoveRequest
}
else -> g.navMoveRequest && navScoreItem(result, navBb)
}
if (newBest)
navApplyItemToResult(result, window, id, navBbRel)
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
val VISIBLE_RATIO = 0.7f
if (g.navMoveRequestFlags has NavMoveFlag.AlsoScoreVisibleSet && window.clipRect overlaps navBb)
if (glm.clamp(navBb.max.y, window.clipRect.min.y, window.clipRect.max.y) - glm.clamp(navBb.min.y, window.clipRect.min.y, window.clipRect.max.y) >= (navBb.max.y - navBb.min.y) * VISIBLE_RATIO)
if (navScoreItem(g.navMoveResultLocalVisibleSet, navBb))
navApplyItemToResult(g.navMoveResultLocalVisibleSet, window, id, navBbRel)
}
// Update window-relative bounding box of navigated item
if (g.navId == id) {
g.navWindow =
window // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.navLayer = window.dc.navLayerCurrent
g.navFocusScopeId = window.dc.navFocusScopeIdCurrent
g.navIdIsAlive = true
g.navIdTabCounter = window.dc.focusCounterTabStop
window.navRectRel[window.dc.navLayerCurrent] =
navBbRel // Store item bounding box (relative to window position)
}
}
fun navCalcPreferredRefPos(): Vec2 {
if (g.navDisableHighlight || !g.navDisableMouseHover || g.navWindow == null) {
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (isMousePosValid(io.mousePos))
return Vec2(io.mousePos)
return Vec2(g.lastValidMousePos)
} else {
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
val rectRel = g.navWindow!!.navRectRel[g.navLayer]
val pos = g.navWindow!!.pos + Vec2(
rectRel.min.x + min(style.framePadding.x * 4, rectRel.width),
rectRel.max.y - min(style.framePadding.y, rectRel.height)
)
val visibleRect = viewportRect
return glm.floor(
glm.clamp(
pos,
visibleRect.min,
visibleRect.max
)
) // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
}
}
/** FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
* This way we could find the last focused window among our children. It would be much less confusing this way? */
fun navSaveLastChildNavWindowIntoParent(navWindow: Window?) {
tailrec fun Window.getParent(): Window {
val parent = parentWindow
return when {
parent != null && flags has Wf._ChildWindow && flags hasnt (Wf._Popup or Wf._ChildMenu) -> parent.getParent()
else -> this
}
}
navWindow?.getParent()?.let { if (it !== navWindow) it.navLastChildNavWindow = navWindow }
}
/** Restore the last focused child.
* Call when we are expected to land on the Main Layer (0) after FocusWindow() */
fun navRestoreLastChildNavWindow(window: Window) = window.navLastChildNavWindow?.takeIf { it.wasActive } ?: window
// FIXME-OPT O(N)
fun findWindowFocusIndex(window: Window): Int {
var i = g.windowsFocusOrder.lastIndex
while (i >= 0) {
if (g.windowsFocusOrder[i] == window)
return i
i--
}
return -1
}
// static spare functions
fun navRestoreLayer(layer: NavLayer) {
g.navLayer = layer
if (layer == NavLayer.Main)
g.navWindow = navRestoreLastChildNavWindow(g.navWindow!!)
val window = g.navWindow!!
if (layer == NavLayer.Main && window.navLastIds[0] != 0)
setNavIDWithRectRel(window.navLastIds[0], layer, 0, window.navRectRel[0])
else
navInitWindow(window, true)
}
fun navScoreItemDistInterval(a0: Float, a1: Float, b0: Float, b1: Float) = when {
a1 < b0 -> a1 - b0
b1 < a0 -> a0 - b1
else -> 0f
}
fun navClampRectToVisibleAreaForMoveDir(moveDir: Dir, r: Rect, clipRect: Rect) = when (moveDir) {
Dir.Left, Dir.Right -> {
r.min.y = glm.clamp(r.min.y, clipRect.min.y, clipRect.max.y)
r.max.y = glm.clamp(r.max.y, clipRect.min.y, clipRect.max.y)
}
else -> {
r.min.x = glm.clamp(r.min.x, clipRect.min.x, clipRect.max.x)
r.max.x = glm.clamp(r.max.x, clipRect.min.x, clipRect.max.x)
}
} | mit | 52ba5fef6a30642725c387999542a68c | 47.496094 | 258 | 0.642321 | 3.871443 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/search/NestedSearch.kt | 1 | 2604 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.search
import ca.uhn.fhir.rest.gclient.IParam
import ca.uhn.fhir.rest.gclient.ReferenceClientParam
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
/** Lets users perform a nested search using [Search.has] api. */
@PublishedApi internal data class NestedSearch(val param: ReferenceClientParam, val search: Search)
/** Keeps the parent context for a nested query loop. */
internal data class NestedContext(val parentType: ResourceType, val param: IParam)
/**
* Provides limited support for the reverse chaining on [Search]
* [https://www.hl7.org/fhir/search.html#has]. For example: search all Patient that have Condition -
* Diabetes. This search uses the subject field in the Condition resource. Code snippet:
* ```
* FhirEngine.search<Patient> {
* has<Condition>(Condition.SUBJECT) {
* filter(Condition.CODE, Coding("http://snomed.info/sct", "44054006", "Diabetes"))
* }
* }
* ```
*/
inline fun <reified R : Resource> Search.has(
referenceParam: ReferenceClientParam,
init: Search.() -> Unit
) {
nestedSearches.add(
NestedSearch(referenceParam, Search(type = R::class.java.newInstance().resourceType)).apply {
search.init()
}
)
}
/**
* Generates the complete nested query going to several depths depending on the [Search] dsl
* specified by the user .
*/
internal fun List<NestedSearch>.nestedQuery(
type: ResourceType,
operation: Operation
): SearchQuery? {
return if (isEmpty()) {
null
} else {
map { it.nestedQuery(type) }.let {
SearchQuery(
query =
it.joinToString(
prefix = "AND a.resourceUuid IN ",
separator = " ${operation.logicalOperator} a.resourceUuid IN"
) { "(\n${it.query}\n) " },
args = it.flatMap { it.args }
)
}
}
}
private fun NestedSearch.nestedQuery(type: ResourceType): SearchQuery {
return search.getQuery(nestedContext = NestedContext(type, param))
}
| apache-2.0 | 56328122e4110e991033a0beb6125315 | 31.962025 | 100 | 0.693932 | 3.840708 | false | false | false | false |
C6H2Cl2/YukariLib | src/main/java/c6h2cl2/YukariLib/Util/BlockPosEx.kt | 1 | 2958 | package c6h2cl2.YukariLib.Util
import net.minecraft.block.Block
import net.minecraft.block.state.IBlockState
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.math.BlockPos.MutableBlockPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
/**
* @author C6H2Cl2
*/
class BlockPosEx(x: Int, y: Int, z: Int) : MutableBlockPos(x, y, z) {
companion object{
@JvmStatic
val Empty = BlockPosEx(0,0,0)
@JvmStatic
val Max_Pos = BlockPosEx(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE)
@JvmStatic
val Min_Pos = BlockPosEx(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
}
//Utils
fun getTileEntityFromPos(world: IBlockAccess) = world.getTileEntity(this)
fun getBlockFromPos(world: World): Block = world.getBlockState(this).block
fun getBlockState(world: World): IBlockState = world.getBlockState(this)
fun writeToNBT(tagCompound: NBTTagCompound): NBTTagCompound = writeToNBT(tagCompound, "BlockPos")
fun writeToNBT(tagCompound: NBTTagCompound, name: String): NBTTagCompound {
val tag: NBTTagCompound = NBTTagCompound()
tag.setInteger("x", x)
tag.setInteger("y", y)
tag.setInteger("z", z)
tagCompound.setTag(name, tag)
return tagCompound
}
fun readFromNBT(tagCompound: NBTTagCompound): BlockPosEx = readFromNBT(tagCompound, "BlockPos")
fun readFromNBT(tagCompound: NBTTagCompound, name: String): BlockPosEx {
val tag = tagCompound.getCompoundTag(name)
return BlockPosEx(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"))
}
fun searchBlock(pos: BlockPosEx, block: Block, world: World): List<BlockPosEx> {
val targets = arrayListOf<BlockPosEx>()
return rangeTo(pos)
.filter {
val b = it.getBlockFromPos(world)
b == block || b === block
}
}
//Operators
operator fun plus(pos: BlockPosEx) = BlockPosEx(x + pos.x, y + pos.y, z + pos.z)
operator fun plusAssign(pos: BlockPosEx) {
add(pos.x, pos.y, pos.z)
}
operator fun minus(pos: BlockPosEx) = BlockPosEx(x - pos.x, y - pos.y, z - pos.z)
operator fun minusAssign(pos: BlockPosEx) {
add(-pos.x, -pos.y, -pos.z)
}
operator fun times(value: Int) = BlockPosEx(x * value, y * value, z * value)
operator fun rangeTo(toPos: BlockPosEx): List<BlockPosEx> {
val list = ArrayList<BlockPosEx>().toMutableList()
for (i in minOf(x, toPos.x)..maxOf(x, toPos.x)) {
for (j in minOf(y, toPos.y)..maxOf(y, toPos.y)) {
(minOf(z, toPos.z)..maxOf(z, toPos.z)).mapTo(list) { BlockPosEx(i, j, it) }
}
}
return list.toList()
}
operator fun get(type: Char): Int {
return when (type) {
'x' -> x
'y' -> y
'z' -> z
else -> 0
}
}
} | mpl-2.0 | fc2c0e305b16b20b23815507c2055820 | 31.516484 | 101 | 0.616633 | 3.730139 | false | false | false | false |
Apolline-Lille/apolline-android | app/src/main/java/science/apolline/utils/HourAxisValueFormatter.kt | 1 | 1255 | package science.apolline.utils
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class HourAxisValueFormatter(private val referenceTimestamp: Long // minimum timestamp in your data set
) : IAxisValueFormatter {
private val mDataFormat: DateFormat
private val mDate: Date
init {
this.mDataFormat = SimpleDateFormat("HH:mm", Locale.ENGLISH)
this.mDate = Date()
}
/**
* Called when a value from an axis is to be formatted
* before being drawn. For performance reasons, avoid excessive calculations
* and memory allocations inside this method.
*/
override fun getFormattedValue(value: Float, axis: AxisBase): String {
val convertedTimestamp = value.toLong()
val originalTimestamp = referenceTimestamp + convertedTimestamp
return getHour(originalTimestamp)
}
private fun getHour(timestamp: Long): String {
try {
mDate.time = timestamp * 1000
return mDataFormat.format(mDate)
} catch (ex: Exception) {
return "xx"
}
}
} | gpl-3.0 | fca0cf96aa2b1a2b2ce3061d06553a35 | 30.4 | 103 | 0.698008 | 4.648148 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/config/AudioPlayerManagerConfiguration.kt | 1 | 13693 | /*
* MIT License
*
* Copyright (c) 2017-2018 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fredboat.config
import com.sedmelluq.discord.lavaplayer.player.AudioConfiguration
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.http.HttpAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.local.LocalAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager
import com.sedmelluq.lava.extensions.youtuberotator.YoutubeIpRotator
import com.sedmelluq.lava.extensions.youtuberotator.planner.AbstractRoutePlanner
import com.sedmelluq.lava.extensions.youtuberotator.planner.BalancingIpRoutePlanner
import com.sedmelluq.lava.extensions.youtuberotator.planner.NanoIpRoutePlanner
import com.sedmelluq.lava.extensions.youtuberotator.planner.RotatingIpRoutePlanner
import com.sedmelluq.lava.extensions.youtuberotator.planner.RotatingNanoIpRoutePlanner
import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.Ipv4Block
import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.Ipv6Block
import fredboat.audio.source.PlaylistImportSourceManager
import fredboat.audio.source.SpotifyPlaylistSourceManager
import fredboat.config.property.AppConfig
import fredboat.config.property.AudioSourcesConfig
import fredboat.util.rest.SpotifyAPIWrapper
import fredboat.util.rest.TrackSearcher
import org.apache.http.client.config.CookieSpecs
import org.apache.http.client.config.RequestConfig
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import java.net.InetAddress
import java.util.*
import java.util.function.Predicate
/**
* Created by napster on 25.02.18.
*
*
* Defines all the AudioPlayerManagers used throughout the application.
*
*
* Two special quirks to keep in mind:
* - if an Http(Audio)SourceManager is used, it needs to be added as the last source manager, because it eats each
* request (either returns with success or throws a failure)
* - the paste service AudioPlayerManager should not contain the paste playlist importer to avoid recursion / users
* abusing fredboat into paste file chains
*
*
* We manage the lifecycles of these Beans ourselves. See [fredboat.event.MusicPersistenceHandler]
*/
@Configuration
class AudioPlayerManagerConfiguration {
private val log: Logger = LoggerFactory.getLogger(AudioPlayerManagerConfiguration::class.java)
/**
* @return all AudioPlayerManagers
*/
@Bean
fun allPlayerManagers(@Qualifier("loadAudioPlayerManager") load: AudioPlayerManager,
@Qualifier("searchAudioPlayerManager") search: AudioPlayerManager,
@Qualifier("pasteAudioPlayerManager") paste: AudioPlayerManager): Set<AudioPlayerManager> {
return setOf(load, search, paste)
}
/**
* @return the AudioPlayerManager to be used for loading the tracks
*/
@Bean(destroyMethod = "")
fun loadAudioPlayerManager(@Qualifier("preconfiguredAudioPlayerManager") playerManager: AudioPlayerManager,
audioSourceManagers: ArrayList<AudioSourceManager>,
playlistImportSourceManager: PlaylistImportSourceManager): AudioPlayerManager {
playerManager.registerSourceManager(playlistImportSourceManager)
for (audioSourceManager in audioSourceManagers) {
playerManager.registerSourceManager(audioSourceManager)
}
return playerManager
}
/**
* @return the AudioPlayerManager to be used for searching
*/
@Bean(destroyMethod = "")
fun searchAudioPlayerManager(@Qualifier("preconfiguredAudioPlayerManager") playerManager: AudioPlayerManager,
youtubeAudioSourceManager: YoutubeAudioSourceManager,
soundCloudAudioSourceManager: SoundCloudAudioSourceManager): AudioPlayerManager {
playerManager.registerSourceManager(youtubeAudioSourceManager)
playerManager.registerSourceManager(soundCloudAudioSourceManager)
return playerManager
}
/**
* @return audioPlayerManager to load from paste lists
*/
@Bean(destroyMethod = "")
fun pasteAudioPlayerManager(@Qualifier("preconfiguredAudioPlayerManager") playerManager: AudioPlayerManager,
audioSourceManagers: ArrayList<AudioSourceManager>): AudioPlayerManager {
for (audioSourceManager in audioSourceManagers) {
playerManager.registerSourceManager(audioSourceManager)
}
return playerManager
}
// it is important that the list is ordered with the httpSourceManager being last
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("DuplicatedCode")
fun getConfiguredAudioSourceManagers(audioSourcesConfig: AudioSourcesConfig,
youtubeAudioSourceManager: YoutubeAudioSourceManager,
soundCloudAudioSourceManager: SoundCloudAudioSourceManager,
bandcampAudioSourceManager: BandcampAudioSourceManager,
twitchStreamAudioSourceManager: TwitchStreamAudioSourceManager,
vimeoAudioSourceManager: VimeoAudioSourceManager,
beamAudioSourceManager: BeamAudioSourceManager,
spotifyPlaylistSourceManager: SpotifyPlaylistSourceManager,
localAudioSourceManager: LocalAudioSourceManager,
httpAudioSourceManager: HttpAudioSourceManager): ArrayList<AudioSourceManager> {
val audioSourceManagers = ArrayList<AudioSourceManager>()
if (audioSourcesConfig.isYouTubeEnabled) {
audioSourceManagers.add(youtubeAudioSourceManager)
}
if (audioSourcesConfig.isSoundCloudEnabled) {
audioSourceManagers.add(soundCloudAudioSourceManager)
}
if (audioSourcesConfig.isBandCampEnabled) {
audioSourceManagers.add(bandcampAudioSourceManager)
}
if (audioSourcesConfig.isTwitchEnabled) {
audioSourceManagers.add(twitchStreamAudioSourceManager)
}
if (audioSourcesConfig.isVimeoEnabled) {
audioSourceManagers.add(vimeoAudioSourceManager)
}
if (audioSourcesConfig.isMixerEnabled) {
audioSourceManagers.add(beamAudioSourceManager)
}
if (audioSourcesConfig.isSpotifyEnabled) {
audioSourceManagers.add(spotifyPlaylistSourceManager)
}
if (audioSourcesConfig.isLocalEnabled) {
audioSourceManagers.add(localAudioSourceManager)
}
if (audioSourcesConfig.isHttpEnabled) {
//add new source managers above the HttpAudio one, because it will either eat your request or throw an exception
//so you will never reach a source manager below it
audioSourceManagers.add(httpAudioSourceManager)
}
return audioSourceManagers
}
/**
* @return a preconfigured AudioPlayerManager, no AudioSourceManagers set
*/
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun preconfiguredAudioPlayerManager(appConfig: AppConfig): AudioPlayerManager {
val playerManager = DefaultAudioPlayerManager()
//Patrons and development get higher quality
var quality: AudioConfiguration.ResamplingQuality = AudioConfiguration.ResamplingQuality.LOW
if (appConfig.isPatronDistribution || appConfig.isDevDistribution) {
quality = AudioConfiguration.ResamplingQuality.MEDIUM
}
playerManager.configuration.resamplingQuality = quality
playerManager.frameBufferDuration = 1000
playerManager.setItemLoaderThreadPoolSize(500)
return playerManager
}
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun playlistImportSourceManager(@Qualifier("pasteAudioPlayerManager") audioPlayerManager: AudioPlayerManager): PlaylistImportSourceManager {
return PlaylistImportSourceManager(audioPlayerManager)
}
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun youtubeAudioSourceManager(routePlanner: AbstractRoutePlanner?): YoutubeAudioSourceManager {
val youtube = YoutubeAudioSourceManager()
if (routePlanner != null) {
YoutubeIpRotator.setup(youtube, routePlanner)
}
youtube.configureRequests { config ->
RequestConfig.copy(config)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.build()
}
youtube.setPlaylistPageCount(5)
return youtube
}
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun soundCloudAudioSourceManager(): SoundCloudAudioSourceManager = SoundCloudAudioSourceManager.createDefault()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun bandcampAudioSourceManager() = BandcampAudioSourceManager()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun twitchStreamAudioSourceManager() = TwitchStreamAudioSourceManager()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun vimeoAudioSourceManager() = VimeoAudioSourceManager()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun beamAudioSourceManager() = BeamAudioSourceManager()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun spotifyPlaylistSourceManager(trackSearcher: TrackSearcher, spotifyAPIWrapper: SpotifyAPIWrapper) =
SpotifyPlaylistSourceManager(trackSearcher, spotifyAPIWrapper)
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun localAudioSourceManager() = LocalAudioSourceManager()
@Bean(destroyMethod = "")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun httpSourceManager() = HttpAudioSourceManager()
@Bean
fun routePlanner(appConfig: AppConfig): AbstractRoutePlanner? {
val rateLimitConfig = appConfig.ratelimit
if (rateLimitConfig == null) {
log.debug("No rate limit config block found, skipping setup of route planner")
return null
}
if (rateLimitConfig.ipBlocks.isEmpty()) {
log.info("List of ip blocks is empty, skipping setup of route planner")
return null
}
val blacklisted = rateLimitConfig.excludedIps.map { InetAddress.getByName(it) }
val filter = Predicate<InetAddress> {
!blacklisted.contains(it)
}
val ipBlocks = rateLimitConfig.ipBlocks.map {
when {
Ipv4Block.isIpv4CidrBlock(it) -> Ipv4Block(it)
Ipv6Block.isIpv6CidrBlock(it) -> Ipv6Block(it)
else -> throw RuntimeException("Invalid IP Block '$it', make sure to provide a valid CIDR notation")
}
}
return when (rateLimitConfig.strategy.toLowerCase().trim()) {
"rotateonban" -> RotatingIpRoutePlanner(ipBlocks, filter, rateLimitConfig.searchTriggersFail)
"loadbalance" -> BalancingIpRoutePlanner(ipBlocks, filter, rateLimitConfig.searchTriggersFail)
"nanoswitch" -> NanoIpRoutePlanner(ipBlocks, rateLimitConfig.searchTriggersFail)
"rotatingnanoswitch" -> RotatingNanoIpRoutePlanner(ipBlocks, filter, rateLimitConfig.searchTriggersFail)
else -> throw RuntimeException("Unknown route planner strategy!")
}
}
}
| mit | 6349c6348238fcb0f8636ceb53c7533d | 45.260135 | 144 | 0.726941 | 5.054633 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/navigation/AbstractKotlinNavigationMultiModuleTest.kt | 6 | 3234 | // 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.navigation
import com.intellij.codeInsight.navigation.GotoTargetHandler
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.codeInsight.GotoSuperActionHandler
import org.jetbrains.kotlin.idea.multiplatform.setupMppProjectFromDirStructure
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.extractMarkerOffset
import org.jetbrains.kotlin.idea.test.findFileWithCaret
import java.io.File
abstract class AbstractKotlinNavigationMultiModuleTest : AbstractMultiModuleTest() {
protected abstract fun doNavigate(editor: Editor, file: PsiFile): GotoTargetHandler.GotoData
protected fun doTest(testDataDir: String) {
setupMppProjectFromDirStructure(File(testDataDir))
val file = project.findFileWithCaret()
val doc = PsiDocumentManager.getInstance(myProject).getDocument(file)!!
val offset = doc.extractMarkerOffset(project, "<caret>")
val editor = EditorFactory.getInstance().createEditor(doc, myProject)
editor.caretModel.moveToOffset(offset)
try {
val gotoData = doNavigate(editor, file)
NavigationTestUtils.assertGotoDataMatching(editor, gotoData, true)
} finally {
EditorFactory.getInstance().releaseEditor(editor)
}
}
}
abstract class AbstractKotlinGotoImplementationMultiModuleTest : AbstractKotlinNavigationMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("navigation/implementations/multiModule")
override fun doNavigate(editor: Editor, file: PsiFile) = NavigationTestUtils.invokeGotoImplementations(editor, file)!!
}
abstract class AbstractKotlinGotoSuperMultiModuleTest : AbstractKotlinNavigationMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("navigation/gotoSuper/multiModule")
override fun doNavigate(editor: Editor, file: PsiFile): GotoTargetHandler.GotoData {
val (superDeclarations, _) = GotoSuperActionHandler.SuperDeclarationsAndDescriptor.forDeclarationAtCaret(editor, file)
return GotoTargetHandler.GotoData(file.findElementAt(editor.caretModel.offset)!!, superDeclarations.toTypedArray(), emptyList())
}
}
abstract class AbstractKotlinGotoRelatedSymbolMultiModuleTest : AbstractKotlinNavigationMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("navigation/relatedSymbols/multiModule")
override fun doNavigate(editor: Editor, file: PsiFile): GotoTargetHandler.GotoData {
val source = file.findElementAt(editor.caretModel.offset)!!
val relatedItems = NavigationUtil.collectRelatedItems(source, null)
return GotoTargetHandler.GotoData(source, relatedItems.map { it.element }.toTypedArray(), emptyList())
}
}
| apache-2.0 | b3870050d57b1969924f471416b23ff8 | 50.333333 | 158 | 0.787879 | 4.885196 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopup.kt | 4 | 11801 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.TreePopup
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ClientProperty
import com.intellij.ui.JBColor
import com.intellij.ui.TreeActions
import com.intellij.ui.components.panels.HorizontalBox
import com.intellij.ui.popup.NextStepHandler
import com.intellij.ui.popup.WizardPopup
import com.intellij.ui.popup.util.PopupImplUtil
import com.intellij.ui.render.RenderingUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.tree.ui.DefaultTreeUI
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.FontUtil
import com.intellij.util.text.nullize
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.tree.TreeUtil
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.ui.branch.GitBranchesTreeUtil.overrideBuiltInAction
import git4idea.ui.branch.GitBranchesTreeUtil.selectFirstLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectLastLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectNextLeaf
import git4idea.ui.branch.GitBranchesTreeUtil.selectPrevLeaf
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.drop
import java.awt.Component
import java.awt.Cursor
import java.awt.Point
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.MouseMotionAdapter
import java.util.function.Supplier
import javax.swing.*
import javax.swing.tree.TreeCellRenderer
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
class GitBranchesTreePopup(project: Project, step: GitBranchesTreePopupStep)
: WizardPopup(project, null, step),
TreePopup, NextStepHandler {
private lateinit var tree: JTree
private var showingChildPath: TreePath? = null
private var pendingChildPath: TreePath? = null
private val treeStep: GitBranchesTreePopupStep
get() = step as GitBranchesTreePopupStep
private lateinit var searchPatternStateFlow: MutableStateFlow<String?>
init {
setMinimumSize(JBDimension(200, 200))
dimensionServiceKey = GitBranchPopup.DIMENSION_SERVICE_KEY
setSpeedSearchAlwaysShown()
}
override fun createContent(): JComponent {
tree = Tree(treeStep.treeModel).also {
configureTreePresentation(it)
overrideTreeActions(it)
addTreeMouseControlsListeners(it)
Disposer.register(this) {
it.model = null
}
}
searchPatternStateFlow = MutableStateFlow(null)
speedSearch.installSupplyTo(tree, false)
@OptIn(FlowPreview::class)
with(uiScope(this)) {
launch {
searchPatternStateFlow.drop(1).debounce(100).collectLatest { pattern ->
treeStep.setSearchPattern(pattern)
selectPreferred()
}
}
}
return tree
}
private fun configureTreePresentation(tree: JTree) = with(tree) {
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_BACKGROUND, Supplier { JBUI.CurrentTheme.Tree.background(true, true) })
ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_FOREGROUND, Supplier { JBUI.CurrentTheme.Tree.foreground(true, true) })
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
isRootVisible = false
showsRootHandles = true
cellRenderer = Renderer(treeStep)
accessibleContext.accessibleName = GitBundle.message("git.branches.popup.tree.accessible.name")
ClientProperty.put(this, DefaultTreeUI.LARGE_MODEL_ALLOWED, true)
rowHeight = JBUIScale.scale(20)
isLargeModel = true
expandsSelectedPaths = true
}
private fun overrideTreeActions(tree: JTree) = with(tree) {
overrideBuiltInAction("toggle") {
val path = selectionPath
if (path != null && model.getChildCount(path.lastPathComponent) == 0) {
handleSelect(true, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Right.ID) {
val path = selectionPath
if (path != null && model.getChildCount(path.lastPathComponent) == 0) {
handleSelect(false, null)
true
}
else false
}
overrideBuiltInAction(TreeActions.Down.ID) {
if (speedSearch.isHoldingFilter) selectNextLeaf()
else false
}
overrideBuiltInAction(TreeActions.Up.ID) {
if (speedSearch.isHoldingFilter) selectPrevLeaf()
else false
}
overrideBuiltInAction(TreeActions.Home.ID) {
if (speedSearch.isHoldingFilter) selectFirstLeaf()
else false
}
overrideBuiltInAction(TreeActions.End.ID) {
if (speedSearch.isHoldingFilter) selectLastLeaf()
else false
}
}
private fun addTreeMouseControlsListeners(tree: JTree) = with(tree) {
addMouseMotionListener(SelectionMouseMotionListener())
addMouseListener(SelectOnClickListener())
}
override fun getActionMap(): ActionMap = tree.actionMap
override fun getInputMap(): InputMap = tree.inputMap
override fun afterShow() {
selectPreferred()
}
private fun selectPreferred() {
val preferredSelection = treeStep.getPreferredSelection()
if (preferredSelection != null) {
tree.makeVisible(preferredSelection)
tree.selectionPath = preferredSelection
TreeUtil.scrollToVisible(tree, preferredSelection, true)
}
else TreeUtil.promiseSelectFirstLeaf(tree)
}
override fun isResizable(): Boolean = true
private inner class SelectionMouseMotionListener : MouseMotionAdapter() {
private var lastMouseLocation: Point? = null
/**
* this method should be changed only in par with
* [com.intellij.ui.popup.list.ListPopupImpl.MyMouseMotionListener.isMouseMoved]
*/
private fun isMouseMoved(location: Point): Boolean {
if (lastMouseLocation == null) {
lastMouseLocation = location
return false
}
val prev = lastMouseLocation
lastMouseLocation = location
return prev != location
}
override fun mouseMoved(e: MouseEvent) {
if (!isMouseMoved(e.locationOnScreen)) return
val path = getPath(e)
if (path != null) {
tree.selectionPath = path
notifyParentOnChildSelection()
if (treeStep.isSelectable(TreeUtil.getUserObject(path.lastPathComponent))) {
tree.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
if (pendingChildPath == null || pendingChildPath != path) {
pendingChildPath = path
restartTimer()
}
return
}
}
tree.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)
}
}
private inner class SelectOnClickListener : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (e.button != MouseEvent.BUTTON1) return
val path = getPath(e) ?: return
val selected = path.lastPathComponent
if (treeStep.isSelectable(TreeUtil.getUserObject(selected))) {
handleSelect(true, e)
}
}
}
private fun getPath(e: MouseEvent): TreePath? = tree.getClosestPathForLocation(e.point.x, e.point.y)
private fun handleSelect(handleFinalChoices: Boolean, e: MouseEvent?) {
val selectionPath = tree.selectionPath
val pathIsAlreadySelected = showingChildPath != null && showingChildPath == selectionPath
if (pathIsAlreadySelected) return
pendingChildPath = null
val selected = tree.lastSelectedPathComponent
if (selected != null) {
val userObject = TreeUtil.getUserObject(selected)
if (treeStep.isSelectable(userObject)) {
disposeChildren()
val hasNextStep = myStep.hasSubstep(userObject)
if (!hasNextStep && !handleFinalChoices) {
showingChildPath = null
return
}
val queriedStep = PopupImplUtil.prohibitFocusEventsInHandleSelect().use {
myStep.onChosen(userObject, handleFinalChoices)
}
if (queriedStep == PopupStep.FINAL_CHOICE || !hasNextStep) {
setFinalRunnable(myStep.finalRunnable)
setOk(true)
disposeAllParents(e)
}
else {
showingChildPath = selectionPath
handleNextStep(queriedStep, selected)
showingChildPath = null
}
}
}
}
override fun handleNextStep(nextStep: PopupStep<*>?, parentValue: Any) {
val selectionPath = tree.selectionPath ?: return
val pathBounds = tree.getPathBounds(selectionPath) ?: return
val point = Point(pathBounds.x, pathBounds.y)
SwingUtilities.convertPointToScreen(point, tree)
myChild = createPopup(this, nextStep, parentValue)
myChild.show(content, content.locationOnScreen.x + content.width - STEP_X_PADDING, point.y, true)
}
override fun onSpeedSearchPatternChanged() {
with(uiScope(this)) {
launch {
searchPatternStateFlow.emit(speedSearch.enteredPrefix.nullize(true))
}
}
}
override fun getPreferredFocusableComponent(): JComponent = tree
override fun onChildSelectedFor(value: Any) {
val path = value as TreePath
if (tree.selectionPath != path) {
tree.selectionPath = path
}
}
companion object {
@JvmStatic
fun show(project: Project, repository: GitRepository) {
GitBranchesTreePopup(project, GitBranchesTreePopupStep(project, repository)).showCenteredInCurrentWindow(project)
}
private fun uiScope(parent: Disposable) =
CoroutineScope(SupervisorJob() + Dispatchers.Main).also {
Disposer.register(parent) { it.cancel() }
}
private class Renderer(private val step: GitBranchesTreePopupStep) : TreeCellRenderer {
private val mainLabel = JLabel().apply {
border = JBUI.Borders.emptyBottom(1)
}
private val secondaryLabel = JLabel().apply {
font = FontUtil.minusOne(font)
border = JBUI.Borders.empty(0, 10, 1, 0)
horizontalAlignment = SwingConstants.RIGHT
}
private val arrowLabel = JLabel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val textPanel = JBUI.Panels.simplePanel()
.addToLeft(mainLabel)
.addToCenter(secondaryLabel)
.andTransparent()
private val mainPanel = JBUI.Panels.simplePanel()
.addToCenter(textPanel)
.addToRight(arrowLabel)
.andTransparent()
override fun getTreeCellRendererComponent(tree: JTree?,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): Component {
val userObject = TreeUtil.getUserObject(value)
mainLabel.apply {
icon = step.getIcon(userObject)
text = step.getText(userObject)
foreground = JBUI.CurrentTheme.Tree.foreground(selected, true)
}
secondaryLabel.apply {
text = step.getSecondaryText(userObject)
//todo: LAF color
foreground = if(selected) JBUI.CurrentTheme.Tree.foreground(true, true) else JBColor.GRAY
}
arrowLabel.apply {
isVisible = step.hasSubstep(userObject)
icon = if (selected) AllIcons.Icons.Ide.MenuArrowSelected else AllIcons.Icons.Ide.MenuArrow
}
return mainPanel
}
}
}
} | apache-2.0 | 3e49c21ebbccd5c07c3598e65e6c0de5 | 32.433428 | 131 | 0.693501 | 4.692247 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/view/MyNetworkImageView.kt | 1 | 20794 | package jp.juggler.subwaytooter.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.Animatable
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.load.resource.gif.MyGifDrawable
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.util.LogCategory
import jp.juggler.util.clipRange
class MyNetworkImageView : AppCompatImageView {
companion object {
internal val log = LogCategory("MyNetworkImageView")
}
// ロード中などに表示するDrawableのリソースID
private var mDefaultImage: Drawable? = null
// エラー時に表示するDrawableのリソースID
private var mErrorImage: Drawable? = null
// 角丸の半径。元画像の短辺に対する割合を指定するらしい
internal var mCornerRadius = 0f
// 表示したい画像のURL
private var mUrl: String? = null
private var mMayGif: Boolean = false
// 非同期処理のキャンセル
private var mTarget: Target<*>? = null
private val procLoadImage: Runnable = Runnable { loadImageIfNecessary() }
private val procFocusPoint: Runnable = Runnable { updateFocusPoint() }
private var mediaTypeDrawable1: Drawable? = null
private var mediaTypeBottom = 0
private var mediaTypeLeft = 0
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
fun setDefaultImage(defaultImage: Drawable?) {
mDefaultImage = defaultImage
loadImageIfNecessary()
}
fun setErrorImage(errorImage: Drawable?) {
mErrorImage = errorImage
loadImageIfNecessary()
}
fun setImageUrl(
r: Float,
url: String?,
gifUrlArg: String? = null,
) {
mCornerRadius = r
val gifUrl = if (PrefB.bpEnableGifAnimation()) gifUrlArg else null
if (gifUrl?.isNotEmpty() == true) {
mUrl = gifUrl
mMayGif = true
} else {
mUrl = url
mMayGif = false
}
loadImageIfNecessary()
}
private fun getGlide(): RequestManager? {
try {
return Glide.with(context)
} catch (ex: IllegalArgumentException) {
if (ex.message?.contains("destroyed activity") == true) {
// ignore it
} else {
log.e(ex, "Glide.with() failed.")
}
} catch (ex: Throwable) {
log.e(ex, "Glide.with() failed.")
}
return null
}
fun cancelLoading(defaultDrawable: Drawable? = null) {
val d = drawable
if (d is Animatable) {
if (d.isRunning) {
//warning.d("cancelLoading: Animatable.stop()")
d.stop()
}
}
setImageDrawable(defaultDrawable)
val target = mTarget
if (target != null) {
try {
getGlide()?.clear(target)
} catch (ex: Throwable) {
log.e(ex, "Glide.clear() failed.")
}
mTarget = null
}
}
// 必要なら非同期処理を開始する
private fun loadImageIfNecessary() {
try {
val url = mUrl
if (url?.isEmpty() != false) {
// if the URL to be loaded in this view is empty,
// cancel any old requests and clear the currently loaded image.
cancelLoading(mDefaultImage)
return
}
// すでにリクエストが発行済みで、リクエストされたURLが同じなら何もしない
if ((mTarget as? UrlTarget)?.urlLoading == url) return
// if there is a pre-existing request, cancel it if it's fetching a different URL.
cancelLoading(mDefaultImage)
// 非表示状態ならロードを延期する
if (!isShown) return
var wrapWidth = false
var wrapHeight = false
val lp = layoutParams
if (lp != null) {
wrapWidth = lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
wrapHeight = lp.height == ViewGroup.LayoutParams.WRAP_CONTENT
}
// Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
val desiredWidth = if (wrapWidth) Target.SIZE_ORIGINAL else width
val desiredHeight = if (wrapHeight) Target.SIZE_ORIGINAL else height
if (desiredWidth != Target.SIZE_ORIGINAL && desiredWidth <= 0 ||
desiredHeight != Target.SIZE_ORIGINAL && desiredHeight <= 0
) {
// desiredWidth,desiredHeight の指定がおかしいと非同期処理中にSimpleTargetが落ちる
// おそらくレイアウト後に再度呼び出される
return
}
val glideHeaders = LazyHeaders.Builder()
.addHeader("Accept", "image/webp,image/*,*/*;q=0.8")
.build()
val glideUrl = GlideUrl(url, glideHeaders)
mTarget = if (mMayGif) {
getGlide()
?.load(glideUrl)
?.into(MyTargetGif(url))
} else {
getGlide()
?.load(glideUrl)
?.into(MyTarget(url))
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
private fun replaceGifDrawable(resource: GifDrawable): Drawable {
// ディスクキャッシュから読んだ画像は角丸が正しく扱われない
// MyGifDrawable に差し替えて描画させる
try {
return MyGifDrawable(resource, mCornerRadius)
} catch (ex: Throwable) {
log.trace(ex)
}
return resource
}
private fun replaceBitmapDrawable(resource: BitmapDrawable): Drawable {
try {
val bitmap = resource.bitmap
if (bitmap != null) return replaceBitmapDrawable(bitmap)
} catch (ex: Throwable) {
log.trace(ex)
}
return resource
}
private fun replaceBitmapDrawable(bitmap: Bitmap): Drawable {
val d = RoundedBitmapDrawableFactory.create(resources, bitmap)
d.cornerRadius = mCornerRadius
return d
}
private fun onLoadFailed(urlLoading: String) {
try {
// 別の画像を表示するよう指定が変化していたなら何もしない
if (urlLoading != mUrl) return
// エラー表示用の画像リソースが指定されていたら使う
when (val drawable = mErrorImage) {
null -> {
// このタイミングでImageViewのDrawableを変更するとチラつきの元になるので何もしない
}
else -> setImageDrawable(drawable)
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
private interface UrlTarget {
val urlLoading: String
}
// 静止画用のターゲット
private inner class MyTarget(
override val urlLoading: String,
) : ImageViewTarget<Drawable>(this@MyNetworkImageView), UrlTarget {
// errorDrawable The error drawable to optionally show, or null.
override fun onLoadFailed(errorDrawable: Drawable?) {
onLoadFailed(urlLoading)
}
override fun setResource(resource: Drawable?) {
try {
// 別の画像を表示するよう指定が変化していたなら何もしない
if (urlLoading != mUrl) return
if (mCornerRadius > 0f) {
if (resource is BitmapDrawable) {
// BitmapDrawableは角丸処理が可能。
setImageDrawable(replaceBitmapDrawable(resource.bitmap))
return
}
// その他のDrawable
// たとえばInstanceTickerのアイコンにSVGが使われていたらPictureDrawableになる
// log.w("cornerRadius=$mCornerRadius,drawable=$resource,url=$urlLoading")
}
setImageDrawable(resource)
return
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
private inner class MyTargetGif(
override val urlLoading: String,
) : ImageViewTarget<Drawable>(this@MyNetworkImageView), UrlTarget {
private var glideDrawable: Drawable? = null
override fun onLoadFailed(errorDrawable: Drawable?) = onLoadFailed(urlLoading)
override fun onResourceReady(
drawable: Drawable,
transition: Transition<in Drawable>?,
) {
try {
// 別の画像を表示するよう指定が変化していたなら何もしない
if (urlLoading != mUrl) return
afterResourceReady(
transition,
when {
mCornerRadius <= 0f -> {
// 角丸でないならそのまま使う
drawable
}
// GidDrawableを置き換える
drawable is GifDrawable -> replaceGifDrawable(drawable)
// Glide 4.xから、静止画はBitmapDrawableになった
drawable is BitmapDrawable -> replaceBitmapDrawable(drawable)
else -> {
log.d("onResourceReady: drawable class=${drawable.javaClass.simpleName}")
drawable
}
}
)
} catch (ex: Throwable) {
log.trace(ex)
}
}
private fun afterResourceReady(transition: Transition<in Drawable>?, drawable: Drawable) {
super.onResourceReady(drawable, transition)
//if( ! drawable.isAnimated() ){
// //XXX: Try to generalize this to other sizes/shapes.
// // This is a dirty hack that tries to make loading square thumbnails and then square full images less costly
// // by forcing both the smaller thumb and the larger version to have exactly the same intrinsic dimensions.
// // If a drawable is replaced in an ImageView by another drawable with different intrinsic dimensions,
// // the ImageView requests a layout. Scrolling rapidly while replacing thumbs with larger images triggers
// // lots of these calls and causes significant amounts of junk.
// float viewRatio = view.getWidth() / (float) view.getHeight();
// float drawableRatio = drawable.getIntrinsicWidth() / (float) drawable.getIntrinsicHeight();
// if( Math.abs( viewRatio - 1f ) <= SQUARE_RATIO_MARGIN
// && Math.abs( drawableRatio - 1f ) <= SQUARE_RATIO_MARGIN ){
// drawable = new SquaringDrawable( drawable, view.getWidth() );
// }
//}
this.glideDrawable = drawable
if (drawable is GifDrawable) {
drawable.setLoopCount(GifDrawable.LOOP_FOREVER)
drawable.start()
} else if (drawable is MyGifDrawable) {
drawable.setLoopCount(GifDrawable.LOOP_FOREVER)
drawable.start()
}
}
// super.onResourceReady から呼ばれる
override fun setResource(drawable: Drawable?) {
setImageDrawable(drawable)
}
override fun onStart() {
val drawable = glideDrawable
if (drawable is Animatable && !drawable.isRunning) {
log.d("MyTargetGif onStart glide_drawable=$drawable")
drawable.start()
}
}
override fun onStop() {
val drawable = glideDrawable
if (drawable is Animatable && drawable.isRunning) {
log.d("MyTargetGif onStop glide_drawable=$drawable")
drawable.stop()
}
}
override fun onDestroy() {
val drawable = glideDrawable
log.d("MyTargetGif onDestroy glide_drawable=$drawable")
super.onDestroy()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
post(procLoadImage)
post(procFocusPoint)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
post(procLoadImage)
}
override fun onDetachedFromWindow() {
cancelLoading(null)
super.onDetachedFromWindow()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
loadImageIfNecessary()
}
override fun drawableStateChanged() {
super.drawableStateChanged()
invalidate()
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
loadImageIfNecessary()
}
fun setMediaType(drawableId: Int) {
if (drawableId == 0) {
mediaTypeDrawable1 = null
} else {
mediaTypeDrawable1 = ContextCompat.getDrawable(context, drawableId)?.mutate()
// DisplayMetrics dm = getResources().getDisplayMetrics();
mediaTypeBottom = 0
mediaTypeLeft = 0
}
invalidate()
}
override fun onDraw(canvas: Canvas) {
// bitmapがrecycledされた場合に例外をキャッチする
try {
super.onDraw(canvas)
} catch (ex: Throwable) {
log.trace(ex)
}
// media type の描画
val mediaTypeDrawable = this.mediaTypeDrawable1
if (mediaTypeDrawable != null) {
val drawableW = mediaTypeDrawable.intrinsicWidth
val drawableH = mediaTypeDrawable.intrinsicHeight
// int view_w = getWidth();
val viewH = height
mediaTypeDrawable.setBounds(
0,
viewH - drawableH,
drawableW,
viewH
)
mediaTypeDrawable.draw(canvas)
}
}
/////////////////////////////////////////////////////////////////////
// プロフ表示の背景画像のレイアウト崩れの対策
var measureProfileBg = false
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (measureProfileBg) {
// このモードではコンテンツを一切見ずにサイズを決める
val wSize = MeasureSpec.getSize(widthMeasureSpec)
val wMeasured = when (MeasureSpec.getMode(widthMeasureSpec)) {
MeasureSpec.EXACTLY -> wSize
MeasureSpec.AT_MOST -> wSize
MeasureSpec.UNSPECIFIED -> 0
else -> 0
}
val hSize = MeasureSpec.getSize(heightMeasureSpec)
val hMeasured = when (MeasureSpec.getMode(heightMeasureSpec)) {
MeasureSpec.EXACTLY -> hSize
MeasureSpec.AT_MOST -> hSize
MeasureSpec.UNSPECIFIED -> 0
else -> 0
}
setMeasuredDimension(wMeasured, hMeasured)
} else {
// 通常のImageViewは内容を見てサイズを決める
// たとえLayoutParamがw,hともmatchParentでも内容を見てしまう
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
/////////////////////////////////////////////////////////////////////
private var focusX: Float = 0f
private var focusY: Float = 0f
fun setFocusPoint(focusX: Float, focusY: Float) {
// フォーカスポイントは上がプラスで下がマイナス
// https://github.com/jonom/jquery-focuspoint#1-calculate-your-images-focus-point
// このタイミングで正規化してしまう
this.focusX = clipRange(-1f, 1f, focusX)
this.focusY = -clipRange(-1f, 1f, focusY)
}
override fun setImageBitmap(bm: Bitmap?) {
super.setImageBitmap(bm)
updateFocusPoint()
}
override fun setImageDrawable(drawable: Drawable?) {
super.setImageDrawable(drawable)
updateFocusPoint()
}
private fun updateFocusPoint() {
// ビューのサイズが0より大きい
val viewW = width.toFloat()
val viewH = height.toFloat()
if (viewW <= 0f || viewH <= 0f) return
// 画像のサイズが0より大きい
val drawable = this.drawable ?: return
val drawableW = drawable.intrinsicWidth.toFloat()
val drawableH = drawable.intrinsicHeight.toFloat()
if (drawableW <= 0f || drawableH <= 0f) return
when (scaleType) {
ScaleType.CENTER_CROP, ScaleType.MATRIX -> {
val viewAspect = viewW / viewH
val drawableAspect = drawableW / drawableH
if (drawableAspect >= viewAspect) {
// ビューより画像の方が横長
val focusX1 = this.focusX
if (focusX1 == 0f) {
scaleType = ScaleType.CENTER_CROP
} else {
val matrix = Matrix()
val scale = viewH / drawableH
val delta = focusX1 * ((drawableW * scale) - viewW)
log.d("updateFocusPoint x delta=$delta")
matrix.postTranslate(drawableW / -2f, drawableH / -2f)
matrix.postScale(scale, scale)
matrix.postTranslate((viewW - delta) / 2f, viewH / 2f)
scaleType = ScaleType.MATRIX
imageMatrix = matrix
}
} else {
// ビューより画像の方が縦長
val focusY1 = this.focusY
if (focusY1 == 0f) {
scaleType = ScaleType.CENTER_CROP
} else {
val matrix = Matrix()
val scale = viewW / drawableW
val delta = focusY1 * ((drawableH * scale) - viewH)
matrix.postTranslate(drawableW / -2f, drawableH / -2f)
matrix.postScale(scale, scale)
matrix.postTranslate(viewW / 2f, (viewH - delta) / 2f)
scaleType = ScaleType.MATRIX
imageMatrix = matrix
}
}
}
else -> {
// not supported.
}
}
}
fun setScaleTypeForMedia() {
when (scaleType) {
ScaleType.CENTER_CROP, ScaleType.MATRIX -> {
// nothing to do
}
else -> {
scaleType = ScaleType.CENTER_CROP
}
}
}
}
| apache-2.0 | 3489a46ac178046ed487b2f6824347ff | 32.443662 | 126 | 0.536189 | 4.762415 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/view/PinchBitmapView.kt | 1 | 16231 | package jp.juggler.subwaytooter.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.os.SystemClock
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import jp.juggler.util.LogCategory
import jp.juggler.util.runOnMainLooper
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sqrt
class PinchBitmapView(context: Context, attrs: AttributeSet?, defStyle: Int) :
View(context, attrs, defStyle) {
companion object {
internal val log = LogCategory("PinchImageView")
// 数値を範囲内にクリップする
private fun clip(min: Float, max: Float, v: Float): Float {
return if (v < min) min else if (v > max) max else v
}
// ビューの幅と画像の描画サイズを元に描画位置をクリップする
private fun clipTranslate(
viewW: Float, // ビューの幅
bitmapW: Float, // 画像の幅
currentScale: Float, // 画像の拡大率
transX: Float, // タッチ操作による表示位置
): Float {
// 余白(拡大率が小さい場合はプラス、拡大率が大きい場合はマイナス)
val padding = viewW - bitmapW * currentScale
// 余白が>=0なら画像を中心に表示する。 <0なら操作された位置をクリップする。
return if (padding >= 0f) padding / 2f else clip(padding, 0f, transX)
}
}
private var callback: Callback? = null
private var bitmap: Bitmap? = null
private var bitmapW: Float = 0.toFloat()
private var bitmapH: Float = 0.toFloat()
private var bitmapAspect: Float = 0.toFloat()
// 画像を表示する位置と拡大率
private var currentTransX: Float = 0.toFloat()
private var currentTransY: Float = 0.toFloat()
private var currentScale: Float = 0.toFloat()
// 画像表示に使う構造体
private val drawMatrix = Matrix()
internal val paint = Paint()
// タッチ操作中に指を動かした
private var bDrag: Boolean = false
// タッチ操作中に指の数を変えた
private var bPointerCountChanged: Boolean = false
// ページめくりに必要なスワイプ強度
private var swipeVelocity = 0f
private var swipeVelocity2 = 0f
// 指を動かしたと判断する距離
private var dragLength = 0f
private var timeTouchStart = 0L
// フリック操作の検出に使う
private var velocityTracker: VelocityTracker? = null
private var clickTime = 0L
private var clickCount = 0
// 移動後の指の位置
internal val pos = PointerAvg()
// 移動開始時の指の位置
private val posStart = PointerAvg()
// 移動開始時の画像の位置
private var startImageTransX: Float = 0.toFloat()
private var startImageTransY: Float = 0.toFloat()
private var startImageScale: Float = 0.toFloat()
private var scaleMin: Float = 0.toFloat()
private var scaleMax: Float = 0.toFloat()
private var viewW: Float = 0.toFloat()
private var viewH: Float = 0.toFloat()
private var viewAspect: Float = 0.toFloat()
private val trackingMatrix = Matrix()
private val trackingMatrixInv = Matrix()
private val avgOnImage1 = FloatArray(2)
private val avgOnImage2 = FloatArray(2)
constructor(context: Context) : this(context, null) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
init(context)
}
init {
init(context)
}
internal fun init(context: Context) {
// 定数をdpからpxに変換
val density = context.resources.displayMetrics.density
swipeVelocity = 1000f * density
swipeVelocity2 = 250f * density
dragLength = 4f * density // 誤反応しがちなのでやや厳しめ
}
// ページめくり操作のコールバック
interface Callback {
fun onSwipe(deltaX: Int, deltaY: Int)
fun onMove(bitmapW: Float, bitmapH: Float, tx: Float, ty: Float, scale: Float)
}
fun setCallback(callback: Callback?) {
this.callback = callback
}
fun setBitmap(b: Bitmap?) {
bitmap?.recycle()
this.bitmap = b
initializeScale()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val bitmap = this.bitmap
if (bitmap != null && !bitmap.isRecycled) {
drawMatrix.reset()
drawMatrix.postScale(currentScale, currentScale)
drawMatrix.postTranslate(currentTransX, currentTransY)
paint.isFilterBitmap = currentScale < 4f
canvas.drawBitmap(bitmap, drawMatrix, paint)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
viewW = max(1f, w.toFloat())
viewH = max(1f, h.toFloat())
viewAspect = viewW / viewH
initializeScale()
}
override fun performClick(): Boolean {
super.performClick()
initializeScale()
return true
}
private var defaultScale: Float = 1f
// 表示位置の初期化
// 呼ばれるのは、ビットマップを変更した時、ビューのサイズが変わった時、画像をクリックした時
private fun initializeScale() {
val bitmap = this.bitmap
if (bitmap != null && !bitmap.isRecycled && viewW >= 1f) {
bitmapW = max(1f, bitmap.width.toFloat())
bitmapH = max(1f, bitmap.height.toFloat())
bitmapAspect = bitmapW / bitmapH
if (viewAspect > bitmapAspect) {
scaleMin = viewH / bitmapH / 2f
scaleMax = viewW / bitmapW * 8f
} else {
scaleMin = viewW / bitmapW / 2f
scaleMax = viewH / bitmapH * 8f
}
if (scaleMax < scaleMin) scaleMax = scaleMin * 16f
defaultScale = if (viewAspect > bitmapAspect) {
viewH / bitmapH
} else {
viewW / bitmapW
}
val drawW = bitmapW * defaultScale
val drawH = bitmapH * defaultScale
currentScale = defaultScale
currentTransX = (viewW - drawW) / 2f
currentTransY = (viewH - drawH) / 2f
callback?.onMove(bitmapW, bitmapH, currentTransX, currentTransY, currentScale)
} else {
defaultScale = 1f
scaleMin = 1f
scaleMax = 1f
currentScale = defaultScale
currentTransY = 0f
currentTransX = 0f
callback?.onMove(0f, 0f, currentTransX, currentTransY, currentScale)
}
// 画像がnullに変化した時も再描画が必要
invalidate()
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent): Boolean {
val bitmap = this.bitmap
if (bitmap == null || bitmap.isRecycled || viewW < 1f) return false
val action = ev.action
if (action == MotionEvent.ACTION_DOWN) {
timeTouchStart = SystemClock.elapsedRealtime()
velocityTracker?.clear()
velocityTracker = VelocityTracker.obtain()
velocityTracker?.addMovement(ev)
bPointerCountChanged = false
bDrag = bPointerCountChanged
trackStart(ev)
return true
}
velocityTracker?.addMovement(ev)
when (action) {
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP -> {
// タッチ操作中に指の数を変えた
bPointerCountChanged = true
bDrag = bPointerCountChanged
trackStart(ev)
}
MotionEvent.ACTION_MOVE -> trackNext(ev)
MotionEvent.ACTION_UP -> {
trackNext(ev)
checkClickOrPaging()
velocityTracker?.recycle()
velocityTracker = null
}
}
return true
}
private fun checkClickOrPaging() {
if (!bDrag) {
// 指を動かしていないなら
val now = SystemClock.elapsedRealtime()
if (now - timeTouchStart >= 1000L) {
// ロングタップはタップカウントをリセットする
log.d("click count reset by long tap")
clickCount = 0
return
}
val delta = now - clickTime
clickTime = now
if (delta > 334L) {
// 前回のタップからの時刻が長いとタップカウントをリセットする
log.d("click count reset by long interval")
clickCount = 0
}
++clickCount
log.d("click $clickCount $delta")
if (clickCount >= 2) {
// ダブルタップでクリック操作
clickCount = 0
performClick()
}
return
}
clickCount = 0
val velocityTracker = this.velocityTracker
if (!bPointerCountChanged && velocityTracker != null) {
// 指の数を変えていないならページめくり操作かもしれない
// 「画像を動かした」かどうかのチェック
val imageMoved = max(
abs(currentTransX - startImageTransX),
abs(currentTransY - startImageTransY)
)
if (imageMoved >= dragLength) {
log.d("image moved. not flick action. $imageMoved")
return
}
velocityTracker.computeCurrentVelocity(1000)
val vx = velocityTracker.xVelocity
val vy = velocityTracker.yVelocity
val avx = abs(vx)
val avy = abs(vy)
val velocity = sqrt(vx * vx + vy * vy)
val aspect = try {
avx / avy
} catch (ignored: Throwable) {
Float.MAX_VALUE
}
when {
aspect >= 0.9f -> {
// 指を動かした方向が左右だった
val vMin = when {
currentScale * bitmapW <= viewW -> swipeVelocity2
else -> swipeVelocity
}
if (velocity < vMin) {
log.d("velocity $velocity not enough to pagingX")
return
}
log.d("pagingX! m=$imageMoved a=$aspect v=$velocity")
runOnMainLooper { callback?.onSwipe(if (vx >= 0f) -1 else 1, 0) }
}
aspect <= 0.333f -> {
// 指を動かした方向が上下だった
val vMin = when {
currentScale * bitmapH <= viewH -> swipeVelocity2
else -> swipeVelocity
}
if (velocity < vMin) {
log.d("velocity $velocity not enough to pagingY")
return
}
log.d("pagingY! m=$imageMoved a=$aspect v=$velocity")
runOnMainLooper { callback?.onSwipe(0, if (vy >= 0f) -1 else 1) }
}
else -> log.d("flick is not horizontal/vertical. aspect=$aspect")
}
}
}
// マルチタッチの中心位置の計算
internal class PointerAvg {
// タッチ位置の数
var count: Int = 0
// タッチ位置の平均
val avg = FloatArray(2)
// 中心と、中心から最も離れたタッチ位置の間の距離
var maxRadius: Float = 0.toFloat()
fun update(ev: MotionEvent) {
count = ev.pointerCount
if (count <= 1) {
avg[0] = ev.x
avg[1] = ev.y
maxRadius = 0f
} else {
avg[0] = 0f
avg[1] = 0f
for (i in 0 until count) {
avg[0] += ev.getX(i)
avg[1] += ev.getY(i)
}
avg[0] /= count.toFloat()
avg[1] /= count.toFloat()
maxRadius = 0f
for (i in 0 until count) {
val dx = ev.getX(i) - avg[0]
val dy = ev.getY(i) - avg[1]
val radius = dx * dx + dy * dy
if (radius > maxRadius) maxRadius = radius
}
maxRadius = sqrt(maxRadius.toDouble()).toFloat()
if (maxRadius < 1f) maxRadius = 1f
}
}
}
private fun trackStart(ev: MotionEvent) {
// 追跡開始時の指の位置
posStart.update(ev)
// 追跡開始時の画像の位置
startImageTransX = currentTransX
startImageTransY = currentTransY
startImageScale = currentScale
}
// 画面上の指の位置から画像中の指の位置を調べる
private fun getCoordinateOnImage(dst: FloatArray, src: FloatArray) {
trackingMatrix.reset()
trackingMatrix.postScale(currentScale, currentScale)
trackingMatrix.postTranslate(currentTransX, currentTransY)
trackingMatrix.invert(trackingMatrixInv)
trackingMatrixInv.mapPoints(dst, src)
}
private fun trackNext(ev: MotionEvent) {
pos.update(ev)
if (pos.count != posStart.count) {
// タッチ操作中に指の数が変わった
log.d("nextTracking: pointer count changed")
bPointerCountChanged = true
bDrag = bPointerCountChanged
trackStart(ev)
return
}
// ズーム操作
if (pos.count > 1) {
// タッチ位置にある絵柄の座標を調べる
getCoordinateOnImage(avgOnImage1, pos.avg)
// ズーム率を変更する
currentScale = clip(
scaleMin,
scaleMax,
startImageScale * pos.maxRadius / posStart.maxRadius
)
// 再び調べる
getCoordinateOnImage(avgOnImage2, pos.avg)
// ズーム変更の前後で位置がズレた分だけ移動させると、タッチ位置にある絵柄がズレない
startImageTransX += currentScale * (avgOnImage2[0] - avgOnImage1[0])
startImageTransY += currentScale * (avgOnImage2[1] - avgOnImage1[1])
}
// 平行移動
run {
// start時から指を動かした量
val moveX = pos.avg[0] - posStart.avg[0]
val moveY = pos.avg[1] - posStart.avg[1]
// 「指を動かした」と判断したらフラグを立てる
if (abs(moveX) >= dragLength || abs(moveY) >= dragLength) {
bDrag = true
}
// 画像の表示位置を更新
currentTransX =
clipTranslate(viewW, bitmapW, currentScale, startImageTransX + moveX)
currentTransY =
clipTranslate(viewH, bitmapH, currentScale, startImageTransY + moveY)
}
callback?.onMove(bitmapW, bitmapH, currentTransX, currentTransY, currentScale)
invalidate()
}
}
| apache-2.0 | f858ff053d5b5b5796c926fd838e59bc | 27.533066 | 90 | 0.526294 | 4.075498 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/graduate/design/common/GraduationDesignMethodControllerCommon.kt | 1 | 7363 | package top.zbeboy.isy.web.graduate.design.common
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartHttpServletRequest
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.domain.tables.pojos.GraduationDesignRelease
import top.zbeboy.isy.domain.tables.pojos.GraduationDesignTeacher
import top.zbeboy.isy.domain.tables.pojos.Student
import top.zbeboy.isy.service.cache.CacheManageService
import top.zbeboy.isy.service.common.FilesService
import top.zbeboy.isy.service.common.UploadService
import top.zbeboy.isy.service.data.StaffService
import top.zbeboy.isy.service.data.StudentService
import top.zbeboy.isy.service.graduate.design.GraduationDesignReleaseFileService
import top.zbeboy.isy.service.graduate.design.GraduationDesignReleaseService
import top.zbeboy.isy.service.graduate.design.GraduationDesignTeacherService
import top.zbeboy.isy.service.graduate.design.GraduationDesignTutorService
import top.zbeboy.isy.service.platform.UsersService
import top.zbeboy.isy.service.platform.UsersTypeService
import top.zbeboy.isy.service.util.FilesUtils
import top.zbeboy.isy.service.util.RequestUtils
import top.zbeboy.isy.web.bean.file.FileBean
import top.zbeboy.isy.web.bean.graduate.design.release.GraduationDesignReleaseBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.PaginationUtils
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
/**
* Created by zbeboy 2018-01-14 .
**/
@Component
open class GraduationDesignMethodControllerCommon {
private val log = LoggerFactory.getLogger(GraduationDesignMethodControllerCommon::class.java)
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
@Resource
open lateinit var graduationDesignReleaseService: GraduationDesignReleaseService
@Resource
open lateinit var graduationDesignReleaseFileService: GraduationDesignReleaseFileService
@Resource
open lateinit var filesService: FilesService
@Resource
open lateinit var usersService: UsersService
@Resource
open lateinit var usersTypeService: UsersTypeService
@Resource
open lateinit var studentService: StudentService
@Resource
open lateinit var staffService: StaffService
@Resource
open lateinit var graduationDesignTutorService: GraduationDesignTutorService
@Resource
open lateinit var graduationDesignTeacherService: GraduationDesignTeacherService
/**
* 获取毕业设计发布数据 用于通用列表数据
*
* @param paginationUtils 分页工具
* @return 数据
*/
fun graduationDesignListDatas(paginationUtils: PaginationUtils): AjaxUtils<GraduationDesignReleaseBean> {
val ajaxUtils = AjaxUtils.of<GraduationDesignReleaseBean>()
val graduationDesignReleaseBean = GraduationDesignReleaseBean()
graduationDesignReleaseBean.graduationDesignIsDel = 0
val commonData = methodControllerCommon.adminOrNormalData()
graduationDesignReleaseBean.departmentId = if (StringUtils.isEmpty(commonData["departmentId"])) -1 else commonData["departmentId"]
graduationDesignReleaseBean.collegeId = if (StringUtils.isEmpty(commonData["collegeId"])) -1 else commonData["collegeId"]
graduationDesignReleaseBean.scienceId = if (StringUtils.isEmpty(commonData["scienceId"])) -1 else commonData["scienceId"]
graduationDesignReleaseBean.allowGrade = if (StringUtils.isEmpty(commonData["grade"])) null else commonData["grade"].toString()
val records = graduationDesignReleaseService.findAllByPage(paginationUtils, graduationDesignReleaseBean)
val graduationDesignReleaseBeens = graduationDesignReleaseService.dealData(paginationUtils, records, graduationDesignReleaseBean)
return ajaxUtils.success().msg("获取数据成功").listData(graduationDesignReleaseBeens).paginationUtils(paginationUtils)
}
/**
* 删除毕业设计附件
*
* @param filePath 文件路径
* @param fileId 文件id
* @param graduationDesignReleaseId 毕业设计发布id
* @param request 请求
* @return true or false
*/
fun deleteFileGraduateDesign(filePath: String, fileId: String, graduationDesignReleaseId: String, request: HttpServletRequest): AjaxUtils<*> {
val ajaxUtils = AjaxUtils.of<Any>()
try {
if (FilesUtils.deleteFile(RequestUtils.getRealPath(request) + filePath)) {
graduationDesignReleaseFileService.deleteByFileIdAndGraduationDesignReleaseId(fileId, graduationDesignReleaseId)
filesService.deleteById(fileId)
ajaxUtils.success().msg("删除文件成功")
} else {
ajaxUtils.fail().msg("删除文件失败")
}
} catch (e: Exception) {
log.error("Delete file exception, is {}", e)
}
return ajaxUtils
}
/**
* 设置教职工id和学生id
*
* @param modelMap 页面对象
*/
fun setStaffIdAndStudentId(modelMap: ModelMap, graduationDesignRelease: GraduationDesignRelease) {
val users = usersService.getUserFromSession()
var hasValue = false
if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) {
val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease.scienceId!!, graduationDesignRelease.allowGrade)
if (studentRecord.isPresent) {
val student = studentRecord.get().into(Student::class.java)
if (!ObjectUtils.isEmpty(student)) {
val staffRecord = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelation(student.studentId!!, graduationDesignRelease.graduationDesignReleaseId)
if (staffRecord.isPresent) {
val graduationDesignTeacher = staffRecord.get().into(GraduationDesignTeacher::class.java)
modelMap.addAttribute("studentId", student.studentId)
modelMap.addAttribute("staffId", graduationDesignTeacher.staffId)
hasValue = true
}
}
}
} else if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) {
val staff = staffService.findByUsername(users!!.username)
if (!ObjectUtils.isEmpty(staff)) {
val staffRecord = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignRelease.graduationDesignReleaseId, staff.staffId!!)
if (staffRecord.isPresent) {
modelMap.addAttribute("studentId", 0)
modelMap.addAttribute("staffId", staff.staffId)
hasValue = true
}
}
}
if (!hasValue) {
modelMap.addAttribute("studentId", 0)
modelMap.addAttribute("staffId", 0)
}
}
} | mit | e039e97b0aec994df90239e9e07d88c3 | 44.64557 | 190 | 0.728193 | 5.099717 | false | false | false | false |
seratch/jslack | slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/ExternalSelectElementBuilder.kt | 1 | 3741 | package com.slack.api.model.kotlin_extension.block.element
import com.slack.api.model.block.composition.ConfirmationDialogObject
import com.slack.api.model.block.composition.OptionObject
import com.slack.api.model.block.composition.PlainTextObject
import com.slack.api.model.block.element.ExternalSelectElement
import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder
import com.slack.api.model.kotlin_extension.block.Builder
import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder
import com.slack.api.model.kotlin_extension.block.composition.OptionObjectBuilder
@BlockLayoutBuilder
class ExternalSelectElementBuilder : Builder<ExternalSelectElement> {
private var placeholder: PlainTextObject? = null
private var actionId: String? = null
private var initialOption: OptionObject? = null
private var minQueryLength: Int? = null
private var confirm: ConfirmationDialogObject? = null
/**
* Adds a plain text object to the placeholder field.
*
* The placeholder text shown on the menu. Maximum length for the text in this field is 150 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#external_select">External select element documentation</a>
*/
fun placeholder(text: String, emoji: Boolean? = null) {
placeholder = PlainTextObject(text, emoji)
}
/**
* An identifier for the action triggered when a menu option is selected. You can use this when you receive an
* interaction payload to identify the source of the action. Should be unique among all other action_ids used
* elsewhere by your app. Maximum length for this field is 255 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#external_select">External select element documentation</a>
*/
fun actionId(id: String) {
actionId = id
}
/**
* A single option that exactly matches one of the options within the options or option_groups loaded from the
* external data source. This option will be selected when the menu initially loads.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#external_select">External select element documentation</a>
*/
fun initialOption(builder: OptionObjectBuilder.() -> Unit) {
initialOption = OptionObjectBuilder().apply(builder).build()
}
/**
* When the typeahead field is used, a request will be sent on every character change. If you prefer fewer
* requests or more fully ideated queries, use the min_query_length attribute to tell Slack the fewest number of
* typed characters required before dispatch. The default value is 3.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#external_select">External select element documentation</a>
*/
fun minQueryLength(length: Int) {
minQueryLength = length
}
/**
* A confirm object that defines an optional confirmation dialog that appears after a menu item is selected.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#external_select">External select element documentation</a>
*/
fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) {
confirm = ConfirmationDialogObjectBuilder().apply(builder).build()
}
override fun build(): ExternalSelectElement {
return ExternalSelectElement.builder()
.placeholder(placeholder)
.actionId(actionId)
.initialOption(initialOption)
.minQueryLength(minQueryLength)
.confirm(confirm)
.build()
}
} | mit | 02e446e438616d58db3dee493e9ed36a | 45.197531 | 136 | 0.714515 | 4.421986 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/view/user/ParticipantViewModel.kt | 1 | 1502 | package backend.view.user
import backend.model.user.Participant
import backend.model.user.User
import org.springframework.format.annotation.DateTimeFormat
import java.time.LocalDate
class ParticipantViewModel {
var id: Long? = null
var eventId: Long? = null
var teamId: Long? = null
var teamName: String? = null
var gender: String? = null
var firstname: String? = null
var lastname: String? = null
var emergencynumber: String? = null
var tshirtsize: String? = null
var postaddress: String? = null
var phonenumber: String? = null
var birthdate: String? = null
var email: String? = null
var eventCity: String? = null
constructor(participant: Participant) {
this.id = participant?.id
this.eventId = participant?.getCurrentTeam()?.event?.id
this.teamId = participant?.getCurrentTeam()?.id
this.teamName = participant?.getCurrentTeam()?.name
this.gender = participant?.gender
this.firstname = participant?.account?.firstname
this.lastname = participant?.account?.lastname
this.emergencynumber = participant?.emergencynumber
this.tshirtsize = participant?.tshirtsize
this.postaddress = participant?.getCurrentTeam()?.postaddress
this.phonenumber = participant?.phonenumber
this.birthdate = participant?.birthdate?.toString()
this.email = participant?.account?.email
this.eventCity = participant?.getCurrentTeam()?.event?.city
}
} | agpl-3.0 | 3d9bb437d8726d3674a3093be50a5d7b | 36.575 | 69 | 0.693076 | 4.456973 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinRenameDispatcherHandler.kt | 2 | 2018 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.rename.RenameHandler
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class KotlinRenameDispatcherHandler : RenameHandler {
companion object {
val EP_NAME = ExtensionPointName<RenameHandler>("org.jetbrains.kotlin.renameHandler")
private val handlers: Array<out RenameHandler>
get() {
@Suppress("DEPRECATION")
return Extensions.getExtensions(EP_NAME)
}
}
fun getRenameHandler(dataContext: DataContext): RenameHandler? {
val availableHandlers = handlers.filterTo(LinkedHashSet()) { it.isRenaming(dataContext) }
availableHandlers.singleOrNull()?.let { return it }
availableHandlers.firstIsInstanceOrNull<KotlinMemberInplaceRenameHandler>()?.let { availableHandlers -= it }
return availableHandlers.firstOrNull()
}
override fun isAvailableOnDataContext(dataContext: DataContext) = handlers.any { it.isAvailableOnDataContext(dataContext) }
override fun isRenaming(dataContext: DataContext) = isAvailableOnDataContext(dataContext)
override fun invoke(project: Project, editor: Editor?, file: PsiFile?, dataContext: DataContext) {
getRenameHandler(dataContext)?.invoke(project, editor, file, dataContext)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
getRenameHandler(dataContext)?.invoke(project, elements, dataContext)
}
} | apache-2.0 | 028e2d13ac971fcbfbeafb1dd42e6873 | 44.886364 | 158 | 0.758176 | 4.862651 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/XmlHelper.kt | 2 | 2398 | /*
* 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.utils
import io.kvision.utils.obj
import org.apache.causeway.client.kroviz.ui.core.Constants
import org.apache.causeway.client.kroviz.utils.js.XmlBeautify
import org.apache.causeway.client.kroviz.utils.js.XmlToJson
import org.w3c.dom.Document
import org.w3c.dom.Node
import org.w3c.dom.asList
import org.w3c.dom.parsing.DOMParser
import org.w3c.fetch.RequestDestination
inline val RequestDestination.Companion.XSLT: RequestDestination
get() {
TODO()
}
object XmlHelper {
fun isXml(input: String): Boolean {
val s = input.trim()
return s.startsWith("<") && s.endsWith(">")
}
fun nonTextChildren(node: Node): List<Node> {
val match = "#text"
val childNodes = node.childNodes.asList()
return childNodes.filter { !it.nodeName.contains(match) }
}
fun firstChildMatching(node: Node, match: String): Node? {
val childNodes = node.childNodes.asList()
val list = childNodes.filter { it.nodeName.contains(match) }
return list.firstOrNull()
}
fun parseXml(xmlStr: String): Document {
val p = DOMParser()
return p.parseFromString(xmlStr, Constants.xmlMimeType)
}
fun format(inputXml: String): String {
val options = obj {
indent = " "
useSelfClosingElement = true
}
return XmlBeautify().beautify(inputXml, options)
}
fun xml2json(xml: String): String {
val json = XmlToJson.parseString(xml)
return JSON.stringify(json)
}
}
| apache-2.0 | cedb2960cf321a6bda7b670f6e4e6e7a | 31.849315 | 68 | 0.68849 | 3.892857 | false | false | false | false |
Kangmo/korbit-scala-sdk | src/main/kotlin/org/kangmo/tradeapi/AbstractChannel.kt | 1 | 1365 | package org.kangmo.tradeapi
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.runBlocking
import org.kangmo.helper.JsonUtil
import org.kangmo.http.HTTPActor
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
abstract class AbstractChannel() {
suspend fun<T> getPublicFuture(resource : String, clazz: Class<T>) : T {
val future = CompletableFuture<T>()
HTTPActor.dispatcher.send(GetPublicResource(resource) { jsonResponse ->
val obj : T = JsonUtil.get().fromJson(jsonResponse, clazz)
future.complete( obj )
})
return future.get()
}
}
abstract class AbstractUserChannel(val ctx : Context) {
suspend fun <T> getUserFuture(resource: String, clazz: Class<T>): T {
val future = CompletableFuture<T>()
HTTPActor.dispatcher.send(GetUserResource(ctx, resource) { jsonResponse ->
val obj: T = JsonUtil.get().fromJson(jsonResponse, clazz)
future.complete(obj)
})
return future.get()
}
suspend fun <T> postUserFuture(resource : String, postData : String, clazz: Class<T>): T {
val future = CompletableFuture<T>()
HTTPActor.dispatcher.send(PostUserResource(ctx, resource, postData) { jsonResponse ->
val obj: T = JsonUtil.get().fromJson(jsonResponse, clazz)
future.complete(obj)
})
return future.get()
}
}
| apache-2.0 | 00ab109fad4352174cc3879a575ebd87 | 28.673913 | 91 | 0.747253 | 3.64 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinByConventionCallUsage.kt | 2 | 3810 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.intentions.RemoveEmptyParenthesesFromLambdaCallIntention
import org.jetbrains.kotlin.idea.intentions.conventionNameCalls.ReplaceInvokeIntention
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.util.OperatorNameConventions
class KotlinByConventionCallUsage(
expression: KtExpression,
private val callee: KotlinCallableDefinitionUsage<*>
) : KotlinUsageInfo<KtExpression>(expression) {
private var resolvedCall: ResolvedCall<*>? = null
private var convertedCallExpression: KtCallExpression? = null
private fun foldExpression(expression: KtDotQualifiedExpression, changeInfo: KotlinChangeInfo) {
when (changeInfo.newName) {
OperatorNameConventions.INVOKE.asString() -> {
with(ReplaceInvokeIntention()) {
if (applicabilityRange(expression) != null) {
OperatorToFunctionIntention.replaceExplicitInvokeCallWithImplicit(expression)
?.getPossiblyQualifiedCallExpression()
?.valueArgumentList
?.let {
RemoveEmptyParenthesesFromLambdaCallIntention.applyToIfApplicable(it)
}
}
}
}
OperatorNameConventions.GET.asString() -> {
with(ReplaceGetOrSetInspection()) {
if (isApplicable(expression)) {
applyTo(expression)
}
}
}
}
}
override fun getElement(): KtExpression? {
return convertedCallExpression ?: super.getElement()
}
override fun preprocessUsage() {
val element = element ?: return
val convertedExpression = OperatorToFunctionIntention.convert(element).first
val callExpression = convertedExpression.getPossiblyQualifiedCallExpression() ?: return
resolvedCall = callExpression.resolveToCall()
convertedCallExpression = callExpression
}
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtExpression, allUsages: Array<out UsageInfo>): Boolean {
val resolvedCall = resolvedCall ?: return true
val callExpression = convertedCallExpression ?: return true
val callProcessor = KotlinFunctionCallUsage(callExpression, callee, resolvedCall)
val newExpression = callProcessor.processUsageAndGetResult(
changeInfo = changeInfo,
element = callExpression,
allUsages = allUsages,
skipRedundantArgumentList = true,
) as? KtExpression
val qualifiedCall = newExpression?.getQualifiedExpressionForSelectorOrThis() as? KtDotQualifiedExpression
if (qualifiedCall != null) {
foldExpression(qualifiedCall, changeInfo)
}
return true
}
} | apache-2.0 | 8ffb44192f96423931b438ec1dc4cef0 | 45.47561 | 158 | 0.702887 | 6.185065 | false | false | false | false |
algra/pact-jvm | pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/HttpPart.kt | 1 | 2258 | package au.com.dius.pact.model
import au.com.dius.pact.model.matchingrules.MatchingRules
import groovy.lang.GroovyObjectSupport
import mu.KLogging
import org.apache.http.entity.ContentType
import java.nio.charset.Charset
/**
* Base trait for an object that represents part of an http message
*/
abstract class HttpPart : GroovyObjectSupport() {
abstract var body: OptionalBody?
abstract var headers: MutableMap<String, String>?
abstract var matchingRules: MatchingRules?
fun mimeType(): String = contentTypeHeader()?.split(Regex("\\s*;\\s*"))?.first().orEmpty()
fun contentTypeHeader(): String? {
val contentTypeKey = headers?.keys?.find { CONTENT_TYPE.equals(it, ignoreCase = true) }
return if (contentTypeKey.isNullOrEmpty()) {
detectContentType()
} else {
headers?.get(contentTypeKey)
}
}
fun jsonBody() = mimeType().matches(Regex("application\\/.*json"))
fun xmlBody() = mimeType().matches(Regex("application\\/.*xml"))
fun detectContentType(): String = when {
body != null && body!!.isPresent() -> {
val s = body?.value?.take(32)?.replace('\n', ' ').orEmpty()
when {
s.matches(XMLREGEXP) -> "application/xml"
s.toUpperCase().matches(HTMLREGEXP) -> "text/html"
s.matches(JSONREGEXP) -> "application/json"
s.matches(XMLREGEXP2) -> "application/xml"
else -> "text/plain"
}
}
else -> "text/plain"
}
fun setDefaultMimeType(mimetype: String) {
if (headers == null) {
headers = mutableMapOf()
}
if (!headers!!.containsKey(CONTENT_TYPE)) {
headers!![CONTENT_TYPE] = mimetype
}
}
companion object : KLogging() {
private const val CONTENT_TYPE = "Content-Type"
val XMLREGEXP = """^\s*<\?xml\s*version.*""".toRegex()
val HTMLREGEXP = """^\s*(<!DOCTYPE)|(<HTML>).*""".toRegex()
val JSONREGEXP = """^\s*(true|false|null|[0-9]+|"\w*|\{\s*(}|"\w+)|\[\s*).*""".toRegex()
val XMLREGEXP2 = """^\s*<\w+\s*(:\w+=[\"”][^\"”]+[\"”])?.*""".toRegex()
}
fun charset(): Charset? {
return try {
ContentType.parse(contentTypeHeader())?.charset
} catch (e: Exception) {
logger.debug { "Failed to parse content type '${contentTypeHeader()}'" }
null
}
}
}
| apache-2.0 | 4e575c997c2fff4ec1eeb2dd667cc030 | 29.849315 | 92 | 0.622114 | 3.740864 | false | false | false | false |
atrujillofalcon/spring-guides-kotlin | gs-messaging-redis/src/main/kotlin/Application.kt | 1 | 2080 | import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.listener.PatternTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter
import receiver.KotlinReceiver
import java.util.concurrent.CountDownLatch
@SpringBootApplication(scanBasePackages = arrayOf("receiver**"))
class Application {
companion object {
val LOGGER: Logger = LoggerFactory.getLogger(Application::class.java)
@JvmStatic
fun main(args: Array<String>) {
val ctx = SpringApplication.run(Application::class.java, *args)
val template = ctx.getBean(StringRedisTemplate::class.java)
val latch = ctx.getBean(CountDownLatch::class.java)
LOGGER.info("Sending message...")
template.convertAndSend("chat", "Hello from Redis!")
latch.await()
System.exit(0)
}
}
@Bean
fun latch(): CountDownLatch = CountDownLatch(1)
@Bean
fun receiver(latch: CountDownLatch): KotlinReceiver = KotlinReceiver(latch)
@Bean
fun template(connectionFactory: RedisConnectionFactory): StringRedisTemplate = StringRedisTemplate(connectionFactory)
@Bean
fun listenerAdapter(receiver: KotlinReceiver): MessageListenerAdapter = MessageListenerAdapter(receiver, "receiveMessage")
@Bean
fun container(connectionFactory: RedisConnectionFactory, listenerAdapter: MessageListenerAdapter): RedisMessageListenerContainer {
val container = RedisMessageListenerContainer()
container.connectionFactory = connectionFactory
container.addMessageListener(listenerAdapter, PatternTopic("chat"))
return container
}
} | apache-2.0 | 478ada13068224482ab6633952f2292d | 39.019231 | 134 | 0.759615 | 5.073171 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/refactorings/rename.k2/src/org/jetbrains/kotlin/idea/refactoring/rename/K2RenameCallablesWithOverridesProcessor.kt | 1 | 6225 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.rename.RenamePsiElementProcessor
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.or
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport
import org.jetbrains.kotlin.idea.refactoring.KotlinK2RefactoringsBundle
import org.jetbrains.kotlin.idea.searching.inheritors.findAllOverridings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
/**
* That processor has two main purposes:
* - Jump from the starting declaration to its deepest super declaration
* - Collect all overrides of the declaration to also rename them
*
* IMPORTANT: This processor searches for all overrides in the project, and
* [com.intellij.refactoring.rename.RenameJavaMethodProcessor.prepareRenaming] does that as well.
* However, we have to do the search ourselves in any case, because
* [com.intellij.refactoring.rename.RenameJavaMethodProcessor] will not kick in at
* all if the rename process starts at Kotlin element.
*/
internal class K2RenameCallablesWithOverridesProcessor : RenamePsiElementProcessor() {
override fun canProcessElement(element: PsiElement): Boolean {
val unwrapped = element.unwrapped as? KtCallableDeclaration
return unwrapped is KtNamedFunction || unwrapped is KtParameter || unwrapped is KtProperty
}
override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? {
val kotlinElement = element.unwrapped as? KtCallableDeclaration ?: return null
val elementToRename = selectElementToRename(element, kotlinElement)
// TODO: handle situation with intersection overrides (more than one deepest super declaration)
return elementToRename.lastOrNull()
}
/**
* User has to choose whether he wants to rename only current method
* or the base method and the whole hierarchy.
*/
private fun selectElementToRename(
element: PsiElement,
kotlinElement: KtCallableDeclaration
): List<PsiElement> {
return KotlinFindUsagesSupport.getInstance(element.project).checkSuperMethods(
kotlinElement,
ignore = emptyList(),
actionString = KotlinBundle.message("text.rename.as.part.of.phrase")
)
}
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) {
val kotlinElement = element.unwrapped as? KtCallableDeclaration ?: return
val allOverrides = collectAllOverrides(kotlinElement)
allRenames += allOverrides.associateWith { newName }
}
private fun collectAllOverrides(element: KtCallableDeclaration): Set<PsiElement> =
runProcessWithProgressSynchronously(
KotlinK2RefactoringsBundle.message("rename.searching.for.all.overrides"),
canBeCancelled = true,
element.project
) {
runReadAction {
element.findAllOverridings().toSet()
}
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): MutableCollection<PsiReference> {
val correctScope = if (element is KtParameter) {
searchScope or element.useScopeForRename
} else {
searchScope
}
return super.findReferences(element, correctScope, searchInCommentsAndStrings)
}
@OptIn(KtAllowAnalysisOnEdt::class)
override fun renameElement(element: PsiElement, newName: String, usages: Array<out UsageInfo>, listener: RefactoringElementListener?) {
val kotlinElement = element.unwrapped as? KtCallableDeclaration ?: return
super.renameElement(kotlinElement, newName, usages, listener)
// analysis is needed to check the overrides
allowAnalysisOnEdt {
dropOverrideKeywordIfNecessary(kotlinElement)
}
}
private fun dropOverrideKeywordIfNecessary(declaration: KtCallableDeclaration) {
if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD) && declaration.overridesNothing()) {
declaration.removeModifier(KtTokens.OVERRIDE_KEYWORD)
}
}
private fun KtCallableDeclaration.overridesNothing(): Boolean {
val declaration = this
analyze(this) {
val declarationSymbol = declaration.getSymbol() as? KtCallableSymbol ?: return false
return declarationSymbol.getDirectlyOverriddenSymbols().isEmpty()
}
}
}
/**
* A utility function to call [ProgressManager.runProcessWithProgressSynchronously] more conveniently.
*/
private inline fun <T> runProcessWithProgressSynchronously(
@NlsSafe @NlsContexts.DialogTitle progressTitle: String,
canBeCancelled: Boolean,
project: Project,
crossinline action: () -> T
): T = ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable { action() },
progressTitle,
canBeCancelled,
project
)
| apache-2.0 | 0fe3a87f1dc96a2149ed76ae5312e3bd | 40.778523 | 139 | 0.750361 | 5.200501 | false | false | false | false |
luca020400/android_packages_apps_CMChangelog | app/src/main/java/org/cyanogenmod/changelog/RestfulUrl.kt | 1 | 2016 | /*
* Copyright (c) 2016 The CyanogenMod Project.
*
* 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 org.cyanogenmod.changelog
import java.net.MalformedURLException
import java.net.URL
internal class RestfulUrl(val baseUrl: String, val endpoint: String) {
/**
* Query string
*/
private var query = ""
/**
* The n parameter can be used to limit the returned results.
*/
private var n = 0
/**
* The start query parameter can be supplied to skip a number of changes from the list.
*/
private var start = 0
fun setN(n: Int) {
this.n = n
}
fun setStart(start: Int) {
this.start = start
}
fun appendQuery(query: String) {
if (!query.isEmpty()) {
if (this.query.isEmpty())
this.query = query
else
this.query = this.query + "+" + query
}
}
override fun toString(): String {
val string = StringBuilder(128)
string.append(baseUrl).append(endpoint).append("?pp=0")
if (!query.isEmpty()) {
string.append("&q=").append(query)
if (n > 0) string.append("&n=").append(n)
if (start > 0) string.append("&start=").append(start)
}
return string.toString()
}
@Throws(MalformedURLException::class)
fun createUrl(): URL {
return URL(toString())
}
}
| gpl-3.0 | 6365e08577a1bcb2d8816284ec009fd9 | 27.394366 | 91 | 0.619048 | 4.156701 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.