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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
qaware/cloudcontrol
|
src/main/kotlin/de/qaware/oss/cloud/control/midi/MidiDeviceController.kt
|
1
|
4207
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 QAware GmbH, Munich, Germany
*
* 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 de.qaware.oss.cloud.control.midi
import de.qaware.oss.cloud.control.midi.LaunchControl.*
import org.apache.deltaspike.core.api.config.ConfigProperty
import org.slf4j.Logger
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
import javax.enterprise.context.ApplicationScoped
import javax.enterprise.event.Observes
import javax.inject.Inject
/**
* The controller takes care of reacting to MIDI device events properly.
*/
@ApplicationScoped
open class MidiDeviceController @Inject constructor(private val launchControl: LaunchControl,
@ConfigProperty(name = "cloudcontrol.factor")
private val factor: Int,
private val logger: Logger) {
@PostConstruct
open fun initDevice() {
launchControl.resetLEDs()
launchControl.color(Channel.USER, Cursor.UP, Color.RED_LOW)
launchControl.color(Channel.USER, Cursor.DOWN, Color.RED_LOW)
launchControl.color(Channel.USER, Cursor.LEFT, Color.RED_LOW)
launchControl.color(Channel.USER, Cursor.RIGHT, Color.RED_LOW)
launchControl.color(Channel.FACTORY, Cursor.UP, Color.RED_LOW)
launchControl.color(Channel.FACTORY, Cursor.DOWN, Color.RED_LOW)
launchControl.color(Channel.FACTORY, Cursor.LEFT, Color.RED_LOW)
launchControl.color(Channel.FACTORY, Cursor.RIGHT, Color.RED_LOW)
}
@PreDestroy
open fun shutdownDevice() {
launchControl.resetLEDs()
}
open fun onCursorPressed(@Observes @Pressed event: CursorEvent) {
launchControl.color(event.channel, event.cursor, Color.RED_FULL)
}
open fun onCursorReleased(@Observes @Released event: CursorEvent) {
launchControl.color(event.channel, event.cursor, Color.RED_LOW)
}
open fun onButtonPressed(@Observes @Pressed event: ButtonEvent) {
// TODO do something with this event
}
open fun onButtonReleased(@Observes @Pressed event: ButtonEvent) {
// TODO do something with this event
}
open fun onKnobTurned(@Observes event: KnobEvent) {
logger.info("Received $event")
if (event.row != 1) {
return
}
if (event.value < factor) {
launchControl.color(event.channel, Button.findByIndex(event.index)!!, Color.AMBER_FULL)
} else {
launchControl.color(event.channel, Button.findByIndex(event.index)!!, Color.GREEN_FULL)
}
}
open fun off(index: Int) = color(index, Color.OFF)
open fun enable(index: Int) = color(index, Color.GREEN_FULL)
open fun disable(index: Int) = color(index, Color.AMBER_FULL)
open fun failure(index: Int) = color(index, Color.RED_FULL)
private fun color(index: Int, color: Color) {
if (index !in 0..15) return
val channel = Channel.findByIndex(index)
val button = Button.findByIndex(index)
launchControl.color(channel!!, button!!, color)
}
}
|
mit
|
988d9647889a8da8e0f91b829ab7b1b4
| 37.254545 | 99 | 0.68695 | 4.228141 | false | false | false | false |
AlmasB/FXGL
|
fxgl-core/src/test/kotlin/com/almasb/fxgl/input/view/ViewTest.kt
|
1
|
2835
|
/*
* 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.input.view
import com.almasb.fxgl.input.InputModifier
import com.almasb.fxgl.input.KeyTrigger
import com.almasb.fxgl.input.MouseTrigger
import com.almasb.fxgl.input.Trigger
import javafx.scene.input.KeyCode
import javafx.scene.input.MouseButton
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class ViewTest {
@Test
fun `Key view`() {
KeyCode.values().forEach {
KeyView(it)
KeyView(it, Color.GOLD)
val view = KeyView(it, Color.WHITE, 15.0)
view.backgroundColor = Color.AQUAMARINE
view.keyColor = Color.RED
assertThat(view.backgroundColor, `is`<Paint>(Color.AQUAMARINE))
assertThat(view.backgroundColorProperty().value, `is`<Paint>(Color.AQUAMARINE))
assertThat(view.keyColor, `is`<Paint>(Color.RED))
}
}
@Test
fun `MouseButton view`() {
val view = MouseButtonView(MouseButton.PRIMARY, Color.BLUE, 20.0)
assertThat(view.color, `is`<Paint>(Color.BLUE))
view.color = Color.RED
assertThat(view.color, `is`<Paint>(Color.RED))
view.backgroundColor = Color.YELLOW
assertThat(view.backgroundColor, `is`<Paint>(Color.YELLOW))
}
@Test
fun `MouseButton view throws if not supported`() {
assertThrows<IllegalArgumentException> {
MouseButtonView(MouseButton.MIDDLE)
}
}
@ParameterizedTest
@EnumSource(InputModifier::class)
fun `Trigger view`(modifier: InputModifier) {
val view = TriggerView(KeyTrigger(KeyCode.C, modifier), Color.BLUE, 18.0)
val nodes = arrayListOf(view.children)
assertTrue(nodes.isNotEmpty())
val trigger = MouseTrigger(MouseButton.SECONDARY)
view.trigger = trigger
assertThat(view.triggerProperty().value, `is`<Trigger>(trigger))
assertThat(view.colorProperty().value, `is`<Color>(Color.BLUE))
assertTrue(view.children.isNotEmpty())
nodes.forEach {
assertThat(view.children, not(hasItem(it)))
}
TriggerView(MouseTrigger(MouseButton.PRIMARY))
TriggerView(MouseTrigger(MouseButton.PRIMARY), Color.GOLD)
view.color = Color.RED
view.size = 24.0
}
}
|
mit
|
6c58ac485ed79ff4923a24f1e612bf84
| 30.164835 | 91 | 0.67866 | 4.026989 | false | true | false | false |
RP-Kit/RPKit
|
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/protocol/Protocol.kt
|
1
|
5138
|
/*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.characters.bukkit.protocol
import com.comphenix.protocol.PacketType.Play.Server.*
import com.comphenix.protocol.ProtocolLibrary
import com.comphenix.protocol.events.PacketContainer
import com.comphenix.protocol.wrappers.EnumWrappers
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction.ADD_PLAYER
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction.REMOVE_PLAYER
import com.comphenix.protocol.wrappers.PlayerInfoData
import com.comphenix.protocol.wrappers.WrappedChatComponent
import com.comphenix.protocol.wrappers.WrappedGameProfile
import com.rpkit.characters.bukkit.character.RPKCharacter
import net.md_5.bungee.api.chat.TextComponent
import net.md_5.bungee.chat.ComponentSerializer
import org.bukkit.entity.Player
fun reloadPlayer(player: Player, character: RPKCharacter, viewers: List<Player>) {
reloadPlayerInfo(player, character, viewers)
reloadPlayerEntity(player, viewers)
}
private fun reloadPlayerInfo(player: Player, character: RPKCharacter, recipients: List<Player>) {
sendRemovePlayerPacket(player, recipients)
sendAddPlayerPacket(player, character, recipients)
}
private fun reloadPlayerEntity(player: Player, recipients: List<Player>) {
sendRemoveEntityPacket(player, recipients)
sendAddEntityPacket(player, recipients)
}
private fun sendRemovePlayerPacket(player: Player, recipients: List<Player>) {
val packet = createRemovePlayerPacket(player)
recipients.forEach { onlinePlayer ->
ProtocolLibrary.getProtocolManager().sendServerPacket(onlinePlayer, packet)
}
}
private fun createRemovePlayerPacket(player: Player): PacketContainer {
val packet = ProtocolLibrary.getProtocolManager().createPacket(PLAYER_INFO)
packet.playerInfoAction.write(0, REMOVE_PLAYER)
val profile = WrappedGameProfile.fromPlayer(player)
val chatComponent = WrappedChatComponent.fromText(profile.name)
val playerInfoData =
PlayerInfoData(profile, player.ping, EnumWrappers.NativeGameMode.fromBukkit(player.gameMode), chatComponent)
packet.playerInfoDataLists.write(0, listOf(playerInfoData))
return packet
}
private fun sendAddPlayerPacket(player: Player, character: RPKCharacter, recipients: List<Player>) {
val packet = createAddPlayerPacket(player, character)
recipients.forEach { onlinePlayer ->
ProtocolLibrary.getProtocolManager().sendServerPacket(onlinePlayer, packet)
}
}
private fun createAddPlayerPacket(
player: Player,
character: RPKCharacter
): PacketContainer {
val packet = ProtocolLibrary.getProtocolManager().createPacket(PLAYER_INFO)
packet.playerInfoAction.write(0, ADD_PLAYER)
val profile = WrappedGameProfile.fromPlayer(player).withName(character.name.take(16))
val tabListTextComponent =
WrappedChatComponent.fromJson(ComponentSerializer.toString(TextComponent.fromLegacyText(player.playerListName)))
val playerInfoData = PlayerInfoData(
profile,
player.ping,
EnumWrappers.NativeGameMode.fromBukkit(player.gameMode),
tabListTextComponent
)
packet.playerInfoDataLists.write(0, listOf(playerInfoData))
return packet
}
private fun sendRemoveEntityPacket(player: Player, recipients: List<Player>) {
val packet = createRemoveEntityPacket(player)
recipients.forEach { onlinePlayer ->
ProtocolLibrary.getProtocolManager().sendServerPacket(onlinePlayer, packet)
}
}
private fun createRemoveEntityPacket(player: Player): PacketContainer {
val packet = ProtocolLibrary.getProtocolManager().createPacket(ENTITY_DESTROY)
packet.intLists.write(0, listOf(player.entityId))
return packet
}
private fun sendAddEntityPacket(player: Player, recipients: List<Player>) {
val packet = createAddEntityPacket(player)
recipients.forEach { onlinePlayer ->
ProtocolLibrary.getProtocolManager().sendServerPacket(onlinePlayer, packet)
}
}
private fun createAddEntityPacket(player: Player): PacketContainer {
val packet = ProtocolLibrary.getProtocolManager().createPacket(NAMED_ENTITY_SPAWN)
packet.integers.write(0, player.entityId)
packet.uuiDs.write(0, player.uniqueId)
packet.doubles.write(0, player.location.x)
packet.doubles.write(1, player.location.y)
packet.doubles.write(2, player.location.z)
val yawByte = (player.location.yaw / 360f * 256f).toInt().toByte()
val pitchByte = (player.location.pitch / 360f * 256f).toInt().toByte()
packet.bytes.write(0, yawByte)
packet.bytes.write(1, pitchByte)
return packet
}
|
apache-2.0
|
2f8b2809843e4cf0afe6118959f31304
| 40.435484 | 120 | 0.775204 | 4.167072 | false | false | false | false |
nickthecoder/tickle
|
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/ChangeZOrder.kt
|
1
|
1623
|
/*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.editor.scene.history
import uk.co.nickthecoder.tickle.editor.scene.SceneEditor
import uk.co.nickthecoder.tickle.resources.ActorResource
class ChangeZOrder(
private val actorResource: ActorResource,
private val newZOrder: Double)
: Change {
private val oldZOrder = actorResource.zOrder
override fun redo(sceneEditor: SceneEditor) {
actorResource.zOrder = newZOrder
updateForm(sceneEditor)
}
override fun undo(sceneEditor: SceneEditor) {
actorResource.zOrder = oldZOrder
updateForm(sceneEditor)
}
/**
* Update the actor attributes box, if it showing this actor resource's attributes.
*/
private fun updateForm(sceneEditor: SceneEditor) {
if (sceneEditor.actorAttributesBox.actorResource == actorResource) {
sceneEditor.actorAttributesBox.actorAttributesForm?.zOrderP?.value = actorResource.zOrder
}
}
}
|
gpl-3.0
|
fa4234cd0871691b29ef681a0aecdfe3
| 32.122449 | 101 | 0.74122 | 4.362903 | false | false | false | false |
kittinunf/ReactiveAndroid
|
reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/widget/CheckedTextViewPropertyTest.kt
|
1
|
2888
|
package com.github.kittinunf.reactiveandroid.widget
import android.annotation.TargetApi
import android.graphics.PorterDuff
import android.os.Build
import android.support.test.InstrumentationRegistry
import android.support.test.annotation.UiThreadTest
import android.support.test.filters.SdkSuppress
import android.support.test.rule.UiThreadTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v4.content.ContextCompat
import android.widget.CheckedTextView
import com.github.kittinunf.reactiveandroid.reactive.bindTo
import com.github.kittinunf.reactiveandroid.reactive.view.withDrawable
import com.github.kittinunf.reactiveandroid.scheduler.AndroidThreadScheduler
import com.github.kittinunf.reactiveandroid.ui.test.R
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CheckedTextViewPropertyTest {
@Rule
@JvmField
val uiThreadTestRule = UiThreadTestRule()
private val context = InstrumentationRegistry.getContext()
private val instrument = InstrumentationRegistry.getInstrumentation()
private val view = CheckedTextView(context)
companion object {
@BeforeClass
@JvmStatic
fun setUp() {
AndroidThreadScheduler.main = Schedulers.trampoline()
}
}
@Test
@UiThreadTest
fun testChecked() {
val checked = view.rx_checked
Observable.just(true).bindTo(checked)
assertThat(view.isChecked, equalTo(true))
checked.bindTo(Observable.just(false))
assertThat(view.isChecked, equalTo(false))
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)
@Test
@UiThreadTest
fun testMarkTintMode() {
val markTintMode = view.rx_checkMarkTintMode
Observable.just(PorterDuff.Mode.SRC).bindTo(markTintMode)
assertThat(view.checkMarkTintMode, equalTo(PorterDuff.Mode.SRC))
markTintMode.bindTo(Observable.just(PorterDuff.Mode.SRC_IN))
assertThat(view.checkMarkTintMode, equalTo(PorterDuff.Mode.SRC_IN))
}
@Test
@UiThreadTest
fun testDrawable() {
val drawable = view.rx_checkMarkDrawable
Observable.just(ContextCompat.getDrawable(context, R.drawable.ic_account_balance_wallet_black_18dp)).bindTo(drawable)
assertThat(view.checkMarkDrawable, withDrawable(context, R.drawable.ic_account_balance_wallet_black_18dp))
drawable.bindTo(Observable.just(ContextCompat.getDrawable(context, R.drawable.ic_accessibility_black_18dp)))
assertThat(view.checkMarkDrawable, withDrawable(context, R.drawable.ic_accessibility_black_18dp))
}
}
|
mit
|
cb87f679a7348426e2448243f29b6f23
| 32.976471 | 125 | 0.764889 | 4.402439 | false | true | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/computer/DeviceKeyboard.kt
|
2
|
4366
|
package com.cout970.magneticraft.systems.computer
import com.cout970.magneticraft.api.computer.IDevice
import com.cout970.magneticraft.api.computer.IRW
import com.cout970.magneticraft.api.computer.IResettable
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.systems.gui.DATA_ID_KEYBOARD_EVENT_CODE
import com.cout970.magneticraft.systems.gui.DATA_ID_KEYBOARD_EVENT_KEY
import com.cout970.magneticraft.systems.gui.DATA_ID_KEYBOARD_KEY_STATES
import com.cout970.magneticraft.systems.gui.DATA_ID_MONITOR_CLIPBOARD
import java.util.*
class DeviceKeyboard : IDevice, IResettable {
//keyboard buffer
var regKeyBufferPtr = 0
var regKeyBufferSize = 0
val keyBuffer = ByteArray(32)
val keyStates = ByteArray(256)
var currentKey = 0
data class KeyEvent(val key: Int, val code: Int)
val events = ArrayDeque<KeyEvent>()
val clipboardToPaste = StringBuilder()
val memStruct = ReadWriteStruct("monitor_header",
ReadWriteStruct("device_header",
ReadOnlyByte("online", { 1 }),
ReadOnlyByte("type", { 1 }),
ReadOnlyShort("status", { 0 })
),
ReadWriteByte("keyBufferPtr", { regKeyBufferPtr = it.toInt() and 0xFF }, { regKeyBufferPtr.toByte() }),
ReadWriteByte("keyBufferSize", { regKeyBufferSize = it.toInt() and 0xFF }, { regKeyBufferSize.toByte() }),
ReadWriteByte("key", { currentKey = it.toInt() and 0xFF }, { currentKey.toByte() }),
ReadOnlyByte("isPressed", { keyStates[currentKey] }),
ReadWriteByteArray("keyBuffer", keyBuffer)
)
override fun update() {
if (clipboardToPaste.isNotEmpty()) {
var key = clipboardToPaste[0]
while (regKeyBufferSize != keyBuffer.size / 2) {
val pos = (regKeyBufferPtr + regKeyBufferSize) % (keyBuffer.size / 2)
keyBuffer[2 * pos] = 1
keyBuffer[2 * pos + 1] = key.toByte()
regKeyBufferSize++
clipboardToPaste.deleteCharAt(0)
if (clipboardToPaste.isEmpty()) break
key = clipboardToPaste[0]
}
}
}
override fun reset() {
clipboardToPaste.delete(0, clipboardToPaste.length)
keyStates.fill(0)
}
fun onKeyPress(key: Int, code: Int) {
keyStates[code and 0xFF] = 1
events.addLast(KeyEvent(key, code))
}
@Suppress("UNUSED_PARAMETER")
fun onKeyRelease(key: Int, code: Int) {
keyStates[code and 0xFF] = 0
}
//Client to Server sync
fun saveToServer(ibd: IBD) {
if (events.isNotEmpty()) {
val e = events.removeFirst()
ibd.setInteger(DATA_ID_KEYBOARD_EVENT_KEY, e.key)
ibd.setInteger(DATA_ID_KEYBOARD_EVENT_CODE, e.code)
}
ibd.setByteArray(DATA_ID_KEYBOARD_KEY_STATES, keyStates)
}
fun loadFromClient(ibd: IBD) {
ibd.getString(DATA_ID_MONITOR_CLIPBOARD) {
clipboardToPaste.append(it)
}
ibd.getInteger(DATA_ID_KEYBOARD_EVENT_KEY) { key ->
val code = ibd.getInteger(DATA_ID_KEYBOARD_EVENT_CODE)
if (regKeyBufferSize != keyBuffer.size / 2) {
val pos = (regKeyBufferPtr + regKeyBufferSize) % (keyBuffer.size / 2)
keyBuffer[2 * pos] = key.toByte()
keyBuffer[2 * pos + 1] = code.toByte()
regKeyBufferSize++
}
}
ibd.getByteArray(DATA_ID_KEYBOARD_KEY_STATES) { buffer ->
System.arraycopy(buffer, 0, keyStates, 0, buffer.size)
}
}
override fun writeByte(bus: IRW, addr: Int, data: Byte) {
memStruct.write(addr, data)
}
override fun readByte(bus: IRW, addr: Int): Byte {
return memStruct.read(addr)
}
override fun serialize(): MutableMap<String, Any> = mutableMapOf(
"KeyBufferPtr" to regKeyBufferPtr,
"KeyBufferSize" to regKeyBufferSize,
"currentKey" to currentKey,
"KeyBuffer" to keyBuffer.copyOf()
)
override fun deserialize(map: MutableMap<String, Any>) {
regKeyBufferPtr = map["KeyBufferPtr"] as Int
regKeyBufferSize = map["KeyBufferSize"] as Int
currentKey = map["currentKey"] as Int
System.arraycopy(map["KeyBuffer"] as ByteArray, 0, keyBuffer, 0, keyBuffer.size)
}
}
|
gpl-2.0
|
b9d3ae2649a0333cbeaef8562036fdd7
| 32.592308 | 114 | 0.624599 | 3.951131 | false | false | false | false |
Shashi-Bhushan/General
|
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/contest/weekly180/Solution.kt
|
1
|
580
|
import kotlin.math.max
import kotlin.math.min
fun luckyNumbers(matrix: Array<IntArray>): List<Int> {
matrix.indices.forEach { row ->
matrix[row].indices.forEach { column ->
var min = Integer.MAX_VALUE
var max = Integer.MIN_VALUE
matrix.indices.forEach { k ->
min = min(matrix[row][k], min)
}
matrix[row].indices.forEach { k ->
max = max(matrix[k][column], max)
}
if (min == matrix[row][column] && max == matrix[row][column]) {
return listOf(matrix[row][column])
}
}
}
return emptyList()
}
|
gpl-2.0
|
bc03e7c342ebe6825f7eb3b74620a99d
| 22.2 | 69 | 0.584483 | 3.580247 | false | false | false | false |
Shynixn/BlockBall
|
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/TeamSettingsPage.kt
|
1
|
9959
|
@file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.blockball.core.logic.business.commandmenu
import com.github.shynixn.blockball.api.business.enumeration.*
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.api.persistence.entity.Arena
import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder
import com.github.shynixn.blockball.api.persistence.entity.TeamMeta
import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity
import com.google.inject.Inject
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class TeamSettingsPage @Inject constructor(private val proxyService: ProxyService) : Page(TeamSettingsPage.ID, MainSettingsPage.ID) {
companion object {
/** Id of the page. */
const val ID = 5
}
/**
* Returns the key of the command when this page should be executed.
*
* @return key
*/
override fun getCommandKey(): MenuPageKey {
return MenuPageKey.TEAMMETA
}
/**
* Executes actions for this page.
*
* @param cache cache
*/
override fun <P> execute(player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String>): MenuCommandResult {
if (command == MenuCommand.TEAM_RED_CONFIGURE) {
cache[2] = 0
}
if (command == MenuCommand.TEAM_BLUE_CONFIGURE) {
cache[2] = 1
} else if (command == MenuCommand.TEAM_SPAWNPOINT) {
val teamMeta = getTeamMeta(cache)
teamMeta.spawnpoint = proxyService.toPosition(proxyService.getEntityLocation<Any, P>(player))
} else if (command == MenuCommand.TEAM_NAME) {
val teamMeta = getTeamMeta(cache)
val name = mergeArgs(2, args)
teamMeta.displayName = name
} else if (command == MenuCommand.TEAM_PREFIX) {
val teamMeta = getTeamMeta(cache)
val name = mergeArgs(2, args)
teamMeta.prefix = name
} else if (command == MenuCommand.TEAM_MINAMOUNT) {
val teamMeta = getTeamMeta(cache)
val amount = args[2].toIntOrNull()
if (amount != null) {
if (amount > teamMeta.maxAmount) {
return MenuCommandResult.MAX_PLAYERS
}
teamMeta.minAmount = amount
}
} else if (command == MenuCommand.TEAM_MAXAMOUNT) {
val teamMeta = getTeamMeta(cache)
val amount = args[2].toIntOrNull()
if (amount != null) {
if (amount < teamMeta.minAmount) {
return MenuCommandResult.MINPLAYERS
}
teamMeta.maxAmount = amount
}
} else if (command == MenuCommand.TEAM_POINTSGOAL) {
val teamMeta = getTeamMeta(cache)
val amount = args[2].toIntOrNull()
if (amount != null) {
teamMeta.pointsPerGoal = amount
}
} else if (command == MenuCommand.TEAM_POINTSDEATH) {
val teamMeta = getTeamMeta(cache)
val amount = args[2].toIntOrNull()
if (amount != null) {
teamMeta.pointsPerEnemyDeath = amount
}
} else if (command == MenuCommand.TEAM_WALKSPEED) {
val teamMeta = getTeamMeta(cache)
val amount = args[2].toDoubleOrNull()
if (amount != null) {
teamMeta.walkingSpeed = amount
}
} else if (command == MenuCommand.TEAM_ARMOR) {
val teamMeta = getTeamMeta(cache)
teamMeta.armorContents = proxyService.getPlayerInventoryArmorCopy(player)
} else if (command == MenuCommand.TEAM_INVENTORY) {
val teamMeta = getTeamMeta(cache)
teamMeta.inventoryContents = proxyService.getPlayerInventoryCopy(player)
}
return super.execute(player, command, cache, args)
}
/**
* Builds the page content.
*
* @param cache cache
* @return content
*/
override fun buildPage(cache: Array<Any?>): ChatBuilder {
var spawnpoint = "none"
val teamMeta = getTeamMeta(cache)
if (teamMeta.spawnpoint != null) {
spawnpoint = teamMeta.spawnpoint!!.toString()
}
return ChatBuilderEntity()
.component("- Name: " + teamMeta.displayName).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_NAME.command)
.setHoverText("Edit the name of the team.")
.builder().nextLine()
.component("- Color: " + teamMeta.prefix + "Color").builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_PREFIX.command)
.setHoverText("Edit the prefix of the team.")
.builder().nextLine()
.component("- Min amount: " + teamMeta.minAmount).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_MINAMOUNT.command)
.setHoverText("Edit the min amount of players required to start a match.")
.builder().nextLine()
.component("- Max amount: " + teamMeta.maxAmount).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_MAXAMOUNT.command)
.setHoverText("Edit the max amount of players which can join this team.")
.builder().nextLine()
.component("- Armor").builder()
.component(MenuClickableItem.COPY_ARMOR.text).setColor(MenuClickableItem.COPY_ARMOR.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.TEAM_ARMOR.command)
.setHoverText("Copies your current equipped armor to the team's armor.")
.builder().nextLine()
.component("- Inventory").builder()
.component(MenuClickableItem.COPY_INVENTORY.text).setColor(MenuClickableItem.COPY_INVENTORY.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.TEAM_INVENTORY.command)
.setHoverText("Copies your current your inventory to the team's inventory.")
.builder().nextLine()
.component("- Walking Speed: " + teamMeta.walkingSpeed).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_WALKSPEED.command)
.setHoverText("Edit the speed each player of this team is going to walk. (default: 0.2)")
.builder().nextLine()
.component("- Points per goal: " + teamMeta.pointsPerGoal).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_POINTSGOAL.command)
.setHoverText("Edit the amount of points this team gets when a goal gets scored. (default: 1)")
.builder().nextLine()
.component("- Points per opponent death: " + teamMeta.pointsPerEnemyDeath).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEAM_POINTSDEATH.command)
.setHoverText("Edit the amount of points this team gets when a player of the opponent team dies. (default: 0)")
.builder().nextLine()
.component("- Spawnpoint: $spawnpoint").builder()
.component(" [location..]").setColor(ChatColor.BLUE)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.TEAM_SPAWNPOINT.command)
.setHoverText("If this spawnpoint is set the team will spawn at this location instead of the spawning location of the ball.")
.builder().nextLine()
.component("- Textbook: ").builder()
.component(MenuClickableItem.PAGE.text).setColor(MenuClickableItem.PAGE.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.TEXTBOOK_OPEN.command)
.setHoverText("Opens the messages and texts specific for this team.")
.builder().nextLine()
}
private fun getTeamMeta(cache: Array<Any?>?): TeamMeta {
val arena = cache!![0] as Arena
val type = cache[2] as Int
return if (type == 0) {
arena.meta.redTeamMeta
} else {
arena.meta.blueTeamMeta
}
}
}
|
apache-2.0
|
c9f49822d4948760d96aa5e99a3be184
| 47.823529 | 137 | 0.645346 | 4.706522 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/settings/MdCodeStyleSettingsSerializable.kt
|
1
|
12019
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.settings
import com.vladsch.md.nav.flex.parser.MdSpecExampleStripTrailingSpacesExtension
import com.vladsch.md.nav.language.MdCodeStyleSettings
/**
* Used to serialize Code Style Settings when exporting all Project settings
*/
class MdCodeStyleSettingsSerializable(val settings: MdCodeStyleSettings) : StateHolderImpl({ MdCodeStyleSettingsSerializable() }), MdCodeStyleSettings.Holder {
companion object {
const val STATE_ELEMENT_NAME: String = "MarkdownNavigatorCodeStyle"
}
override fun getStyleSettings(): MdCodeStyleSettings {
return settings
}
override fun setStyleSettings(styleSettings: MdCodeStyleSettings) {
settings.copyFrom(styleSettings)
}
constructor() : this(MdCodeStyleSettings())
override fun getStateHolder(): StateHolder = TagItemHolder(STATE_ELEMENT_NAME).addItems(
BooleanAttribute("ATTRIBUTES_COMBINE_CONSECUTIVE", { settings.ATTRIBUTES_COMBINE_CONSECUTIVE }, { settings.ATTRIBUTES_COMBINE_CONSECUTIVE = it }),
BooleanAttribute("CODE_FENCE_MATCH_CLOSING_MARKER", { settings.CODE_FENCE_MATCH_CLOSING_MARKER }, { settings.CODE_FENCE_MATCH_CLOSING_MARKER = it }),
BooleanAttribute("CODE_FENCE_MINIMIZE_INDENT", { settings.CODE_FENCE_MINIMIZE_INDENT }, { settings.CODE_FENCE_MINIMIZE_INDENT = it }),
BooleanAttribute("CODE_FENCE_SPACE_BEFORE_INFO", { settings.CODE_FENCE_SPACE_BEFORE_INFO }, { settings.CODE_FENCE_SPACE_BEFORE_INFO = it }),
BooleanAttribute("ESCAPE_NUMBERED_LEAD_IN_ON_WRAP", { settings.ESCAPE_NUMBERED_LEAD_IN_ON_WRAP }, { settings.ESCAPE_NUMBERED_LEAD_IN_ON_WRAP = it }),
BooleanAttribute("ESCAPE_SPECIAL_CHARS_ON_WRAP", { settings.ESCAPE_SPECIAL_CHARS_ON_WRAP }, { settings.ESCAPE_SPECIAL_CHARS_ON_WRAP = it }),
BooleanAttribute("LIST_ADD_BLANK_LINE_BEFORE", { settings.LIST_ADD_BLANK_LINE_BEFORE }, { settings.LIST_ADD_BLANK_LINE_BEFORE = it }),
BooleanAttribute("LIST_RENUMBER_ITEMS", { settings.LIST_RENUMBER_ITEMS }, { settings.LIST_RENUMBER_ITEMS = it }),
BooleanAttribute("LIST_RESET_FIRST_ITEM_NUMBER", { settings.LIST_RESET_FIRST_ITEM_NUMBER }, { settings.LIST_RESET_FIRST_ITEM_NUMBER = it }),
BooleanAttribute("PARA_WRAP_TEXT", { settings.PARA_WRAP_TEXT }, { settings.PARA_WRAP_TEXT = it }),
BooleanAttribute("SETEXT_HEADER_EQUALIZE_MARKER", { settings.SETEXT_HEADER_EQUALIZE_MARKER }, { settings.SETEXT_HEADER_EQUALIZE_MARKER = it }),
BooleanAttribute("SMART_EDIT_ATX_HEADER", { settings.SMART_EDIT_ATX_HEADER }, { settings.SMART_EDIT_ATX_HEADER = it }),
BooleanAttribute("SMART_EDIT_SETEXT_HEADER", { settings.SMART_EDIT_SETEXT_HEADER }, { settings.SMART_EDIT_SETEXT_HEADER = it }),
BooleanAttribute("SMART_EDIT_TABLE_SEPARATOR_LINE", { settings.SMART_EDIT_TABLE_SEPARATOR_LINE }, { settings.SMART_EDIT_TABLE_SEPARATOR_LINE = it }),
BooleanAttribute("SMART_EDIT_TABLES", { settings.SMART_EDIT_TABLES }, { settings.SMART_EDIT_TABLES = it }),
BooleanAttribute("SMART_ENTER_ATX_HEADER", { settings.SMART_ENTER_ATX_HEADER }, { settings.SMART_ENTER_ATX_HEADER = it }),
BooleanAttribute("SMART_ENTER_SETEXT_HEADER", { settings.SMART_ENTER_SETEXT_HEADER }, { settings.SMART_ENTER_SETEXT_HEADER = it }),
BooleanAttribute("SMART_TABS", { settings.SMART_TABS }, { settings.SMART_TABS = it }),
BooleanAttribute("TABLE_ADJUST_COLUMN_WIDTH", { settings.TABLE_ADJUST_COLUMN_WIDTH }, { settings.TABLE_ADJUST_COLUMN_WIDTH = it }),
BooleanAttribute("TABLE_APPLY_COLUMN_ALIGNMENT", { settings.TABLE_APPLY_COLUMN_ALIGNMENT }, { settings.TABLE_APPLY_COLUMN_ALIGNMENT = it }),
BooleanAttribute("TABLE_FILL_MISSING_COLUMNS", { settings.TABLE_FILL_MISSING_COLUMNS }, { settings.TABLE_FILL_MISSING_COLUMNS = it }),
BooleanAttribute("TABLE_LEAD_TRAIL_PIPES", { settings.TABLE_LEAD_TRAIL_PIPES }, { settings.TABLE_LEAD_TRAIL_PIPES = it }),
BooleanAttribute("TABLE_SPACE_AROUND_PIPE", { settings.TABLE_SPACE_AROUND_PIPE }, { settings.TABLE_SPACE_AROUND_PIPE = it }),
BooleanAttribute("TABLE_TRIM_CELLS", { settings.TABLE_TRIM_CELLS }, { settings.TABLE_TRIM_CELLS = it }),
BooleanAttribute("TOC_FORMAT_ON_SAVE", { settings.TOC_FORMAT_ON_SAVE }, { settings.TOC_FORMAT_ON_SAVE = it }),
BooleanAttribute("TOC_GENERATE_HTML", { settings.TOC_GENERATE_HTML }, { settings.TOC_GENERATE_HTML = it }),
BooleanAttribute("TOC_GENERATE_NUMBERED_LIST", { settings.TOC_GENERATE_NUMBERED_LIST }, { settings.TOC_GENERATE_NUMBERED_LIST = it }),
BooleanAttribute("TOC_GENERATE_TEXT_ONLY", { settings.TOC_GENERATE_TEXT_ONLY }, { settings.TOC_GENERATE_TEXT_ONLY = it }),
BooleanAttribute("UNESCAPE_SPECIAL_CHARS_ON_WRAP", { settings.UNESCAPE_SPECIAL_CHARS_ON_WRAP }, { settings.UNESCAPE_SPECIAL_CHARS_ON_WRAP = it }),
BooleanAttribute("USE_ACTUAL_CHAR_WIDTH", { settings.USE_ACTUAL_CHAR_WIDTH }, { settings.USE_ACTUAL_CHAR_WIDTH = it }),
BooleanAttribute("USE_TAB_CHARACTER", { settings.USE_TAB_CHARACTER }, { settings.USE_TAB_CHARACTER = it }),
BooleanAttribute("VERBATIM_MINIMIZE_INDENT", { settings.VERBATIM_MINIMIZE_INDENT }, { settings.VERBATIM_MINIMIZE_INDENT = it }),
IntAttribute("ABBREVIATIONS_PLACEMENT", { settings.ABBREVIATIONS_PLACEMENT }, { settings.ABBREVIATIONS_PLACEMENT = it }),
IntAttribute("ABBREVIATIONS_SORT", { settings.ABBREVIATIONS_SORT }, { settings.ABBREVIATIONS_SORT = it }),
IntAttribute("ATTRIBUTE_EQUAL_SPACE", { settings.ATTRIBUTE_EQUAL_SPACE }, { settings.ATTRIBUTE_EQUAL_SPACE = it }),
IntAttribute("ATTRIBUTE_VALUE_QUOTES", { settings.ATTRIBUTE_VALUE_QUOTES }, { settings.ATTRIBUTE_VALUE_QUOTES = it }),
IntAttribute("ATTRIBUTES_SPACES", { settings.ATTRIBUTES_SPACES }, { settings.ATTRIBUTES_SPACES = it }),
IntAttribute("ATX_HEADER_TRAILING_MARKER", { settings.ATX_HEADER_TRAILING_MARKER }, { settings.ATX_HEADER_TRAILING_MARKER = it }),
IntAttribute("BLOCK_QUOTE_MARKERS", { settings.BLOCK_QUOTE_MARKERS }, { settings.BLOCK_QUOTE_MARKERS = it }),
IntAttribute("BULLET_LIST_ITEM_MARKER", { settings.BULLET_LIST_ITEM_MARKER }, { settings.BULLET_LIST_ITEM_MARKER = it }),
IntAttribute("CODE_FENCE_MARKER_LENGTH", { settings.CODE_FENCE_MARKER_LENGTH }, { settings.CODE_FENCE_MARKER_LENGTH = it }),
IntAttribute("CODE_FENCE_MARKER_TYPE", { settings.CODE_FENCE_MARKER_TYPE }, { settings.CODE_FENCE_MARKER_TYPE = it }),
IntAttribute("CODE_KEEP_TRAILING_SPACES", { settings.CODE_KEEP_TRAILING_SPACES }, { settings.CODE_KEEP_TRAILING_SPACES = it }),
IntAttribute("DEFINITION_MARKER_SPACES", { settings.DEFINITION_MARKER_SPACES }, { settings.DEFINITION_MARKER_SPACES = it }),
IntAttribute("DEFINITION_MARKER_TYPE", { settings.DEFINITION_MARKER_TYPE }, { settings.DEFINITION_MARKER_TYPE = it }),
IntAttribute("ENUMERATED_REFERENCE_FORMAT_PLACEMENT", { settings.ENUMERATED_REFERENCE_FORMAT_PLACEMENT }, { settings.ENUMERATED_REFERENCE_FORMAT_PLACEMENT = it }),
IntAttribute("ENUMERATED_REFERENCE_FORMAT_SORT", { settings.ENUMERATED_REFERENCE_FORMAT_SORT }, { settings.ENUMERATED_REFERENCE_FORMAT_SORT = it }),
IntAttribute("FOOTNOTE_PLACEMENT", { settings.FOOTNOTE_PLACEMENT }, { settings.FOOTNOTE_PLACEMENT = it }),
IntAttribute("FOOTNOTE_SORT", { settings.FOOTNOTE_SORT }, { settings.FOOTNOTE_SORT = it }),
IntAttribute("FORMAT_WITH_SOFT_WRAP", { settings.FORMAT_WITH_SOFT_WRAP }, { settings.FORMAT_WITH_SOFT_WRAP = it }),
IntAttribute("HEADING_PREFERENCE", { settings.HEADING_PREFERENCE }, { settings.HEADING_PREFERENCE = it }),
IntAttribute("INDENT_SIZE", { settings.INDENT_SIZE }, { settings.INDENT_SIZE = it }),
IntAttribute("KEEP_AT_START_EXPLICIT_LINK", { settings.KEEP_AT_START_EXPLICIT_LINK }, { settings.KEEP_AT_START_EXPLICIT_LINK = it }),
IntAttribute("KEEP_AT_START_IMAGE_LINKS", { settings.KEEP_AT_START_IMAGE_LINKS }, { settings.KEEP_AT_START_IMAGE_LINKS = it }),
IntAttribute("KEEP_BLANK_LINES", { settings.KEEP_BLANK_LINES }, { settings.KEEP_BLANK_LINES = it }),
IntAttribute("KEEP_TRAILING_SPACES", { settings.KEEP_TRAILING_SPACES }, { settings.KEEP_TRAILING_SPACES = it }),
IntAttribute("LIST_ALIGN_NUMERIC", { settings.LIST_ALIGN_NUMERIC }, { settings.LIST_ALIGN_NUMERIC = it }),
IntAttribute("LIST_ORDERED_TASK_ITEM_PRIORITY", { settings.LIST_ORDERED_TASK_ITEM_PRIORITY }, { settings.LIST_ORDERED_TASK_ITEM_PRIORITY = it }),
IntAttribute("LIST_SPACING", { settings.LIST_SPACING }, { settings.LIST_SPACING = it }),
IntAttribute("MACRO_PLACEMENT", { settings.MACRO_PLACEMENT }, { settings.MACRO_PLACEMENT = it }),
IntAttribute("MACRO_SORT", { settings.MACRO_SORT }, { settings.MACRO_SORT = it }),
IntAttribute("NEW_BULLET_LIST_ITEM_MARKER", { settings.NEW_BULLET_LIST_ITEM_MARKER }, { settings.NEW_BULLET_LIST_ITEM_MARKER = it }),
IntAttribute("TASK_ITEM_CONTINUATION", { settings.TASK_ITEM_CONTINUATION }, { settings.TASK_ITEM_CONTINUATION = it }),
IntAttribute("REFERENCE_PLACEMENT", { settings.REFERENCE_PLACEMENT }, { settings.REFERENCE_PLACEMENT = it }),
IntAttribute("REFERENCE_SORT", { settings.REFERENCE_SORT }, { settings.REFERENCE_SORT = it }),
IntAttribute("RIGHT_MARGIN", { settings.RIGHT_MARGIN }, { settings.RIGHT_MARGIN = it }),
IntAttribute("SPACE_AFTER_ATX_MARKER", { settings.SPACE_AFTER_ATX_MARKER }, { settings.SPACE_AFTER_ATX_MARKER = it }),
IntAttribute("TAB_SIZE", { settings.TAB_SIZE }, { settings.TAB_SIZE = it }),
IntAttribute("TABLE_CAPTION", { settings.TABLE_CAPTION }, { settings.TABLE_CAPTION = it }),
IntAttribute("TABLE_CAPTION_SPACES", { settings.TABLE_CAPTION_SPACES }, { settings.TABLE_CAPTION_SPACES = it }),
IntAttribute("TABLE_LEFT_ALIGN_MARKER", { settings.TABLE_LEFT_ALIGN_MARKER }, { settings.TABLE_LEFT_ALIGN_MARKER = it }),
IntAttribute("TASK_LIST_ITEM_CASE", { settings.TASK_LIST_ITEM_CASE }, { settings.TASK_LIST_ITEM_CASE = it }),
IntAttribute("TASK_LIST_ITEM_PLACEMENT", { settings.TASK_LIST_ITEM_PLACEMENT }, { settings.TASK_LIST_ITEM_PLACEMENT = it }),
IntAttribute("TOC_GENERATE_STRUCTURE", { settings.TOC_GENERATE_STRUCTURE }, { settings.TOC_GENERATE_STRUCTURE = it }),
IntAttribute("TOC_HEADING_LEVELS", { settings.TOC_HEADING_LEVELS }, { settings.TOC_HEADING_LEVELS = it }),
IntAttribute("TOC_TITLE_LEVEL", { settings.TOC_TITLE_LEVEL }, { settings.TOC_TITLE_LEVEL = it }),
IntAttribute("TOC_UPDATE_ON_DOC_FORMAT", { settings.TOC_UPDATE_ON_DOC_FORMAT }, { settings.TOC_UPDATE_ON_DOC_FORMAT = it }),
IntAttribute("WRAP_ON_TYPING", { settings.WRAP_ON_TYPING }, { settings.WRAP_ON_TYPING = it }),
StringAttribute("TOC_TITLE", { settings.TOC_TITLE }, { settings.TOC_TITLE = it }),
IntAttribute("FLEXMARK_EXAMPLE_KEEP_TRAILING_SPACES", true, { -2 }, { if (it != -2) settings.setTrailingSpacesOption(MdSpecExampleStripTrailingSpacesExtension.OPTION_ID, it); }),
HashMapItem<String, Int>("TRAILING_SPACES_OPTIONS",
{ settings.trailingSpacesOptions },
{ settings.trailingSpacesOptions.clear(); settings.trailingSpacesOptions.putAll(it); },
{ key, value -> Pair(key, TrailingSpacesType.ADAPTER.get(value).displayName) },
{ key, value -> Pair(key, TrailingSpacesType.ADAPTER.findEnum(value).intValue) }
)
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MdCodeStyleSettingsSerializable) return false
return settings == other.settings
}
override fun hashCode(): Int {
var result = 0
result = 31 * result + settings.hashCode()
return result
}
}
|
apache-2.0
|
602c3a9158994532deb1b97040ed8711
| 92.170543 | 186 | 0.699226 | 3.973223 | false | false | false | false |
find-sec-bugs/find-sec-bugs
|
findsecbugs-samples-kotlin/src/test/kotlin/com/h3xstream/findsecbugs/password/HardcodedPassword.kt
|
2
|
3269
|
package com.h3xstream.findsecbugs.password
abstract class EqualsPasswordField {
fun hardcodedLogin1(username: String, password: String): Boolean {
if (username == "admin") {
println("OK")
}
if (username == "abc") {
println("OK")
}
if (password == "@dm1n") { //!!
return true
}
return validateDb(username, password)
}
fun hardcodedLogin2(username: String, password: String): Boolean {
return if ("adm1nL3ft" == password) { //!!
true
} else validateDb(username, password)
}
fun hardcodedLogin3(username: String, p1: String): Boolean {
val password = p1
return if ("adm1nL3ft!!!!" == password) { //!! (Not supported at the moment)
true
} else validateDb(username, password)
}
fun safeLogin1(username: String, password: String): Boolean {
return if (password == "") {
true
} else validateDb(username, password)
}
fun safeLogin2(username: String, password: String): Boolean {
return if ("" == password) {
false
} else validateDb(username, password)
}
fun safeLogin3(username: String, password: String): Boolean {
return if (getPassword(username) == password) {
false
} else validateDb(username, password)
}
fun safeLogin4(username: String, password: String): Boolean {
return if (password == getPassword(username)) {
false
} else validateDb(username, password)
}
abstract fun validateDb(username: String, password: String): Boolean
abstract fun getPassword(username: String): String
}
fun hardcodedLogin1(username: String, password: String): Boolean {
if (username == "admin") {
println("OK")
}
if (username == "abc") {
println("OK")
}
if (password == "@dm1n") { //!!
return true
}
return validateDb(username, password)
}
fun hardcodedLogin2(username: String, password: String): Boolean {
return if ("adm1nL3ft" == password) { //!!
true
} else validateDb(username, password)
}
fun hardcodedLogin3(username: String, p1: String): Boolean {
val password = p1
return if ("adm1nL3ft!!!!" == password) { //!! (Not supported at the moment)
true
} else validateDb(username, password)
}
fun safeLogin1(username: String, password: String): Boolean {
return if (password == "") {
true
} else validateDb(username, password)
}
fun safeLogin2(username: String, password: String): Boolean {
return if ("" == password) {
false
} else validateDb(username, password)
}
fun safeLogin3(username: String, password: String): Boolean {
return if (getPassword(username) == password) {
false
} else validateDb(username, password)
}
fun safeLogin4(username: String, password: String): Boolean {
return if (password == getPassword(username)) {
false
} else validateDb(username, password)
}
fun validateDb(username: String, password: String): Boolean {
return false
}
fun getPassword(username: String): String {
throw IllegalStateException("Not implemented")
}
|
lgpl-3.0
|
e9f0822669198dc86d93069a65be3048
| 21.390411 | 84 | 0.607219 | 4.132743 | false | false | false | false |
paronos/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt
|
3
|
6752
|
package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* A simple implementation for sources from a website using Jsoup, an HTML parser.
*/
abstract class ParsedHttpSource : HttpSource() {
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(popularMangaSelector()).map { element ->
popularMangaFromElement(element)
}
val hasNextPage = popularMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
abstract protected fun popularMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [popularMangaSelector].
*/
abstract protected fun popularMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
abstract protected fun popularMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(searchMangaSelector()).map { element ->
searchMangaFromElement(element)
}
val hasNextPage = searchMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
abstract protected fun searchMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [searchMangaSelector].
*/
abstract protected fun searchMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
abstract protected fun searchMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(latestUpdatesSelector()).map { element ->
latestUpdatesFromElement(element)
}
val hasNextPage = latestUpdatesNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
abstract protected fun latestUpdatesSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [latestUpdatesSelector].
*/
abstract protected fun latestUpdatesFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
abstract protected fun latestUpdatesNextPageSelector(): String?
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response): SManga {
return mangaDetailsParse(response.asJsoup())
}
/**
* Returns the details of the manga from the given [document].
*
* @param document the parsed document.
*/
abstract protected fun mangaDetailsParse(document: Document): SManga
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
return document.select(chapterListSelector()).map { chapterFromElement(it) }
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter.
*/
abstract protected fun chapterListSelector(): String
/**
* Returns a chapter from the given element.
*
* @param element an element obtained from [chapterListSelector].
*/
abstract protected fun chapterFromElement(element: Element): SChapter
/**
* Parses the response from the site and returns the page list.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response): List<Page> {
return pageListParse(response.asJsoup())
}
/**
* Returns a page list from the given document.
*
* @param document the parsed document.
*/
abstract protected fun pageListParse(document: Document): List<Page>
/**
* Parse the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response): String {
return imageUrlParse(response.asJsoup())
}
/**
* Returns the absolute url to the source image from the document.
*
* @param document the parsed document.
*/
abstract protected fun imageUrlParse(document: Document): String
}
|
apache-2.0
|
6931819c06e6ef2590386832e870c37a
| 31.76 | 97 | 0.647512 | 5.201849 | false | false | false | false |
aedans/M
|
src/main/kotlin/io/github/aedans/m/Environment.kt
|
1
|
4543
|
package io.github.aedans.m
import io.github.aedans.kons.*
import java.io.File
import java.io.InputStream
import java.io.OutputStream
/**
* Created by Aedan Smith.
*/
data class RuntimeEnvironment(val symbolTable: SymbolTable, val memory: Memory) {
fun getVar(name: String) = symbolTable.getLocation(name)?.toAccessible()?.get(memory)
fun setVar(name: String, obj: Any) {
val location = symbolTable.allocateLocation(name)
symbolTable.setLocation(name, location)
location.toAccessible().set(memory, obj)
}
}
fun getDefaultRuntimeEnvironment(
`in`: InputStream = System.`in`,
out: OutputStream = System.out,
err: OutputStream = System.err
) = RuntimeEnvironment(IRSymbolTable(), Memory(Heap(0) { Nil }, Stack())).apply {
setVar("true", true)
setVar("false", false)
setVar("nil", Nil)
setVar("cons", mFunction<Any, Cons<Any>, Cons<Any>> { a, b -> a cons b })
setVar("car", mFunction(Cons<Any>::car))
setVar("cdr", mFunction(Cons<Any>::cdr))
setVar("!", mFunction(Boolean::not))
setVar("|", mFunction(Boolean::or))
setVar("&", mFunction(Boolean::and))
setVar("=", mFunction(Any::equals))
setVar("+i", mFunction<Int, Int, Int>(Int::plus))
setVar("-i", mFunction<Int, Int, Int>(Int::minus))
setVar("*i", mFunction<Int, Int, Int>(Int::times))
setVar("/i", mFunction<Int, Int, Int>(Int::div))
setVar("%i", mFunction<Int, Int, Int>(Int::rem))
setVar("+l", mFunction<Long, Long, Long>(Long::plus))
setVar("-l", mFunction<Long, Long, Long>(Long::minus))
setVar("*l", mFunction<Long, Long, Long>(Long::times))
setVar("/l", mFunction<Long, Long, Long>(Long::div))
setVar("%l", mFunction<Long, Long, Long>(Long::rem))
setVar("+f", mFunction<Float, Float, Float>(Float::plus))
setVar("-f", mFunction<Float, Float, Float>(Float::minus))
setVar("*f", mFunction<Float, Float, Float>(Float::times))
setVar("/f", mFunction<Float, Float, Float>(Float::div))
setVar("%f", mFunction<Float, Float, Float>(Float::rem))
setVar("+d", mFunction<Double, Double, Double>(Double::plus))
setVar("-d", mFunction<Double, Double, Double>(Double::minus))
setVar("*d", mFunction<Double, Double, Double>(Double::times))
setVar("/d", mFunction<Double, Double, Double>(Double::div))
setVar("%d", mFunction<Double, Double, Double>(Double::rem))
setVar("<i", mFunction { x: Int, y: Int -> x < y })
setVar(">i", mFunction { x: Int, y: Int -> x > y })
setVar("<l", mFunction { x: Long, y: Long -> x < y })
setVar(">l", mFunction { x: Long, y: Long -> x > y })
setVar("<f", mFunction { x: Float, y: Float -> x < y })
setVar(">f", mFunction { x: Float, y: Float -> x > y })
setVar("<d", mFunction { x: Double, y: Double -> x < y })
setVar(">d", mFunction { x: Double, y: Double -> x > y })
setVar("stdin", `in`)
setVar("stdout", out)
setVar("stderr", err)
setVar("write", mFunction<OutputStream, Char, Unit> { p, c -> p.write(c.toInt()) })
setVar("read", mFunction<InputStream, Char> { i -> i.read().toChar() })
setVar("newline", '\n')
setVar("string", mFunction<Any, Cons<Char>> { it.toString().asIterable().toCons() })
setVar("defmacro", Macro { it: Any ->
val name = ((it as Cons<*>).car as IdentifierExpression).name
val lambda = it.unsafeCdr.car as Cons<*>
@Suppress("UNCHECKED_CAST")
val macro = Macro(lambda.toIRExpression(symbolTable).toEvaluable().eval(memory) as MFunction)
setVar(name, macro)
Nil
})
setVar("include", Macro { it: Any ->
@Suppress("UNCHECKED_CAST")
val name = ((it as Cons<*>).car as IdentifierExpression).name
val file = File(name).absoluteFile
if (file.isDirectory)
file
.listFiles()
.map { consOf(IdentifierExpression("include"), IdentifierExpression("$file/${it.nameWithoutExtension}")) }
.let { IdentifierExpression("do") cons it.toConsList() }
else
File(file.absolutePath + ".m")
.reader()
.iterator()
.lookaheadIterator()
.parse()
.asSequence()
.toList()
.let { IdentifierExpression("do") cons it.toConsList() }
})
setVar("macroexpand", Macro { it: Any ->
@Suppress("UNCHECKED_CAST")
QuoteExpression((it as SExpression).unsafeCar.expand(this))
})
}
|
mit
|
9dfd6306445b08aa9577a2a3d0dbf526
| 39.927928 | 126 | 0.59234 | 3.690496 | false | false | false | false |
microg/android_packages_apps_GmsCore
|
play-services-maps-core-mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/UiSettings.kt
|
1
|
4002
|
/*
* Copyright (C) 2019 microG Project Team
*
* 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.microg.gms.maps.mapbox
import android.os.Parcel
import android.os.RemoteException
import android.util.Log
import com.google.android.gms.maps.internal.IUiSettingsDelegate
import com.mapbox.mapboxsdk.maps.UiSettings
class UiSettingsImpl(private val uiSettings: UiSettings) : IUiSettingsDelegate.Stub() {
override fun setZoomControlsEnabled(zoom: Boolean) {
Log.d(TAG, "unimplemented Method: setZoomControlsEnabled")
}
override fun setCompassEnabled(compass: Boolean) {
uiSettings.isCompassEnabled = compass
}
override fun setMyLocationButtonEnabled(locationButton: Boolean) {
Log.d(TAG, "unimplemented Method: setMyLocationButtonEnabled")
}
override fun setScrollGesturesEnabled(scrollGestures: Boolean) {
uiSettings.isScrollGesturesEnabled = scrollGestures
}
override fun setZoomGesturesEnabled(zoomGestures: Boolean) {
uiSettings.isZoomGesturesEnabled = zoomGestures
}
override fun setTiltGesturesEnabled(tiltGestures: Boolean) {
uiSettings.isTiltGesturesEnabled = tiltGestures
}
override fun setRotateGesturesEnabled(rotateGestures: Boolean) {
uiSettings.isRotateGesturesEnabled = rotateGestures
}
override fun setAllGesturesEnabled(gestures: Boolean) {
uiSettings.setAllGesturesEnabled(gestures)
}
override fun isZoomControlsEnabled(): Boolean {
Log.d(TAG, "unimplemented Method: isZoomControlsEnabled")
return false
}
override fun isCompassEnabled(): Boolean = uiSettings.isCompassEnabled
override fun isMyLocationButtonEnabled(): Boolean {
Log.d(TAG, "unimplemented Method: isMyLocationButtonEnabled")
return false
}
override fun isScrollGesturesEnabled(): Boolean = uiSettings.isScrollGesturesEnabled
override fun isZoomGesturesEnabled(): Boolean = uiSettings.isZoomGesturesEnabled
override fun isTiltGesturesEnabled(): Boolean = uiSettings.isTiltGesturesEnabled
override fun isRotateGesturesEnabled(): Boolean = uiSettings.isRotateGesturesEnabled
override fun setIndoorLevelPickerEnabled(indoorLevelPicker: Boolean) {
Log.d(TAG, "unimplemented Method: setIndoorLevelPickerEnabled")
}
override fun isIndoorLevelPickerEnabled(): Boolean {
Log.d(TAG, "unimplemented Method: isIndoorLevelPickerEnabled")
return false
}
override fun setMapToolbarEnabled(mapToolbar: Boolean) {
Log.d(TAG, "unimplemented Method: setMapToolbarEnabled")
}
override fun isMapToolbarEnabled(): Boolean {
Log.d(TAG, "unimplemented Method: isMapToolbarEnabled")
return false
}
override fun setScrollGesturesEnabledDuringRotateOrZoom(scrollDuringZoom: Boolean) {
Log.d(TAG, "unimplemented Method: setScrollGesturesEnabledDuringRotateOrZoom")
}
override fun isScrollGesturesEnabledDuringRotateOrZoom(): Boolean {
Log.d(TAG, "unimplemented Method: isScrollGesturesEnabledDuringRotateOrZoom")
return true
}
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean =
if (super.onTransact(code, data, reply, flags)) {
true
} else {
Log.d(TAG, "onTransact [unknown]: $code, $data, $flags"); false
}
companion object {
private val TAG = "GmsMapsUi"
}
}
|
apache-2.0
|
a1d78c99d2d858bb4042360f39061c6a
| 32.915254 | 91 | 0.723888 | 4.845036 | false | false | false | false |
Retronic/life-in-space
|
core/src/main/kotlin/com/retronicgames/lis/ui/LISSkin.kt
|
1
|
4664
|
package com.retronicgames.lis.ui
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.ui.List
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable
import com.retronicgames.lis.manager.Assets
import com.retronicgames.utils.RGDialog
object LISSkin : Skin() {
// FIXME: All these fonts should be part of a texture atlas, instead of creating a texture per font
private val fontDefault = createFont("default", "fonts/PixelOperator/PixelOperator.ttf", 15)
private val fontDefaultBold = createFont("defaultBold", "fonts/PixelOperator/PixelOperator-Bold.ttf", 15)
val MAIN_PALETTE = intArrayOf(0xD9D5C3FF.toInt(), 0x999082FF.toInt(), 0x575B67FF, 0x3D3940FF)
val MAIN_PALETTE_COLORS = MAIN_PALETTE.map { Color(it) }.toTypedArray()
init {
addStyleLabel()
addStyleButton()
addStyleDialog()
addStyleList()
addStyleScrollPane()
}
private fun addStyleLabel() {
val style = Label.LabelStyle(fontDefault, MAIN_PALETTE_COLORS[3])
add("default", style)
val stylePanel1 = Label.LabelStyle(fontDefault, MAIN_PALETTE_COLORS[3])
stylePanel1.background = drawable9("panel1")
add("panel1", stylePanel1)
val stylePanel2 = Label.LabelStyle(fontDefault, MAIN_PALETTE_COLORS[3])
stylePanel2.background = drawable9("panel2")
add("panel2", stylePanel2)
}
private fun addStyleButton() {
val style = Button.ButtonStyle(drawable9("buttonUp"), drawable9("buttonDown"), null)
style.over = drawable9("buttonOver")
add("default", style)
val styleText = TextButton.TextButtonStyle(drawable9("buttonUp"), drawable9("buttonDown"), null, fontDefaultBold)
styleText.fontColor = MAIN_PALETTE_COLORS[3]
styleText.over = drawable9("buttonOver")
add("default", styleText)
}
private fun addStyleDialog() {
val style = Window.WindowStyle(fontDefault, Color.BLACK, drawable9("backDialog"))
add("default", style)
}
private fun addStyleList() {
val style = List.ListStyle(fontDefault, MAIN_PALETTE_COLORS[0], MAIN_PALETTE_COLORS[2], drawable("listSelection"))
add("default", style)
}
private fun addStyleScrollPane() {
val style = ScrollPane.ScrollPaneStyle()
add("default", style)
}
fun button(upImageId: String, downImageId: String? = null): Button {
val upDrawable = drawable(upImageId)
val downDrawable = drawable(downImageId)
val style = Button.ButtonStyle(upDrawable, downDrawable, null)
return Button(style)
}
fun button9(upImageId: String, downImageId: String? = null): Button {
val upDrawable = drawable9(upImageId)
val downDrawable = drawable9(downImageId)
val style = Button.ButtonStyle(upDrawable, downDrawable, null)
return Button(style)
}
fun textButton9(text: String, textColor: Color, upImageId: String, downImageId: String? = null): Button {
val upDrawable = drawable9(upImageId)
val downDrawable = drawable9(downImageId)
val style = TextButton.TextButtonStyle(upDrawable, downDrawable, null, fontDefault)
style.fontColor = textColor
return TextButton(text, style)
}
fun dialog(title: String): RGDialog {
val result = RGDialog(title, this)
result.isMovable = false
result.isModal = true
return result
}
private fun createFont(fontName: String, fontPath: String, fontSize: Int): BitmapFont {
val parameter = FreeTypeFontGenerator.FreeTypeFontParameter();
val generator = FreeTypeFontGenerator(Gdx.files.internal(fontPath));
parameter.size = scaled(fontSize);
parameter.kerning = true
val font = generator.generateFont(parameter);
font.color = Color.BLACK;
add(fontName, font)
generator.dispose()
return font
}
private fun scaled(fontSize: Int) = fontSize
@Suppress("NOTHING_TO_INLINE")
private inline fun drawable(id: String?) = if (id != null) SpriteDrawable(Assets.sprite("ui", id)) else null
@Suppress("NOTHING_TO_INLINE")
private inline fun drawable9(id: String?) = if (id != null) NinePatchDrawable(Assets.ninePatch("ui", id)) else null
fun wrappedLabel(text: String): Label {
val result = Label(text, this)
result.setWrap(true)
return result
}
fun <T> scrollList(vararg items: T): ScrollPane {
val list = com.badlogic.gdx.scenes.scene2d.ui.List<T>(this)
list.setItems(*items)
val scroll = ScrollPane(list, this)
return scroll
}
fun panel(id: String): Table {
val result = Table(LISSkin)
result.background = drawable9(id)
return result
}
fun image(atlas: String, id: String) = Image(Assets.sprite(atlas, id))
}
|
gpl-3.0
|
4b83fe85ea32e268b8b9e921bf28df0b
| 29.690789 | 116 | 0.746998 | 3.41685 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/wildplot/android/parsing/Atom.kt
|
1
|
5827
|
/****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.parsing
import com.wildplot.android.parsing.Atom.AtomType.*
import com.wildplot.android.parsing.AtomTypes.*
class Atom(private val parser: TopLevelParser) : TreeElement {
var atomType: AtomType = INVALID
private lateinit var atomObject: TreeElement
private lateinit var expression: Expression
enum class AtomType {
VARIABLE, NUMBER, EXP_IN_BRACKETS, FUNCTION_MATH, FUNCTION_X, FUNCTION_X_Y, INVALID
}
constructor(atomString: String, parser: TopLevelParser) : this(parser) {
val isValid: Boolean = TopLevelParser.stringHasValidBrackets(atomString) &&
(
initAsExpInBrackets(atomString) ||
initAsFunctionMath(atomString) ||
initAsFunctionX(atomString) ||
initAsFunctionXY(atomString) ||
initAsNumber(atomString) ||
initAsXVariable(atomString) ||
initAsYVariable(atomString) ||
initAsVariable(atomString)
)
if (!isValid) {
atomType = INVALID
}
}
private fun initAsExpInBrackets(atomString: String): Boolean {
return if (atomString.isNotEmpty() && atomString.startsWith('(') && atomString.endsWith(')')) {
val expressionString = atomString.substring(1, atomString.length - 1)
val expressionInBrackets = Expression(expressionString, parser)
if (expressionInBrackets.expressionType != Expression.ExpressionType.INVALID) {
expression = expressionInBrackets
atomType = EXP_IN_BRACKETS
true
} else false
} else
false
}
private fun initAsFunctionMath(atomString: String): Boolean {
val mathFunctionAtom = MathFunctionAtom(atomString, parser)
return if (mathFunctionAtom.mathType != MathFunctionAtom.MathType.INVALID) {
atomType = FUNCTION_MATH
atomObject = mathFunctionAtom
true
} else false
}
private fun initAsFunctionX(atomString: String): Boolean {
val functionXAtom = FunctionXAtom(atomString, parser)
return if (functionXAtom.atomType != INVALID) {
atomType = FUNCTION_X
atomObject = functionXAtom
true
} else false
}
private fun initAsFunctionXY(atomString: String): Boolean {
val functionXYAtom = FunctionXYAtom(atomString, parser)
return if (functionXYAtom.atomType != INVALID) {
atomType = FUNCTION_X_Y
atomObject = functionXYAtom
true
} else false
}
private fun initAsNumber(atomString: String): Boolean {
val numberAtom = NumberAtom(atomString)
return if (numberAtom.getAtomType() !== INVALID) {
atomType = numberAtom.getAtomType()
atomObject = numberAtom
true
} else false
}
private fun initAsXVariable(atomString: String): Boolean {
return if (atomString == parser.getxName()) {
atomType = VARIABLE
atomObject = XVariableAtom(parser)
true
} else false
}
private fun initAsYVariable(atomString: String): Boolean {
return if (atomString == parser.getyName()) {
atomType = VARIABLE
atomObject = YVariableAtom(parser)
true
} else false
}
private fun initAsVariable(atomString: String): Boolean {
val variableAtom = VariableAtom(atomString, parser)
return if (variableAtom.atomType !== INVALID) {
atomType = variableAtom.atomType
atomObject = variableAtom
true
} else false
}
@get:Throws(ExpressionFormatException::class)
override val value: Double
get() = when (atomType) {
EXP_IN_BRACKETS -> expression.value
VARIABLE, NUMBER, FUNCTION_MATH, FUNCTION_X, FUNCTION_X_Y -> atomObject.value
INVALID -> throw ExpressionFormatException("Cannot parse Atom object")
}
@get:Throws(ExpressionFormatException::class)
override val isVariable: Boolean
get() = when (atomType) {
EXP_IN_BRACKETS -> expression.isVariable
VARIABLE, NUMBER, FUNCTION_MATH, FUNCTION_X, FUNCTION_X_Y -> atomObject.isVariable
INVALID -> throw ExpressionFormatException("Cannot parse Atom object")
}
}
|
gpl-3.0
|
4bf8856b1d7f886eb272b83c25cefe0e
| 41.532847 | 103 | 0.565299 | 5.120387 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/user/ProfileFragment.kt
|
1
|
7634
|
package de.westnordost.streetcomplete.user
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import androidx.core.net.toUri
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osmnotes.NotesModule
import de.westnordost.streetcomplete.data.UnsyncedChangesCountSource
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.data.user.*
import de.westnordost.streetcomplete.data.user.achievements.AchievementsSource
import de.westnordost.streetcomplete.data.user.statistics.StatisticsSource
import de.westnordost.streetcomplete.databinding.FragmentProfileBinding
import de.westnordost.streetcomplete.ktx.createBitmap
import de.westnordost.streetcomplete.ktx.tryStartActivity
import de.westnordost.streetcomplete.ktx.viewBinding
import de.westnordost.streetcomplete.ktx.viewLifecycleScope
import kotlinx.coroutines.*
import java.io.File
import java.util.Locale
import javax.inject.Inject
/** Shows the user profile: username, avatar, star count and a hint regarding unpublished changes */
class ProfileFragment : Fragment(R.layout.fragment_profile) {
@Inject internal lateinit var userDataSource: UserDataSource
@Inject internal lateinit var userLoginStatusController: UserLoginStatusController
@Inject internal lateinit var userUpdater: UserUpdater
@Inject internal lateinit var statisticsSource: StatisticsSource
@Inject internal lateinit var achievementsSource: AchievementsSource
@Inject internal lateinit var unsyncedChangesCountSource: UnsyncedChangesCountSource
private lateinit var anonAvatar: Bitmap
private val binding by viewBinding(FragmentProfileBinding::bind)
private val unsyncedChangesCountListener = object : UnsyncedChangesCountSource.Listener {
override fun onIncreased() { viewLifecycleScope.launch { updateUnpublishedQuestsText() } }
override fun onDecreased() { viewLifecycleScope.launch { updateUnpublishedQuestsText() } }
}
private val questStatisticsDaoListener = object : StatisticsSource.Listener {
override fun onAddedOne(questType: QuestType<*>) {
viewLifecycleScope.launch { updateSolvedQuestsText() }
}
override fun onSubtractedOne(questType: QuestType<*>) {
viewLifecycleScope.launch { updateSolvedQuestsText() }
}
override fun onUpdatedAll() {
viewLifecycleScope.launch { updateStatisticsTexts() }
}
override fun onCleared() {
viewLifecycleScope.launch { updateStatisticsTexts() }
}
override fun onUpdatedDaysActive() {
viewLifecycleScope.launch { updateDaysActiveText() }
}
}
private val userListener = object : UserDataSource.Listener {
override fun onUpdated() { viewLifecycleScope.launch { updateUserName() } }
}
private val userAvatarListener = object : UserUpdater.Listener {
override fun onUserAvatarUpdated() { viewLifecycleScope.launch { updateAvatar() } }
}
init {
Injector.applicationComponent.inject(this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
anonAvatar = context.getDrawable(R.drawable.ic_osm_anon_avatar)!!.createBitmap()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.logoutButton.setOnClickListener {
userLoginStatusController.logOut()
}
binding.profileButton.setOnClickListener {
openUrl("https://www.openstreetmap.org/user/" + userDataSource.userName)
}
}
override fun onStart() {
super.onStart()
viewLifecycleScope.launch {
userDataSource.addListener(userListener)
userUpdater.addUserAvatarListener(userAvatarListener)
statisticsSource.addListener(questStatisticsDaoListener)
unsyncedChangesCountSource.addListener(unsyncedChangesCountListener)
updateUserName()
updateAvatar()
updateSolvedQuestsText()
updateUnpublishedQuestsText()
updateDaysActiveText()
updateGlobalRankText()
updateLocalRankText()
updateAchievementLevelsText()
}
}
override fun onStop() {
super.onStop()
unsyncedChangesCountSource.removeListener(unsyncedChangesCountListener)
statisticsSource.removeListener(questStatisticsDaoListener)
userDataSource.removeListener(userListener)
userUpdater.removeUserAvatarListener(userAvatarListener)
}
private fun updateUserName() {
binding.userNameTextView.text = userDataSource.userName
}
private fun updateAvatar() {
val cacheDir = NotesModule.getAvatarsCacheDirectory(requireContext())
val avatarFile = File(cacheDir.toString() + File.separator + userDataSource.userId)
val avatar = if (avatarFile.exists()) BitmapFactory.decodeFile(avatarFile.path) else anonAvatar
binding.userAvatarImageView.setImageBitmap(avatar)
}
private suspend fun updateStatisticsTexts() {
updateSolvedQuestsText()
updateDaysActiveText()
updateGlobalRankText()
updateLocalRankText()
}
private suspend fun updateSolvedQuestsText() {
binding.solvedQuestsText.text = withContext(Dispatchers.IO) { statisticsSource.getSolvedCount().toString() }
}
private suspend fun updateUnpublishedQuestsText() {
val unsyncedChanges = unsyncedChangesCountSource.getCount()
binding.unpublishedQuestsText.text = getString(R.string.unsynced_quests_description, unsyncedChanges)
binding.unpublishedQuestsText.isGone = unsyncedChanges <= 0
}
private fun updateDaysActiveText() {
val daysActive = statisticsSource.daysActive
binding.daysActiveContainer.isGone = daysActive <= 0
binding.daysActiveText.text = daysActive.toString()
}
private fun updateGlobalRankText() {
val rank = statisticsSource.rank
binding.globalRankContainer.isGone = rank <= 0 || statisticsSource.getSolvedCount() <= 100
binding.globalRankText.text = "#$rank"
}
private suspend fun updateLocalRankText() {
val statistics = withContext(Dispatchers.IO) {
statisticsSource.getCountryStatisticsOfCountryWithBiggestSolvedCount()
}
if (statistics == null) binding.localRankContainer.isGone = true
else {
val shouldShow = statistics.rank != null && statistics.rank > 0 && statistics.solvedCount > 50
val countryLocale = Locale("", statistics.countryCode)
binding.localRankContainer.isGone = !shouldShow
binding.localRankText.text = "#${statistics.rank}"
binding.localRankLabel.text = getString(R.string.user_profile_local_rank, countryLocale.displayCountry)
}
}
private suspend fun updateAchievementLevelsText() {
val levels = withContext(Dispatchers.IO) { achievementsSource.getAchievements().sumOf { it.second } }
binding.achievementLevelsContainer.isGone = levels <= 0
binding.achievementLevelsText.text = "$levels"
}
private fun openUrl(url: String): Boolean {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
return tryStartActivity(intent)
}
}
|
gpl-3.0
|
4cc94eb4526e01eba991a1cad6189281
| 40.264865 | 116 | 0.725832 | 4.979778 | false | false | false | false |
tokenbrowser/token-android-client
|
app/src/main/java/com/toshi/util/sharedPrefs/AppPrefsInterface.kt
|
1
|
2167
|
/*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.util.sharedPrefs
import com.toshi.model.local.network.Network
interface AppPrefsInterface {
companion object {
const val HAS_ONBOARDED = "hasOnboarded"
const val HAS_SIGNED_OUT = "hasSignedIn"
const val HAS_BACKED_UP_PHRASE = "hasBackedUpPhrase"
const val HAS_LOADED_APP_FIRST_TIME = "hasLoadedAppFirstTime"
const val LOCAL_CURRENCY_CODE = "localCurrencyCode"
const val WAS_MIGRATED = "wasMigrated"
const val FORCE_USER_UPDATE = "forceUserUpdate_2"
const val CURRENT_NETWORK = "currentNetwork"
const val HAS_CLEARED_NOTIFICATION_CHANNELS = "hasClearedNotificationChannels"
}
fun hasOnboarded(): Boolean
fun setHasOnboarded(hasOnboarded: Boolean)
fun hasLoadedApp(): Boolean
fun setHasLoadedApp()
fun setSignedIn()
fun setSignedOut()
fun hasSignedOut(): Boolean
fun setHasBackedUpPhrase()
fun hasBackedUpPhrase(): Boolean
fun saveCurrency(currencyCode: String)
fun getCurrency(): String
fun getCurrencyFromLocaleAndSave(): String
fun setWasMigrated(wasMigrated: Boolean)
fun wasMigrated(): Boolean
fun setForceUserUpdate(forceUpdate: Boolean)
fun shouldForceUserUpdate(): Boolean
fun setCurrentNetwork(network: Network)
fun getCurrentNetworkId(): String?
fun setHasClearedNotificationChannels()
fun hasClearedNotificationChannels(): Boolean
fun clear()
}
|
gpl-3.0
|
8e0579b35bd66baf51a7a75164c41485
| 37.035088 | 86 | 0.714813 | 4.274162 | false | false | false | false |
Fargren/kotlin-map-alarm
|
app/src/main/java/epsz/mapalarm/MapActivity.kt
|
1
|
3907
|
package epsz.mapalarm
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.widget.Toast
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.mapalarm.datatypes.Position
import com.mapalarm.usecases.*
import kotlinx.android.synthetic.main.activity_map.*
class MapActivity : FragmentActivity(), OnMapReadyCallback, MapUI {
private val presenter = MapUIPresenter(this)
lateinit private var controller:MapActivityController
lateinit private var map: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
controller = MapActivityController(presenter, ToastAlarm(this), AddTriggerUseCase(presenter))
setContentView(R.layout.activity_map)
loadMap()
this.add_alarm_button.setOnClickListener({
enterEditMode()
})
}
private fun loadMap() {
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
createMap(googleMap)
controller.refreshPosition()
controller.listAllTriggers()
}
private fun createMap(googleMap: GoogleMap) {
googleMap.isMyLocationEnabled = true
map = googleMap
map.setOnMapClickListener {
controller.addTrigger(it)
exitEditMode()
}
}
private fun enterEditMode() {
controller.editMode = true
this.toolbar_title.setText(R.string.instructions_add_mode)
}
private fun exitEditMode() {
controller.editMode = false
this.toolbar_title.setText(R.string.app_name)
}
override fun moveMapTo(latitude: Double, longitude: Double) {
val here = LatLng(latitude, longitude)
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(here, 14f))
animateCamera(CameraUpdateFactory.newLatLng(LatLng(latitude, longitude)))
}
}
override fun showUpdatingPositionToast() {
throw UnsupportedOperationException()
}
override fun showCircleAt(pos: Position, radius: Double) {
map.addCircle(CircleOptions()
.center(LatLng(pos.latitude, pos.longitude))
.radius(radius)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
}
}
class ToastAlarm(val context: Context) : AlarmPresenter {
override fun ring() {
Toast.makeText(context, "Alarm!", Toast.LENGTH_LONG).show()
}
}
class MapActivityController(val presenter: MapUIPresenter,
val alarm: AlarmPresenter,
val addTriggerUseCase: AddTrigger) : MapUIController {
var editMode: Boolean = false
private val moveUseCase = MoveUseCase(presenter, alarm)
private val listTriggersUseCase = ListTriggersUseCase(presenter)
override fun refreshPosition() {
moveUseCase.refreshPosition()
}
override fun listAllTriggers() {
listTriggersUseCase.listAll()
}
override fun addTrigger(position: LatLng) {
if (editMode)
addTriggerUseCase.addTriggerAt(Position(position.latitude, position.longitude))
}
}
interface MapUIController {
open fun addTrigger(position: LatLng)
open fun refreshPosition()
open fun listAllTriggers()
}
interface MapUI {
open fun moveMapTo(latitude: Double, longitude: Double)
open fun showUpdatingPositionToast()
open fun showCircleAt(pos: Position, radius: Double)
}
|
mit
|
57c9880506724e2f2899e122b00f1aea
| 29.523438 | 101 | 0.693371 | 4.684652 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/provider/MechanicsProvider.kt
|
1
|
1126
|
package com.boardgamegeek.provider
import android.net.Uri
import com.boardgamegeek.provider.BggContract.Mechanics
import com.boardgamegeek.provider.BggContract.Companion.PATH_MECHANICS
import com.boardgamegeek.provider.BggDatabase.Tables
class MechanicsProvider : BasicProvider() {
override fun getType(uri: Uri) = Mechanics.CONTENT_TYPE
override val path = PATH_MECHANICS
override val table = Tables.MECHANICS
override val defaultSortOrder = Mechanics.DEFAULT_SORT
override val insertedIdColumn = Mechanics.Columns.MECHANIC_ID
override fun buildExpandedSelection(uri: Uri, projection: Array<String>?): SelectionBuilder {
val builder = SelectionBuilder()
.mapToTable(Mechanics.Columns.MECHANIC_ID, table)
if (projection.orEmpty().contains(Mechanics.Columns.ITEM_COUNT)) {
builder
.table(Tables.MECHANICS_JOIN_COLLECTION)
.groupBy("$table.${Mechanics.Columns.MECHANIC_ID}")
.mapAsCount(Mechanics.Columns.ITEM_COUNT)
} else {
builder.table(table)
}
return builder
}
}
|
gpl-3.0
|
aad034e50d6cedb43b8a6987e97b7730
| 33.121212 | 97 | 0.702487 | 4.614754 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss-client-android/src/com/hendraanggrian/openpss/ui/BaseFragments.kt
|
1
|
2666
|
package com.hendraanggrian.openpss.ui
import android.app.Dialog
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.preference.DialogPreference
import com.hendraanggrian.bundler.Extra
import com.hendraanggrian.bundler.bindExtras
import com.hendraanggrian.openpss.AndroidComponent
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.prefy.android.AndroidPreferences
import com.takisoft.preferencex.PreferenceFragmentCompat
import java.util.ResourceBundle
open class BaseFragment : Fragment(), AndroidComponent {
override val prefs: AndroidPreferences get() = openpssActivity.prefs
override val rootLayout: View get() = openpssActivity.rootLayout
override val login: Employee get() = openpssActivity.login
override val resourceBundle: ResourceBundle get() = openpssActivity.resourceBundle
inline val openpssActivity: Activity get() = activity as Activity
}
abstract class BasePreferenceFragment : PreferenceFragmentCompat(), AndroidComponent {
override val prefs: AndroidPreferences get() = openpssActivity.prefs
override val rootLayout: View get() = openpssActivity.rootLayout
override val login: Employee get() = openpssActivity.login
override val resourceBundle: ResourceBundle get() = openpssActivity.resourceBundle
inline val openpssActivity: Activity get() = activity as Activity
inline var DialogPreference.titleAll: CharSequence?
get() = title
set(value) {
title = value
dialogTitle = value
}
}
open class BaseDialogFragment : AppCompatDialogFragment(), AndroidComponent {
override val prefs: AndroidPreferences get() = openpssActivity.prefs
override val rootLayout: View get() = openpssActivity.rootLayout
override val login: Employee get() = openpssActivity.login
override val resourceBundle: ResourceBundle get() = openpssActivity.resourceBundle
inline val openpssActivity: Activity get() = activity as Activity
fun show(manager: FragmentManager) = show(manager, null)
fun args(bundle: Bundle): BaseDialogFragment = apply { arguments = bundle }
}
class TextDialogFragment : BaseDialogFragment() {
@Extra lateinit var text: String
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
bindExtras()
return AlertDialog.Builder(context!!)
.setMessage(text)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.create()
}
}
|
apache-2.0
|
28c0d2360707080cc1c0e42f19a804e2
| 32.746835 | 86 | 0.760315 | 5.020716 | false | false | false | false |
raatiniemi/worker
|
app/src/main/java/me/raatiniemi/worker/features/projects/ProjectsModule.kt
|
1
|
2043
|
/*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.features.projects
import me.raatiniemi.worker.domain.interactor.*
import me.raatiniemi.worker.features.projects.createproject.viewmodel.CreateProjectViewModel
import me.raatiniemi.worker.features.projects.viewmodel.ClockActivityViewModel
import me.raatiniemi.worker.features.projects.viewmodel.ProjectsViewModel
import me.raatiniemi.worker.features.projects.viewmodel.RefreshActiveProjectsViewModel
import me.raatiniemi.worker.features.projects.viewmodel.RemoveProjectViewModel
import org.koin.android.viewmodel.ext.koin.viewModel
import org.koin.dsl.module.module
val projectsModule = module {
single {
val getProjects = GetProjects(get())
val getProjectTimeSince = GetProjectTimeSince(get())
ProjectsViewModel.ViewModel(getProjects, getProjectTimeSince)
}
single {
val clockIn = ClockIn(get())
val clockOut = ClockOut(get())
val getProjectTimeSince = GetProjectTimeSince(get())
ClockActivityViewModel.ViewModel(clockIn, clockOut, getProjectTimeSince)
}
single {
RemoveProjectViewModel.ViewModel(RemoveProject(get()))
}
single { RefreshActiveProjectsViewModel.ViewModel() }
viewModel {
val findProject = FindProject(get())
val createProject = CreateProject(findProject, get())
CreateProjectViewModel(createProject, findProject)
}
}
|
gpl-2.0
|
96edf2fb162a4254fe95b58b9b245b6f
| 35.482143 | 92 | 0.755751 | 4.480263 | false | false | false | false |
mercadopago/px-android
|
px-services/src/main/java/com/mercadopago/android/px/internal/core/ProductIdProvider.kt
|
1
|
932
|
package com.mercadopago.android.px.internal.core
import android.content.SharedPreferences
class ProductIdProvider(private val sharedPreferences: SharedPreferences) {
private var internalProductId: String? = null
val productId: String
get() {
if (internalProductId == null) {
internalProductId = sharedPreferences.getString(PREF_PRODUCT_ID, DEFAULT_PRODUCT_ID)
}
return internalProductId!!
}
fun configure(productId: String) {
internalProductId = productId
sharedPreferences.edit().putString(PREF_PRODUCT_ID, productId).apply()
}
fun clear() {
internalProductId = DEFAULT_PRODUCT_ID
sharedPreferences.edit().remove(PREF_PRODUCT_ID).apply()
}
companion object {
const val DEFAULT_PRODUCT_ID = "BJEO9NVBF6RG01IIIOTG"
private const val PREF_PRODUCT_ID = "PREF_HEADER_PRODUCT_ID"
}
}
|
mit
|
6942e4becb1513308cc14762fcd55932
| 30.1 | 100 | 0.668455 | 4.591133 | false | false | false | false |
MehdiK/Humanizer.jvm
|
test/main/kotlin/org/humanizer/jvm/tests/DateHumanizerTests.kt
|
1
|
5260
|
package org.humanizer.jvm.tests
import org.humanizer.jvm.humanize
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.givenData
import org.jetbrains.spek.api.shouldEqual
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import org.junit.Test as Test
public class DateHumanizerTests(): Spek() {
// TODO: Output of tests isn't clear. What it timeunit?
data class ParamClass(val timeUnit: Int
,val input: Int
,val expected: String
,val dateToUse: Date = GregorianCalendar(2014,Calendar.JANUARY, 5).getTime()){
override fun toString(): String {
return "a date and $input"
}
}
init {
val data = listOf(
ParamClass(Calendar.SECOND, -1, "one second ago"),
ParamClass(Calendar.SECOND, -10 , "10 seconds ago"),
ParamClass(Calendar.SECOND, -59 , "59 seconds ago"),
ParamClass(Calendar.SECOND, -60 , "a minute ago"),
ParamClass(Calendar.SECOND, 1 , "one second from now"),
ParamClass(Calendar.SECOND, 10 , "10 seconds from now"),
ParamClass(Calendar.SECOND, 59 , "59 seconds from now"),
ParamClass(Calendar.SECOND, 60 , "a minute from now"),
ParamClass(Calendar.MINUTE,-1, "a minute ago"),
ParamClass(Calendar.MINUTE,-10, "10 minutes ago"),
ParamClass(Calendar.MINUTE,-59, "59 minutes ago"),
ParamClass(Calendar.MINUTE,-60, "an hour ago"),
ParamClass(Calendar.MINUTE,-119, "an hour ago"),
ParamClass(Calendar.MINUTE,-120, "2 hours ago"),
ParamClass(Calendar.MINUTE,1, "a minute from now"),
ParamClass(Calendar.MINUTE,10, "10 minutes from now"),
ParamClass(Calendar.MINUTE,59, "59 minutes from now"),
ParamClass(Calendar.MINUTE,60, "an hour from now"),
ParamClass(Calendar.MINUTE,119, "an hour from now"),
ParamClass(Calendar.MINUTE,120, "2 hours from now"),
ParamClass(Calendar.HOUR,-1, "an hour ago"),
ParamClass(Calendar.HOUR,-10, "10 hours ago"),
ParamClass(Calendar.HOUR,-23, "23 hours ago"),
ParamClass(Calendar.HOUR,-24, "yesterday"),
ParamClass(Calendar.HOUR,1, "an hour from now"),
ParamClass(Calendar.HOUR,10, "10 hours from now"),
ParamClass(Calendar.HOUR,23, "23 hours from now"),
ParamClass(Calendar.HOUR,24, "tomorrow"),
ParamClass(Calendar.DATE,-1, "yesterday"),
ParamClass(Calendar.DATE,-10, "10 days ago"),
ParamClass(Calendar.DATE,-28, "28 days ago"),
ParamClass(Calendar.DATE,-32, "one month ago"),
ParamClass(Calendar.DATE,1, "tomorrow"),
ParamClass(Calendar.DATE,10, "10 days from now"),
ParamClass(Calendar.DATE,28, "28 days from now"),
ParamClass(Calendar.DATE,29, "one month from now",GregorianCalendar(2014,Calendar.FEBRUARY, 5).getTime()),
ParamClass(Calendar.DATE,32, "one month from now"),
ParamClass(Calendar.MONTH,-1, "one month ago"),
ParamClass(Calendar.MONTH,-10, "10 months ago"),
ParamClass(Calendar.MONTH,-11, "11 months ago"),
ParamClass(Calendar.MONTH,-12, "one year ago"),
ParamClass(Calendar.MONTH,1, "one month from now"),
ParamClass(Calendar.MONTH,10, "10 months from now"),
ParamClass(Calendar.MONTH,11, "11 months from now"),
ParamClass(Calendar.MONTH,12, "one year from now"),
ParamClass(Calendar.YEAR,-1, "one year ago"),
ParamClass(Calendar.YEAR,-2, "2 years ago"),
ParamClass(Calendar.YEAR,1, "one year from now"),
ParamClass(Calendar.YEAR,2, "2 years from now"),
ParamClass(Calendar.SECOND,0, "now"),
ParamClass(Calendar.MINUTE,0, "now"),
ParamClass(Calendar.HOUR,0, "now"),
ParamClass(Calendar.DAY_OF_YEAR,0, "now"),
ParamClass(Calendar.MONTH,0, "now"),
ParamClass(Calendar.YEAR,0, "now")
)
givenData(data) {
on("calling humanize with ${it.input} for timeunit ${it.timeUnit}", {
val cal = GregorianCalendar()
cal.setTime(it.dateToUse)
cal.add(it.timeUnit, it.input)
val actual = cal.getTime().humanize(it.dateToUse)
it("should be ${it.expected}", {
shouldEqual(it.expected, actual)
})
})
}
given("date that is 1 year in the future") {
on("calling humanize against current date", {
val cal = GregorianCalendar()
cal.add(Calendar.MONTH, 13)
val actual = cal.getTime().humanize()
it("should be one year from now", {
shouldEqual("one year from now", actual)
})
})
}
}}
|
apache-2.0
|
4029469d6444a0e994ddfb0816bd64b2
| 48.158879 | 122 | 0.556464 | 4.329218 | false | false | false | false |
die-tageszeitung/tazapp-android
|
tazapp/src/main/java/de/thecode/android/tazreader/dialognew/DownloadInfoDialog.kt
|
1
|
8107
|
package de.thecode.android.tazreader.dialognew
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.widget.CheckBox
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.*
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import de.thecode.android.tazreader.*
import de.thecode.android.tazreader.R
import de.thecode.android.tazreader.data.DownloadState
import de.thecode.android.tazreader.data.Paper
import de.thecode.android.tazreader.data.UnmeteredDownloadOnly
import de.thecode.android.tazreader.download.TazDownloadManager
import de.thecode.android.tazreader.utils.Connection
import de.thecode.android.tazreader.utils.ConnectionInfo
import kotlinx.coroutines.*
class DownloadInfoDialog : DialogFragment() {
interface CancelDownloadDialogListener {
fun onCancelDownload(bookId: String)
}
companion object {
const val DIALOG_TAG = "downloadInfoDialog"
private const val BOOK_ID = "bookId"
private const val TITLE = "title"
fun newInstance(paper: Paper): DownloadInfoDialog {
val args = Bundle()
args.putString(BOOK_ID, paper.bookId)
args.putString(TITLE, paper.getTitelWithDate(res))
val fragment = DownloadInfoDialog()
fragment.arguments = args
return fragment
}
}
val bookId: String by lazy {
requireArguments().getString(BOOK_ID)
}
var dialog: MaterialDialog? = null
private val state: TextView by lazy {
dialog!!.getCustomView()
.findViewById<TextView>(R.id.state)
}
private val connected: CheckBox by lazy {
dialog!!.getCustomView()
.findViewById<CheckBox>(R.id.checkBoxConnected)
}
private val metered: CheckBox by lazy {
dialog!!.getCustomView()
.findViewById<CheckBox>(R.id.checkBoxMetered)
}
private val roaming: CheckBox by lazy {
dialog!!.getCustomView()
.findViewById<CheckBox>(R.id.checkBoxRoaming)
}
private val progress: ProgressBar by lazy {
dialog!!.getCustomView()
.findViewById<ProgressBar>(R.id.progress)
}
private val dmlog: TextView by lazy {
dialog!!.getCustomView()
.findViewById<TextView>(R.id.dmLog)
}
private val useMobile: TextView by lazy {
dialog!!.getCustomView()
.findViewById<TextView>(R.id.useMobile)
}
private val title: TextView by lazy {
dialog!!.getCustomView()
.findViewById<TextView>(R.id.title)
}
private val viewModel: DownloadInfoDialogViewModel by lazy {
ViewModelProvider(this, DownloadInfoDialogViewModelFactory(requireArguments().getString(BOOK_ID)!!))
.get(DownloadInfoDialogViewModel::class.java)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
context?.let {
dialog = MaterialDialog(requireContext())
.customView(viewRes = R.layout.dialog_download_info, scrollable = true)
.negativeButton(res = R.string.downloadinfo_cancel_download, click = {
(activity as CancelDownloadDialogListener).onCancelDownload(requireArguments().getString(BOOK_ID)!!)
})
.positiveButton()
title.text = app.getString(R.string.downloadinfo_dialog_title, requireArguments().getString(TITLE))
viewModel.downloadInfo.observe(this, Observer {
if (it.state == DownloadState.READY) {
dismiss()
}
connected.isChecked = it.connectionInfo.connected
metered.isChecked = it.connectionInfo.metered
roaming.isChecked = it.connectionInfo.roaming
@SuppressLint("SetTextI18n")
state.text = it.state.readable()
dmlog.text = it.dmLog
progress.progress = it.progress
useMobile.text = getString(when (it.unmeteredOnly) {
UnmeteredDownloadOnly.YES -> R.string.use_mobile_no
UnmeteredDownloadOnly.NO -> R.string.use_mobile_yes
UnmeteredDownloadOnly.UNKNOWN -> R.string.use_mobile_unknown
})
})
return dialog!!
}
return super.onCreateDialog(savedInstanceState)
}
}
class DownloadInfoDialogViewModel(val bookId: String) : ViewModel(), Connection.ConnectionChangeListener {
private val viewModelJob = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
// val paperLiveData = paperRepository.getLivePaper(bookId);
val downloadInfo = MutableLiveData<DownloadInfo>()
val downloadLiveData = downloadsRepository.getLiveData(bookId)
init {
downloadInfo.value = DownloadInfo()
onNetworkConnectionChanged(Connection.getConnectionInfo())
Connection.addListener(this)
downloadLiveData.observeForever {
it?.let {
downloadInfo.value!!.unmeteredOnly = it.unmeteredOnly!!
downloadInfo.value!!.state = it.state
when (it.state) {
DownloadState.DOWNLOADING -> poll()
DownloadState.EXTRACTING, DownloadState.CHECKING -> {
downloadInfo.value!!.progress = it.progress
}
else -> {
}
}
downloadInfo.value = downloadInfo.value
}
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
private fun poll() {
uiScope.launch {
withContext(Dispatchers.Default) {
val download = paperRepository.getDownloadForPaper(bookId)
when (download.state) {
DownloadState.DOWNLOADING, DownloadState.DOWNLOADED -> {
val systemDownloadInfo = TazDownloadManager.getInstance()
.getSystemDownloadManagerInfo(download.downloadManagerId)
val downloadInfoValue = downloadInfo.value!!
downloadInfoValue.progress = if (systemDownloadInfo.totalSizeBytes != 0L) (systemDownloadInfo.bytesDownloadedSoFar * 100 / systemDownloadInfo.totalSizeBytes).toInt() else 0
val reason = if (systemDownloadInfo.reason != 0) " (${systemDownloadInfo.reasonText})" else ""
downloadInfoValue.dmLog = "${systemDownloadInfo.statusText}$reason"
downloadInfo.postValue(downloadInfoValue)
delay(200)
if (downloadInfo.value!!.state == DownloadState.DOWNLOADING || downloadInfo.value!!.state == DownloadState.DOWNLOADED) {
poll()
}
}
else -> {
}
}
}
}
}
override fun onNetworkConnectionChanged(info: ConnectionInfo) {
val downloadInfoValue = downloadInfo.value
downloadInfoValue!!.connectionInfo = info
downloadInfo.value = downloadInfoValue
}
}
class DownloadInfoDialogViewModelFactory(val bookId: String) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return DownloadInfoDialogViewModel(bookId) as T
}
}
data class DownloadInfo(var connectionInfo: ConnectionInfo = ConnectionInfo(),
var unmeteredOnly: UnmeteredDownloadOnly = UnmeteredDownloadOnly.UNKNOWN,
var state: DownloadState = DownloadState.NONE,
var progress: Int = 0,
var dmLog: String = "")
|
agpl-3.0
|
1eb8688aa302cee1370558d6feb36755
| 36.711628 | 196 | 0.621685 | 5.101951 | false | false | false | false |
lfkdsk/JustDB
|
src/storage/Block.kt
|
1
|
724
|
package storage
/**
* Block in File - Block-Box-Model
* @param fileName : Block's file Name
* @param blockNumber: Block Number
* Created by liufengkai on 2017/4/24.
*/
class Block(val fileName: String, var blockNumber: Int) {
override fun toString(): String {
return "Block(fileName='$fileName', blockName='$blockNumber')"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
return equals(other as Block)
}
fun equals(other: Block): Boolean {
if (fileName != other.fileName) return false
if (blockNumber != other.blockNumber) return false
return true
}
override fun hashCode(): Int {
return toString().hashCode()
}
}
|
apache-2.0
|
9a3d538bd48252fcca4cb9f6c5375403
| 23.166667 | 64 | 0.694751 | 3.693878 | false | false | false | false |
clappr/clappr-android
|
clappr/src/test/kotlin/io/clappr/player/PlayerTest.kt
|
1
|
21408
|
package io.clappr.player
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import androidx.test.core.app.ApplicationProvider
import io.clappr.player.base.*
import io.clappr.player.components.Core
import io.clappr.player.components.Playback
import io.clappr.player.components.PlaybackEntry
import io.clappr.player.components.PlaybackSupportCheck
import io.clappr.player.plugin.Loader
import io.clappr.player.plugin.PluginEntry
import io.clappr.player.plugin.UIPlugin
import io.clappr.player.plugin.core.CorePlugin
import io.clappr.player.plugin.core.externalinput.ExternalInputDevice
import io.clappr.player.plugin.core.externalinput.ExternalInputPlugin
import org.junit.Assert.*
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
import kotlin.test.assertNull
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [23])
open class PlayerTest {
private val playerTestEvent = "playerTestEvent"
lateinit var player: Player
@Before
fun setup() {
Player.initialize(ApplicationProvider.getApplicationContext())
Loader.clearPlaybacks()
Loader.register(CoreTestPlugin.entry)
Loader.register(PlayerTestPlayback.entry)
PlayerTestPlayback.internalState = Playback.State.NONE
EventTestPlayback.event = null
CoreTestPlugin.event = null
player = Player(playbackEventsToListen = mutableSetOf(playerTestEvent))
}
@Test
fun `should have invalid states before configure`() {
assertEquals("valid duration", Double.NaN, player.duration, 0.0)
assertEquals("valid position", Double.NaN, player.position, 0.0)
assertFalse("play enabled", player.play())
assertFalse("stop enabled", player.stop())
assertFalse("pause enabled", player.pause())
assertFalse("seek enabled", player.seek(0))
assertFalse("load enabled", player.load(""))
}
@SuppressLint("IgnoreWithoutReason") @Ignore @Test
fun `should have invalid states with unsupported media`() {
player.configure(Options(source = ""))
assertEquals("valid duration", Double.NaN, player.duration, 0.0)
assertEquals("valid position", Double.NaN, player.position, 0.0)
assertFalse("play enabled", player.play())
assertFalse("stop enabled", player.stop())
assertFalse("pause enabled", player.pause())
assertFalse("seek enabled", player.seek(0))
assertFalse("load enabled", player.load(""))
assertTrue("load disabled", player.load("valid"))
}
@Test
fun `configured player`() {
player.configure(Options(source = "valid"))
assertNotEquals("invalid duration", Double.NaN, player.duration, 0.0)
assertNotEquals("invalid position", Double.NaN, player.position, 0.0)
assertTrue("play disabled", player.play())
assertTrue("stop disabled", player.stop())
assertTrue("pause disabled", player.pause())
assertTrue("seek disabled", player.seek(0))
}
@Test
fun `should trigger events`() {
var willPauseCalled = false
var didPauseCalled = false
player.on(Event.WILL_PAUSE.value) { willPauseCalled = true }
player.on(Event.DID_PAUSE.value) { didPauseCalled = true }
player.configure(Options(source = "valid"))
player.pause()
assertTrue("WILL_PAUSE not triggered", willPauseCalled)
assertTrue("DID_PAUSE not triggered", didPauseCalled)
}
@Test
fun `player states`() {
assertEquals("invalid state (not NONE)", Player.State.NONE, player.state)
player.configure(Options(source = "valid"))
assertEquals("invalid state (not NONE)", Player.State.NONE, player.state)
PlayerTestPlayback.internalState = Playback.State.ERROR
assertEquals("invalid state (not ERROR)", Player.State.ERROR, player.state)
PlayerTestPlayback.internalState = Playback.State.IDLE
assertEquals("invalid state (not IDLE)", Player.State.IDLE, player.state)
PlayerTestPlayback.internalState = Playback.State.PAUSED
assertEquals("invalid state (not PAUSED)", Player.State.PAUSED, player.state)
PlayerTestPlayback.internalState = Playback.State.PLAYING
assertEquals("invalid state (not PLAYING)", Player.State.PLAYING, player.state)
PlayerTestPlayback.internalState = Playback.State.STALLING
assertEquals("invalid state (not STALLING)", Player.State.STALLING, player.state)
}
@Test
fun `should unbind on configure`() {
var willPauseCalled = false
var didPauseCalled = false
player.on(Event.WILL_PAUSE.value) { willPauseCalled = true }
player.on(Event.DID_PAUSE.value) { didPauseCalled = true }
player.configure(Options(source = "valid"))
player.pause()
assertTrue("WILL_PAUSE not triggered", willPauseCalled)
assertTrue("DID_PAUSE not triggered", didPauseCalled)
willPauseCalled = false
didPauseCalled = false
player.configure(Options(source = ""))
player.pause()
assertFalse("WILL_PAUSE triggered", willPauseCalled)
assertFalse("DID_PAUSE triggered", didPauseCalled)
}
/************************************* DISCLAIMER ***********************************************
* The following tests use unconventional methods to test core related behaviours in the Player
* class. Since now the core is protected in Player we can no longer use it to test some
* behaviours. To ensure testability we should inject core in the Player and not create it
* there. Until we change our architecture, to maintain the same tests we use some plugins and
* send some events with data that will normally not be sent. To be easier to understand each
* test we tried to explain it and add some comments.
***********************************************************************************************/
/**
* This test use the CoreTestPlugin to send by PlayerTest event the current option passed by
* options. That way we ensure that we are changing the options when we call a load before a
* configure.
*/
@Test
fun `should core change options on player configure`() {
val expectedFirstOption = "first option"
val expectedSecondOption = "second option"
var option = ""
player.on(playerTestEvent) { bundle ->
bundle?.let {
option = it.getString("option") ?: ""
}
}
player.configure(Options(source = "123", options = hashMapOf("test_option" to expectedFirstOption)))
player.play()
assertEquals(expectedFirstOption, option)
player.configure(Options(source = "321", options = hashMapOf("test_option" to expectedSecondOption)))
player.play()
assertEquals(expectedSecondOption, option)
}
/**
* This test use the CoreTestPlugin to send by PlayerTest event the current mime type passed by
* options. That way we ensure that we are changing the options when we call a load before a
* configure.
*/
@Test
fun `should core change mime type on player configure`() {
val expectedFirstMimeType = "mimeType"
val expectedSecondMimeType = "other-mimeType"
var mimeType = ""
player.on(playerTestEvent) { bundle ->
bundle?.let {
mimeType = it.getString("mimeType") ?: ""
}
}
player.configure(Options(source = "123", mimeType = expectedFirstMimeType))
player.play()
assertEquals(expectedFirstMimeType, mimeType)
player.configure(Options(source = "321", mimeType = expectedSecondMimeType))
player.play()
assertEquals(expectedSecondMimeType, mimeType)
}
/**
* This test use the CoreTestPlugin to send by PlayerTest event the current mime type passed by
* options. That way we ensure that we are changing the options when we call a load before a
* configure.
*/
@Test
fun `should core change mime type on player load`() {
val expectedFirstMimeType = "mimeType"
val expectedSecondMimeType = "other-mimeType"
var mimeType = ""
player.on(playerTestEvent) { bundle ->
bundle?.let {
mimeType = it.getString("mimeType") ?: ""
}
}
player.configure(Options(source = "123", mimeType = expectedFirstMimeType))
player.play()
assertEquals(expectedFirstMimeType, mimeType)
player.load(source = "321", mimeType = expectedSecondMimeType)
player.play()
assertEquals(expectedSecondMimeType, mimeType)
}
/**
* This test use the CoreTestPlugin to send by PlayerTest event the current source passed by
* options. That way we ensure that we are changing the options when we call a load before a
* configure.
*/
@Test
fun `should core change source on player configure`() {
val expectedFirstSource = "source"
val expectedSecondSource = "other-source"
var sourceToPlay = ""
player.on(playerTestEvent) { bundle ->
bundle?.let {
sourceToPlay = it.getString("source") ?: ""
}
}
player.configure(Options(source = expectedFirstSource))
player.play()
assertEquals(expectedFirstSource, sourceToPlay)
player.configure(Options(source = expectedSecondSource))
player.play()
assertEquals(expectedSecondSource, sourceToPlay)
}
/**
* This test use the CoreTestPlugin to send by PlayerTest event the current source passed by
* options. That way we ensure that we are changing the options when we call a load before a
* configure.
*/
@Test
fun `should core change ource on player load`() {
val expectedFirstSource = "source"
val expectedSecondSource = "other-source"
var sourceToPlay = ""
player.on(playerTestEvent) { bundle ->
bundle?.let {
sourceToPlay = it.getString("source") ?: ""
}
}
player.configure(Options(source = expectedFirstSource))
player.play()
assertEquals(expectedFirstSource, sourceToPlay)
player.load(source = expectedSecondSource)
player.play()
assertEquals(expectedSecondSource, sourceToPlay)
}
/**
* This test use the CoreTestPlugin to send by PlayerTest event the core id. That way we can
* compare the hash between two configures performed in Player, ensuring that the same core
* instance is used between configures. To force the CoreTestPlugin to send the test event we
* trigger a WILL_PLAY event when the Playback play is called using the PlayerTestPlayback.
*/
@Test
fun `should core have same instance on player configure`() {
val expectedDistinctCoreId = 1
val coreIdList = mutableSetOf<String>()
player.on(playerTestEvent) { bundle ->
bundle?.let {
it.getString("coreId")?.let {coreId ->
coreIdList.add(coreId)
}
}
}
player.configure(Options(source = "123"))
player.play()
player.configure(Options(source = "321"))
player.play()
assertEquals(expectedDistinctCoreId, coreIdList.size)
}
@Test
fun `should listen ready event out of player`() {
assertPlaybackEventWasTriggered(Event.READY.value)
}
@Test
fun `should listen error event out of player`() {
assertPlaybackEventWasTriggered(Event.ERROR.value)
}
@Test
fun `should listen playing event out of player`() {
assertPlaybackEventWasTriggered(Event.PLAYING.value)
}
@Test
fun `should listen did complete event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_COMPLETE.value)
}
@Test
fun `should listen did pause event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_PAUSE.value)
}
@Test
fun `should listen stalling event out of player`() {
assertPlaybackEventWasTriggered(Event.STALLING.value)
}
@Test
fun `should listen did stop event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_STOP.value)
}
@Test
fun `should listen did seek event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_SEEK.value)
}
@Test
fun `should listen did update buffer event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_UPDATE_BUFFER.value)
}
@Test
fun `should listen did update position event outOf player`() {
assertPlaybackEventWasTriggered(Event.DID_UPDATE_POSITION.value)
}
@Test
fun `should listen will play event out of player`() {
assertPlaybackEventWasTriggered(Event.WILL_PLAY.value)
}
@Test
fun `should listen will pause event out of player`() {
assertPlaybackEventWasTriggered(Event.WILL_PAUSE.value)
}
@Test
fun `should listen will week event out of player`() {
assertPlaybackEventWasTriggered(Event.WILL_SEEK.value)
}
@Test
fun `should listen will stop event out of player`() {
assertPlaybackEventWasTriggered(Event.WILL_STOP.value)
}
@Test
fun `should listen did change DVR status event out fo player`() {
assertPlaybackEventWasTriggered(Event.DID_CHANGE_DVR_STATUS.value)
}
@Test
fun `should listen did change DVR availability event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_CHANGE_DVR_AVAILABILITY.value)
}
@Test
fun `should listen did updaten bitrate event out of player`() {
assertPlaybackEventWasTriggered(Event.DID_UPDATE_BITRATE.value)
}
@Test
fun `should listen media option update event out of player`() {
assertPlaybackEventWasTriggered(Event.MEDIA_OPTIONS_UPDATE.value)
}
@Test
fun `should listen media option selected event out of player triggered by core`() {
assertCoreEventWasTriggered(Event.MEDIA_OPTIONS_SELECTED.value)
}
@Test
fun `should listen did select audio event out of player triggered by core`() {
assertCoreEventWasTriggered(Event.DID_SELECT_AUDIO.value)
}
@Test
fun `should listen did select subtitle event out of player triggered by core`() {
assertCoreEventWasTriggered(Event.DID_SELECT_SUBTITLE.value)
}
@Test
fun `should listen request fullscreen event out of player triggered by core`() {
assertCoreEventWasTriggered(Event.REQUEST_FULLSCREEN.value)
}
@Test
fun `should listen exit fullscreen event out of player triggered by core`() {
assertCoreEventWasTriggered(Event.EXIT_FULLSCREEN.value)
}
@Test
fun `should pass key event to external input class`(){
val expectedKeyEvent = KeyEvent(1, 2, 3, 4, 5)
ExternalInputPluginTest.keyEvent = null
Loader.register(ExternalInputPluginTest.entry)
player = Player()
player.configure(Options(source = "valid"))
player.holdKeyEvent(expectedKeyEvent)
assertEquals(expectedKeyEvent, ExternalInputPluginTest.keyEvent)
}
private fun assertCoreEventWasTriggered(event: String) {
var eventWasCalled = false
CoreTestPlugin.event = event
player.on(event) { bundle ->
eventWasCalled = bundle?.getBoolean(CoreTestPlugin.eventBundle) ?: false
}
player.configure(Options(source = "valid"))
player.play()
assertTrue(eventWasCalled)
}
private fun assertPlaybackEventWasTriggered(event: String){
var eventWasCalled = false
Loader.register(EventTestPlayback.entry)
EventTestPlayback.event = event
player = Player(playbackEventsToListen = mutableSetOf(playerTestEvent))
player.on(event) { bundle ->
eventWasCalled = bundle?.getBoolean(EventTestPlayback.eventBundle) ?: false
}
player.configure(Options(source = "valid"))
player.play()
assertTrue(eventWasCalled)
}
class EventTestPlayback(source: String, mimeType: String? = null, options: Options = Options()):
Playback(source, mimeType, options, name = name, supportsSource = supportsSource) {
companion object {
const val name: String = "player_test"
val supportsSource: PlaybackSupportCheck = { source, _ -> source.isNotEmpty() }
val entry = PlaybackEntry(
name = name,
supportsSource = supportsSource,
factory = { source, mimeType, options -> EventTestPlayback(source, mimeType, options) })
const val eventBundle = "test-bundle"
var event: String? = null
}
override fun play(): Boolean {
event?.let {
Bundle().apply {
putBoolean(eventBundle, true)
trigger(it, this)
}
}
return super.play()
}
}
class PlayerTestPlayback(source: String, mimeType: String? = null, options: Options = Options()) :
Playback(source, mimeType, options, name = name, supportsSource = supportsSource) {
companion object {
const val name: String = "player_test"
val supportsSource: PlaybackSupportCheck = { source, _ -> source.isNotEmpty() }
val entry = PlaybackEntry(
name = name,
supportsSource = supportsSource,
factory = { source, mimeType, options -> PlayerTestPlayback(source, mimeType, options) })
var internalState = State.NONE
}
override val state: State
get() = internalState
override val duration: Double = 1.0
override val position: Double = 0.0
override fun stop(): Boolean {
return true
}
override fun seek(seconds: Int): Boolean {
return true
}
override fun play(): Boolean {
trigger(Event.WILL_PLAY.value)
return true
}
override fun pause(): Boolean {
trigger(Event.WILL_PAUSE.value)
trigger(Event.DID_PAUSE.value)
return true
}
}
@Test
fun `should not have UIPlugins loaded with chromeless options set`() {
val options = Options(
options = hashMapOf(ClapprOption.CHROMELESS.value to true)
)
player = Player()
player.configure(options)
assertNull(player.getCore().plugins.filterIsInstance(UIPlugin::class.java).firstOrNull())
assertNull(
player.getCore().containers.firstOrNull()?.plugins?.filterIsInstance(
UIPlugin::class.java
)?.firstOrNull()
)
}
private fun Player.getCore(): Core =
Player::class.memberProperties.first { it.name == "core" }.run {
isAccessible = true
get(this@getCore) as Core
}
class CoreTestPlugin(core: Core) : CorePlugin(core) {
companion object : NamedType {
override val name = "coreTestPlugin"
val entry = PluginEntry.Core(name = name, factory = { core -> CoreTestPlugin(core) })
const val eventBundle = "test-bundle"
var event: String? = null
}
init {
listenTo(core, InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value) { bindPlaybackEvents() }
}
private fun bindPlaybackEvents() {
core.activePlayback?.let { playback ->
listenTo(playback, Event.WILL_PLAY.value) {
triggerTestEvent(playback)
triggerCoreEvent()
}
}
}
private fun triggerTestEvent(playback: Playback) {
playback.trigger("playerTestEvent", Bundle().apply {
putString("source", core.options.source)
putString("mimeType", core.options.mimeType)
putString("coreId", core.id)
core.options.options["test_option"]?.let { testOption ->
putString("option", testOption as String)
}
})
}
private fun triggerCoreEvent() {
event?.let {
Bundle().apply {
putBoolean(eventBundle, true)
core.trigger(it, this)
}
}
}
}
class ExternalInputPluginTest(core: Core) : CorePlugin(core, name = name), ExternalInputDevice {
companion object : NamedType {
override val name = ExternalInputPlugin.name
val entry = PluginEntry.Core(
name = name,
factory = { core -> ExternalInputPluginTest(core) })
var keyEvent: KeyEvent? = null
}
override fun holdKeyEvent(event: KeyEvent) {
keyEvent = event
}
}
}
|
bsd-3-clause
|
eda5e0181f0407423d7b26e21c21c634
| 32.503912 | 109 | 0.633221 | 4.733142 | false | true | false | false |
TeamAmaze/AmazeFileManager
|
app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/AndroidFtpFile.kt
|
3
|
6365
|
/*
* 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.filesystem.ftpserver
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build.VERSION_CODES.KITKAT
import android.provider.DocumentsContract
import androidx.annotation.RequiresApi
import androidx.documentfile.provider.DocumentFile
import org.apache.ftpserver.ftplet.FtpFile
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.lang.ref.WeakReference
@RequiresApi(KITKAT)
@Suppress("TooManyFunctions") // Don't ask me. Ask Apache why.
class AndroidFtpFile(
context: Context,
private val parentDocument: DocumentFile,
private val backingDocument: DocumentFile?,
private val path: String
) : FtpFile {
private val _context: WeakReference<Context> = WeakReference(context)
private val context: Context
get() = _context.get()!!
override fun getAbsolutePath(): String {
return path
}
/**
* @see FtpFile.getName
* @see DocumentFile.getName
*/
override fun getName(): String = backingDocument?.name ?: path.substringAfterLast('/')
/**
* @see FtpFile.isHidden
*/
override fun isHidden(): Boolean = name.startsWith(".") && name != "."
/**
* @see FtpFile.isDirectory
* @see DocumentFile.isDirectory
*/
override fun isDirectory(): Boolean = backingDocument?.isDirectory ?: false
/**
* @see FtpFile.isFile
* @see DocumentFile.isFile
*/
override fun isFile(): Boolean = backingDocument?.isFile ?: false
/**
* @see FtpFile.doesExist
* @see DocumentFile.exists
*/
override fun doesExist(): Boolean = backingDocument?.exists() ?: false
/**
* @see FtpFile.isReadable
* @see DocumentFile.canRead
*/
override fun isReadable(): Boolean = backingDocument?.canRead() ?: false
/**
* @see FtpFile.isWritable
* @see DocumentFile.canWrite
*/
override fun isWritable(): Boolean = backingDocument?.canWrite() ?: true
/**
* @see FtpFile.isRemovable
* @see DocumentFile.canWrite
*/
override fun isRemovable(): Boolean = backingDocument?.canWrite() ?: true
/**
* @see FtpFile.getOwnerName
*/
override fun getOwnerName(): String = "user"
/**
* @see FtpFile.getGroupName
*/
override fun getGroupName(): String = "user"
/**
* @see FtpFile.getLinkCount
*/
override fun getLinkCount(): Int = 0
/**
* @see FtpFile.getLastModified
* @see DocumentFile.lastModified
*/
override fun getLastModified(): Long = backingDocument?.lastModified() ?: 0L
/**
* @see FtpFile.setLastModified
* @see DocumentsContract.Document.COLUMN_LAST_MODIFIED
* @see ContentResolver.update
*/
override fun setLastModified(time: Long): Boolean {
return if (doesExist()) {
val updateValues = ContentValues().also {
it.put(DocumentsContract.Document.COLUMN_LAST_MODIFIED, time)
}
val docUri: Uri = backingDocument!!.uri
val updated: Int = context.contentResolver.update(
docUri,
updateValues,
null,
null
)
return updated == 1
} else {
false
}
}
/**
* @see FtpFile.getSize
* @see DocumentFile.length
*/
override fun getSize(): Long = backingDocument?.length() ?: 0L
/**
* @see FtpFile.getPhysicalFile
*/
override fun getPhysicalFile(): Any = backingDocument!!
/**
* @see FtpFile.mkdir
* @see DocumentFile.createDirectory
*/
override fun mkdir(): Boolean = parentDocument.createDirectory(name) != null
/**
* @see FtpFile.delete
* @see DocumentFile.delete
*/
override fun delete(): Boolean = backingDocument?.delete() ?: false
/**
* @see FtpFile.move
* @see DocumentFile.renameTo
*/
override fun move(destination: FtpFile): Boolean =
backingDocument?.renameTo(destination.name) ?: false
/**
* @see FtpFile.listFiles
* @see DocumentFile.listFiles
*/
override fun listFiles(): MutableList<out FtpFile> = if (doesExist()) {
backingDocument!!.listFiles().map {
AndroidFtpFile(context, backingDocument, it, it.name!!)
}.toMutableList()
} else {
mutableListOf()
}
/**
* @see FtpFile.createOutputStream
* @see ContentResolver.openOutputStream
*/
override fun createOutputStream(offset: Long): OutputStream? = runCatching {
val uri = if (doesExist()) {
backingDocument!!.uri
} else {
val newFile = parentDocument.createFile("", name)
newFile?.uri ?: throw IOException("Cannot create file at $path")
}
context.contentResolver.openOutputStream(uri)
}.getOrThrow()
/**
* @see FtpFile.createInputStream
* @see ContentResolver.openInputStream
*/
override fun createInputStream(offset: Long): InputStream? = runCatching {
if (doesExist()) {
context.contentResolver.openInputStream(backingDocument!!.uri).also {
it?.skip(offset)
}
} else {
throw FileNotFoundException(path)
}
}.getOrThrow()
}
|
gpl-3.0
|
35caaf6f6a4177b537eae2c056165f4e
| 28.604651 | 107 | 0.641948 | 4.645985 | false | false | false | false |
gotev/android-upload-service
|
uploadservice-ftp/src/test/java/net/gotev/uploadservice/ftp/TestRolePermissions.kt
|
2
|
5962
|
package net.gotev.uploadservice.ftp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
class TestRolePermissions {
@Test
fun `no permissions`() {
val permissions = UnixPermissions.RolePermissions.fromChar('0')
assertFalse(permissions.read)
assertFalse(permissions.write)
assertFalse(permissions.execute)
}
@Test
fun `no permissions serialization`() {
val permissions = UnixPermissions.RolePermissions()
assertEquals("0", permissions.toString())
}
@Test
fun `only execute`() {
val permissions = UnixPermissions.RolePermissions.fromChar('1')
assertFalse(permissions.read)
assertFalse(permissions.write)
assertTrue(permissions.execute)
}
@Test
fun `only execute serialization`() {
val permissions = UnixPermissions.RolePermissions(execute = true)
assertEquals("1", permissions.toString())
}
@Test
fun `only write`() {
val permissions = UnixPermissions.RolePermissions.fromChar('2')
assertFalse(permissions.read)
assertTrue(permissions.write)
assertFalse(permissions.execute)
}
@Test
fun `only write serialization`() {
val permissions = UnixPermissions.RolePermissions(write = true)
assertEquals("2", permissions.toString())
}
@Test
fun `write and execute`() {
val permissions = UnixPermissions.RolePermissions.fromChar('3')
assertFalse(permissions.read)
assertTrue(permissions.write)
assertTrue(permissions.execute)
}
@Test
fun `write and execute serialization`() {
val permissions = UnixPermissions.RolePermissions(write = true, execute = true)
assertEquals("3", permissions.toString())
}
@Test
fun `read only`() {
val permissions = UnixPermissions.RolePermissions.fromChar('4')
assertTrue(permissions.read)
assertFalse(permissions.write)
assertFalse(permissions.execute)
}
@Test
fun `read only serialization`() {
val permissions = UnixPermissions.RolePermissions(read = true)
assertEquals("4", permissions.toString())
}
@Test
fun `read and execute`() {
val permissions = UnixPermissions.RolePermissions.fromChar('5')
assertTrue(permissions.read)
assertFalse(permissions.write)
assertTrue(permissions.execute)
}
@Test
fun `read and execute serialization`() {
val permissions = UnixPermissions.RolePermissions(read = true, execute = true)
assertEquals("5", permissions.toString())
}
@Test
fun `read and write`() {
val permissions = UnixPermissions.RolePermissions.fromChar('6')
assertTrue(permissions.read)
assertTrue(permissions.write)
assertFalse(permissions.execute)
}
@Test
fun `read and write serialization`() {
val permissions = UnixPermissions.RolePermissions(read = true, write = true)
assertEquals("6", permissions.toString())
}
@Test
fun `all permissions`() {
val permissions = UnixPermissions.RolePermissions.fromChar('7')
assertTrue(permissions.read)
assertTrue(permissions.write)
assertTrue(permissions.execute)
}
@Test
fun `all permissions serialization`() {
val permissions = UnixPermissions.RolePermissions(read = true, write = true, execute = true)
assertEquals("7", permissions.toString())
}
@Test
fun `default UnixPermissions`() {
val permissions = UnixPermissions()
assertEquals("644", permissions.toString())
assertTrue(permissions.owner.read)
assertTrue(permissions.owner.write)
assertFalse(permissions.owner.execute)
assertTrue(permissions.group.read)
assertFalse(permissions.group.write)
assertFalse(permissions.group.execute)
assertTrue(permissions.world.read)
assertFalse(permissions.world.write)
assertFalse(permissions.world.execute)
}
@Test
fun `permission 754`() {
val permissions = UnixPermissions("754")
assertEquals("754", permissions.toString())
assertTrue(permissions.owner.read)
assertTrue(permissions.owner.write)
assertTrue(permissions.owner.execute)
assertTrue(permissions.group.read)
assertFalse(permissions.group.write)
assertTrue(permissions.group.execute)
assertTrue(permissions.world.read)
assertFalse(permissions.world.write)
assertFalse(permissions.world.execute)
}
@Test
fun `invalid string`() {
try {
UnixPermissions("7541")
fail("this should throw an exception")
} catch (exc: Throwable) {
assertTrue(exc is IllegalArgumentException)
}
}
@Test
fun `invalid string 2`() {
try {
UnixPermissions("75")
fail("this should throw an exception")
} catch (exc: Throwable) {
assertTrue(exc is IllegalArgumentException)
}
}
@Test
fun `invalid string 3`() {
try {
UnixPermissions("7")
fail("this should throw an exception")
} catch (exc: Throwable) {
assertTrue(exc is IllegalArgumentException)
}
}
@Test
fun `invalid string 4`() {
try {
UnixPermissions("asdmn2")
fail("this should throw an exception")
} catch (exc: Throwable) {
assertTrue(exc is IllegalArgumentException)
}
}
@Test
fun `invalid string 5`() {
try {
UnixPermissions("")
fail("this should throw an exception")
} catch (exc: Throwable) {
assertTrue(exc is IllegalArgumentException)
}
}
}
|
apache-2.0
|
571ba053906557c8516cf9fd5089544c
| 27.663462 | 100 | 0.632841 | 4.874898 | false | true | false | false |
NextFaze/dev-fun
|
devfun/src/main/java/com/nextfaze/devfun/invoke/view/simple/Injected.kt
|
1
|
771
|
package com.nextfaze.devfun.invoke.view.simple
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.nextfaze.devfun.invoke.view.WithValue
import kotlin.reflect.KClass
/** A simple view that should tell the user if a parameter is being injected. */
interface InjectedParameterView : WithValue<KClass<*>>
internal class InjectedView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle
) : AppCompatTextView(context, attrs, defStyleAttr), InjectedParameterView {
override var value: KClass<*> = Unit::class
set(value) {
this.text = value.qualifiedName
field = value
}
}
|
apache-2.0
|
bb9b31eff59a455d3391bc1f909aa40f
| 32.521739 | 80 | 0.743191 | 4.508772 | false | false | false | false |
andrei-heidelbacher/metanalysis
|
chronolens-core/src/main/kotlin/org/chronolens/core/model/DiffUtils.kt
|
1
|
4137
|
/*
* Copyright 2018-2021 Andrei Heidelbacher <[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("Utils")
@file:JvmMultifileClass
package org.chronolens.core.model
import org.chronolens.core.model.ListEdit.Companion.diff
import org.chronolens.core.model.SetEdit.Companion.diff
/**
* Returns the smallest edit distance between the two given arrays using the
* Wagner-Fischer algorithm.
*/
internal fun diff(a: IntArray, b: IntArray): List<ListEdit<Int>> {
val dp = Array(size = a.size + 1) {
IntArray(size = b.size + 1) { a.size + b.size }
}
dp[0] = IntArray(size = b.size + 1) { it }
for (i in 1..a.size) {
dp[i][0] = i
for (j in 1..b.size) {
dp[i][j] =
if (a[i - 1] == b[j - 1]) dp[i - 1][j - 1]
else 1 + minOf(dp[i - 1][j], dp[i][j - 1])
}
}
val edits = arrayListOf<ListEdit<Int>>()
var i = a.size
var j = b.size
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {
i--
j--
} else if (i > 0 && dp[i][j] == dp[i - 1][j] + 1) {
edits += ListEdit.Remove(i - 1)
i--
} else {
edits += ListEdit.Add(i, b[j - 1])
j--
}
}
return edits
}
/**
* Returns the edit which must be applied on this source node in order to obtain
* the [other] source node, or `null` if the two nodes are equal (child nodes
* are not taken into account).
*
* @throws IllegalArgumentException if the two source nodes have different ids
* or types
*/
internal fun SourceTreeNode<*>.diff(other: SourceTreeNode<*>)
: SourceTreeEdit? {
val sameQualifiedId = qualifiedId == other.qualifiedId
val sameKind = sourceNode.kind == other.sourceNode.kind
require(sameQualifiedId && sameKind) {
"Can't compute diff between '$qualifiedId' and '${other.qualifiedId}'!"
}
val editBuilder = when (sourceNode) {
is SourceFile -> { _ -> null }
is Type -> sourceNode.diff(other.sourceNode as Type)
is Function -> sourceNode.diff(other.sourceNode as Function)
is Variable -> sourceNode.diff(other.sourceNode as Variable)
}
return editBuilder.invoke(qualifiedId)
}
private typealias SourceTreeEditBuilder = (String) -> SourceTreeEdit?
private fun Type.diff(other: Type): SourceTreeEditBuilder {
val supertypeEdits = supertypes.diff(other.supertypes)
val modifierEdits = modifiers.diff(other.modifiers)
val changed = supertypeEdits.isNotEmpty() || modifierEdits.isNotEmpty()
return { qualifiedId ->
if (!changed) null
else EditType(qualifiedId, supertypeEdits, modifierEdits)
}
}
private fun Function.diff(other: Function): SourceTreeEditBuilder {
val parameterEdits = parameters.diff(other.parameters)
val modifierEdits = modifiers.diff(other.modifiers)
val bodyEdits = body.diff(other.body)
val changed = parameterEdits.isNotEmpty() ||
modifierEdits.isNotEmpty() ||
bodyEdits.isNotEmpty()
return { qualifiedId ->
if (!changed) null
else EditFunction(qualifiedId, parameterEdits, modifierEdits, bodyEdits)
}
}
private fun Variable.diff(other: Variable): SourceTreeEditBuilder {
val modifierEdits = modifiers.diff(other.modifiers)
val initializerEdits = initializer.diff(other.initializer)
val changed = modifierEdits.isNotEmpty() || initializerEdits.isNotEmpty()
return { qualifiedId ->
if (!changed) null
else EditVariable(qualifiedId, modifierEdits, initializerEdits)
}
}
|
apache-2.0
|
2f5a300e56234d82226d4a497669ad54
| 34.358974 | 80 | 0.649504 | 3.877226 | false | false | false | false |
SpineEventEngine/core-java
|
buildSrc/src/main/kotlin/io/spine/internal/gradle/publish/SpinePublishing.kt
|
2
|
15843
|
/*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.publish
import io.spine.internal.gradle.Repository
import org.gradle.api.Project
import org.gradle.api.publish.PublicationContainer
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.findByType
import org.gradle.kotlin.dsl.getByType
/**
* Configures [SpinePublishing] extension.
*
* This extension sets up publishing of artifacts to Maven repositories.
*
* The extension can be configured for single- and multi-module projects.
*
* When used with a multi-module project, the extension should be opened in a root project's
* build file. The published modules are specified explicitly by their names:
*
* ```
* spinePublishing {
* modules = setOf(
* "subprojectA",
* "subprojectB",
* )
* destinations = setOf(
* PublishingRepos.cloudRepo,
* PublishingRepos.cloudArtifactRegistry,
* )
* }
* ```
*
* When used with a single-module project, the extension should be opened in a project's build file.
* Only destinations should be specified:
*
* ```
* spinePublishing {
* destinations = setOf(
* PublishingRepos.cloudRepo,
* PublishingRepos.cloudArtifactRegistry,
* )
* }
* ```
*
* It is worth to mention, that publishing of a module can be configured only from a single place.
* For example, declaring `subprojectA` as published in a root project and opening
* `spinePublishing` extension within `subprojectA` itself would lead to an exception.
*
* In Gradle, in order to publish something somewhere one should create a publication. In each
* of published modules, the extension will create a [publication][MavenJavaPublication]
* named "mavenJava". All artifacts, published by this extension belong to this publication.
*
* By default, along with the compilation output of "main" source set, the extension publishes
* the following artifacts:
*
* 1. [sourcesJar] – sources from "main" source set. Includes "hand-made" Java,
* Kotlin and Proto files. In order to include the generated code into this artifact, a module
* should specify those files as a part of "main" source set.
*
* Here's an example of how to do that:
*
* ```
* sourceSets {
* val generatedDir by extra("$projectDir/generated")
* val generatedSpineDir by extra("$generatedDir/main/java")
* main {
* java.srcDir(generatedSpineDir)
* }
* }
* ```
* 2. [protoJar] – only Proto sources from "main" source set. It's published only if
* Proto files are actually present in the source set. Publication of this artifact is optional
* and can be disabled via [SpinePublishing.protoJar].
* 3. [javadocJar] - javadoc, generated upon Java sources from "main" source set.
* If javadoc for Kotlin is also needed, apply Dokka plugin. It tunes `javadoc` task to generate
* docs upon Kotlin sources as well.
*
* Additionally, [testJar] artifact can be published. This artifact contains compilation output
* of "test" source set. Use [SpinePublishing.testJar] to enable its publishing.
*
* @see [registerArtifacts]
*/
fun Project.spinePublishing(configuration: SpinePublishing.() -> Unit) {
apply<MavenPublishPlugin>()
val name = SpinePublishing::class.java.simpleName
val extension = with(extensions) {
findByType<SpinePublishing>() ?: create(name, project)
}
extension.run {
configuration()
configured()
}
}
/**
* A Gradle extension for setting up publishing of spine modules using `maven-publish` plugin.
*
* @param project
* a project in which the extension is opened. By default, this project will be
* published as long as a [set][modules] of modules to publish is not specified explicitly.
*
* @see spinePublishing
*/
open class SpinePublishing(private val project: Project) {
private val protoJar = ProtoJar()
private val testJar = TestJar()
private val dokkaJar = DokkaJar()
/**
* Set of modules to be published.
*
* Both module's name or path can be used.
*
* Use this property if the extension is configured from a root project's build file.
*
* If left empty, the [project], in which the extension is opened, will be published.
*
* Empty by default.
*/
var modules: Set<String> = emptySet()
/**
* Set of modules that have custom publications and do not need standard ones.
*
* Empty by default.
*/
var modulesWithCustomPublishing: Set<String> = emptySet()
/**
* Set of repositories, to which the resulting artifacts will be sent.
*
* Usually, Spine-related projects are published to one or more repositories,
* declared in [PublishingRepos]:
*
* ```
* destinations = setOf(
* PublishingRepos.cloudRepo,
* PublishingRepos.cloudArtifactRegistry,
* PublishingRepos.gitHub("base"),
* )
* ```
*
* Empty by default.
*/
var destinations: Set<Repository> = emptySet()
/**
* A prefix to be added before the name of each artifact.
*
* Default value is "spine-".
*/
var artifactPrefix: String = "spine-"
/**
* Allows disabling publishing of [protoJar] artifact, containing all Proto sources
* from `sourceSets.main.proto`.
*
* Here's an example of how to disable it for some of published modules:
*
* ```
* spinePublishing {
* modules = setOf(
* "subprojectA",
* "subprojectB",
* )
* protoJar {
* exclusions = setOf(
* "subprojectB",
* )
* }
* }
* ```
*
* For all modules, or when the extension is configured within a published module itself:
*
* ```
* spinePublishing {
* protoJar {
* disabled = true
* }
* }
* ```
*
* The resulting artifact is available under "proto" classifier. I.e., in Gradle 7+, one could
* depend on it like this:
*
* ```
* implementation("io.spine:spine-client:$version@proto")
* ```
*/
fun protoJar(configuration: ProtoJar.() -> Unit) = protoJar.run(configuration)
/**
* Allows enabling publishing of [testJar] artifact, containing compilation output
* of "test" source set.
*
* Here's an example of how to enable it for some of published modules:
*
* ```
* spinePublishing {
* modules = setOf(
* "subprojectA",
* "subprojectB",
* )
* testJar {
* inclusions = setOf(
* "subprojectB",
* )
* }
* }
* ```
*
* For all modules, or when the extension is configured within a published module itself:
*
* ```
* spinePublishing {
* testJar {
* enabled = true
* }
* }
* ```
*
* The resulting artifact is available under "test" classifier. I.e., in Gradle 7+, one could
* depend on it like this:
*
* ```
* implementation("io.spine:spine-client:$version@test")
* ```
*/
fun testJar(configuration: TestJar.() -> Unit) = testJar.run(configuration)
/**
* Configures publishing of [dokkaJar] artifact, containing Dokka-generated documentation. By
* default, publishing of the artifact is disabled.
*
* Remember that the Dokka Gradle plugin should be applied to publish this artifact as it is
* produced by the `dokkaHtml` task. It can be done by using the
* [io.spine.internal.dependency.Dokka] dependency object or by applying the
* `buildSrc/src/main/kotlin/dokka-for-java` script plugin for Java projects.
*
* Here's an example of how to use this option:
*
* ```
* spinePublishing {
* dokkaJar {
* enabled = true
* }
* }
* ```
*
* The resulting artifact is available under "dokka" classifier.
*/
fun dokkaJar(configuration: DokkaJar.() -> Unit) = dokkaJar.run(configuration)
/**
* Called to notify the extension that its configuration is completed.
*
* On this stage the extension will validate the received configuration and set up
* `maven-publish` plugin for each published module.
*/
internal fun configured() {
ensureProtoJarExclusionsArePublished()
ensureTestJarInclusionsArePublished()
ensuresModulesNotDuplicated()
val protoJarExclusions = protoJar.exclusions
val testJarInclusions = testJar.inclusions
val publishedProjects = publishedProjects()
publishedProjects.forEach { project ->
val name = project.name
val includeProtoJar = (protoJarExclusions.contains(name) || protoJar.disabled).not()
val includeTestJar = (testJarInclusions.contains(name) || testJar.enabled)
setUpPublishing(project, includeProtoJar, includeTestJar, dokkaJar.enabled)
}
}
/**
* Maps the names of published modules to [Project] instances.
*
* The method considers two options:
*
* 1. The [set][modules] of subprojects to publish is not empty. It means that the extension
* is opened from a root project.
* 2. The [set][modules] is empty. Then, the [project] in which the extension is opened
* will be published.
*
* @see modules
*/
private fun publishedProjects() = modules.union(modulesWithCustomPublishing)
.map { name -> project.project(name) }
.ifEmpty { setOf(project) }
/**
* Sets up `maven-publish` plugin for the given project.
*
* Firstly, an instance of [PublishingConfig] is assembled for the project.
* Then, this config is applied.
*
* This method utilizes `project.afterEvaluate` closure. General rule of thumb is to avoid using
* of this closure, as it configures a project when its configuration is considered completed.
* Which is quite counter-intuitive.
*
* The root cause why it is used here is a possibility to configure publishing of multiple
* modules from a root project. When this possibility is employed, in fact, we configure
* publishing for a module, build file of which has not been even evaluated by that time.
* That leads to an unexpected behavior.
*
* The simplest example here is specifying of `version` and `group` for Maven coordinates.
* Let's suppose, they are declared in a module's build file. It is a common practice.
* But publishing of the module is configured from a root project's build file. By the time,
* when we need to specify them, we just don't know them. As a result, we have to use
* `project.afterEvaluate` in order to guarantee that a module will be configured by the time
* we configure publishing for it.
*/
private fun setUpPublishing(
project: Project,
includeProtoJar: Boolean,
includeTestJar: Boolean,
includeDokkaJar: Boolean
) {
val artifactId = artifactId(project)
val customPublishing = modulesWithCustomPublishing.contains(project.name)
val publishingConfig = if (customPublishing) {
PublishingConfig(artifactId, destinations)
} else {
PublishingConfig(
artifactId, destinations,
includeProtoJar, includeTestJar, includeDokkaJar
)
}
project.afterEvaluate {
publishingConfig.apply(project)
}
}
/**
* Obtains an artifact ID for the given project.
*
* It consists of a project's name and [prefix][artifactPrefix]:
* `<artifactPrefix><project.name>`.
*/
fun artifactId(project: Project): String = "$artifactPrefix${project.name}"
/**
* Ensures that all modules, marked as excluded from [protoJar] publishing,
* are actually published.
*
* It makes no sense to tell a module don't publish [protoJar] artifact, if the module is not
* published at all.
*/
private fun ensureProtoJarExclusionsArePublished() {
val nonPublishedExclusions = protoJar.exclusions.minus(modules)
if (nonPublishedExclusions.isNotEmpty()) {
throw IllegalStateException("One or more modules are marked as `excluded from proto " +
"JAR publication`, but they are not even published: $nonPublishedExclusions")
}
}
/**
* Ensures that all modules, marked as included into [testJar] publishing,
* are actually published.
*
* It makes no sense to tell a module publish [testJar] artifact, if the module is not
* published at all.
*/
private fun ensureTestJarInclusionsArePublished() {
val nonPublishedInclusions = testJar.inclusions.minus(modules)
if (nonPublishedInclusions.isNotEmpty()) {
error(
"One or more modules are marked as `included into test JAR publication`," +
" but they are not even published: $nonPublishedInclusions."
)
}
}
/**
* Ensures that publishing of a module is configured only from a single place.
*
* We allow configuration of publishing from two places - a root project and module itself.
* Here we verify that publishing of a module is not configured in both places simultaneously.
*/
private fun ensuresModulesNotDuplicated() {
val rootProject = project.rootProject
if (rootProject == project) {
return
}
val rootExtension = with(rootProject.extensions) { findByType<SpinePublishing>() }
rootExtension?.let { rootPublishing ->
val thisProject = setOf(project.name, project.path)
if (thisProject.minus(rootPublishing.modules).size != 2) {
error(
"Publishing of `$thisProject` module is already configured in a root project!"
)
}
}
}
}
/**
* Obtains [PublishingExtension] of this project.
*/
internal val Project.publishingExtension: PublishingExtension
get() = extensions.getByType()
/**
* Obtains [PublicationContainer] of this project.
*/
internal val Project.publications: PublicationContainer
get() = publishingExtension.publications
|
apache-2.0
|
179ff87a8d31d0d5193f83965301ef47
| 34.834842 | 100 | 0.64922 | 4.460434 | false | true | false | false |
michaelgallacher/intellij-community
|
platform/configuration-store-impl/src/SchemeManagerImpl.kt
|
1
|
33214
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.extensions.AbstractExtensionPointBean
import com.intellij.openapi.options.*
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.PathUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.ConcurrentList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.*
import com.intellij.util.loadElement
import com.intellij.util.messages.MessageBus
import com.intellij.util.text.UniqueNameGenerator
import gnu.trove.THashSet
import org.jdom.Document
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.Path
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Function
class SchemeManagerImpl<T : Scheme, MUTABLE_SCHEME : T>(val fileSpec: String,
private val processor: SchemeProcessor<T, MUTABLE_SCHEME>,
private val provider: StreamProvider?,
private val ioDirectory: Path,
val roamingType: RoamingType = RoamingType.DEFAULT,
val presentableName: String? = null,
private val isUseOldFileNameSanitize: Boolean = false,
private val messageBus: MessageBus? = null) : SchemeManager<T>(), SafeWriteRequestor {
private val isLoadingSchemes = AtomicBoolean()
private val schemesRef = AtomicReference(ContainerUtil.createLockFreeCopyOnWriteList<T>() as ConcurrentList<T>)
private val schemes: ConcurrentList<T>
get() = schemesRef.get()
private val readOnlyExternalizableSchemes = ContainerUtil.newConcurrentMap<String, T>()
/**
* Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance.
*/
private @Volatile var currentPendingSchemeName: String? = null
private var currentScheme: T? = null
private var cachedVirtualDirectory: VirtualFile? = null
private val schemeExtension: String
private val updateExtension: Boolean
private val filesToDelete = ContainerUtil.newConcurrentSet<String>()
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
private val schemeToInfo = ContainerUtil.newConcurrentMap<T, ExternalInfo>(ContainerUtil.identityStrategy())
private val useVfs = messageBus != null
init {
if (processor is SchemeExtensionProvider) {
schemeExtension = processor.schemeExtension
updateExtension = true
}
else {
schemeExtension = FileStorageCoreUtil.DEFAULT_EXT
updateExtension = false
}
if (useVfs && (provider == null || !provider.isApplicable(fileSpec, roamingType))) {
LOG.catchAndLog { refreshVirtualDirectoryAndAddListener() }
}
}
private inner class SchemeFileTracker() : BulkFileListener.Adapter() {
private fun isMy(file: VirtualFile) = isMy(file.nameSequence)
private fun isMy(name: CharSequence) = name.endsWith(schemeExtension, ignoreCase = true) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name))
override fun after(events: MutableList<out VFileEvent>) {
eventLoop@ for (event in events) {
if (event.requestor is SchemeManagerImpl<*, *>) {
continue
}
fun isMyDirectory(parent: VirtualFile) = cachedVirtualDirectory.let { if (it == null) ioDirectory.systemIndependentPath == parent.path else it == parent }
when (event) {
is VFileContentChangeEvent -> {
if (!isMy(event.file) || !isMyDirectory(event.file.parent)) {
continue@eventLoop
}
val oldCurrentScheme = currentScheme
findExternalizableSchemeByFileName(event.file.name)?.let {
removeScheme(it)
processor.onSchemeDeleted(it)
}
updateCurrentScheme(oldCurrentScheme, readSchemeFromFile(event.file)?.let {
processor.initScheme(it)
processor.onSchemeAdded(it)
it
})
}
is VFileCreateEvent -> {
if (isMy(event.childName)) {
if (isMyDirectory(event.parent)) {
event.file?.let { schemeCreatedExternally(it) }
}
}
else if (event.file?.isDirectory ?: false) {
val dir = virtualDirectory
if (event.file == dir) {
for (file in dir!!.children) {
if (isMy(file)) {
schemeCreatedExternally(file)
}
}
}
}
}
is VFileDeleteEvent -> {
val oldCurrentScheme = currentScheme
if (event.file.isDirectory) {
val dir = virtualDirectory
if (event.file == dir) {
cachedVirtualDirectory = null
removeExternalizableSchemes()
}
}
else if (isMy(event.file) && isMyDirectory(event.file.parent)) {
val scheme = findExternalizableSchemeByFileName(event.file.name) ?: continue@eventLoop
removeScheme(scheme)
processor.onSchemeDeleted(scheme)
}
updateCurrentScheme(oldCurrentScheme)
}
}
}
}
private fun schemeCreatedExternally(file: VirtualFile) {
val readScheme = readSchemeFromFile(file)
if (readScheme != null) {
processor.initScheme(readScheme)
processor.onSchemeAdded(readScheme)
}
}
private fun updateCurrentScheme(oldScheme: T?, newScheme: T? = null) {
if (currentScheme != null) {
return
}
if (oldScheme != currentScheme) {
val scheme = newScheme ?: schemes.firstOrNull()
currentPendingSchemeName = null
currentScheme = scheme
// must be equals by reference
if (oldScheme !== scheme) {
processor.onCurrentSchemeSwitched(oldScheme, scheme)
}
}
else if (newScheme != null) {
processPendingCurrentSchemeName(newScheme)
}
}
}
private fun refreshVirtualDirectoryAndAddListener() {
// store refreshes root directory, so, we don't need to use refreshAndFindFile
val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return
this.cachedVirtualDirectory = directory
directory.children
if (directory is NewVirtualFile) {
directory.markDirty()
}
directory.refresh(true, false)
}
override fun loadBundledScheme(resourceName: String, requestor: Any) {
try {
val url = if (requestor is AbstractExtensionPointBean)
requestor.loaderForClass.getResource(resourceName)
else
DecodeDefaultsUtil.getDefaults(requestor, resourceName)
if (url == null) {
LOG.error("Cannot read scheme from $resourceName")
return
}
val bytes = URLUtil.openStream(url).readBytes()
lazyPreloadScheme(bytes, isUseOldFileNameSanitize) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val schemeName = name ?: (processor as LazySchemeProcessor).getName(attributeProvider)
val fileName = PathUtilRt.getFileName(url.path)
val extension = getFileExtension(fileName, true)
val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension)
externalInfo.schemeName = schemeName
val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeName, attributeProvider, true)
val oldInfo = schemeToInfo.put(scheme, externalInfo)
LOG.assertTrue(oldInfo == null)
val oldScheme = readOnlyExternalizableSchemes.put(scheme.name, scheme)
if (oldScheme != null) {
LOG.warn("Duplicated scheme ${scheme.name} - old: $oldScheme, new $scheme")
}
schemes.add(scheme)
}
}
catch (e: Throwable) {
LOG.error("Cannot read scheme from $resourceName", e)
}
}
private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String {
return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) {
schemeExtension
}
else if (StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT)) {
DEFAULT_EXT
}
else if (allowAny) {
PathUtil.getFileExtension(fileName.toString())!!
}
else {
throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out")
}
}
override fun loadSchemes(): Collection<T> {
if (!isLoadingSchemes.compareAndSet(false, true)) {
throw IllegalStateException("loadSchemes is already called")
}
try {
val filesToDelete = THashSet<String>()
val oldSchemes = schemes
val schemes = oldSchemes.toMutableList()
val newSchemesOffset = schemes.size
if (provider != null && provider.isApplicable(fileSpec, roamingType)) {
provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly ->
catchAndLog(name) {
val scheme = loadScheme(name, input, schemes, filesToDelete)
if (readOnly && scheme != null) {
readOnlyExternalizableSchemes.put(scheme.name, scheme)
}
}
true
}
}
else {
ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) {
for (file in it) {
if (file.isDirectory()) {
continue
}
catchAndLog(file.fileName.toString()) { filename ->
file.inputStream().use { loadScheme(filename, it, schemes, filesToDelete) }
}
}
}
}
this.filesToDelete.addAll(filesToDelete)
replaceSchemeList(oldSchemes, schemes)
@Suppress("UNCHECKED_CAST")
for (i in newSchemesOffset..schemes.size - 1) {
val scheme = schemes.get(i) as MUTABLE_SCHEME
processor.initScheme(scheme)
@Suppress("UNCHECKED_CAST")
processPendingCurrentSchemeName(scheme)
}
messageBus?.let { it.connect().subscribe(VirtualFileManager.VFS_CHANGES, SchemeFileTracker()) }
return schemes.subList(newSchemesOffset, schemes.size)
}
finally {
isLoadingSchemes.set(false)
}
}
private fun replaceSchemeList(oldList: ConcurrentList<T>, newList: List<T>) {
if (!schemesRef.compareAndSet(oldList, ContainerUtil.createLockFreeCopyOnWriteList(newList) as ConcurrentList<T>)) {
throw IllegalStateException("Scheme list was modified")
}
}
override fun reload() {
// we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously)
removeExternalizableSchemes()
loadSchemes()
}
private fun removeExternalizableSchemes() {
// todo check is bundled/read-only schemes correctly handled
val iterator = schemes.iterator()
for (scheme in iterator) {
if (processor.getState(scheme) == SchemeState.NON_PERSISTENT) {
continue
}
if (scheme === currentScheme) {
currentScheme = null
}
iterator.remove()
@Suppress("UNCHECKED_CAST")
processor.onSchemeDeleted(scheme as MUTABLE_SCHEME)
}
retainExternalInfo()
}
@Suppress("UNCHECKED_CAST")
private fun findExternalizableSchemeByFileName(fileName: String) = schemes.firstOrNull { fileName == "${it.fileName}$schemeExtension" } as MUTABLE_SCHEME?
private fun isOverwriteOnLoad(existingScheme: T): Boolean {
val info = schemeToInfo.get(existingScheme)
// scheme from file with old extension, so, we must ignore it
return info != null && schemeExtension != info.fileExtension
}
private inner class SchemeDataHolderImpl(private val bytes: ByteArray, private val externalInfo: ExternalInfo) : SchemeDataHolder<MUTABLE_SCHEME> {
override fun read(): Element = loadElement(bytes.inputStream())
override fun updateDigest(scheme: MUTABLE_SCHEME) {
try {
updateDigest(processor.writeScheme(scheme) as Element)
}
catch (e: WriteExternalException) {
LOG.error("Cannot update digest", e)
}
}
override fun updateDigest(data: Element) {
externalInfo.digest = data.digest()
}
}
private fun loadScheme(fileName: String, input: InputStream, schemes: MutableList<T>, filesToDelete: MutableSet<String>? = null): MUTABLE_SCHEME? {
val extension = getFileExtension(fileName, false)
if (filesToDelete != null && filesToDelete.contains(fileName)) {
LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete")
return null
}
val fileNameWithoutExtension = fileName.substring(0, fileName.length - extension.length)
fun checkExisting(schemeName: String): Boolean {
if (filesToDelete == null) {
return true
}
schemes.firstOrNull({ it.name == schemeName})?.let { existingScheme ->
if (readOnlyExternalizableSchemes.get(existingScheme.name) === existingScheme) {
// so, bundled scheme is shadowed
removeFirstScheme({ it === existingScheme }, schemes, scheduleDelete = false)
return true
}
else if (processor.isExternalizable(existingScheme) && isOverwriteOnLoad(existingScheme)) {
removeFirstScheme({ it === existingScheme }, schemes)
}
else {
if (schemeExtension != extension && schemeToInfo.get(existingScheme as Scheme)?.fileNameWithoutExtension == fileNameWithoutExtension) {
// 1.oldExt is loading after 1.newExt - we should delete 1.oldExt
filesToDelete.add(fileName)
}
else {
// We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name.
// It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it.
LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"$schemeName\"")
}
return false
}
}
return true
}
fun createInfo(schemeName: String, element: Element?): ExternalInfo {
val info = ExternalInfo(fileNameWithoutExtension, extension)
element?.let {
info.digest = it.digest()
}
info.schemeName = schemeName
return info
}
val duringLoad = filesToDelete != null
var scheme: MUTABLE_SCHEME? = null
if (processor is LazySchemeProcessor) {
val bytes = input.readBytes()
lazyPreloadScheme(bytes, isUseOldFileNameSanitize) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val schemeName = name ?: processor.getName(attributeProvider)
if (!checkExisting(schemeName)) {
return null
}
val externalInfo = createInfo(schemeName, null)
scheme = processor.createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeName, attributeProvider)
schemeToInfo.put(scheme, externalInfo)
this.filesToDelete.remove(fileName)
}
}
else {
val element = loadElement(input)
scheme = (processor as NonLazySchemeProcessor).readScheme(element, duringLoad) ?: return null
val schemeName = scheme!!.name
if (!checkExisting(schemeName)) {
return null
}
schemeToInfo.put(scheme, createInfo(schemeName, element))
this.filesToDelete.remove(fileName)
}
@Suppress("UNCHECKED_CAST")
if (duringLoad) {
schemes.add(scheme as T)
}
else {
addNewScheme(scheme as T, true)
}
return scheme
}
private val T.fileName: String?
get() = schemeToInfo.get(this)?.fileNameWithoutExtension
fun canRead(name: CharSequence) = (updateExtension && name.endsWith(DEFAULT_EXT, true) || name.endsWith(schemeExtension, true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name))
private fun readSchemeFromFile(file: VirtualFile, schemes: MutableList<T> = this.schemes): MUTABLE_SCHEME? {
val fileName = file.name
if (file.isDirectory || !canRead(fileName)) {
return null
}
catchAndLog(fileName) {
return file.inputStream.use { loadScheme(fileName, it, schemes) }
}
return null
}
fun save(errors: MutableList<Throwable>) {
if (isLoadingSchemes.get()) {
LOG.warn("Skip save - schemes are loading")
}
var hasSchemes = false
val nameGenerator = UniqueNameGenerator()
val schemesToSave = SmartList<MUTABLE_SCHEME>()
for (scheme in schemes) {
val state = processor.getState(scheme)
if (state == SchemeState.NON_PERSISTENT) {
continue
}
hasSchemes = true
if (state != SchemeState.UNCHANGED) {
@Suppress("UNCHECKED_CAST")
schemesToSave.add(scheme as MUTABLE_SCHEME)
}
val fileName = scheme.fileName
if (fileName != null && !isRenamed(scheme)) {
nameGenerator.addExistingName(fileName)
}
}
for (scheme in schemesToSave) {
try {
saveScheme(scheme, nameGenerator)
}
catch (e: Throwable) {
errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e))
}
}
val filesToDelete = THashSet(filesToDelete)
if (!filesToDelete.isEmpty) {
this.filesToDelete.removeAll(filesToDelete)
deleteFiles(errors, filesToDelete)
// remove empty directory only if some file was deleted - avoid check on each save
if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) {
removeDirectoryIfEmpty(errors)
}
}
}
private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) {
ioDirectory.directoryStreamIfExists {
for (file in it) {
if (!file.isHidden()) {
LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists")
return@removeDirectoryIfEmpty
}
}
}
LOG.info("Remove schemes directory ${ioDirectory.fileName}")
cachedVirtualDirectory = null
var deleteUsingIo = !useVfs
if (!deleteUsingIo) {
virtualDirectory?.let {
runWriteAction {
try {
it.delete(this)
}
catch (e: IOException) {
deleteUsingIo = true
errors.add(e)
}
}
}
}
if (deleteUsingIo) {
errors.catch { ioDirectory.delete() }
}
}
private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator) {
var externalInfo: ExternalInfo? = schemeToInfo.get(scheme)
val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension
val parent = processor.writeScheme(scheme)
val element = if (parent is Element) parent else (parent as Document).detachRootElement()
if (JDOMUtil.isEmpty(element)) {
externalInfo?.scheduleDelete()
return
}
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.name, isUseOldFileNameSanitize))
}
val newDigest = element!!.digest()
if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest)) {
return
}
// save only if scheme differs from bundled
val bundledScheme = readOnlyExternalizableSchemes.get(scheme.name)
if (bundledScheme != null && schemeToInfo.get(bundledScheme)?.isDigestEquals(newDigest) ?: false) {
externalInfo?.scheduleDelete()
return
}
// we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open)
if (processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest)) {
externalInfo?.scheduleDelete()
return
}
val fileName = fileNameWithoutExtension!! + schemeExtension
// file will be overwritten, so, we don't need to delete it
filesToDelete.remove(fileName)
// stream provider always use LF separator
val byteOut = element.toBufferExposingByteArray()
var providerPath: String?
if (provider != null && provider.enabled) {
providerPath = "$fileSpec/$fileName"
if (!provider.isApplicable(providerPath, roamingType)) {
providerPath = null
}
}
else {
providerPath = null
}
// if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation)
val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension)
if (providerPath == null) {
if (useVfs) {
var file: VirtualFile? = null
var dir = virtualDirectory
if (dir == null || !dir.isValid) {
dir = createDir(ioDirectory, this)
cachedVirtualDirectory = dir
}
if (renamed) {
file = dir.findChild(externalInfo!!.fileName)
if (file != null) {
runWriteAction {
file!!.rename(this, fileName)
}
}
}
if (file == null) {
file = getFile(fileName, dir, this)
}
runWriteAction {
file!!.getOutputStream(this).use {
byteOut.writeTo(it)
}
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete()
}
ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size())
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete()
}
provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType)
}
if (externalInfo == null) {
externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension)
schemeToInfo.put(scheme, externalInfo)
}
else {
externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension)
}
externalInfo.digest = newDigest
externalInfo.schemeName = scheme.name
}
private fun ExternalInfo.scheduleDelete() {
filesToDelete.add(fileName)
}
private fun isRenamed(scheme: T): Boolean {
val info = schemeToInfo.get(scheme)
return info != null && scheme.name != info.schemeName
}
private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) {
if (provider != null && provider.enabled) {
val iterator = filesToDelete.iterator()
for (name in iterator) {
errors.catch {
val spec = "$fileSpec/$name"
if (provider.isApplicable(spec, roamingType)) {
iterator.remove()
provider.delete(spec, roamingType)
}
}
}
}
if (filesToDelete.isEmpty()) {
return
}
if (useVfs) {
virtualDirectory?.let {
var token: AccessToken? = null
try {
for (file in it.children) {
if (filesToDelete.contains(file.name)) {
if (token == null) {
token = WriteAction.start()
}
errors.catch {
file.delete(this)
}
}
}
}
finally {
token?.finish()
}
return
}
}
for (name in filesToDelete) {
errors.catch { ioDirectory.resolve(name).delete() }
}
}
private val virtualDirectory: VirtualFile?
get() {
var result = cachedVirtualDirectory
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath)
cachedVirtualDirectory = result
}
return result
}
override fun getRootDirectory(): File = ioDirectory.toFile()
override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) {
if (removeCondition == null) {
schemes.clear()
}
else {
val iterator = schemes.iterator()
for (scheme in iterator) {
if (removeCondition.value(scheme)) {
iterator.remove()
}
}
}
schemes.addAll(newSchemes)
val oldCurrentScheme = currentScheme
retainExternalInfo()
if (oldCurrentScheme != newCurrentScheme) {
val newScheme: T?
if (newCurrentScheme != null) {
currentScheme = newCurrentScheme
newScheme = newCurrentScheme
}
else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) {
newScheme = schemes.firstOrNull()
currentScheme = newScheme
}
else {
newScheme = null
}
if (oldCurrentScheme != newScheme) {
processor.onCurrentSchemeSwitched(oldCurrentScheme, newScheme)
}
}
}
private fun retainExternalInfo() {
if (schemeToInfo.isEmpty()) {
return
}
val iterator = schemeToInfo.entries.iterator()
l@ for ((scheme, info) in iterator) {
if (readOnlyExternalizableSchemes.get(scheme.name) == scheme) {
continue
}
for (s in schemes) {
if (s === scheme) {
filesToDelete.remove(info.fileName)
continue@l
}
}
iterator.remove()
info.scheduleDelete()
}
}
override fun addNewScheme(scheme: T, replaceExisting: Boolean) {
var toReplace = -1
val schemes = schemes
for (i in schemes.indices) {
val existing = schemes.get(i)
if (existing.name == scheme.name) {
if (existing.javaClass != scheme.javaClass) {
LOG.warn("'${scheme.name}' ${existing.javaClass.simpleName} replaced with ${scheme.javaClass.simpleName}")
}
toReplace = i
if (replaceExisting && processor.isExternalizable(existing)) {
val oldInfo = schemeToInfo.remove(existing)
if (oldInfo != null && processor.isExternalizable(scheme) && !schemeToInfo.containsKey(scheme)) {
schemeToInfo.put(scheme, oldInfo)
}
}
break
}
}
if (toReplace == -1) {
schemes.add(scheme)
}
else if (replaceExisting || !processor.isExternalizable(scheme)) {
schemes.set(toReplace, scheme)
}
else {
(scheme as ExternalizableScheme).renameScheme(UniqueNameGenerator.generateUniqueName(scheme.name, collectExistingNames(schemes)))
schemes.add(scheme)
}
if (processor.isExternalizable(scheme) && filesToDelete.isNotEmpty()) {
schemeToInfo.get(scheme)?.let {
filesToDelete.remove(it.fileName)
}
}
processPendingCurrentSchemeName(scheme)
}
private fun collectExistingNames(schemes: Collection<T>): Collection<String> {
val result = THashSet<String>(schemes.size)
for (scheme in schemes) {
result.add(scheme.name)
}
return result
}
override fun clearAllSchemes() {
for (it in schemeToInfo.values) {
it.scheduleDelete()
}
currentScheme = null
schemes.clear()
schemeToInfo.clear()
}
override fun getAllSchemes(): List<T> = Collections.unmodifiableList(schemes)
override fun isEmpty() = schemes.isEmpty()
override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { it.name == schemeName }
override fun setCurrent(scheme: T?, notify: Boolean) {
currentPendingSchemeName = null
val oldCurrent = currentScheme
currentScheme = scheme
if (notify && oldCurrent !== scheme) {
processor.onCurrentSchemeSwitched(oldCurrent, scheme)
}
}
override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) {
currentPendingSchemeName = schemeName
val scheme = if (schemeName == null) null else findSchemeByName(schemeName)
// don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment)
if (scheme != null || schemeName == null) {
setCurrent(scheme, notify)
}
}
override fun getCurrentScheme() = currentScheme
override fun getCurrentSchemeName() = currentScheme?.name ?: currentPendingSchemeName
private fun processPendingCurrentSchemeName(newScheme: T) {
if (newScheme.name == currentPendingSchemeName) {
setCurrent(newScheme, false)
}
}
override fun removeScheme(schemeName: String) = removeFirstScheme({it.name == schemeName}, schemes)
override fun removeScheme(scheme: T) {
removeFirstScheme({ it == scheme }, schemes)
}
private fun removeFirstScheme(condition: (T) -> Boolean, schemes: MutableList<T>, scheduleDelete: Boolean = true): T? {
val iterator = schemes.iterator()
for (scheme in iterator) {
if (!condition(scheme)) {
continue
}
if (currentScheme === scheme) {
currentScheme = null
}
iterator.remove()
if (scheduleDelete && processor.isExternalizable(scheme)) {
schemeToInfo.remove(scheme)?.scheduleDelete()
}
return scheme
}
return null
}
override fun getAllSchemeNames() = schemes.let { if (it.isEmpty()) emptyList() else it.map { it.name } }
override fun isMetadataEditable(scheme: T) = !readOnlyExternalizableSchemes.containsKey(scheme.name)
private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) {
// we keep it to detect rename
var schemeName: String? = null
var digest: ByteArray? = null
val fileName: String
get() = "$fileNameWithoutExtension$fileExtension"
fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) {
fileNameWithoutExtension = nameWithoutExtension
fileExtension = extension
}
fun isDigestEquals(newDigest: ByteArray) = Arrays.equals(digest, newDigest)
override fun toString() = fileName
}
override fun toString() = fileSpec
}
private fun ExternalizableScheme.renameScheme(newName: String) {
if (newName != name) {
name = newName
LOG.assertTrue(newName == name)
}
}
private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) {
try {
runnable()
}
catch (e: Throwable) {
add(e)
}
}
fun createDir(ioDir: Path, requestor: Any): VirtualFile {
ioDir.createDirectories()
val parentFile = ioDir.parent
val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile))
return getFile(ioDir.fileName.toString(), parentVirtualFile, requestor)
}
fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile {
return parent.findChild(fileName) ?: runWriteAction { parent.createChildData(requestor, fileName) }
}
private inline fun catchAndLog(fileName: String, runnable: (fileName: String) -> Unit) {
try {
runnable(fileName)
}
catch (e: Throwable) {
LOG.error("Cannot read scheme $fileName", e)
}
}
|
apache-2.0
|
29045a2000bf20f70c291b431a8a9df4
| 32.584429 | 229 | 0.656651 | 4.862246 | false | false | false | false |
Light-Team/ModPE-IDE-Source
|
app/src/main/kotlin/com/brackeys/ui/feature/main/adapters/TabAdapter.kt
|
1
|
4587
|
/*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.feature.main.adapters
import androidx.recyclerview.widget.RecyclerView
abstract class TabAdapter<T, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() {
val selectedPosition
get() = _selectedPosition
private var _selectedPosition = -1
val currentList: List<T>
get() = _currentList
private var _currentList: MutableList<T> = mutableListOf()
private var onTabSelectedListener: OnTabSelectedListener? = null
private var onTabMovedListener: OnTabMovedListener? = null
private var onDataRefreshListener: OnDataRefreshListener? = null
private var recyclerView: RecyclerView? = null
private var isClosing = false
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
this.recyclerView = recyclerView
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
this.recyclerView = null
}
override fun getItemCount(): Int = currentList.size
fun submitList(list: List<T>) {
_currentList = list.toMutableList()
notifyDataSetChanged()
onDataRefreshListener?.onDataRefresh()
}
fun move(from: Int, to: Int): Boolean {
val temp = currentList[from]
_currentList.removeAt(from)
_currentList.add(to, temp)
when {
selectedPosition in to until from -> _selectedPosition++
selectedPosition in (from + 1)..to -> _selectedPosition--
from == selectedPosition -> _selectedPosition = to
}
onTabMovedListener?.onTabMoved(from, to)
notifyItemMoved(from, to)
return true
}
fun select(newPosition: Int) {
if (newPosition == selectedPosition && !isClosing) {
onTabSelectedListener?.onTabReselected(selectedPosition)
} else {
val previousPosition = selectedPosition
_selectedPosition = newPosition
if (previousPosition > -1 && selectedPosition > -1 && previousPosition < currentList.size) {
notifyItemChanged(previousPosition) // Update previous selected item
if (!isClosing) {
onTabSelectedListener?.onTabUnselected(previousPosition)
}
}
if (selectedPosition > -1) {
notifyItemChanged(selectedPosition) // Update new selected item
onTabSelectedListener?.onTabSelected(selectedPosition)
recyclerView?.smoothScrollToPosition(selectedPosition)
}
}
}
// I'm going crazy with this
fun close(position: Int) {
isClosing = true
var newPosition = selectedPosition
if (position == selectedPosition) {
newPosition = when {
position - 1 > -1 -> position - 1
position + 1 < itemCount -> position
else -> -1
}
}
if (position < selectedPosition) {
newPosition -= 1
}
_currentList.removeAt(position)
notifyItemRemoved(position)
onDataRefreshListener?.onDataRefresh()
select(newPosition)
isClosing = false
}
fun setOnTabSelectedListener(listener: OnTabSelectedListener) {
onTabSelectedListener = listener
}
fun setOnTabMovedListener(listener: OnTabMovedListener) {
onTabMovedListener = listener
}
fun setOnDataRefreshListener(listener: OnDataRefreshListener) {
onDataRefreshListener = listener
}
interface OnTabSelectedListener {
fun onTabReselected(position: Int) = Unit
fun onTabUnselected(position: Int) = Unit
fun onTabSelected(position: Int) = Unit
}
interface OnTabMovedListener {
fun onTabMoved(from: Int, to: Int)
}
interface OnDataRefreshListener {
fun onDataRefresh()
}
}
|
apache-2.0
|
555cf17890e71852eeb752f1a46675f5
| 32.246377 | 104 | 0.652496 | 5.346154 | false | false | false | false |
nickthecoder/paratask
|
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/NewPlacesFileTask.kt
|
1
|
1480
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.tools.places
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.StringParameter
import java.io.File
class NewPlacesFileTask() : AbstractTask() {
override val taskD = TaskDescription("createNewPlacesFile")
val directoryP = FileParameter("directory", mustExist = true, expectFile = false)
val filenameP = StringParameter("filename")
init {
taskD.addParameters(directoryP, filenameP)
}
constructor(directory: File) : this() {
directoryP.value = directory
}
override fun run() {
val file = File(directoryP.value!!, filenameP.value)
file.writeText("")
}
}
|
gpl-3.0
|
27f0428885fbf6dc14b1d24a00b6ef55
| 31.173913 | 85 | 0.753378 | 4.340176 | false | false | false | false |
nextcloud/android
|
app/src/main/java/com/nextcloud/client/etm/EtmViewModel.kt
|
1
|
6580
|
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.etm.pages.EtmAccountsFragment
import com.nextcloud.client.etm.pages.EtmBackgroundJobsFragment
import com.nextcloud.client.etm.pages.EtmFileTransferFragment
import com.nextcloud.client.etm.pages.EtmMigrations
import com.nextcloud.client.etm.pages.EtmPreferencesFragment
import com.nextcloud.client.files.downloader.TransferManagerConnection
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.JobInfo
import com.nextcloud.client.migrations.MigrationInfo
import com.nextcloud.client.migrations.MigrationsDb
import com.nextcloud.client.migrations.MigrationsManager
import com.owncloud.android.R
import com.owncloud.android.lib.common.accounts.AccountUtils
import javax.inject.Inject
@Suppress("LongParameterList") // Dependencies Injection
@SuppressLint("StaticFieldLeak")
class EtmViewModel @Inject constructor(
private val context: Context,
private val defaultPreferences: SharedPreferences,
private val platformAccountManager: AccountManager,
private val accountManager: UserAccountManager,
private val resources: Resources,
private val backgroundJobManager: BackgroundJobManager,
private val migrationsManager: MigrationsManager,
private val migrationsDb: MigrationsDb
) : ViewModel() {
companion object {
val ACCOUNT_USER_DATA_KEYS = listOf(
// AccountUtils.Constants.KEY_COOKIES, is disabled
AccountUtils.Constants.KEY_DISPLAY_NAME,
AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
AccountUtils.Constants.KEY_OC_BASE_URL,
AccountUtils.Constants.KEY_OC_VERSION,
AccountUtils.Constants.KEY_USER_ID
)
const val PAGE_SETTINGS = 0
const val PAGE_ACCOUNTS = 1
const val PAGE_JOBS = 2
const val PAGE_MIGRATIONS = 3
}
/**
* This data class holds all relevant account information that is
* otherwise kept in separate collections.
*/
data class AccountData(val account: Account, val userData: Map<String, String?>)
val currentUser: User get() = accountManager.user
val currentPage: LiveData<EtmMenuEntry?> = MutableLiveData()
val pages: List<EtmMenuEntry> = listOf(
EtmMenuEntry(
iconRes = R.drawable.ic_settings,
titleRes = R.string.etm_preferences,
pageClass = EtmPreferencesFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_user,
titleRes = R.string.etm_accounts,
pageClass = EtmAccountsFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_clock,
titleRes = R.string.etm_background_jobs,
pageClass = EtmBackgroundJobsFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_arrow_up,
titleRes = R.string.etm_migrations,
pageClass = EtmMigrations::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_cloud_download,
titleRes = R.string.etm_transfer,
pageClass = EtmFileTransferFragment::class
)
)
val transferManagerConnection = TransferManagerConnection(context, accountManager.user)
val preferences: Map<String, String> get() {
return defaultPreferences.all
.map { it.key to "${it.value}" }
.sortedBy { it.first }
.toMap()
}
val accounts: List<AccountData> get() {
val accountType = resources.getString(R.string.account_type)
return platformAccountManager.getAccountsByType(accountType).map { account ->
val userData: Map<String, String?> = ACCOUNT_USER_DATA_KEYS.map { key ->
key to platformAccountManager.getUserData(account, key)
}.toMap()
AccountData(account, userData)
}
}
val backgroundJobs: LiveData<List<JobInfo>> get() {
return backgroundJobManager.jobs
}
val migrationsInfo: List<MigrationInfo> get() {
return migrationsManager.info
}
val migrationsStatus: MigrationsManager.Status get() {
return migrationsManager.status.value ?: MigrationsManager.Status.UNKNOWN
}
val lastMigratedVersion: Int get() {
return migrationsDb.lastMigratedVersion
}
init {
(currentPage as MutableLiveData).apply {
value = null
}
}
fun onPageSelected(index: Int) {
if (index < pages.size) {
currentPage as MutableLiveData
currentPage.value = pages[index]
}
}
fun onBackPressed(): Boolean {
(currentPage as MutableLiveData)
return if (currentPage.value != null) {
currentPage.value = null
true
} else {
false
}
}
fun pruneJobs() {
backgroundJobManager.pruneJobs()
}
fun cancelAllJobs() {
backgroundJobManager.cancelAllJobs()
}
fun startTestJob(periodic: Boolean) {
if (periodic) {
backgroundJobManager.scheduleTestJob()
} else {
backgroundJobManager.startImmediateTestJob()
}
}
fun cancelTestJob() {
backgroundJobManager.cancelTestJob()
}
fun clearMigrations() {
migrationsDb.clearMigrations()
}
}
|
gpl-2.0
|
4a3da9711385d2dba01dddd8f74811a1
| 33.093264 | 91 | 0.685714 | 4.768116 | false | false | false | false |
jitsi/jicofo
|
jicofo/src/main/kotlin/org/jitsi/jicofo/xmpp/muc/ChatRoomRoleManager.kt
|
1
|
5487
|
/*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2021-Present 8x8, 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 org.jitsi.jicofo.xmpp.muc
import org.jitsi.impl.protocol.xmpp.ChatRoom
import org.jitsi.impl.protocol.xmpp.ChatRoomMember
import org.jitsi.jicofo.auth.AuthenticationAuthority
import org.jitsi.jicofo.auth.AuthenticationListener
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.logging2.createLogger
/**
* Manages to XMPP roles of occupants in a chat room, i.e. grants ownership to certain users.
*/
sealed class ChatRoomRoleManager(
protected val chatRoom: ChatRoom
) : ChatRoomListener {
protected val logger = createLogger()
/** Grants ownership to [member], blocks for a response from the MUC service. */
protected fun grantOwner(member: ChatRoomMember): Boolean {
if (!chatRoom.userRole.hasOwnerRights()) {
logger.warn("Can not grant owner, lacking privileges.")
return false
}
return try {
chatRoom.grantOwnership(member)
true
} catch (e: RuntimeException) {
logger.error("Failed to grant owner status to ${member.jid}", e)
false
}
}
override fun memberLeft(member: ChatRoomMember) = memberLeftOrKicked(member)
override fun memberKicked(member: ChatRoomMember) = memberLeftOrKicked(member)
protected open fun memberLeftOrKicked(member: ChatRoomMember) {}
open fun stop() {}
open val debugState: OrderedJsonObject = OrderedJsonObject()
}
/**
* A [ChatRoomRoleManager] which grants ownership to a single occupant in the room (if the room is left without an
* owner, it elects a new one).
*/
class AutoOwnerRoleManager(chatRoom: ChatRoom) : ChatRoomRoleManager(chatRoom) {
private var owner: ChatRoomMember? = null
override fun memberJoined(member: ChatRoomMember) {
if (owner == null) { electNewOwner() }
}
override fun memberLeftOrKicked(member: ChatRoomMember) {
if (member == owner) {
logger.debug("The owner left the room, electing a new one.")
owner = null
electNewOwner()
}
}
override fun localRoleChanged(newRole: MemberRole, oldRole: MemberRole?) {
if (!newRole.hasOwnerRights()) {
logger.error("Local role has no owner rights, can not manage roles.")
return
}
electNewOwner()
}
private fun electNewOwner() {
if (owner != null) {
return
}
// Skip if this is a breakout room.
if (chatRoom.isBreakoutRoom) {
return
}
owner = chatRoom.members.find { !it.isRobot && it.role.hasOwnerRights() }
if (owner != null) {
return
}
val newOwner = chatRoom.members.find { !it.isRobot && it.role != MemberRole.VISITOR }
if (newOwner != null) {
logger.info("Electing new owner: $newOwner")
grantOwner(newOwner)
owner = newOwner
}
}
override val debugState
get() = OrderedJsonObject().apply {
put("class", [email protected])
put("owner", owner?.jid?.toString() ?: "null")
}
}
/** A [ChatRoomRoleManager] which grants ownership to all authenticated users. */
class AuthenticationRoleManager(
chatRoom: ChatRoom,
/** Used to check whether a user is authenticated, and subscribe to authentication events. */
private val authenticationAuthority: AuthenticationAuthority
) : ChatRoomRoleManager(chatRoom) {
private val authenticationListener = AuthenticationListener { userJid, _, _ ->
chatRoom.members.find { it.jid == userJid }?.let { grantOwner(it) }
}
init {
authenticationAuthority.addAuthenticationListener(authenticationListener)
}
private fun grantOwnerToAuthenticatedUsers() {
chatRoom.members.filter {
!it.role.hasOwnerRights() && authenticationAuthority.getSessionForJid(it.jid) != null
}.forEach {
grantOwner(it)
}
}
override fun localRoleChanged(newRole: MemberRole, oldRole: MemberRole?) {
if (!newRole.hasOwnerRights()) {
logger.error("Local role has no owner rights, can not manage roles.")
return
}
grantOwnerToAuthenticatedUsers()
}
/**
* Handles cases where moderators(already authenticated users) reload and join again.
*/
override fun memberJoined(member: ChatRoomMember) {
if (member.role != MemberRole.OWNER && authenticationAuthority.getSessionForJid(member.jid) != null) {
grantOwner(member)
}
}
override fun stop() = authenticationAuthority.removeAuthenticationListener(authenticationListener)
override val debugState = OrderedJsonObject().apply {
put("class", [email protected])
}
}
|
apache-2.0
|
bb8b09b01fbb4a8c72d68c73fa43d436
| 32.254545 | 114 | 0.662475 | 4.460976 | false | false | false | false |
panpf/sketch
|
sketch/src/main/java/com/github/panpf/sketch/decode/BitmapDecodeResult.kt
|
1
|
3020
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.decode
import android.graphics.Bitmap
import com.github.panpf.sketch.datasource.DataFrom
import com.github.panpf.sketch.util.toInfoString
import java.util.LinkedList
/**
* The result of [BitmapDecoder.decode]
*/
data class BitmapDecodeResult constructor(
val bitmap: Bitmap,
val imageInfo: ImageInfo,
val dataFrom: DataFrom,
/**
* Store the transformation history of the Bitmap
*/
val transformedList: List<String>?,
/**
* Store some additional information for consumer use,
* You can add information here during decoding, transformation, interceptor, etc.
*/
val extras: Map<String, String>?,
) {
fun newResult(
bitmap: Bitmap = this.bitmap,
imageInfo: ImageInfo = this.imageInfo,
dataFrom: DataFrom = this.dataFrom,
block: (Builder.() -> Unit)? = null
): BitmapDecodeResult = Builder(
bitmap = bitmap,
imageInfo = imageInfo,
dataFrom = dataFrom,
transformedList = transformedList?.toMutableList(),
extras = extras?.toMutableMap(),
).apply {
block?.invoke(this)
}.build()
override fun toString(): String =
"BitmapDecodeResult(bitmap=${bitmap.toInfoString()}, " +
"imageInfo=$imageInfo, " +
"dataFrom=$dataFrom, " +
"transformedList=$transformedList, " +
"extras=$extras)"
class Builder internal constructor(
private val bitmap: Bitmap,
private val imageInfo: ImageInfo,
private val dataFrom: DataFrom,
private var transformedList: MutableList<String>? = null,
private var extras: MutableMap<String, String>? = null,
) {
fun addTransformed(transformed: String): Builder = apply {
this.transformedList = (this.transformedList ?: LinkedList()).apply {
add(transformed)
}
}
fun addExtras(key: String, value: String): Builder = apply {
this.extras = (this.extras ?: mutableMapOf()).apply {
put(key, value)
}
}
fun build(): BitmapDecodeResult = BitmapDecodeResult(
bitmap = bitmap,
imageInfo = imageInfo,
dataFrom = dataFrom,
transformedList = transformedList?.toList(),
extras = extras?.toMap(),
)
}
}
|
apache-2.0
|
80cf20e62fe05bebd90cffa14431a4e3
| 32.197802 | 86 | 0.633113 | 4.786054 | false | false | false | false |
atsushi-ageet/gradle-apkname-plugin
|
buildSrc/src/main/kotlin/com/ageet/gradle/plugin/apkname/ApkNameFormatter.kt
|
1
|
682
|
package com.ageet.gradle.plugin.apkname
import com.android.build.gradle.api.ApplicationVariant
class ApkNameFormatter(val projectName: String, val variant: ApplicationVariant, val gitShortHash: String) {
val applicationId: String get() = variant.mergedFlavor.applicationId.orEmpty()
val versionCode: Int get() = variant.mergedFlavor.versionCode ?: 0
val versionName: String get() = variant.mergedFlavor.versionName.orEmpty()
val variantName: String get() = variant.name
val flavorName: String get() = variant.flavorName
val flavorNames: List<String> get() = variant.productFlavors.map { it.name }
val buildType: String get() = variant.buildType.name
}
|
apache-2.0
|
a7be17c8c6769cf62fa4b5053404dece
| 51.461538 | 108 | 0.759531 | 4.133333 | false | false | false | false |
BilledTrain380/sporttag-psa
|
app/psa-runtime-service/psa-service-participation/src/test/kotlin/ch/schulealtendorf/psa/service/participation/ParticipationControllerTest.kt
|
1
|
7082
|
package ch.schulealtendorf.psa.service.participation
import ch.schulealtendorf.psa.configuration.test.PsaWebMvcTest
import ch.schulealtendorf.psa.dto.oauth.PSAScope
import ch.schulealtendorf.psa.dto.participation.ATHLETICS
import ch.schulealtendorf.psa.dto.participation.ParticipationCommand
import ch.schulealtendorf.psa.dto.participation.SportDto
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.http.MediaType
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
internal class ParticipationControllerTest : PsaWebMvcTest() {
companion object {
private const val PARTICIPATION_ENDPOINT = "/api/participation"
private const val PARTICIPATION_STATUS_ENDPOINT = "/api/participation-status"
private const val SPORTS_ENDPOINT = "/api/sports"
private const val PARTICIPATION_LIST_DOWNLOAD_ENDPOINT = "/api/participation-list/download"
private const val START_LIST_DOWNLOAD_ENDPOINT = "/api/start-list/download"
private val PARTICIPANT_List_BODY = listOf(
SportDto(ATHLETICS)
)
}
@Test
internal fun getParticipation() {
mockMvc.perform(
get(PARTICIPATION_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPATION))
).andExpect(status().isOk)
mockMvc.perform(
get(PARTICIPATION_ENDPOINT)
.with(bearerTokenUser(PSAScope.PARTICIPATION))
).andExpect(status().isOk)
}
@Test
internal fun getParticipationWhenUnauthorized() {
mockMvc.perform(get(PARTICIPATION_ENDPOINT))
.andExpect(status().isUnauthorized)
}
@Test
internal fun getParticipationWhenMissingScope() {
mockMvc.perform(
get(PARTICIPATION_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPANT_WRITE))
).andExpect(status().isNotFound)
}
@Test
internal fun getParticipationStatus() {
mockMvc.perform(
get(PARTICIPATION_STATUS_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPATION))
).andExpect(status().isOk)
mockMvc.perform(
get(PARTICIPATION_STATUS_ENDPOINT)
.with(bearerTokenUser(PSAScope.PARTICIPATION))
).andExpect(status().isOk)
}
@Test
internal fun getParticipationStatusWhenUnauthorized() {
mockMvc.perform(get(PARTICIPATION_STATUS_ENDPOINT))
.andExpect(status().isUnauthorized)
}
@Test
internal fun getParticipationStatusWhenMissingScope() {
mockMvc.perform(
get(PARTICIPATION_STATUS_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPANT_WRITE))
).andExpect(status().isNotFound)
}
@Test
@DirtiesContext
internal fun updateParticipation() {
mockMvc.perform(
patch(PARTICIPATION_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPATION))
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(ParticipationCommand.CLOSE))
).andExpect(status().isOk)
}
@Test
internal fun updateParticipationWhenUnauthorized() {
mockMvc.perform(
patch(PARTICIPATION_ENDPOINT)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(ParticipationCommand.CLOSE))
).andExpect(status().isUnauthorized)
}
@Test
internal fun updateParticipationWhenMissingScope() {
mockMvc.perform(
patch(PARTICIPATION_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPANT_WRITE))
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(ParticipationCommand.CLOSE))
).andExpect(status().isNotFound)
}
@Test
internal fun updateParticipationWhenMissingAuthority() {
mockMvc.perform(
patch(PARTICIPATION_ENDPOINT)
.with(bearerTokenUser(PSAScope.PARTICIPATION))
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(ParticipationCommand.CLOSE))
).andExpect(status().isNotFound)
}
@Test
@Disabled("This endpoint is not need at the moment")
internal fun getSportTypes() {
mockMvc.perform(
get(SPORTS_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.SPORT_READ))
).andExpect(status().isOk)
mockMvc.perform(
get(SPORTS_ENDPOINT)
.with(bearerTokenUser(PSAScope.SPORT_READ))
).andExpect(status().isOk)
}
@Test
internal fun getSportTypesWhenUnauthorized() {
mockMvc.perform(get(SPORTS_ENDPOINT))
.andExpect(status().isUnauthorized)
}
@Test
internal fun getSportTypesWhenMissingScope() {
mockMvc.perform(
get(SPORTS_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.PARTICIPANT_WRITE))
).andExpect(status().isNotFound)
}
@Test
internal fun downloadParticipationListWhenUnauthorized() {
mockMvc.perform(
post(PARTICIPATION_LIST_DOWNLOAD_ENDPOINT)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(PARTICIPANT_List_BODY))
).andExpect(status().isUnauthorized)
}
@Test
internal fun downloadParticipationListWhenMissingScope() {
mockMvc.perform(
post(PARTICIPATION_LIST_DOWNLOAD_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.COMPETITOR_WRITE))
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(PARTICIPANT_List_BODY))
).andExpect(status().isNotFound)
}
@Test
internal fun downloadParticipationListWhenMissingAuthority() {
mockMvc.perform(
post(PARTICIPATION_LIST_DOWNLOAD_ENDPOINT)
.with(bearerTokenUser(PSAScope.PARTICIPATION))
.contentType(MediaType.APPLICATION_JSON)
.content(jsonBodyOf(PARTICIPANT_List_BODY))
).andExpect(status().isNotFound)
}
@Test
internal fun downloadStartListWhenUnauthorized() {
mockMvc.perform(get(START_LIST_DOWNLOAD_ENDPOINT))
.andExpect(status().isUnauthorized)
}
@Test
internal fun downloadStartListWhenMissingScope() {
mockMvc.perform(
get(START_LIST_DOWNLOAD_ENDPOINT)
.with(bearerTokenAdmin(PSAScope.COMPETITOR_WRITE))
).andExpect(status().isNotFound)
}
@Test
internal fun downloadStartListWhenMissingAuthority() {
mockMvc.perform(
get(START_LIST_DOWNLOAD_ENDPOINT)
.with(bearerTokenUser(PSAScope.PARTICIPATION))
).andExpect(status().isNotFound)
}
}
|
gpl-3.0
|
b79375d29f46763ac41bd94c92ddc656
| 34.059406 | 99 | 0.663513 | 4.801356 | false | true | false | false |
UnknownJoe796/ponderize
|
app/src/main/java/com/ivieleague/ponderize/Config.kt
|
1
|
1740
|
package com.ivieleague.ponderize
import android.appwidget.AppWidgetManager
import android.content.Context
import com.ivieleague.ponderize.model.Verse
import com.lightningkite.kotlincomponents.gsonFrom
import com.lightningkite.kotlincomponents.gsonTo
import com.lightningkite.kotlincomponents.logging.logD
import org.jetbrains.anko.defaultSharedPreferences
import java.util.*
/**
* Created by josep on 10/4/2015.
*/
object Config {
const val ROOT: String = "http://scriptures.desh.es/api/v1"
const val VERSE: String = "verse"
public fun extraVerse(id: Int): String = VERSE + id.toString()
public fun getVerses(context: Context, id: Int): ArrayList<Verse> {
var verseJSON: String? = context.defaultSharedPreferences.getString(extraVerse(id), null)
logD(verseJSON)
if (verseJSON == null) {
verseJSON = context.defaultSharedPreferences.getString(extraVerse(AppWidgetManager.INVALID_APPWIDGET_ID), null)
}
if (verseJSON == null) return ArrayList()
try {
val results = verseJSON.gsonFrom<ArrayList<Verse>>()!!
logD(results)
return results
} catch(e: Exception) {
try {
val result = verseJSON.gsonFrom<Verse>()!!
logD(result)
return arrayListOf(result)
} catch(e: Exception) {
e.printStackTrace()
return ArrayList()
}
}
}
public fun setVerses(context: Context, id: Int, verses: ArrayList<Verse>) {
val verseJSON = verses.gsonTo()
logD(verseJSON)
context.defaultSharedPreferences.edit().putString(extraVerse(id),
verseJSON
).commit()
}
}
|
mit
|
113aff0b83d3bc1fe3310956b99f2080
| 33.137255 | 123 | 0.643103 | 4.461538 | false | false | false | false |
AndroidX/androidx
|
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/Dialog.desktop.kt
|
3
|
11749
|
/*
* 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.compose.ui.window
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Stable
import androidx.compose.runtime.currentCompositionLocalContext
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.awt.ComposeDialog
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.ComponentUpdater
import androidx.compose.ui.util.makeDisplayable
import androidx.compose.ui.util.setIcon
import androidx.compose.ui.util.setPositionSafely
import androidx.compose.ui.util.setSizeSafely
import androidx.compose.ui.util.setUndecoratedSafely
import java.awt.Dialog.ModalityType
import java.awt.Window
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.JDialog
/**
* Composes platform dialog in the current composition. When Dialog enters the composition,
* a new platform dialog will be created and receives the focus. When Dialog leaves the
* composition, dialog will be disposed and closed.
*
* Dialog is a modal window. It means it blocks the parent [Window] / [Dialog] in which composition
* context it was created.
*
* Usage:
* ```
* @Composable
* fun main() = application {
* val isDialogOpen by remember { mutableStateOf(true) }
* if (isDialogOpen) {
* Dialog(onCloseRequest = { isDialogOpen = false })
* }
* }
* ```
* @param onCloseRequest Callback that will be called when the user closes the dialog.
* Usually in this callback we need to manually tell Compose what to do:
* - change `isOpen` state of the dialog (which is manually defined)
* - close the whole application (`onCloseRequest = ::exitApplication` in [ApplicationScope])
* - don't close the dialog on close request (`onCloseRequest = {}`)
* @param state The state object to be used to control or observe the dialog's state
* When size/position is changed by the user, state will be updated.
* When size/position of the dialog is changed by the application (changing state),
* the native dialog will update its corresponding properties.
* If [DialogState.position] is not [WindowPosition.isSpecified], then after the first show on the
* screen [DialogState.position] will be set to the absolute values.
* @param visible Is [Dialog] visible to user.
* If `false`:
* - internal state of [Dialog] is preserved and will be restored next time the dialog
* will be visible;
* - native resources will not be released. They will be released only when [Dialog]
* will leave the composition.
* @param title Title in the titlebar of the dialog
* @param icon Icon in the titlebar of the window (for platforms which support this).
* On macOs individual windows can't have a separate icon. To change the icon in the Dock,
* set it via `iconFile` in build.gradle
* (https://github.com/JetBrains/compose-jb/tree/master/tutorials/Native_distributions_and_local_execution#platform-specific-options)
* @param undecorated Disables or enables decorations for this window.
* @param transparent Disables or enables window transparency. Transparency should be set
* only if window is undecorated, otherwise an exception will be thrown.
* @param resizable Can dialog be resized by the user (application still can resize the dialog
* changing [state])
* @param enabled Can dialog react to input events
* @param focusable Can dialog receive focus
* @param onPreviewKeyEvent This callback is invoked when the user interacts with the hardware
* keyboard. It gives ancestors of a focused component the chance to intercept a [KeyEvent].
* Return true to stop propagation of this event. If you return false, the key event will be
* sent to this [onPreviewKeyEvent]'s child. If none of the children consume the event,
* it will be sent back up to the root using the onKeyEvent callback.
* @param onKeyEvent This callback is invoked when the user interacts with the hardware
* keyboard. While implementing this callback, return true to stop propagation of this event.
* If you return false, the key event will be sent to this [onKeyEvent]'s parent.
* @param content content of the dialog
*/
@Composable
fun Dialog(
onCloseRequest: () -> Unit,
state: DialogState = rememberDialogState(),
visible: Boolean = true,
title: String = "Untitled",
icon: Painter? = null,
undecorated: Boolean = false,
transparent: Boolean = false,
resizable: Boolean = true,
enabled: Boolean = true,
focusable: Boolean = true,
onPreviewKeyEvent: ((KeyEvent) -> Boolean) = { false },
onKeyEvent: ((KeyEvent) -> Boolean) = { false },
content: @Composable DialogWindowScope.() -> Unit
) {
val owner = LocalWindow.current
val currentState by rememberUpdatedState(state)
val currentTitle by rememberUpdatedState(title)
val currentIcon by rememberUpdatedState(icon)
val currentUndecorated by rememberUpdatedState(undecorated)
val currentTransparent by rememberUpdatedState(transparent)
val currentResizable by rememberUpdatedState(resizable)
val currentEnabled by rememberUpdatedState(enabled)
val currentFocusable by rememberUpdatedState(focusable)
val currentOnCloseRequest by rememberUpdatedState(onCloseRequest)
val updater = remember(::ComponentUpdater)
Dialog(
visible = visible,
onPreviewKeyEvent = onPreviewKeyEvent,
onKeyEvent = onKeyEvent,
create = {
ComposeDialog(owner, ModalityType.DOCUMENT_MODAL).apply {
// close state is controlled by DialogState.isOpen
defaultCloseOperation = JDialog.DO_NOTHING_ON_CLOSE
addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
currentOnCloseRequest()
}
})
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
currentState.size = DpSize(width.dp, height.dp)
}
override fun componentMoved(e: ComponentEvent) {
currentState.position = WindowPosition(x.dp, y.dp)
}
})
}
},
dispose = ComposeDialog::dispose,
update = { dialog ->
updater.update {
set(currentTitle, dialog::setTitle)
set(currentIcon, dialog::setIcon)
set(currentUndecorated, dialog::setUndecoratedSafely)
set(currentTransparent, dialog::isTransparent::set)
set(currentResizable, dialog::setResizable)
set(currentEnabled, dialog::setEnabled)
set(currentFocusable, dialog::setFocusable)
set(state.size, dialog::setSizeSafely)
set(state.position, dialog::setPositionSafely)
}
},
content = content
)
}
// TODO(demin): fix mouse hover after opening a dialog.
// When we open a modal dialog, ComposeLayer/mouseExited will
// never be called for the parent window. See ./gradlew run3
/**
* Compose [ComposeDialog] obtained from [create]. The [create] block will be called
* exactly once to obtain the [ComposeDialog] to be composed, and it is also guaranteed to
* be invoked on the UI thread (Event Dispatch Thread).
*
* Once Dialog leaves the composition, [dispose] will be called to free resources that
* obtained by the [ComposeDialog].
*
* Dialog is a modal window. It means it blocks the parent [Window] / [Dialog] in which composition
* context it was created.
*
* The [update] block can be run multiple times (on the UI thread as well) due to recomposition,
* and it is the right place to set [ComposeDialog] properties depending on state.
* When state changes, the block will be reexecuted to set the new properties.
* Note the block will also be ran once right after the [create] block completes.
*
* Dialog is needed for creating dialog's that still can't be created with
* the default Compose function [androidx.compose.ui.window.Dialog]
*
* @param visible Is [ComposeDialog] visible to user.
* If `false`:
* - internal state of [ComposeDialog] is preserved and will be restored next time the dialog
* will be visible;
* - native resources will not be released. They will be released only when [Dialog]
* will leave the composition.
* @param onPreviewKeyEvent This callback is invoked when the user interacts with the hardware
* keyboard. It gives ancestors of a focused component the chance to intercept a [KeyEvent].
* Return true to stop propagation of this event. If you return false, the key event will be
* sent to this [onPreviewKeyEvent]'s child. If none of the children consume the event,
* it will be sent back up to the root using the onKeyEvent callback.
* @param onKeyEvent This callback is invoked when the user interacts with the hardware
* keyboard. While implementing this callback, return true to stop propagation of this event.
* If you return false, the key event will be sent to this [onKeyEvent]'s parent.
* @param create The block creating the [ComposeDialog] to be composed.
* @param dispose The block to dispose [ComposeDialog] and free native resources.
* Usually it is simple `ComposeDialog::dispose`
* @param update The callback to be invoked after the layout is inflated.
* @param content Composable content of the creating dialog.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Suppress("unused")
@Composable
fun Dialog(
visible: Boolean = true,
onPreviewKeyEvent: ((KeyEvent) -> Boolean) = { false },
onKeyEvent: ((KeyEvent) -> Boolean) = { false },
create: () -> ComposeDialog,
dispose: (ComposeDialog) -> Unit,
update: (ComposeDialog) -> Unit = {},
content: @Composable DialogWindowScope.() -> Unit
) {
val currentLocals by rememberUpdatedState(currentCompositionLocalContext)
AwtWindow(
visible = visible,
create = {
create().apply {
setContent(onPreviewKeyEvent, onKeyEvent) {
CompositionLocalProvider(currentLocals) {
content()
}
}
}
},
dispose = dispose,
update = {
update(it)
if (!it.isDisplayable) {
it.makeDisplayable()
it.contentPane.paint(it.graphics)
}
}
)
}
/**
* Receiver scope which is used by [androidx.compose.ui.window.Dialog].
*/
@Stable
interface DialogWindowScope : WindowScope {
/**
* [ComposeDialog] that was created inside [androidx.compose.ui.window.Dialog].
*/
override val window: ComposeDialog
}
|
apache-2.0
|
9588b8e17f3c5e1ffc3765d5d4eee8a9
| 43.847328 | 133 | 0.70823 | 4.596635 | false | false | false | false |
exponent/exponent
|
android/expoview/src/main/java/host/exp/exponent/network/ManualExpoResponse.kt
|
2
|
1395
|
package host.exp.exponent.network
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
class ManualExpoResponse : ExpoResponse {
override var isSuccessful = true
private var expoBody: ExpoBody? = null
private var code = 200
private val expoHeaders = ManualExpoHeaders()
private var networkResponse: ExpoResponse? = null
internal inner class ManualExpoBody(private val string: String) : ExpoBody {
@Throws(IOException::class)
override fun string(): String = string
override fun byteStream(): InputStream = ByteArrayInputStream(string.toByteArray())
@Throws(IOException::class)
override fun bytes(): ByteArray = string.toByteArray()
}
internal inner class ManualExpoHeaders : ExpoHeaders {
val headers = mutableMapOf<String, String>()
override fun get(name: String): String? = headers[name]
}
fun setBody(string: String) {
expoBody = ManualExpoBody(string)
}
fun setCode(code: Int) {
this.code = code
}
fun setHeader(key: String, value: String) {
expoHeaders.headers[key] = value
}
fun setNetworkResponse(expoResponse: ExpoResponse) {
networkResponse = expoResponse
}
override fun body(): ExpoBody = expoBody!!
override fun code(): Int = code
override fun headers(): ExpoHeaders = expoHeaders
override fun networkResponse(): ExpoResponse? = networkResponse
}
|
bsd-3-clause
|
9b229915c695a4f6bf390230fadd85c5
| 25.320755 | 87 | 0.729032 | 4.373041 | false | false | false | false |
satamas/fortran-plugin
|
src/main/kotlin/org/jetbrains/fortran/lang/parser/FortranParserUtil.kt
|
1
|
7783
|
package org.jetbrains.fortran.lang.parser
import com.intellij.lang.ForeignLeafType
import com.intellij.lang.PsiBuilder
import com.intellij.lang.PsiParser
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import org.jetbrains.fortran.lang.psi.FortranIncludeForeignLeafType
/**
* Created by Sergei on 13.04.17.
* The class for manual parsing of the external rules in the bnf grammar
* This is a copy of generated grammar to test, how it compiles
*/
object FortranParserUtil {
@JvmStatic
fun parseIdentifier(builder: PsiBuilder, level: Int): Boolean {
return IdentifierParser().parse(builder, level)
}
@JvmStatic
fun parseKeyword(builder: PsiBuilder, level: Int, keyword: String): Boolean {
return KeywordParser(keyword).parse(builder, level)
}
@JvmStatic
fun parseLabeledDoConstruct(builder: PsiBuilder, level: Int): Boolean {
return LabeledDoConstructParser().parse(builder, level)
}
fun getUnwrappedTokenType(base: IElementType?): IElementType? {
var unwrappedType = base
while (unwrappedType is ForeignLeafType) {
unwrappedType = unwrappedType.delegate
}
return unwrappedType
}
fun cloneTTwithBase(oldType: IElementType?, newType: IElementType): IElementType {
return if (oldType is FortranIncludeForeignLeafType) {
val newDelegate = cloneTTwithBase(oldType.delegate, newType)
FortranIncludeForeignLeafType(newDelegate, oldType.tokenText)
} else {
newType
}
}
@JvmStatic
fun nextTokenIs(builder: PsiBuilder, token: IElementType): Boolean =
GeneratedParserUtilBase.nextTokenIs(builder, token)
@JvmStatic
fun nextTokenIs(builder: PsiBuilder, frameName: String, vararg tokens: IElementType): Boolean =
GeneratedParserUtilBase.nextTokenIs(builder, frameName, *tokens)
@JvmStatic
fun nextTokenIsSmart(builder: PsiBuilder, token: IElementType): Boolean =
GeneratedParserUtilBase.nextTokenIsSmart(builder, token)
@JvmStatic
fun nextTokenIsSmart(builder: PsiBuilder, vararg tokens: IElementType): Boolean =
GeneratedParserUtilBase.nextTokenIsSmart(builder, *tokens)
@JvmStatic
fun consumeTokens(builder: PsiBuilder, pin: Int, vararg tokens: IElementType): Boolean =
GeneratedParserUtilBase.consumeTokens(builder, pin, *tokens)
@JvmStatic
fun consumeTokenSmart(builder: PsiBuilder, token: IElementType): Boolean =
consumeToken(builder, getUnwrappedTokenType(token))
@JvmStatic
fun consumeToken(builder: PsiBuilder, token: IElementType?): Boolean =
GeneratedParserUtilBase.consumeToken(builder, token)
//Method proxies to GeneratedParserUtil. The only way to override a couple of methods from there
@JvmField
val TRUE_CONDITION: Parser = object : Parser {
override fun parse(builder: PsiBuilder?, level: Int) = true
}
@JvmStatic
fun eof(builder: PsiBuilder, level: Int): Boolean = GeneratedParserUtilBase.eof(builder, level)
@JvmStatic
fun current_position_(builder: PsiBuilder): Int = GeneratedParserUtilBase.current_position_(builder)
@JvmStatic
fun recursion_guard_(builder: PsiBuilder, level: Int, funcName: String): Boolean =
GeneratedParserUtilBase.recursion_guard_(builder, level, funcName)
@JvmStatic
fun empty_element_parsed_guard_(builder: PsiBuilder, funcName: String, pos: Int): Boolean =
GeneratedParserUtilBase.empty_element_parsed_guard_(builder, funcName, pos)
@JvmStatic
fun create_token_set_(vararg tokenTypes: IElementType): TokenSet =
GeneratedParserUtilBase.create_token_set_(*tokenTypes)
@JvmStatic
fun consumeTokenSmart(builder: PsiBuilder, token: String): Boolean =
GeneratedParserUtilBase.consumeTokenSmart(builder, token)
@JvmStatic
fun consumeToken(builder: PsiBuilder, text: String): Boolean =
GeneratedParserUtilBase.consumeToken(builder, text)
@JvmStatic
fun consumeToken(builder: PsiBuilder, text: String, caseSensitive: Boolean): Boolean =
GeneratedParserUtilBase.consumeToken(builder, text, caseSensitive)
@JvmStatic
fun nextTokenIs(builder: PsiBuilder, tokenText: String): Boolean =
GeneratedParserUtilBase.nextTokenIs(builder, tokenText)
// here's the new section API for compact parsers & less IntelliJ platform API exposure
@JvmField
val _NONE_ = GeneratedParserUtilBase._NONE_
@JvmField
val _COLLAPSE_ = GeneratedParserUtilBase._COLLAPSE_
@JvmField
val _LEFT_ = GeneratedParserUtilBase._LEFT_
@JvmField
val _LEFT_INNER_ = GeneratedParserUtilBase._LEFT_INNER_
@JvmField
val _AND_ = GeneratedParserUtilBase._AND_
@JvmField
val _NOT_ = GeneratedParserUtilBase._NOT_
@JvmField
val _UPPER_ = GeneratedParserUtilBase._COLLAPSE_
// simple enter/exit methods pair that doesn't require frame object
@JvmStatic
fun enter_section_(builder: PsiBuilder): PsiBuilder.Marker =
GeneratedParserUtilBase.enter_section_(builder)
@JvmStatic
fun exit_section_(builder: PsiBuilder, marker: PsiBuilder.Marker, elementType: IElementType?, result: Boolean) =
GeneratedParserUtilBase.exit_section_(builder, marker, elementType, result)
@JvmStatic
fun enter_section_(builder: PsiBuilder, level: Int, modifiers: Int, frameName: String?): PsiBuilder.Marker =
GeneratedParserUtilBase.enter_section_(builder, level, modifiers, frameName)
@JvmStatic
fun enter_section_(builder: PsiBuilder, level: Int, modifiers: Int): PsiBuilder.Marker =
GeneratedParserUtilBase.enter_section_(builder, level, modifiers)
@JvmStatic
fun enter_section_(builder: PsiBuilder, level: Int, modifiers: Int, elementType: IElementType?, frameName: String?): PsiBuilder.Marker =
GeneratedParserUtilBase.enter_section_(builder, level, modifiers, elementType, frameName)
@JvmStatic
fun exit_section_(builder: PsiBuilder, level: Int, marker: PsiBuilder.Marker, result: Boolean, pinned: Boolean,
eatMore: Parser?) =
GeneratedParserUtilBase.exit_section_(builder, level, marker, result, pinned, eatMore)
@JvmStatic
fun exit_section_(builder: PsiBuilder, level: Int, marker: PsiBuilder.Marker, elementType: IElementType?,
result: Boolean, pinned: Boolean, eatMore: Parser?) =
GeneratedParserUtilBase.exit_section_(builder, level, marker, elementType, result, pinned, eatMore)
@JvmStatic
fun report_error_(builder: PsiBuilder, result: Boolean): Boolean =
GeneratedParserUtilBase.report_error_(builder, result)
@JvmStatic
fun report_error_(builder: PsiBuilder, state: GeneratedParserUtilBase.ErrorState, advance: Boolean) =
GeneratedParserUtilBase.report_error_(builder, state, advance)
@JvmStatic
fun adapt_builder_(root: IElementType, builder: PsiBuilder, parser: PsiParser): PsiBuilder =
adapt_builder_(root, builder, parser, null)
@JvmStatic
fun adapt_builder_(root: IElementType, builder: PsiBuilder, parser: PsiParser, extendsSets: Array<TokenSet>?): PsiBuilder {
val state = GeneratedParserUtilBase.ErrorState()
GeneratedParserUtilBase.ErrorState.initState(state, builder, root, extendsSets)
return FortranBuilderAdapter(builder, state, parser)
}
@JvmStatic
fun addVariant(builder: PsiBuilder, text: String) =
GeneratedParserUtilBase.addVariant(builder, text)
interface Parser : GeneratedParserUtilBase.Parser
}
|
apache-2.0
|
400a6ff4f3603dbca84630c310d57f57
| 39.118557 | 140 | 0.715277 | 4.960484 | false | false | false | false |
brianwernick/ExoMedia
|
library/src/main/kotlin/com/devbrackets/android/exomedia/core/video/scale/MatrixManager.kt
|
1
|
6676
|
package com.devbrackets.android.exomedia.core.video.scale
import android.graphics.Point
import android.util.Log
import android.view.View
import androidx.annotation.IntRange
import java.lang.ref.WeakReference
import kotlin.math.max
import kotlin.math.min
open class MatrixManager {
companion object {
private const val TAG = "MatrixManager"
protected const val QUARTER_ROTATION = 90
}
protected var intrinsicVideoSize = Point(0, 0)
@IntRange(from = 0, to = 359)
protected var currentRotation = 0
get() = requestedRotation ?: field
var currentScaleType = ScaleType.FIT_CENTER
get() = requestedScaleType ?: field
protected var requestedRotation: Int? = null
protected var requestedScaleType: ScaleType? = null
protected var requestedModificationView = WeakReference<View>(null)
fun reset() {
setIntrinsicVideoSize(0, 0)
currentRotation = 0
}
fun ready(): Boolean {
return intrinsicVideoSize.x > 0 && intrinsicVideoSize.y > 0
}
fun setIntrinsicVideoSize(@IntRange(from = 0) width: Int, @IntRange(from = 0) height: Int) {
val currentWidthHeightSwapped = currentRotation / QUARTER_ROTATION % 2 == 1
intrinsicVideoSize.x = if (currentWidthHeightSwapped) height else width
intrinsicVideoSize.y = if (currentWidthHeightSwapped) width else height
if (ready()) {
applyRequestedModifications()
}
}
fun rotate(view: View, @IntRange(from = 0, to = 359) rotation: Int) {
if (!ready()) {
requestedRotation = rotation
requestedModificationView = WeakReference(view)
return
}
val swapWidthHeight = rotation / QUARTER_ROTATION % 2 == 1
val currentWidthHeightSwapped = currentRotation / QUARTER_ROTATION % 2 == 1
// Makes sure the width and height are correctly swapped
if (swapWidthHeight != currentWidthHeightSwapped) {
val tempX = intrinsicVideoSize.x
intrinsicVideoSize.x = intrinsicVideoSize.y
intrinsicVideoSize.y = tempX
// We re-apply the scale to make sure it is correct
scale(view, currentScaleType)
}
currentRotation = rotation
view.rotation = rotation.toFloat()
}
/**
* Performs the requested scaling on the `view`'s matrix
*
* @param view The View to alter the matrix to achieve the requested scale type
* @param scaleType The type of scaling to use for the specified view
* @return True if the scale was applied
*/
fun scale(view: View, scaleType: ScaleType): Boolean {
if (!ready()) {
requestedScaleType = scaleType
requestedModificationView = WeakReference(view)
return false
}
if (view.height == 0 || view.width == 0) {
Log.d(TAG, "Unable to apply scale with a view size of (" + view.width + ", " + view.height + ")")
return false
}
currentScaleType = scaleType
when (scaleType) {
ScaleType.CENTER -> applyCenter(view)
ScaleType.CENTER_CROP -> applyCenterCrop(view)
ScaleType.CENTER_INSIDE -> applyCenterInside(view)
ScaleType.FIT_CENTER -> applyFitCenter(view)
ScaleType.FIT_XY -> applyFitXy(view)
ScaleType.NONE -> setScale(view, 1f, 1f)
}
return true
}
/**
* Applies the [ScaleType.CENTER] to the specified matrix. This will
* perform no scaling as this just indicates that the video should be centered
* in the View
*
* @param view The view to apply the transformation to
*/
protected fun applyCenter(view: View) {
val xScale = intrinsicVideoSize.x.toFloat() / view.width
val yScale = intrinsicVideoSize.y.toFloat() / view.height
setScale(view, xScale, yScale)
}
/**
* Applies the [ScaleType.CENTER_CROP] to the specified matrix. This will
* make sure the smallest side fits the parent container, cropping the other
*
* @param view The view to apply the transformation to
*/
protected fun applyCenterCrop(view: View) {
var xScale = view.width.toFloat() / intrinsicVideoSize.x
var yScale = view.height.toFloat() / intrinsicVideoSize.y
val scale = max(xScale, yScale)
xScale = scale / xScale
yScale = scale / yScale
setScale(view, xScale, yScale)
}
/**
* Applies the [ScaleType.CENTER_INSIDE] to the specified matrix. This will
* only perform scaling if the video is too large to fit completely in the `view`
* in which case it will be scaled to fit
*
* @param view The view to apply the transformation to
*/
protected fun applyCenterInside(view: View) {
if (intrinsicVideoSize.x <= view.width && intrinsicVideoSize.y <= view.height) {
applyCenter(view)
} else {
applyFitCenter(view)
}
}
/**
* Applies the [ScaleType.FIT_CENTER] to the specified matrix. This will
* scale the video so that the largest side will always match the `view`
*
* @param view The view to apply the transformation to
*/
protected fun applyFitCenter(view: View) {
var xScale = view.width.toFloat() / intrinsicVideoSize.x
var yScale = view.height.toFloat() / intrinsicVideoSize.y
val scale = min(xScale, yScale)
xScale = scale / xScale
yScale = scale / yScale
setScale(view, xScale, yScale)
}
/**
* Applies the [ScaleType.FIT_XY] to the specified matrix. This will
* scale the video so that both the width and height will always match that of
* the `view`
*
* @param view The view to apply the transformation to
*/
protected fun applyFitXy(view: View) {
setScale(view, 1f, 1f)
}
/**
* Applies the specified scale modification to the view
*
* @param view The view to scale
* @param xScale The scale to apply to the x axis
* @param yScale The scale to apply to the y axis
*/
protected fun setScale(view: View, xScale: Float, yScale: Float) {
//If the width and height have been swapped, we need to re-calculate the scales based on the swapped sizes
val currentWidthHeightSwapped = currentRotation / QUARTER_ROTATION % 2 == 1
if (currentWidthHeightSwapped) {
view.scaleX = yScale * view.height / view.width
view.scaleY = xScale * view.width / view.height
return
}
view.scaleX = xScale
view.scaleY = yScale
}
/**
* Applies any scale or rotation that was requested before the MatrixManager was
* ready to apply those modifications.
*/
protected fun applyRequestedModifications() {
requestedModificationView.get()?.let { view ->
requestedRotation?.let {
rotate(view, it)
requestedRotation = null
}
requestedScaleType?.let {
scale(view, it)
requestedScaleType = null
}
}
requestedModificationView = WeakReference<View>(null)
}
}
|
apache-2.0
|
308d3e4eb7f875f5bb57918e48a2a61a
| 29.769585 | 110 | 0.682445 | 4.103258 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/util/files.kt
|
1
|
1703
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.util.jar.Attributes
import java.util.jar.JarFile
import java.util.jar.Manifest
val VirtualFile.localFile: File
get() = VfsUtilCore.virtualToIoFile(this)
val Path.virtualFile: VirtualFile?
get() = LocalFileSystem.getInstance().refreshAndFindFileByPath(this.toAbsolutePath().toString())
val Path.virtualFileOrError: VirtualFile
get() = virtualFile ?: throw IllegalStateException("Failed to find file: $this")
val VirtualFile.manifest: Manifest?
get() = try {
JarFile(localFile).use { it.manifest }
} catch (e: IOException) {
null
}
// Technically resource domains are much more restricted ([a-z0-9_-]+) in modern versions, but we want to support as much as possible
private val RESOURCE_LOCATION_PATTERN = Regex("^.*?/(assets|data)/([^/]+)/(.*?)$")
val VirtualFile.mcDomain: String?
get() = RESOURCE_LOCATION_PATTERN.matchEntire(this.path)?.groupValues?.get(2)
val VirtualFile.mcPath: String?
get() = RESOURCE_LOCATION_PATTERN.matchEntire(this.path)?.groupValues?.get(3)
operator fun Manifest.get(attribute: String): String? = mainAttributes.getValue(attribute)
operator fun Manifest.get(attribute: Attributes.Name): String? = mainAttributes.getValue(attribute)
fun VirtualFile.refreshFs(): VirtualFile {
return this.parent.findOrCreateChildData(this, this.name)
}
|
mit
|
21525fe3603829863d23378bee7acae2
| 31.75 | 133 | 0.746917 | 3.978972 | false | false | false | false |
kirtan403/K4Kotlin
|
k4kotlin-androidx/src/main/java/com/livinglifetechway/k4kotlin/core/androidx/Fragment.kt
|
1
|
2734
|
package com.livinglifetechway.k4kotlin.core.androidx
/**
* This file contains the various extension functions from core library that requires context
* That should also be called from the fragment directly without explicitly calling on context
*/
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.livinglifetechway.k4kotlin.core.cancelAndMakeToast
import com.livinglifetechway.k4kotlin.core.dpToPx
import com.livinglifetechway.k4kotlin.core.hideKeyboard
import com.livinglifetechway.k4kotlin.core.isNetworkAvailable
import com.livinglifetechway.k4kotlin.core.makeCall
import com.livinglifetechway.k4kotlin.core.makeToast
import com.livinglifetechway.k4kotlin.core.openPlayStore
import com.livinglifetechway.k4kotlin.core.openUrl
import com.livinglifetechway.k4kotlin.core.pxToDp
import com.livinglifetechway.k4kotlin.core.pxToSp
import com.livinglifetechway.k4kotlin.core.sendEmail
import com.livinglifetechway.k4kotlin.core.sendSms
import com.livinglifetechway.k4kotlin.core.share
import com.livinglifetechway.k4kotlin.core.showKeyboard
import com.livinglifetechway.k4kotlin.core.spToPx
/* Functions for Conversions */
fun Fragment.pxToDp(px: Float) = context?.pxToDp(px)
fun Fragment.dpToPx(dp: Float) = context?.dpToPx(dp)
fun Fragment.spToPx(sp: Float) = context?.spToPx(sp)
fun Fragment.pxToSp(px: Float) = context?.pxToSp(px)
/* Functions for toast */
fun Fragment?.toast(msg: String) = makeToast(this?.context, msg, Toast.LENGTH_LONG)
fun Fragment?.shortToast(msg: String) = makeToast(this?.context, msg, Toast.LENGTH_SHORT)
fun Fragment?.longToast(msg: String) = makeToast(this?.context, msg, Toast.LENGTH_LONG)
fun Fragment?.toastNow(msg: String) = cancelAndMakeToast(this?.context, msg, Toast.LENGTH_LONG)
fun Fragment?.shortToastNow(msg: String) = cancelAndMakeToast(this?.context, msg, Toast.LENGTH_SHORT)
fun Fragment?.longToastNow(msg: String) = cancelAndMakeToast(this?.context, msg, Toast.LENGTH_LONG)
/* Functions for Keyboard */
fun Fragment.hideKeyboard() = activity?.hideKeyboard()
fun Fragment.showKeyboard() = activity?.showKeyboard()
/* Functions for Network */
fun Fragment.isNetworkAvailable() = context?.isNetworkAvailable()
/* Functions for Share */
fun Fragment.openUrl(url: String, newTask: Boolean = false) = context?.openUrl(url, newTask)
fun Fragment.share(text: String, subject: String = "") = context?.share(text, subject)
fun Fragment.sendEmail(email: String, subject: String = "", text: String = "") = context?.sendEmail(email, subject, text)
fun Fragment.makeCall(number: String) = context?.makeCall(number)
fun Fragment.sendSms(number: String, text: String = "") = context?.sendSms(number, text)
fun Fragment.openPlayStore() = context?.openPlayStore()
|
apache-2.0
|
1cbae0c3c6907964e61fdd38dac9be23
| 44.566667 | 121 | 0.795903 | 3.482803 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua
|
src/main/java/com/tang/intellij/lua/editor/completion/ClassMemberCompletionProvider.kt
|
2
|
9399
|
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.editor.completion
import com.intellij.codeInsight.completion.CompletionInitializationContext
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.Processor
import com.tang.intellij.lua.lang.LuaIcons
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
enum class MemberCompletionMode {
Dot, // self.xxx
Colon, // self:xxx()
All // self.xxx && self:xxx()
}
/**
* Created by tangzx on 2016/12/25.
*/
open class ClassMemberCompletionProvider : LuaCompletionProvider() {
protected abstract class HandlerProcessor {
open fun processLookupString(lookupString: String, member: LuaClassMember, memberTy: ITy?): String = lookupString
abstract fun process(element: LuaLookupElement, member: LuaClassMember, memberTy: ITy?): LookupElement
}
override fun addCompletions(session: CompletionSession) {
val completionParameters = session.parameters
val completionResultSet = session.resultSet
val psi = completionParameters.position
val indexExpr = psi.parent
if (indexExpr is LuaIndexExpr) {
val isColon = indexExpr.colon != null
val project = indexExpr.project
val contextTy = LuaPsiTreeUtil.findContextClass(indexExpr)
val context = SearchContext.get(project)
val prefixType = indexExpr.guessParentType(context)
if (!Ty.isInvalid(prefixType)) {
complete(isColon, project, contextTy, prefixType, completionResultSet, completionResultSet.prefixMatcher, null)
}
//smart
val nameExpr = indexExpr.prefixExpr
if (nameExpr is LuaNameExpr) {
val colon = if (isColon) ":" else "."
val prefixName = nameExpr.text
val postfixName = indexExpr.name?.let { it.substring(0, it.indexOf(CompletionInitializationContext.DUMMY_IDENTIFIER_TRIMMED)) }
val matcher = completionResultSet.prefixMatcher.cloneWithPrefix(prefixName)
LuaDeclarationTree.get(indexExpr.containingFile).walkUpLocal(indexExpr) { d ->
val it = d.firstDeclaration.psi
val txt = it.name
if (it is LuaTypeGuessable && txt != null && prefixName != txt && matcher.prefixMatches(txt)) {
val type = it.guessType(context)
if (!Ty.isInvalid(prefixType)) {
val prefixMatcher = completionResultSet.prefixMatcher
val resultSet = completionResultSet.withPrefixMatcher("$prefixName*$postfixName")
complete(isColon, project, contextTy, type, resultSet, prefixMatcher, object : HandlerProcessor() {
override fun process(element: LuaLookupElement, member: LuaClassMember, memberTy: ITy?): LookupElement {
element.itemText = txt + colon + element.itemText
element.lookupString = txt + colon + element.lookupString
return PrioritizedLookupElement.withPriority(element, -2.0)
}
})
}
}
true
}
}
}
}
private fun complete(isColon: Boolean,
project: Project,
contextTy: ITy,
prefixType: ITy,
completionResultSet: CompletionResultSet,
prefixMatcher: PrefixMatcher,
handlerProcessor: HandlerProcessor?) {
val mode = if (isColon) MemberCompletionMode.Colon else MemberCompletionMode.Dot
prefixType.eachTopClass(Processor { luaType ->
addClass(contextTy, luaType, project, mode, completionResultSet, prefixMatcher, handlerProcessor)
true
})
}
protected fun addClass(contextTy: ITy,
luaType:ITyClass,
project: Project,
completionMode:MemberCompletionMode,
completionResultSet: CompletionResultSet,
prefixMatcher: PrefixMatcher,
handlerProcessor: HandlerProcessor?) {
val context = SearchContext.get(project)
luaType.lazyInit(context)
luaType.processMembers(context) { curType, member ->
ProgressManager.checkCanceled()
member.name?.let {
if (prefixMatcher.prefixMatches(it) && curType.isVisibleInScope(project, contextTy, member.visibility)) {
addMember(completionResultSet,
member,
curType,
luaType,
completionMode,
project,
handlerProcessor)
}
}
}
}
protected fun addMember(completionResultSet: CompletionResultSet,
member: LuaClassMember,
thisType: ITyClass,
callType: ITyClass,
completionMode: MemberCompletionMode,
project: Project,
handlerProcessor: HandlerProcessor?) {
val type = member.guessType(SearchContext.get(project))
val bold = thisType == callType
val className = thisType.displayName
if (type is ITyFunction) {
val fn = type.substitute(TySelfSubstitutor(project, null, callType))
if (fn is ITyFunction)
addFunction(completionResultSet, bold, completionMode != MemberCompletionMode.Dot, className, member, fn, thisType, callType, handlerProcessor)
} else if (member is LuaClassField) {
if (completionMode != MemberCompletionMode.Colon)
addField(completionResultSet, bold, className, member, type, handlerProcessor)
}
}
protected fun addField(completionResultSet: CompletionResultSet,
bold: Boolean,
clazzName: String,
field: LuaClassField,
ty:ITy?,
handlerProcessor: HandlerProcessor?) {
val name = field.name
if (name != null) {
this.session?.addWord(name)
val element = LookupElementFactory.createFieldLookupElement(clazzName, name, field, ty, bold)
val ele = handlerProcessor?.process(element, field, null) ?: element
completionResultSet.addElement(ele)
}
}
private fun addFunction(completionResultSet: CompletionResultSet,
bold: Boolean,
isColonStyle: Boolean,
clazzName: String,
classMember: LuaClassMember,
fnTy: ITyFunction,
thisType: ITyClass,
callType: ITyClass,
handlerProcessor: HandlerProcessor?) {
val name = classMember.name
if (name != null) {
this.session?.addWord(name)
fnTy.process(Processor {
val firstParam = it.getFirstParam(thisType, isColonStyle)
if (isColonStyle) {
if (firstParam == null) return@Processor true
if (!callType.subTypeOf(firstParam.ty, SearchContext.get(classMember.project), true))
return@Processor true
}
val lookupString = handlerProcessor?.processLookupString(name, classMember, fnTy) ?: name
val element = LookupElementFactory.createMethodLookupElement(clazzName,
lookupString,
classMember,
it,
bold,
isColonStyle,
fnTy,
LuaIcons.CLASS_METHOD)
val ele = handlerProcessor?.process(element, classMember, fnTy) ?: element
completionResultSet.addElement(ele)
true
})
}
}
}
|
apache-2.0
|
7822f1c5e5478c4c47819aee2d1e3c5d
| 44.626214 | 159 | 0.576125 | 5.568128 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua
|
src/main/java/com/tang/intellij/lua/ty/TyTuple.kt
|
2
|
2624
|
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.ty
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.tang.intellij.lua.search.SearchContext
class TyTuple(val list: List<ITy>) : Ty(TyKind.Tuple) {
val size: Int get() {
return list.size
}
override fun substitute(substitutor: ITySubstitutor): ITy {
val list = list.map { it.substitute(substitutor) }
return TyTuple(list)
}
override fun accept(visitor: ITyVisitor) {
visitor.visitTuple(this)
}
override fun acceptChildren(visitor: ITyVisitor) {
list.forEach { it.accept(visitor) }
}
override fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean {
if (other is TyTuple && other.size == size) {
for (i in 0 until size) {
if (!list[i].subTypeOf(other.list[i], context, strict)) {
return false
}
}
return true
}
return false
}
override fun hashCode(): Int {
var hash = 0
for (ty in list) {
hash = hash * 31 + ty.hashCode()
}
return hash
}
override fun equals(other: Any?): Boolean {
if (other is TyTuple && other.size == size) {
for (i in 0 until size) {
if (list[i] != other.list[i]) {
return false
}
}
return true
}
return super.equals(other)
}
}
object TyTupleSerializer : TySerializer<TyTuple>() {
override fun deserializeTy(flags: Int, stream: StubInputStream): TyTuple {
val size = stream.readByte().toInt()
val list = mutableListOf<ITy>()
for (i in 0 until size) list.add(Ty.deserialize(stream))
return TyTuple(list)
}
override fun serializeTy(ty: TyTuple, stream: StubOutputStream) {
stream.writeByte(ty.list.size)
ty.list.forEach { Ty.serialize(it, stream) }
}
}
|
apache-2.0
|
231f35b10c26724d87e5c24a53b9854f
| 29.172414 | 90 | 0.612043 | 4.132283 | false | false | false | false |
raxden/square
|
square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/fragmentbottomnavigation/HasFragmentBottomNavigationInterceptor.kt
|
2
|
2882
|
package com.raxdenstudios.square.interceptor.commons.fragmentbottomnavigation
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.view.View
import com.raxdenstudios.square.interceptor.HasInterceptor
/**
* Created by Ángel Gómez on 29/12/2016.
*
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_view"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Toolbar" />
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="@+id/container_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar_view" />
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation"/>
</android.support.constraint.ConstraintLayout>
*/
interface HasFragmentBottomNavigationInterceptor<T : Fragment> : HasInterceptor {
fun onCreateBottomNavigationView(): BottomNavigationView
fun onBottomNavigationViewCreated(bottomNavigationView: BottomNavigationView)
fun onLoadFragmentContainer(): View
fun onCreateFragment(itemId: Int): T
fun onFragmentLoaded(itemId: Int, fragment: T)
fun onBottomNavigationItemSelected(itemId: Int)
}
|
apache-2.0
|
71269c1e8bd9bf3738f1daec7228a725
| 38.452055 | 81 | 0.677083 | 4.383562 | false | false | false | false |
RightHandedMonkey/PersonalWebNotifier
|
app/src/main/java/com/rhm/pwn/home_feature/HomeFeature.kt
|
1
|
4743
|
package com.rhm.pwn.home_feature
import android.util.Log
import com.rhm.pwn.home_feature.HomeFeature.State
import com.rhm.pwn.home_feature.HomeFeature.Wish
import com.rhm.pwn.home_feature.HomeFeature.Effect
import com.rhm.pwn.home_feature.HomeFeature.News
import com.badoo.mvicore.element.Actor
import com.badoo.mvicore.element.Bootstrapper
import com.badoo.mvicore.element.NewsPublisher
import com.badoo.mvicore.element.Reducer
import com.badoo.mvicore.feature.ActorReducerFeature
import com.rhm.pwn.model.URLCheck
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
class HomeFeature(getListService: Observable<List<URLCheck>>) : ActorReducerFeature<Wish, Effect, State, News>(
initialState = State(),
actor = ActorImpl(getListService),
reducer = ReducerImpl(),
bootstrapper = BootstrapperImpl(),
newsPublisher = NewsPublisherImpl()
) {
//TODO : Use new app icons and branding
data class State(
val isLoading: Boolean = false,
val editShown: Boolean = false,
val editUrlCheck: URLCheck? = null,
val viewUrlCheck: URLCheck? = null,
val debug: Boolean = false,
val list: List<URLCheck> = emptyList())
sealed class Wish {
object HomeScreenLoading : Wish()
data class HomeScreenView(val urlCheck: URLCheck) : Wish()
data class HomeScreenEditOpen(val urlCheck: URLCheck) : Wish()
object HomeScreenDebug : Wish()
}
sealed class Effect {
object StartedLoading : Effect()
data class FinishedWithSuccess(val urlChecks: List<URLCheck>) : Effect()
data class FinishedWithFailure(val throwable: Throwable) : Effect()
data class StatelessShowEditDialog(val urlCheck: URLCheck) : Effect()
data class StatelessLaunchViewPage(val urlCheck: URLCheck) : Effect()
}
sealed class News {
data class ShowEditDialog(val urlCheck: URLCheck) : News()
data class LaunchViewPage(val urlCheck: URLCheck) : News()
}
class NewsPublisherImpl : NewsPublisher<Wish, Effect, State, News> {
override fun invoke(wish: Wish, effect: Effect, state: State): News? = when (effect) {
is Effect.StatelessShowEditDialog -> News.ShowEditDialog(effect.urlCheck)
is Effect.StatelessLaunchViewPage -> News.LaunchViewPage(effect.urlCheck)
else -> null
}
}
class ActorImpl(private val service: Observable<List<URLCheck>>) : Actor<State, Wish, Effect> {
override fun invoke(state: State, wish: Wish): Observable<Effect> {
Log.d("SAMB", this.javaClass.name + ", invoke() called $wish")
return when (wish) {
is Wish.HomeScreenLoading -> {
if (!state.isLoading) {
service
.observeOn(AndroidSchedulers.mainThread())
.map { Effect.FinishedWithSuccess(urlChecks = it) as Effect }
.startWith(Effect.StartedLoading)
.onErrorReturn { Effect.FinishedWithFailure(it) }
} else {
Observable.empty()
}
}
is Wish.HomeScreenEditOpen -> {
Observable.just(Effect.StatelessShowEditDialog(wish.urlCheck))
}
else -> Observable.empty()
}
}
}
class ReducerImpl : Reducer<State, Effect> {
override fun invoke(state: State, effect: Effect): State {
Log.d("SAMB", this.javaClass.name + ", invoke() called $effect")
return when (effect) {
is Effect.StartedLoading -> state.copy(
isLoading = true
)
is Effect.FinishedWithSuccess -> {
Log.d("SAMB", this.javaClass.name + ", items found: ${effect.urlChecks.size}")
state.copy(
isLoading = false,
list = effect.urlChecks
)
}
is Effect.FinishedWithFailure -> state.copy(
isLoading = false
)
is Effect.StatelessShowEditDialog -> state.copy(editUrlCheck = effect.urlCheck, viewUrlCheck = null)
is Effect.StatelessLaunchViewPage -> state.copy(viewUrlCheck = effect.urlCheck, editUrlCheck = null)
}
}
}
class BootstrapperImpl : Bootstrapper<Wish> {
override fun invoke(): Observable<Wish> = Observable.just(Wish.HomeScreenLoading as Wish).observeOn(AndroidSchedulers.mainThread())
}
}
|
mit
|
1deb096eecd8bbe45c947c572ec43ffb
| 40.973451 | 139 | 0.604259 | 4.700694 | false | false | false | false |
heinika/MyGankio
|
app/src/main/java/lijin/heinika/cn/mygankio/ganhuodataview/GanHuoPresenter.kt
|
1
|
2514
|
package lijin.heinika.cn.mygankio.ganhuodataview
import android.util.Log
import lijin.heinika.cn.mygankio.entiy.BaseData
import lijin.heinika.cn.mygankio.entiy.GanHuoBean
import lijin.heinika.cn.mygankio.http.ServiceGenerator
import lijin.heinika.cn.mygankio.schedulers.BaseSchedulerProvider
import lijin.heinika.cn.mygankio.schedulers.SchedulerProvider
import rx.Observer
import rx.subscriptions.CompositeSubscription
/**
* Created by heinika on 17-1-3.
*
*/
class GanHuoPresenter internal constructor(private val mGanHuoView: GanHuoContract.View, schedulerProvider: BaseSchedulerProvider) : GanHuoContract.Presenter {
private val mSchedulerProvider: SchedulerProvider
private val mSubscriptions: CompositeSubscription
private lateinit var ganhuoDataList: MutableList<GanHuoBean>
private lateinit var mType: String
fun setType(type: String) {
this.mType = type
}
init {
mSchedulerProvider = schedulerProvider as SchedulerProvider
mSubscriptions = CompositeSubscription()
mGanHuoView.setPresenter(this)
}
override fun subscribe() {
loadGanHuoData(mType, 1)
}
override fun unsubscribe() {
mSubscriptions.clear()
}
internal fun loadGanHuoData(type: String, page: Int) {
val gankioApi = ServiceGenerator.getGankioApi()
val observable = gankioApi.getGanHuoData(type, 10, page)
mGanHuoView.showLoadingData()
val subscription = observable.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(object : Observer<BaseData<List<GanHuoBean>>> {
override fun onCompleted() {
Log.i("wxl", "onCompleted")
}
override fun onError(e: Throwable) {
Log.i("wxl", "e=" + e.message)
}
override fun onNext(gankData: BaseData<List<GanHuoBean>>) {
Log.i("wxl", "" + gankData.results!!.size)
if (page == 1) {
ganhuoDataList = gankData.results as MutableList<GanHuoBean>
} else {
ganhuoDataList.addAll(gankData.results!!)
}
mGanHuoView.showGanHuo(ganhuoDataList)
mGanHuoView.hideLoadingData()
}
})
mSubscriptions.add(subscription)
}
}
|
apache-2.0
|
e3a95077cc9db04fc7342d610e766195
| 34.408451 | 159 | 0.621321 | 4.881553 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/data/local/implementation/RealmTaskLocalRepository.kt
|
1
|
11683
|
package com.habitrpg.android.habitica.data.local.implementation
import com.habitrpg.android.habitica.data.local.TaskLocalRepository
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.models.tasks.RemindersItem
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskList
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.habitrpg.shared.habitica.models.tasks.TasksOrder
import hu.akarnokd.rxjava3.bridge.RxJavaBridge
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
import io.realm.kotlin.toFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.filter
class RealmTaskLocalRepository(realm: Realm) : RealmBaseLocalRepository(realm), TaskLocalRepository {
override fun getTasks(taskType: TaskType, userID: String, includedGroupIDs: Array<String>): Flow<List<Task>> {
if (realm.isClosed) return emptyFlow()
return findTasks(taskType, userID, includedGroupIDs)
.toFlow()
.filter { it.isLoaded }
}
override fun getTasksFlowable(taskType: TaskType, userID: String, includedGroupIDs: Array<String>): Flowable<out List<Task>> {
if (realm.isClosed) return Flowable.empty()
return RxJavaBridge.toV3Flowable(findTasks(taskType, userID, includedGroupIDs)
.asFlowable()
.filter { it.isLoaded })
}
private fun findTasks(
taskType: TaskType,
ownerID: String,
includedGroupIDs: Array<String>
): RealmResults<Task> {
return realm.where(Task::class.java)
.equalTo("typeValue", taskType.value)
.beginGroup()
.equalTo("userId", ownerID)
.or()
.beginGroup()
.`in`("group.groupID", includedGroupIDs)
.and()
.beginGroup()
.contains("group.assignedUsers", ownerID)
.or()
.isEmpty("group.assignedUsers")
.endGroup()
.endGroup()
.or()
.equalTo("group.groupID", ownerID)
.endGroup()
.sort("position", Sort.ASCENDING, "dateCreated", Sort.DESCENDING)
.findAll()
}
override fun getTasks(userId: String): Flow<List<Task>> {
if (realm.isClosed) return emptyFlow()
return realm.where(Task::class.java).equalTo("userId", userId)
.sort("position", Sort.ASCENDING, "dateCreated", Sort.DESCENDING)
.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun saveTasks(ownerID: String, tasksOrder: TasksOrder, tasks: TaskList) {
val sortedTasks = mutableListOf<Task>()
sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.habits))
sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.dailys))
sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.todos))
sortedTasks.addAll(sortTasks(tasks.tasks, tasksOrder.rewards))
for (task in tasks.tasks.values) {
task.position = (sortedTasks.lastOrNull { it.type == task.type }?.position ?: -1) + 1
sortedTasks.add(task)
}
removeOldTasks(ownerID, sortedTasks)
val allChecklistItems = ArrayList<ChecklistItem>()
val allReminders = ArrayList<RemindersItem>()
sortedTasks.forEach {
if (it.userId.isBlank() && it.group?.groupID?.isNotBlank() != true) {
it.userId = ownerID
}
it.checklist?.let { it1 -> allChecklistItems.addAll(it1) }
it.reminders?.let { it1 -> allReminders.addAll(it1) }
}
removeOldReminders(allReminders)
removeOldChecklists(allChecklistItems)
executeTransaction { realm1 -> realm1.insertOrUpdate(sortedTasks) }
}
override fun saveCompletedTodos(userId: String, tasks: MutableCollection<Task>) {
removeCompletedTodos(userId, tasks)
executeTransaction { realm1 -> realm1.insertOrUpdate(tasks) }
}
private fun removeOldChecklists(onlineItems: List<ChecklistItem>) {
val localItems = realm.where(ChecklistItem::class.java).findAll().createSnapshot()
val itemsToDelete = localItems.filterNot { onlineItems.contains(it) }
executeTransaction {
for (item in itemsToDelete) {
item.deleteFromRealm()
}
}
}
private fun removeOldReminders(onlineReminders: List<RemindersItem>) {
val localReminders = realm.where(RemindersItem::class.java).findAll().createSnapshot()
val itemsToDelete = localReminders.filterNot { onlineReminders.contains(it) }
executeTransaction {
for (item in itemsToDelete) {
item.deleteFromRealm()
}
}
}
private fun sortTasks(taskMap: MutableMap<String, Task>, taskOrder: List<String>): List<Task> {
val taskList = ArrayList<Task>()
var position = 0
for (taskId in taskOrder) {
val task = taskMap[taskId]
if (task != null) {
task.position = position
taskList.add(task)
position++
taskMap.remove(taskId)
}
}
return taskList
}
private fun removeOldTasks(ownerID: String, onlineTaskList: List<Task>) {
if (realm.isClosed) return
val localTasks = realm.where(Task::class.java)
.beginGroup()
.equalTo("userId", ownerID)
.or()
.equalTo("group.groupID", ownerID)
.endGroup()
.beginGroup()
.beginGroup()
.equalTo("typeValue", TaskType.TODO.value)
.equalTo("completed", false)
.endGroup()
.or()
.notEqualTo("typeValue", TaskType.TODO.value)
.endGroup()
.findAll()
.createSnapshot()
val tasksToDelete = localTasks.filterNot { onlineTaskList.contains(it) }
executeTransaction {
for (localTask in tasksToDelete) {
localTask.deleteFromRealm()
}
}
}
private fun removeCompletedTodos(userID: String, onlineTaskList: MutableCollection<Task>) {
val localTasks = realm.where(Task::class.java)
.equalTo("userId", userID)
.equalTo("typeValue", TaskType.TODO.value)
.equalTo("completed", true)
.findAll()
.createSnapshot()
val tasksToDelete = localTasks.filterNot { onlineTaskList.contains(it) }
executeTransaction {
for (localTask in tasksToDelete) {
localTask.deleteFromRealm()
}
}
}
override fun deleteTask(taskID: String) {
val task = realm.where(Task::class.java).equalTo("id", taskID).findFirst()
executeTransaction {
if (task?.isManaged == true) {
task.deleteFromRealm()
}
}
}
override fun getTask(taskId: String): Flowable<Task> {
if (realm.isClosed) {
return Flowable.empty()
}
return RxJavaBridge.toV3Flowable(
realm.where(Task::class.java).equalTo("id", taskId).findAll().asFlowable()
.filter { realmObject -> realmObject.isLoaded && realmObject.isNotEmpty() }
.map { it.first() }
.cast(Task::class.java)
)
}
override fun getTaskCopy(taskId: String): Flowable<Task> {
return getTask(taskId)
.map { task ->
return@map if (task.isManaged && task.isValid) {
realm.copyFromRealm(task)
} else {
task
}
}
}
override fun markTaskCompleted(taskId: String, isCompleted: Boolean) {
val task = realm.where(Task::class.java).equalTo("id", taskId).findFirst()
executeTransaction { task?.completed = true }
}
override fun swapTaskPosition(firstPosition: Int, secondPosition: Int) {
val firstTask = realm.where(Task::class.java).equalTo("position", firstPosition).findFirst()
val secondTask = realm.where(Task::class.java).equalTo("position", secondPosition).findFirst()
if (firstTask != null && secondTask != null && firstTask.isValid && secondTask.isValid) {
executeTransaction {
firstTask.position = secondPosition
secondTask.position = firstPosition
}
}
}
override fun getTaskAtPosition(taskType: String, position: Int): Flowable<Task> {
return RxJavaBridge.toV3Flowable(
realm.where(Task::class.java).equalTo("typeValue", taskType).equalTo("position", position)
.findAll()
.asFlowable()
.filter { realmObject -> realmObject.isLoaded && realmObject.isNotEmpty() }
.map { it.first() }
.filter { realmObject -> realmObject.isLoaded }
.cast(Task::class.java)
)
}
override fun updateIsdue(daily: TaskList): Maybe<TaskList> {
return Flowable.just(realm.where(Task::class.java).equalTo("typeValue", TaskType.DAILY.value).findAll())
.firstElement()
.map { tasks ->
realm.beginTransaction()
tasks.filter { daily.tasks.containsKey(it.id) }.forEach { it.isDue = daily.tasks[it.id]?.isDue }
realm.commitTransaction()
daily
}
}
override fun updateTaskPositions(taskOrder: List<String>) {
if (taskOrder.isNotEmpty()) {
val tasks = realm.where(Task::class.java).`in`("id", taskOrder.toTypedArray()).findAll()
executeTransaction { _ ->
tasks.filter { taskOrder.contains(it.id) }.forEach { it.position = taskOrder.indexOf(it.id) }
}
}
}
override fun getErroredTasks(userID: String): Flowable<out List<Task>> {
return RxJavaBridge.toV3Flowable(
realm.where(Task::class.java)
.equalTo("userId", userID)
.equalTo("hasErrored", true)
.sort("position")
.findAll()
.asFlowable()
.filter { it.isLoaded }
).retry(1)
}
override fun getUser(userID: String): Flowable<User> {
return RxJavaBridge.toV3Flowable(
realm.where(User::class.java)
.equalTo("id", userID)
.findAll()
.asFlowable()
.filter { realmObject -> realmObject.isLoaded && realmObject.isValid && !realmObject.isEmpty() }
.map { users -> users.first() }
)
}
override fun getTasksForChallenge(challengeID: String?, userID: String?): Flowable<out List<Task>> {
return RxJavaBridge.toV3Flowable(
realm.where(Task::class.java)
.equalTo("challengeID", challengeID)
.equalTo("userId", userID)
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
.retry(1)
}
}
|
gpl-3.0
|
ff2e3419d2cadd61c4d8523a4d8cdcb3
| 37.60339 | 130 | 0.58033 | 4.714689 | false | false | false | false |
btnewton/tartarus
|
core/src/com/brandtsoftwarecompany/CipherTool.kt
|
1
|
2448
|
package com.brandtsoftwarecompany
import java.lang.RuntimeException
import java.security.SecureRandom
import javax.crypto.Cipher
import kotlin.reflect.KMutableProperty1
import javax.crypto.spec.IvParameterSpec
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
/**
* Created by brandt on 7/20/17.
*/
class CipherTool() {
val encryptedProperties = arrayOf(Credentials::email, Credentials::password)
fun unlock(credentials: Credentials, masterPassword: ByteArray) {
applyCipher(credentials, masterPassword, Cipher.DECRYPT_MODE)
}
fun lock(credentials: Credentials, masterPassword: ByteArray) {
applyCipher(credentials, masterPassword, Cipher.ENCRYPT_MODE)
}
private fun applyCipher(credentials: Credentials, masterPassword: ByteArray, mode: Int) {
encryptedProperties.forEach { prop -> credentials.encrypt(prop, masterPassword, mode) }
}
fun Credentials.encrypt(prop: KMutableProperty1<Credentials, String>, masterPassword: ByteArray, mode: Int) {
val ALGORITHM = "AES"
val TRANSFORMATION = "AES"
try {
// val random = SecureRandom()
// val salt = ByteArray(16)
// random.nextBytes(salt)
//
// val spec = PBEKeySpec("password".toCharArray(), salt, 65536, 256) // AES-256
// val f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
// val key = f.generateSecret(spec).encoded
//
// val ivBytes = ByteArray(16)
// random.nextBytes(ivBytes)
// val iv = IvParameterSpec(ivBytes)
//
// val c = Cipher.getInstance("AES/CBC/PKCS5Padding")
// c.init(Cipher.ENCRYPT_MODE, key, iv)
//
// val plainText = prop.get(this);
// val encValue = c.doFinal(plainText.toByteArray())
//
// val finalCipherText = ByteArray(encValue.size + 2 * 16)
// System.arraycopy(ivBytes, 0, finalCipherText, 0, 16)
// System.arraycopy(salt, 0, finalCipherText, 16, 16)
// System.arraycopy(encValue, 0, finalCipherText, 32, encValue.size)
//
//
// val encryptedData =
// val outputBytes = encrypt.doFinal(encryptedData.toByteArray())
// val decryptedData = String(outputBytes)
//
// prop.set(this, decryptedData)
} catch (ex: Exception) {
throw RuntimeException("Error encrypting/decrypting file", ex)
}
}
}
|
mit
|
5e5c00645cf046bf10b86351aa06b5d0
| 34.492754 | 113 | 0.650327 | 4.149153 | false | false | false | false |
hotmobmobile/hotmob-android-sdk
|
AndroidStudio/HotmobSDKShowcase/app/src/main/java/com/hotmob/sdk/hotmobsdkshowcase/banner/recycleview/BannerInRecycleViewFragment.kt
|
1
|
2742
|
package com.hotmob.sdk.hotmobsdkshowcase.banner.recycleview
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hotmob.sdk.ad.HotmobBanner
import com.hotmob.sdk.hotmobsdkshowcase.R
import com.hotmob.sdk.hotmobsdkshowcase.banner.recycleview.dummy.DummyItem
import java.util.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.forEach
import kotlin.collections.set
/**
* A fragment representing a list of Items.
*/
class BannerInRecycleViewFragment : androidx.fragment.app.Fragment() {
private var columnCount = 1
private var listAdapter: ListItemRecyclerViewAdapter? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_banner_recycleview, container, false)
// Set the adapter
if (view is androidx.recyclerview.widget.RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> androidx.recyclerview.widget.LinearLayoutManager(context)
else -> androidx.recyclerview.widget.GridLayoutManager(context, columnCount)
}
val dummyItems = ArrayList<DummyItem>()
for (i in 1..30) {
dummyItems.add(DummyItem(
id = i.toString(),
content = "Item $i"
))
}
// setup Hotmob Ad and put in adapter
val ad1 = HotmobBanner(context)
ad1.identifier = "List Banner 1"
ad1.adCode = context.resources.getStringArray(R.array.banner_click_action_adcodes)[0]
ad1.focusableAd = false
ad1.animated = true
val ad2 = HotmobBanner(context)
ad2.identifier = "List Banner 2"
ad2.adCode = context.resources.getStringArray(R.array.banner_click_action_adcodes)[2]
ad2.focusableAd = false
val ads = HashMap<Int, HotmobBanner>()
ads[0] = ad1
ads[15] = ad2
listAdapter = ListItemRecyclerViewAdapter(dummyItems, ads)
adapter = listAdapter
}
}
return view
}
override fun onDestroyView() {
listAdapter!!.adMap.values.forEach {
it.destroy()
}
super.onDestroyView()
}
}
|
mit
|
0e2008f2f6ac2c36dbd7123c2a1bbc08
| 36.054054 | 101 | 0.625821 | 4.695205 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/solutions/ui/adapter/delegate/SolutionSectionAdapterDelegate.kt
|
2
|
1865
|
package org.stepik.android.view.solutions.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_solution_section.view.*
import org.stepic.droid.R
import org.stepik.android.domain.solutions.model.SolutionItem
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapters.selection.SelectionHelper
class SolutionSectionAdapterDelegate(
private val selectionHelper: SelectionHelper,
private val onClick: (SolutionItem.SectionItem) -> Unit
) : AdapterDelegate<SolutionItem, DelegateViewHolder<SolutionItem>>() {
override fun isForViewType(position: Int, data: SolutionItem): Boolean =
data is SolutionItem.SectionItem
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<SolutionItem> =
ViewHolder(createView(parent, R.layout.item_solution_section))
private inner class ViewHolder(root: View) : DelegateViewHolder<SolutionItem>(root) {
private val sectionTitle = root.sectionTitle
private val sectionCheckBox = root.sectionCheckBox
init {
sectionCheckBox.setOnClickListener { (itemData as? SolutionItem.SectionItem)?.let(onClick) }
}
override fun onBind(data: SolutionItem) {
data as SolutionItem.SectionItem
selectionHelper.isSelected(adapterPosition).let { isSelected ->
itemView.isSelected = isSelected
sectionCheckBox.isChecked = isSelected
}
sectionCheckBox.isEnabled = data.isEnabled
sectionTitle.text = context.resources.getString(
R.string.solutions_section_placeholder,
data.section.position,
data.section.title
)
}
}
}
|
apache-2.0
|
1f2f4b2e34b2ed0c8fb282eeb99b0a63
| 40.466667 | 104 | 0.719035 | 4.94695 | false | false | false | false |
quarck/SmartNotify
|
app/src/main/java/com/github/quarck/smartnotify/OngoingNotificationManager.kt
|
1
|
2524
|
package com.github.quarck.smartnotify
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
object OngoingNotificationManager
{
fun showUpdateOngoingNotification(ctx: Context)
{
if (!Settings(ctx).isOngoingNotificationEnabled)
{
cancelOngoingNotification(ctx)
return
}
val intent = Intent(ctx, ToggleMuteBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val mainActivityIntent = Intent(ctx, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(ctx, 0, mainActivityIntent, 0)
val view = RemoteViews(ctx.packageName,
if (!GlobalState.getIsMuted(ctx)) R.layout.notification_view else R.layout.notification_view_muted)
view.setOnClickPendingIntent(R.id.buttonMute, pendingIntent)
if (!GlobalState.getIsMuted(ctx))
{
val cntActive = GlobalState.getLastCountHandledNotifications(ctx)
val intervalMin = GlobalState.getCurrentRemindInterval(ctx) / 60 / 1000
val sb = StringBuilder()
sb.append(cntActive)
sb.append(" ")
if (cntActive != 1)
sb.append(ctx.getString(R.string.notification_hint_apps))
else
sb.append(ctx.getString(R.string.notification_hint_app))
sb.append(ctx.getString(R.string.notification_hint_every))
sb.append(" ")
sb.append(intervalMin)
sb.append(" ")
if (intervalMin != 1L)
sb.append(ctx.getString(R.string.notification_hint_mins))
else
sb.append(ctx.getString(R.string.notification_hint_min))
view.setTextViewText(R.id.textViewSmallText, sb.toString())
}
val ongoingNotification = Notification.Builder(ctx).setContent(view).setSmallIcon(R.drawable.ic_notification).setOngoing(true).setPriority(Notification.PRIORITY_MIN).setContentIntent(pendingMainActivityIntent).build()
(ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(Consts.notificationIdOngoing, ongoingNotification) // would update if already exists
}
fun cancelOngoingNotification(ctx: Context)
{
(ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Consts.notificationIdOngoing)
}
fun updateNotification(ctx: Context)
{
if (GlobalState.getLastCountHandledNotifications(ctx) > 0 || GlobalState.getIsMuted(ctx))
{
showUpdateOngoingNotification(ctx)
}
else
{
cancelOngoingNotification(ctx)
}
}
}
|
bsd-3-clause
|
658d79cc2a4c0161871c56e222db7d78
| 31.779221 | 219 | 0.775753 | 3.744807 | false | false | false | false |
NerdNumber9/TachiyomiEH
|
app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/BasePresenter.kt
|
1
|
3253
|
package eu.kanade.tachiyomi.ui.base.presenter
import android.os.Bundle
import nucleus.presenter.RxPresenter
import nucleus.presenter.delivery.Delivery
import rx.Observable
open class BasePresenter<V> : RxPresenter<V>() {
override fun onCreate(savedState: Bundle?) {
try {
super.onCreate(savedState)
} catch (e: NullPointerException) {
// Swallow this error. This should be fixed in the library but since it's not critical
// (only used by restartables) it should be enough. It saves me a fork.
}
}
/**
* Subscribes an observable with [deliverFirst] and adds it to the presenter's lifecycle
* subscription list.
*
* @param onNext function to execute when the observable emits an item.
* @param onError function to execute when the observable throws an error.
*/
fun <T> Observable<T>.subscribeFirst(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null)
= compose(deliverFirst<T>()).subscribe(split(onNext, onError)).apply { add(this) }
/**
* Subscribes an observable with [deliverLatestCache] and adds it to the presenter's lifecycle
* subscription list.
*
* @param onNext function to execute when the observable emits an item.
* @param onError function to execute when the observable throws an error.
*/
fun <T> Observable<T>.subscribeLatestCache(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null)
= compose(deliverLatestCache<T>()).subscribe(split(onNext, onError)).apply { add(this) }
/**
* Subscribes an observable with [deliverReplay] and adds it to the presenter's lifecycle
* subscription list.
*
* @param onNext function to execute when the observable emits an item.
* @param onError function to execute when the observable throws an error.
*/
fun <T> Observable<T>.subscribeReplay(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null)
= compose(deliverReplay<T>()).subscribe(split(onNext, onError)).apply { add(this) }
/**
* Subscribes an observable with [DeliverWithView] and adds it to the presenter's lifecycle
* subscription list.
*
* @param onNext function to execute when the observable emits an item.
* @param onError function to execute when the observable throws an error.
*/
fun <T> Observable<T>.subscribeWithView(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null)
= compose(DeliverWithView<V, T>(view())).subscribe(split(onNext, onError)).apply { add(this) }
/**
* A deliverable that only emits to the view if attached, otherwise the event is ignored.
*/
class DeliverWithView<View, T>(private val view: Observable<View>) : Observable.Transformer<T, Delivery<View, T>> {
override fun call(observable: Observable<T>): Observable<Delivery<View, T>> {
return observable
.materialize()
.filter { notification -> !notification.isOnCompleted }
.flatMap { notification ->
view.take(1).filter { it != null }.map { Delivery(it, notification) }
}
}
}
}
|
apache-2.0
|
00b1ef2ddead3a24d0faec5ec2ae3b40
| 42.959459 | 119 | 0.640947 | 4.395946 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
search_usecases/src/test/java/com/vmenon/mpo/search/usecases/QueueDownloadForShowTest.kt
|
1
|
3122
|
package com.vmenon.mpo.search.usecases
import com.vmenon.mpo.downloads.domain.DownloadsService
import com.vmenon.mpo.my_library.domain.MyLibraryService
import com.vmenon.mpo.test.TestData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
import org.junit.Assert.assertEquals
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@ExperimentalCoroutinesApi
class QueueDownloadForShowTest {
private val myLibraryService: MyLibraryService = mock()
private val downloadsService: DownloadsService = mock()
@Test
fun queueDownloadForShowSavesShowAndEpisodeIfNotExists() = runBlockingTest {
val usecase = QueueDownloadForShow(myLibraryService, downloadsService)
whenever(myLibraryService.getShowByName(TestData.showSearchResultModel.name)).thenReturn(
null
)
whenever(myLibraryService.saveShow(any())).thenReturn(TestData.show)
whenever(
myLibraryService.getEpisodeByName(
TestData.showSearchResultEpisodeModel.name
)
).thenReturn(null)
whenever(myLibraryService.saveEpisode(any())).thenReturn(TestData.episode)
whenever(downloadsService.queueDownload(any())).thenReturn(TestData.download)
assertEquals(
TestData.download,
usecase.invoke(TestData.showSearchResultModel, TestData.showSearchResultEpisodeModel)
)
}
@Test
fun queueDownloadForShowSavesShowIfNotExistsButUsesExistingEpisode() = runBlockingTest {
val usecase = QueueDownloadForShow(myLibraryService, downloadsService)
whenever(myLibraryService.getShowByName(TestData.showSearchResultModel.name)).thenReturn(
null
)
whenever(myLibraryService.saveShow(any())).thenReturn(TestData.show)
whenever(
myLibraryService.getEpisodeByName(
TestData.showSearchResultEpisodeModel.name
)
).thenReturn(TestData.episode)
whenever(downloadsService.queueDownload(any())).thenReturn(TestData.download)
assertEquals(
TestData.download,
usecase.invoke(TestData.showSearchResultModel, TestData.showSearchResultEpisodeModel)
)
}
@Test
fun queueDownloadUsesExistingShowSavesEpisodeIfNotExists() = runBlockingTest {
val usecase = QueueDownloadForShow(myLibraryService, downloadsService)
whenever(myLibraryService.getShowByName(TestData.showSearchResultModel.name)).thenReturn(
TestData.show
)
whenever(
myLibraryService.getEpisodeByName(
TestData.showSearchResultEpisodeModel.name
)
).thenReturn(null)
whenever(myLibraryService.saveEpisode(any())).thenReturn(TestData.episode)
whenever(downloadsService.queueDownload(any())).thenReturn(TestData.download)
assertEquals(
TestData.download,
usecase.invoke(TestData.showSearchResultModel, TestData.showSearchResultEpisodeModel)
)
}
}
|
apache-2.0
|
8ab92f3a2d31ae4a8ab5af385426cb23
| 40.092105 | 97 | 0.721653 | 4.963434 | false | true | false | false |
exponentjs/exponent
|
packages/expo-image-manipulator/android/src/main/java/expo/modules/imagemanipulator/arguments/Actions.kt
|
2
|
1302
|
package expo.modules.imagemanipulator.arguments
import expo.modules.imagemanipulator.actions.Action
import expo.modules.imagemanipulator.actions.CropAction
import expo.modules.imagemanipulator.actions.FlipAction
import expo.modules.imagemanipulator.actions.ResizeAction
import expo.modules.imagemanipulator.actions.RotateAction
import java.util.ArrayList
private const val KEY_CROP = "crop"
private const val KEY_FLIP = "flip"
private const val KEY_RESIZE = "resize"
private const val KEY_ROTATE = "rotate"
class Actions(public val actions: List<Action>) {
companion object {
fun fromArgument(rawList: ArrayList<Any?>): Actions {
val actions: MutableList<Action> = mutableListOf()
for (rawObject in rawList) {
require(rawObject is Map<*, *>)
when {
rawObject.containsKey(KEY_CROP) -> actions.add(CropAction.fromObject(rawObject[KEY_CROP]!!))
rawObject.containsKey(KEY_FLIP) -> actions.add(FlipAction.fromObject(rawObject[KEY_FLIP]!! as String))
rawObject.containsKey(KEY_RESIZE) -> actions.add(ResizeAction.fromObject(rawObject[KEY_RESIZE]!!))
rawObject.containsKey(KEY_ROTATE) -> actions.add(RotateAction.fromObject((rawObject[KEY_ROTATE]!! as Double).toInt()))
}
}
return Actions(actions)
}
}
}
|
bsd-3-clause
|
057bf6406db1fdba3995f7554d30b7e9
| 38.454545 | 128 | 0.731951 | 4.09434 | false | false | false | false |
santoslucas/guarda-filme-android
|
app/src/main/java/com/guardafilme/model/WatchedMovie.kt
|
1
|
659
|
package com.guardafilme.model
import com.google.firebase.database.Exclude
import java.util.*
/**
* Created by lucassantos on 06/08/17.
*/
data class WatchedMovie(
val uid: String,
val movieId: Int,
val title: String,
val originalTitle: String,
val watchedDate: Long,
val poster: String = "",
val backdrop: String = "",
val rate: Float = 0F) {
constructor() : this("", -1, "", "", -1)
@Exclude
fun getWatchedDateAsCalendar(): Calendar {
val watchedCalendar = Calendar.getInstance()
watchedCalendar.timeInMillis = watchedDate
return watchedCalendar
}
}
|
gpl-3.0
|
7bf46c237fbdbca7d512299ae5ce7715
| 24.384615 | 52 | 0.617602 | 4.197452 | false | false | false | false |
sjnyag/stamp
|
app/src/main/java/com/sjn/stamp/ui/fragment/SettingFragment.kt
|
1
|
10486
|
package com.sjn.stamp.ui.fragment
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.preference.EditTextPreference
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.widget.Toast
import com.sjn.stamp.R
import com.sjn.stamp.controller.SongController
import com.sjn.stamp.controller.UserSettingController
import com.sjn.stamp.ui.DialogFacade
import com.sjn.stamp.ui.DrawerMenu
import com.sjn.stamp.ui.activity.DrawerActivity
import com.sjn.stamp.ui.activity.MusicPlayerListActivity
import com.sjn.stamp.ui.activity.MusicPlayerListActivity.Companion.START_FRAGMENT_KEY
import com.sjn.stamp.utils.*
import io.multimoon.colorful.Colorful
import io.multimoon.colorful.ThemeColorInterface
class SettingFragment : PreferenceFragmentCompat() {
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
menu?.clear()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
findPreference("primary_theme")?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if (newValue is ThemeColorInterface) {
context?.let {
Colorful().edit()
.setPrimaryColor(newValue)
.apply(it) {
reboot()
}
}
}
true
}
findPreference("accent_theme")?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if (newValue is ThemeColorInterface) {
context?.let {
Colorful().edit()
.setAccentColor(newValue)
.apply(it) {
reboot()
}
}
}
true
}
findPreference("dark_theme")?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if (newValue is Boolean) {
context?.let {
Colorful().edit()
.setDarkTheme(newValue)
.apply(it) {
reboot()
}
}
}
true
}
findPreference("translucent")?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if (newValue is Boolean) {
context?.let {
Colorful().edit()
.setTranslucent(newValue)
.apply(it) {
reboot()
}
}
}
true
}
findPreference("hide_album_art_on_lock_screen")?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if (newValue is Boolean) {
context?.let {
PreferenceHelper.setHideAlbumArtOnLockScreen(context, newValue)
}
}
true
}
findPreference("song_db_refresh")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.let {
DialogFacade.createConfirmDialog(it, R.string.dialog_confirm_song_db_refresh) { _, _ ->
context?.let {
AnalyticsHelper.trackSetting(it, "song_db_refresh")
Thread(Runnable { SongController(it).refreshAllSongs(MediaRetrieveHelper.allMediaMetadataCompat(it, null)) }).start()
}
}.show()
}
true
}
findPreference("song_db_unknown")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
fragmentManager?.let {
val transaction = it.beginTransaction()
transaction.replace(R.id.container, UnknownSongListFragment(), DrawerActivity.FRAGMENT_TAG)
transaction.addToBackStack(null)
transaction.commit()
}
true
}
findPreference("import_backup")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.let {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(intent, REQUEST_BACKUP)
}
true
}
findPreference("export_backup")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.let {
DialogFacade.createConfirmDialog(it, R.string.dialog_confirm_export) { _, _ ->
context?.let {
AnalyticsHelper.trackSetting(it, "export_backup")
}
ProgressDialog(activity).run {
setMessage(getString(R.string.message_processing))
show()
activity?.let { RealmHelper.exportBackUp(it) }
dismiss()
}
}.show()
}
true
}
findPreference("licence").onPreferenceClickListener = Preference.OnPreferenceClickListener {
context?.let {
AnalyticsHelper.trackSetting(it, "licence")
}
activity?.let {
DialogFacade.createLicenceDialog(it).show()
}
true
}
findPreference("setting_songs_new_song_days").onPreferenceClickListener = Preference.OnPreferenceClickListener { preference ->
if (preference is EditTextPreference) {
preference.text = UserSettingController().newSongDays.toString()
}
true
}
findPreference("setting_songs_new_song_days").onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
context?.let {
AnalyticsHelper.trackSetting(it, "setting_songs_new_song_days", newValue.toString())
}
try {
val newSongDays = Integer.parseInt(newValue.toString())
if (newSongDays in 0..999) {
UserSettingController().newSongDays = newSongDays
}
} catch (e: Exception) {
e.printStackTrace()
}
false
}
findPreference("setting_songs_most_played_song_size").onPreferenceClickListener = Preference.OnPreferenceClickListener { preference ->
if (preference is EditTextPreference) {
preference.text = UserSettingController().mostPlayedSongSize.toString()
}
true
}
findPreference("setting_songs_most_played_song_size").onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
context?.let {
AnalyticsHelper.trackSetting(it, "setting_songs_most_played_song_size", newValue.toString())
}
try {
val mostPlayedSongSize = Integer.parseInt(newValue.toString())
if (mostPlayedSongSize in 0..999) {
UserSettingController().mostPlayedSongSize = mostPlayedSongSize
}
} catch (e: Exception) {
e.printStackTrace()
}
false
}
}
override fun onStart() {
super.onStart()
activity?.let {
(it.findViewById<View>(R.id.fab) as FloatingActionButton).let {
ViewCompat.animate(it)
.scaleX(0f).scaleY(0f)
.alpha(0f).setDuration(100)
.start()
}
}
}
override fun onStop() {
super.onStop()
activity?.let {
(it.findViewById<View>(R.id.fab) as FloatingActionButton).visibility = View.VISIBLE
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
LogHelper.d(TAG, "onActivityResult: requestCode=$requestCode, resultCode=$resultCode")
if (requestCode == REQUEST_BACKUP) {
if (resultCode == AppCompatActivity.RESULT_OK) {
activity?.let { activity ->
if (data?.data?.path?.endsWith(".realm") == true) {
DialogFacade.createConfirmDialog(activity, R.string.dialog_confirm_import) { _, _ ->
context?.let {
AnalyticsHelper.trackSetting(it, "import_backup")
ProgressDialog(it).run {
setMessage(getString(R.string.message_processing))
show()
RealmHelper.importBackUp(activity, data.data)
dismiss()
}
DialogFacade.createRestartDialog(it) { _, _ ->
reboot()
}.show()
}
}.show()
} else {
Toast.makeText(activity, R.string.invalid_backup_selected, Toast.LENGTH_SHORT).show()
}
}
}
}
}
private fun reboot() {
activity?.finish()
startActivity(Intent(activity, MusicPlayerListActivity::class.java).apply { putExtra(START_FRAGMENT_KEY, DrawerMenu.SETTING.menuId) })
}
companion object {
private val TAG = LogHelper.makeLogTag(SettingFragment::class.java)
private const val REQUEST_BACKUP = 1
}
}
|
apache-2.0
|
9c58e2fc66340ef38b1b2c0a0bafb271
| 38.870722 | 145 | 0.546348 | 5.68039 | false | false | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/PluginStartup.kt
|
1
|
1625
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.StartupActivity
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.options.OptionScope
/**
* @author Alex Plate
*/
class PluginStartup : StartupActivity.DumbAware/*, LightEditCompatible*/ {
private var firstInitializationOccurred = false
override fun runActivity(project: Project) {
if (firstInitializationOccurred) return
firstInitializationOccurred = true
// This code should be executed once
VimPlugin.getInstance().initialize()
}
}
// This is a temporal workaround for VIM-2487
class PyNotebooksCloseWorkaround : ProjectManagerListener {
override fun projectClosingBeforeSave(project: Project) {
val close = injector.optionService.getOptionValue(OptionScope.GLOBAL, "closenotebooks").asBoolean()
if (close) {
localEditors().forEach { editor ->
val virtualFile = EditorHelper.getVirtualFile(editor)
if (virtualFile?.extension == "ipynb") {
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)
fileEditorManager.closeFile(virtualFile)
}
}
}
}
}
|
mit
|
475ec914321e8ff9ce849e6661a8a5ac
| 31.5 | 103 | 0.756923 | 4.501385 | false | false | false | false |
duncte123/SkyBot
|
src/main/kotlin/ml/duncte123/skybot/commands/fun/JokeCommand.kt
|
1
|
2293
|
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.`fun`
import me.duncte123.botcommons.messaging.EmbedUtils
import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed
import me.duncte123.botcommons.web.WebUtils
import ml.duncte123.skybot.extensions.abbreviate
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandCategory
import ml.duncte123.skybot.objects.command.CommandContext
import net.dv8tion.jda.api.entities.MessageEmbed
class JokeCommand : Command() {
init {
this.category = CommandCategory.FUN
this.name = "joke"
this.help = "See a funny joke. Dad's love them!"
}
override fun execute(ctx: CommandContext) {
when (ctx.random.nextInt(2)) {
0 -> sendJokeFromApi(ctx)
1 -> sendRanddomJoke(ctx)
}
}
private fun sendJokeFromApi(ctx: CommandContext) {
val json = ctx.apis.executeDefaultGetRequest("joke", false)["data"]
val embed = EmbedUtils.getDefaultEmbed()
.setTitle(json["title"].asText().abbreviate(MessageEmbed.TITLE_MAX_LENGTH), json["url"].asText())
.setDescription(json["body"].asText().abbreviate(MessageEmbed.TEXT_MAX_LENGTH))
sendEmbed(ctx, embed)
}
private fun sendRanddomJoke(ctx: CommandContext) {
WebUtils.ins.getJSONObject("https://icanhazdadjoke.com/").async {
sendEmbed(ctx, EmbedUtils.embedMessage(it["joke"].asText()))
}
}
}
|
agpl-3.0
|
b24dc4a229624d9705397854cb0a8c8a
| 37.216667 | 109 | 0.709115 | 4.036972 | false | false | false | false |
EmmanuelMess/AmazeFileManager
|
app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt
|
1
|
23235
|
/*
* 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.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.DialogFragment
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.internal.MDButton
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.asynchronous.asynctasks.AsyncTaskResult
import com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask
import com.amaze.filemanager.asynchronous.asynctasks.ssh.PemToKeyPairTask
import com.amaze.filemanager.database.UtilsHandler
import com.amaze.filemanager.database.models.OperationData
import com.amaze.filemanager.databinding.SftpDialogBinding
import com.amaze.filemanager.file_operations.filesystem.OpenMode
import com.amaze.filemanager.filesystem.ssh.SshClientUtils
import com.amaze.filemanager.filesystem.ssh.SshConnectionPool
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.activities.superclasses.ThemedActivity
import com.amaze.filemanager.ui.icons.MimeTypes
import com.amaze.filemanager.ui.provider.UtilitiesProvider
import com.amaze.filemanager.utils.BookSorter
import com.amaze.filemanager.utils.DataUtils
import com.amaze.filemanager.utils.MinMaxInputFilter
import com.amaze.filemanager.utils.SimpleTextWatcher
import com.google.android.material.snackbar.Snackbar
import net.schmizz.sshj.common.SecurityUtils
import java.io.BufferedReader
import java.lang.ref.WeakReference
import java.security.KeyPair
import java.security.PublicKey
import java.util.Collections
/** SSH/SFTP connection setup dialog. */
class SftpConnectDialog : DialogFragment() {
private val TAG = SftpConnectDialog::class.java.simpleName
companion object {
const val ARG_NAME = "name"
const val ARG_EDIT = "edit"
const val ARG_ADDRESS = "address"
const val ARG_PORT = "port"
const val ARG_USERNAME = "username"
const val ARG_PASSWORD = "password"
const val ARG_DEFAULT_PATH = "defaultPath"
const val ARG_HAS_PASSWORD = "hasPassword"
const val ARG_KEYPAIR_NAME = "keypairName"
private val VALID_PORT_RANGE = IntRange(1, 65535)
}
private var ctx: WeakReference<Context>? = null
private var selectedPem: Uri? = null
private var selectedParsedKeyPair: KeyPair? = null
private var selectedParsedKeyPairName: String? = null
private var oldPath: String? = null
private var _binding: SftpDialogBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@Suppress("ComplexMethod")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
ctx = WeakReference(activity)
_binding = SftpDialogBinding.inflate(LayoutInflater.from(context))
val utilsProvider: UtilitiesProvider = AppConfig.getInstance().utilsProvider
val edit = requireArguments().getBoolean(ARG_EDIT, false)
initForm(edit)
val accentColor = (activity as ThemedActivity).accent
// Use system provided action to get Uri to PEM.
binding.selectPemBTN.setOnClickListener {
val intent = Intent()
.setType(MimeTypes.ALL_MIME_TYPES)
.setAction(Intent.ACTION_GET_CONTENT)
activityResultHandler.launch(intent)
}
// Define action for buttons
val dialogBuilder = MaterialDialog.Builder(ctx!!.get()!!)
.title(R.string.scp_connection)
.autoDismiss(false)
.customView(binding.root, true)
.theme(utilsProvider.appTheme.materialDialogTheme)
.negativeText(R.string.cancel)
.positiveText(if (edit) R.string.update else R.string.create)
.positiveColor(accentColor)
.negativeColor(accentColor)
.neutralColor(accentColor)
.onPositive(handleOnPositiveButton(edit))
.onNegative { dialog: MaterialDialog, _: DialogAction? ->
dialog.dismiss()
}
// If we are editing connection settings, give new actions for neutral and negative buttons
if (edit) {
appendButtonListenersForEdit(dialogBuilder)
}
val dialog = dialogBuilder.build()
// Some validations to make sure the Create/Update button is clickable only when required
// setting values are given
val okBTN: MDButton = dialog.getActionButton(DialogAction.POSITIVE)
if (!edit) okBTN.isEnabled = false
val validator: TextWatcher = createValidator(edit, okBTN)
binding.ipET.addTextChangedListener(validator)
binding.portET.addTextChangedListener(validator)
binding.usernameET.addTextChangedListener(validator)
binding.passwordET.addTextChangedListener(validator)
return dialog
}
private fun initForm(edit: Boolean) = binding.run {
portET.apply {
filters = arrayOf(MinMaxInputFilter(VALID_PORT_RANGE))
// For convenience, so I don't need to press backspace all the time
onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
if (hasFocus) {
selectAll()
}
}
}
// If it's new connection setup, set some default values
// Otherwise, use given Bundle instance for filling in the blanks
if (!edit) {
connectionET.setText(R.string.scp_connection)
portET.setText(SshConnectionPool.SSH_DEFAULT_PORT.toString())
} else {
connectionET.setText(requireArguments().getString(ARG_NAME))
ipET.setText(requireArguments().getString(ARG_ADDRESS))
portET.setText(requireArguments().getInt(ARG_PORT).toString())
defaultPathET.setText(requireArguments().getString(ARG_DEFAULT_PATH))
usernameET.setText(requireArguments().getString(ARG_USERNAME))
if (requireArguments().getBoolean(ARG_HAS_PASSWORD)) {
passwordET.setHint(R.string.password_unchanged)
} else {
selectedParsedKeyPairName = requireArguments().getString(ARG_KEYPAIR_NAME)
selectPemBTN.text = selectedParsedKeyPairName
}
oldPath = SshClientUtils.deriveSftpPathFrom(
requireArguments().getString(ARG_ADDRESS)!!,
requireArguments().getInt(ARG_PORT),
requireArguments().getString(ARG_DEFAULT_PATH, ""),
requireArguments().getString(ARG_USERNAME)!!,
requireArguments().getString(ARG_PASSWORD),
selectedParsedKeyPair
)
}
}
private fun appendButtonListenersForEdit(
dialogBuilder: MaterialDialog.Builder
) {
createConnectionSettings().run {
dialogBuilder
.negativeText(R.string.delete)
.onNegative { dialog: MaterialDialog, _: DialogAction? ->
val path = SshClientUtils.deriveSftpPathFrom(
hostname,
port,
defaultPath,
username,
requireArguments().getString(ARG_PASSWORD, null),
selectedParsedKeyPair
)
val i = DataUtils.getInstance().containsServer(
arrayOf(connectionName, path)
)
if (i > -1) {
DataUtils.getInstance().removeServer(i)
AppConfig.getInstance()
.runInBackground {
AppConfig.getInstance().utilsHandler.removeFromDatabase(
OperationData(
UtilsHandler.Operation.SFTP,
path,
connectionName,
null,
null,
null
)
)
}
(activity as MainActivity).drawer.refreshDrawer()
}
dialog.dismiss()
}.neutralText(R.string.cancel)
.onNeutral { dialog: MaterialDialog, _: DialogAction? -> dialog.dismiss() }
}
}
private fun createValidator(edit: Boolean, okBTN: MDButton): SimpleTextWatcher {
return object : SimpleTextWatcher() {
override fun afterTextChanged(s: Editable) {
val portETValue = binding.portET.text.toString()
val port = if (portETValue.isDigitsOnly() && (portETValue.length in 1..5)) {
portETValue.toInt()
} else {
-1
}
val hasCredential: Boolean = if (edit) {
if (true == binding.passwordET.text?.isNotEmpty() ||
!TextUtils.isEmpty(requireArguments().getString(ARG_PASSWORD))
) {
true
} else {
true == selectedParsedKeyPairName?.isNotEmpty()
}
} else {
true == binding.passwordET.text?.isNotEmpty() || selectedParsedKeyPair != null
}
okBTN.isEnabled = true == binding.connectionET.text?.isNotEmpty() &&
true == binding.ipET.text?.isNotEmpty() &&
port in VALID_PORT_RANGE &&
true == binding.usernameET.text?.isNotEmpty() &&
hasCredential
}
}
}
private fun handleOnPositiveButton(edit: Boolean):
MaterialDialog.SingleButtonCallback =
MaterialDialog.SingleButtonCallback { _, _ ->
createConnectionSettings().run {
// Get original SSH host key
AppConfig.getInstance().utilsHandler.getSshHostKey(
SshClientUtils.deriveSftpPathFrom(
hostname,
port,
defaultPath,
username,
arguments?.getString(ARG_PASSWORD, null),
selectedParsedKeyPair
)
)?.let { sshHostKey ->
SshConnectionPool.removeConnection(
SshClientUtils.deriveSftpPathFrom(
hostname,
port,
defaultPath,
username,
password,
selectedParsedKeyPair
)
) {
reconnectToServerToVerifyHostFingerprint(
this,
sshHostKey,
edit
)
}
} ?: firstConnectToServer(this, edit)
}
}
private fun firstConnectToServer(
connectionSettings: ConnectionSettings,
edit: Boolean
) = connectionSettings.run {
GetSshHostFingerprintTask(
hostname,
port
) { taskResult: AsyncTaskResult<PublicKey> ->
taskResult.result?.run {
val hostKeyFingerprint = SecurityUtils.getFingerprint(this)
val hostAndPort = StringBuilder(hostname).also {
if (port != SshConnectionPool.SSH_DEFAULT_PORT && port > 0) {
it.append(':').append(port)
}
}.toString()
AlertDialog.Builder(ctx!!.get())
.setTitle(R.string.ssh_host_key_verification_prompt_title)
.setMessage(
getString(
R.string.ssh_host_key_verification_prompt,
hostAndPort,
algorithm,
hostKeyFingerprint
)
).setCancelable(true)
.setPositiveButton(R.string.yes) {
dialog1: DialogInterface, _: Int ->
// This closes the host fingerprint verification dialog
dialog1.dismiss()
if (authenticateAndSaveSetup(
connectionSettings,
hostKeyFingerprint,
edit
)
) {
dialog1.dismiss()
Log.d(TAG, "Saved setup")
dismiss()
}
}.setNegativeButton(R.string.no) {
dialog1: DialogInterface, _: Int ->
dialog1.dismiss()
}.show()
}
}.execute()
}
private fun reconnectToServerToVerifyHostFingerprint(
connectionSettings: ConnectionSettings,
sshHostKey: String,
edit: Boolean
) {
connectionSettings.run {
GetSshHostFingerprintTask(hostname, port) {
taskResult: AsyncTaskResult<PublicKey> ->
taskResult.result?.let { hostKey ->
val hostKeyFingerprint = SecurityUtils.getFingerprint(hostKey)
if (hostKeyFingerprint == sshHostKey) {
authenticateAndSaveSetup(
connectionSettings,
sshHostKey,
edit
)
} else {
AlertDialog.Builder(ctx!!.get())
.setTitle(
R.string.ssh_connect_failed_host_key_changed_title
).setMessage(
R.string.ssh_connect_failed_host_key_changed_prompt
).setPositiveButton(
R.string.update_host_key
) { _: DialogInterface?, _: Int ->
authenticateAndSaveSetup(
connectionSettings,
hostKeyFingerprint,
edit
)
}.setNegativeButton(R.string.cancel_recommended) {
dialog1: DialogInterface, _: Int ->
dialog1.dismiss()
}.show()
}
}
}.execute()
}
}
@Suppress("LabeledExpression")
private val activityResultHandler = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (Activity.RESULT_OK == it.resultCode) {
it.data?.data?.run {
selectedPem = this
runCatching {
requireContext().contentResolver.openInputStream(this)?.let {
selectedKeyContent ->
PemToKeyPairTask(selectedKeyContent) { result: KeyPair? ->
selectedParsedKeyPair = result
selectedParsedKeyPairName = this
.lastPathSegment!!
.substring(
this.lastPathSegment!!
.indexOf('/') + 1
)
val okBTN = (dialog as MaterialDialog)
.getActionButton(DialogAction.POSITIVE)
okBTN.isEnabled = okBTN.isEnabled || true
binding.selectPemBTN.text = selectedParsedKeyPairName
}.execute()
}
}.onFailure {
Log.e(TAG, "Error reading PEM key", it)
}
}
}
}
private fun authenticateAndSaveSetup(
connectionSettings: ConnectionSettings,
hostKeyFingerprint: String,
isEdit: Boolean
): Boolean = connectionSettings.run {
val path = SshClientUtils.deriveSftpPathFrom(
hostname,
port,
defaultPath,
username,
password,
selectedParsedKeyPair
)
val encryptedPath = SshClientUtils.encryptSshPathAsNecessary(path)
return if (!isEdit) {
saveSshConnection(
connectionSettings,
hostKeyFingerprint,
path,
encryptedPath,
selectedParsedKeyPairName,
selectedParsedKeyPair
)
} else {
updateSshConnection(connectionName, hostKeyFingerprint, path, encryptedPath)
}
}
private fun saveSshConnection(
connectionSettings: ConnectionSettings,
hostKeyFingerprint: String,
path: String,
encryptedPath: String,
selectedParsedKeyPairName: String?,
selectedParsedKeyPair: KeyPair?
): Boolean {
connectionSettings.run {
return runCatching {
SshConnectionPool.getConnection(
hostname,
port,
hostKeyFingerprint,
username,
password,
selectedParsedKeyPair
)?.run {
if (DataUtils.getInstance().containsServer(path) == -1) {
DataUtils.getInstance().addServer(arrayOf(connectionName, path))
(activity as MainActivity).drawer.refreshDrawer()
AppConfig.getInstance().utilsHandler.saveToDatabase(
OperationData(
UtilsHandler.Operation.SFTP,
encryptedPath,
connectionName,
hostKeyFingerprint,
selectedParsedKeyPairName,
getPemContents()
)
)
val ma = (activity as MainActivity).currentMainFragment
ma?.loadlist(path, false, OpenMode.SFTP)
dismiss()
} else {
Snackbar.make(
requireActivity().findViewById(R.id.content_frame),
getString(R.string.connection_exists),
Snackbar.LENGTH_SHORT
).show()
dismiss()
}
true
} ?: false
}.getOrElse {
false
}
}
}
private fun updateSshConnection(
connectionName: String,
hostKeyFingerprint: String,
path: String,
encryptedPath: String
): Boolean {
DataUtils.getInstance().removeServer(DataUtils.getInstance().containsServer(oldPath))
DataUtils.getInstance().addServer(arrayOf(connectionName, path))
Collections.sort(DataUtils.getInstance().servers, BookSorter())
(activity as MainActivity).drawer.refreshDrawer()
AppConfig.getInstance().runInBackground {
AppConfig.getInstance().utilsHandler.updateSsh(
connectionName,
requireArguments().getString(ARG_NAME),
encryptedPath,
hostKeyFingerprint,
selectedParsedKeyPairName,
getPemContents()
)
}
dismiss()
return true
}
// Read the PEM content from InputStream to String.
private fun getPemContents(): String? = selectedPem?.run {
runCatching {
requireContext().contentResolver.openInputStream(this)
?.bufferedReader()
?.use(BufferedReader::readText)
}.getOrNull()
}
private data class ConnectionSettings(
val connectionName: String,
val hostname: String,
val port: Int,
val defaultPath: String? = null,
val username: String,
val password: String? = null,
val selectedParsedKeyPairName: String? = null,
val selectedParsedKeyPair: KeyPair? = null
)
private fun createConnectionSettings() =
ConnectionSettings(
connectionName = binding.connectionET.text.toString(),
hostname = binding.ipET.text.toString(),
port = binding.portET.text.toString().toInt(),
defaultPath = binding.defaultPathET.text.toString(),
username = binding.usernameET.text.toString(),
password = if (true == binding.passwordET.text?.isEmpty()) {
arguments?.getString(ARG_PASSWORD, null)
} else {
binding.passwordET.text.toString()
},
selectedParsedKeyPairName = this.selectedParsedKeyPairName,
selectedParsedKeyPair = selectedParsedKeyPair
)
}
|
gpl-3.0
|
7dac98e1bc4cf2a4a58e9c3a65d24820
| 40.714542 | 107 | 0.543232 | 5.752662 | false | false | false | false |
y20k/transistor
|
app/src/main/java/org/y20k/transistor/dialogs/FindStationDialog.kt
|
1
|
9247
|
/*
* FindStationDialog.kt
* Implements the FindStationDialog class
* A FindStationDialog shows a dialog with search box and list of results
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.dialogs
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.view.LayoutInflater
import android.view.inputmethod.InputMethodManager
import android.widget.ProgressBar
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textview.MaterialTextView
import org.y20k.transistor.Keys
import org.y20k.transistor.R
import org.y20k.transistor.core.Station
import org.y20k.transistor.helpers.LogHelper
import org.y20k.transistor.search.RadioBrowserResult
import org.y20k.transistor.search.RadioBrowserResultAdapter
import org.y20k.transistor.search.RadioBrowserSearch
/*
* FindStationDialog class
*/
class FindStationDialog (private var context: Context, private var listener: FindFindStationDialogListener): RadioBrowserResultAdapter.RadioBrowserResultAdapterListener, RadioBrowserSearch.RadioBrowserSearchListener {
/* Interface used to communicate back to activity */
interface FindFindStationDialogListener {
fun onFindStationDialog(remoteStationLocation: String, station: Station) {
}
}
/* Define log tag */
private val TAG = LogHelper.makeLogTag(FindStationDialog::class.java.simpleName)
/* Main class variables */
private lateinit var dialog: AlertDialog
private lateinit var stationSearchBoxView: SearchView
private lateinit var searchRequestProgressIndicator: ProgressBar
private lateinit var noSearchResultsTextView: MaterialTextView
private lateinit var stationSearchResultList: RecyclerView
private lateinit var searchResultAdapter: RadioBrowserResultAdapter
private lateinit var radioBrowserSearch: RadioBrowserSearch
private var currentSearchString: String = String()
private val handler: Handler = Handler()
private var remoteStationLocation: String = String()
private var station: Station = Station()
/* Overrides onSearchResultTapped from RadioBrowserResultAdapterListener */
override fun onSearchResultTapped(radioBrowserResult: RadioBrowserResult) {
station = radioBrowserResult.toStation()
// hide keyboard
val imm: InputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(stationSearchBoxView.windowToken, 0)
// make add button clickable
activateAddButton()
}
/* Overrides onRadioBrowserSearchResults from RadioBrowserSearchListener */
override fun onRadioBrowserSearchResults(results: Array<RadioBrowserResult>) {
if (results.isNotEmpty()) {
searchResultAdapter.searchResults = results
searchResultAdapter.notifyDataSetChanged()
resetLayout(clearAdapter = false)
} else {
showNoResultsError()
}
}
/* Construct and show dialog */
fun show() {
// initialize a radio browser search
radioBrowserSearch = RadioBrowserSearch(this)
// prepare dialog builder
val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
// set title
builder.setTitle(R.string.dialog_find_station_title)
// get views
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_find_station, null)
stationSearchBoxView = view.findViewById(R.id.station_search_box_view)
searchRequestProgressIndicator = view.findViewById(R.id.search_request_progress_indicator)
stationSearchResultList = view.findViewById(R.id.station_search_result_list)
noSearchResultsTextView = view.findViewById(R.id.no_results_text_view)
noSearchResultsTextView.isGone = true
// set up list of search results
setupRecyclerView(context)
// add okay ("import") button
builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ ->
// listen for click on add button
(listener).onFindStationDialog(remoteStationLocation, station)
}
// add cancel button
builder.setNegativeButton(R.string.dialog_generic_button_cancel) { _, _ ->
// listen for click on cancel button
radioBrowserSearch.stopSearchRequest()
}
// handle outside-click as "no"
builder.setOnCancelListener {
radioBrowserSearch.stopSearchRequest()
}
// listen for input
stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(query: String): Boolean {
handleSearchBoxLiveInput(context, query)
return true
}
override fun onQueryTextSubmit(query: String): Boolean {
handleSearchBoxInput(context, query)
return true
}
})
// set dialog view
builder.setView(view)
// create and display dialog
dialog = builder.create()
dialog.show()
// initially disable "Add" button
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
}
/* Sets up list of results (RecyclerView) */
private fun setupRecyclerView(context: Context) {
searchResultAdapter = RadioBrowserResultAdapter(this, arrayOf())
stationSearchResultList.adapter = searchResultAdapter
val layoutManager: LinearLayoutManager = object: LinearLayoutManager(context) {
override fun supportsPredictiveItemAnimations(): Boolean {
return true
}
}
stationSearchResultList.layoutManager = layoutManager
stationSearchResultList.itemAnimator = DefaultItemAnimator()
}
/* Handles user input into search box - user has to submit the search */
private fun handleSearchBoxInput(context: Context, query: String) {
when {
// handle empty search box input
query.isEmpty() -> {
resetLayout(clearAdapter = true)
}
// handle direct URL input
query.startsWith("http") -> {
remoteStationLocation = query
activateAddButton()
}
// handle search string input
else -> {
showProgressIndicator()
radioBrowserSearch.searchStation(context, query, Keys.SEARCH_TYPE_BY_KEYWORD)
}
}
}
/* Handles live user input into search box */
private fun handleSearchBoxLiveInput(context: Context, query: String) {
currentSearchString = query
if (query.startsWith("htt")) {
// handle direct URL input
remoteStationLocation = query
activateAddButton()
} else if (query.contains(" ") || query.length > 2 ) {
// show progress indicator
showProgressIndicator()
// handle search string input - delay request to manage server load (not sure if necessary)
handler.postDelayed({
// only start search if query is the same as one second ago
if (currentSearchString == query) radioBrowserSearch.searchStation(context, query, Keys.SEARCH_TYPE_BY_KEYWORD)
}, 1000)
} else if (query.isEmpty()) {
resetLayout(clearAdapter = true)
}
}
/* Makes the "Add" button clickable */
private fun activateAddButton() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true
}
/* Resets the dialog layout to default state */
private fun resetLayout(clearAdapter: Boolean = false) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true
searchResultAdapter.resetSelection(clearAdapter)
}
/* Display the "No Results" error - hide other unneeded views */
private fun showNoResultsError() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isVisible = true
}
/* Display the "No Results" error - hide other unneeded views */
private fun showProgressIndicator() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
searchRequestProgressIndicator.isVisible = true
noSearchResultsTextView.isGone = true
}
}
|
mit
|
f30f9698af104daa1b49950a099ffe72
| 36.897541 | 217 | 0.692549 | 5.100386 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/gradle/code-insight-common/src/org/jetbrains/kotlin/idea/gradleCodeInsightCommon/SettingsScriptBuilder.kt
|
1
|
3228
|
// 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.gradleCodeInsightCommon
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
abstract class SettingsScriptBuilder<T: PsiFile>(val scriptFile: T) {
private val builder = StringBuilder(scriptFile.text)
private fun findBlockBody(blockName: String, startFrom: Int = 0): Int {
val blockOffset = builder.indexOf(blockName, startFrom)
if (blockOffset < 0) return -1
return builder.indexOf('{', blockOffset + 1) + 1
}
private fun getOrPrependTopLevelBlockBody(blockName: String): Int {
val blockBody = findBlockBody(blockName)
if (blockBody >= 0) return blockBody
builder.insert(0, "$blockName {}\n")
return findBlockBody(blockName)
}
private fun getOrAppendInnerBlockBody(blockName: String, offset: Int): Int {
val repositoriesBody = findBlockBody(blockName, offset)
if (repositoriesBody >= 0) return repositoriesBody
builder.insert(offset, "\n$blockName {}\n")
return findBlockBody(blockName, offset)
}
private fun appendExpressionToBlockIfAbsent(expression: String, offset: Int) {
var braceCount = 1
var blockEnd = offset
for (i in offset..builder.lastIndex) {
when (builder[i]) {
'{' -> braceCount++
'}' -> braceCount--
}
if (braceCount == 0) {
blockEnd = i
break
}
}
if (!builder.substring(offset, blockEnd).contains(expression.trim())) {
builder.insert(blockEnd, "\n$expression\n")
}
}
private fun getOrCreatePluginManagementBody() = getOrPrependTopLevelBlockBody("pluginManagement")
protected fun addPluginRepositoryExpression(expression: String) {
val repositoriesBody = getOrAppendInnerBlockBody("repositories", getOrCreatePluginManagementBody())
appendExpressionToBlockIfAbsent(expression, repositoriesBody)
}
fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
abstract fun addPluginRepository(repository: RepositoryDescription)
fun addResolutionStrategy(pluginId: String) {
val resolutionStrategyBody = getOrAppendInnerBlockBody("resolutionStrategy", getOrCreatePluginManagementBody())
val eachPluginBody = getOrAppendInnerBlockBody("eachPlugin", resolutionStrategyBody)
appendExpressionToBlockIfAbsent(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent(),
eachPluginBody
)
}
fun addIncludedModules(modules: List<String>) {
builder.append(modules.joinToString(prefix = "include ", postfix = "\n") { "'$it'" })
}
fun build() = builder.toString()
abstract fun buildPsiFile(project: Project): T
}
|
apache-2.0
|
f61d0f62d71aede1292e0f49561b6a49
| 38.365854 | 158 | 0.664498 | 5.371048 | false | false | false | false |
Major-/Vicis
|
legacy/src/main/kotlin/rs/emulate/legacy/version/map/MapIndexDecoder.kt
|
1
|
1110
|
package rs.emulate.legacy.version.map
import rs.emulate.legacy.archive.Archive
import java.io.FileNotFoundException
/**
* Decoder for the version lists "map_index" entry.
*
* @param archive The version list [Archive].
* @throws FileNotFoundException If the `map_index` entry could not be found.
*/
class MapIndexDecoder constructor(archive: Archive) {
private val data = archive[MapIndex.ENTRY_NAME].buffer.copy()
/**
* Decodes the contents of the `map_index` entry into a [MapIndex].
*/
fun decode(): MapIndex {
val count = data.readableBytes() / (3 * java.lang.Short.BYTES + java.lang.Byte.BYTES)
val areas = IntArray(count)
val maps = IntArray(count)
val objects = IntArray(count)
val members = BooleanArray(count)
for (index in 0 until count) {
areas[index] = data.readUnsignedShort()
maps[index] = data.readUnsignedShort()
objects[index] = data.readUnsignedShort()
members[index] = data.readBoolean()
}
return MapIndex(areas, objects, maps, members)
}
}
|
isc
|
a0ff6c15cdecea86901f4f9137d1e0a0
| 29 | 93 | 0.64955 | 4.141791 | false | false | false | false |
Major-/Vicis
|
legacy/src/main/kotlin/rs/emulate/legacy/archive/ArchiveCodec.kt
|
1
|
4004
|
package rs.emulate.legacy.archive
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import rs.emulate.legacy.archive.CompressionType.ARCHIVE_COMPRESSION
import rs.emulate.legacy.archive.CompressionType.ENTRY_COMPRESSION
import rs.emulate.legacy.archive.CompressionType.NO_COMPRESSION
import rs.emulate.util.compression.bunzip2
import rs.emulate.util.compression.bzip2
import rs.emulate.util.readUnsignedTriByte
import rs.emulate.util.toByteArray
import rs.emulate.util.writeTriByte
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.ArrayList
/**
* Contains methods for encoding and decoding [Archive]s.
*/
object ArchiveCodec {
/**
* Decodes the [Archive] in the specified [ByteBuf].
* @throws IOException If there is an error decompressing the data.
*/
fun decode(buffer: ByteBuf): Archive {
var buffer = buffer
if (buffer.readableBytes() == 0) {
return Archive.EMPTY_ARCHIVE
}
val extractedSize = buffer.readUnsignedTriByte()
val size = buffer.readUnsignedTriByte()
var extracted = false
if (size != extractedSize) {
buffer = buffer.bunzip2(extractedSize)
extracted = true
}
val count = buffer.readUnsignedShort()
val identifiers = IntArray(count)
val extractedSizes = IntArray(count)
val compressedSizes = IntArray(count)
for (entry in 0 until count) {
identifiers[entry] = buffer.readInt()
extractedSizes[entry] = buffer.readUnsignedTriByte()
compressedSizes[entry] = buffer.readUnsignedTriByte()
}
val entries = ArrayList<ArchiveEntry>(count)
for (entry in 0 until count) {
val entrySize = if (extracted) extractedSizes[entry] else compressedSizes[entry]
val data = buffer.readSlice(entrySize)
val uncompressed = if (extracted) data else data.bunzip2(extractedSizes[entry])
entries += ArchiveEntry(identifiers[entry], uncompressed)
}
return Archive(entries)
}
/**
* Encodes the specified [Archive] into a [ByteBuf].
* @throws IOException If there is an error compressing the archive.
*/
fun encode(archive: Archive, compression: CompressionType): ByteBuf {
ByteArrayOutputStream(archive.size).use { bos ->
val entries = archive.entries
val entryCount = entries.size
val meta = Unpooled.buffer(entryCount * (Integer.BYTES + 2 * 3) + java.lang.Short.BYTES)
meta.writeShort(entryCount)
for (entry in entries) {
val uncompressed = entry.buffer
val compressed = uncompressed.bzip2()
uncompressed.readerIndex(0) // We just read from this buffer, so reset the position
meta.writeInt(entry.identifier)
meta.writeTriByte(uncompressed.readableBytes())
meta.writeTriByte(compressed.readableBytes())
when (compression) {
ARCHIVE_COMPRESSION, NO_COMPRESSION -> bos.write(uncompressed.toByteArray())
ENTRY_COMPRESSION -> bos.write(compressed.toByteArray())
}
}
val compressed = bos.toByteArray()
var data = Unpooled.buffer(meta.readableBytes() + compressed.size)
data.writeBytes(meta).writeBytes(compressed)
val header = Unpooled.buffer(2 * 3)
val extracted = data.readableBytes()
header.writeTriByte(extracted)
if (compression === ARCHIVE_COMPRESSION) {
data = data.bzip2()
}
val compressedLength = data.readableBytes()
header.writeTriByte(compressedLength)
val buffer = Unpooled.buffer(header.readableBytes() + data.readableBytes())
buffer.writeBytes(header).writeBytes(data)
return buffer
}
}
}
|
isc
|
369ad1843271c0e3230c965bda32eae6
| 34.122807 | 100 | 0.638861 | 4.783751 | false | false | false | false |
iPoli/iPoli-android
|
app/src/main/java/io/ipoli/android/store/usecase/PurchaseGemPackUseCase.kt
|
1
|
1459
|
package io.ipoli.android.store.usecase
import io.ipoli.android.Constants
import io.ipoli.android.common.UseCase
import io.ipoli.android.pet.Pet
import io.ipoli.android.pet.PetAvatar
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
import io.ipoli.android.store.gem.GemPack
import io.ipoli.android.store.gem.GemPackType
/**
* Created by Venelin Valkov <[email protected]>
* on 12/28/17.
*/
class PurchaseGemPackUseCase(private val playerRepository: PlayerRepository) :
UseCase<PurchaseGemPackUseCase.Params, PurchaseGemPackUseCase.Result> {
override fun execute(parameters: Params): Result {
val player = playerRepository.find()
requireNotNull(player)
val gemPack = parameters.gemPack
val hasUnlockedPet = !player!!.hasPet(PetAvatar.DOG) && gemPack.type == GemPackType.SMART
val newPlayer = player.copy(
gems = player.gems + gemPack.gems,
inventory = if (hasUnlockedPet)
player.inventory.addPet(
Pet(
name = Constants.DEFAULT_PET_NAME,
avatar = PetAvatar.DOG
)
)
else player.inventory
)
return Result(playerRepository.save(newPlayer), hasUnlockedPet)
}
data class Params(val gemPack: GemPack)
data class Result(val player: Player, val hasUnlockedPet: Boolean)
}
|
gpl-3.0
|
019461a780ec8909ab374772ae404ff3
| 31.444444 | 97 | 0.671008 | 4.216763 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/highlighter/KotlinTestRunLineMarkerContributor.kt
|
2
|
6038
|
// 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.highlighter
import com.intellij.execution.TestStateStorage
import com.intellij.execution.lineMarker.ExecutorAction
import com.intellij.execution.lineMarker.RunLineMarkerContributor
import com.intellij.psi.PsiElement
import com.intellij.util.Function
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinBaseCodeInsightBundle
import org.jetbrains.kotlin.idea.base.codeInsight.PsiOnlyKotlinMainFunctionDetector
import org.jetbrains.kotlin.idea.base.codeInsight.hasMain
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.codeInsight.tooling.tooling
import org.jetbrains.kotlin.idea.base.util.isGradleModule
import org.jetbrains.kotlin.idea.base.util.isUnderKotlinSourceRootTypes
import org.jetbrains.kotlin.idea.testIntegration.framework.KotlinTestFramework
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.platform.SimplePlatform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.isMultiPlatform
import org.jetbrains.kotlin.platform.konan.NativePlatformWithTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.Icon
class KotlinTestRunLineMarkerContributor : RunLineMarkerContributor() {
companion object {
/**
* Users may want to try to run that individual test, for example to check if it still fails because of some third party problem,
* but it's not executed when a whole class or test package run.
*
* On other side Gradle has its own built-in support for JUnit but doesn't allow fine-tuning behaviour.
* As of now launching ignored tests (for Gradle) is impossible.
*/
private fun KtNamedDeclaration.isIgnoredForGradleModule(includeSlowProviders: Boolean): Boolean {
val ktNamedFunction = this.safeAs<KtNamedFunction>().takeIf { module?.isGradleModule == true } ?: return false
val testFramework = KotlinTestFramework.getApplicableFor(this, includeSlowProviders)
return testFramework?.isIgnoredMethod(ktNamedFunction) == true
}
fun getTestStateIcon(urls: List<String>, declaration: KtNamedDeclaration): Icon {
val testStateStorage = TestStateStorage.getInstance(declaration.project)
val isClass = declaration is KtClass
val state: TestStateStorage.Record? = run {
for (url in urls) {
testStateStorage.getState(url)?.let { return@run it }
}
null
}
return getTestStateIcon(state, isClass)
}
private fun SimplePlatform.providesRunnableTests(): Boolean {
if (this is NativePlatformWithTarget) {
return when {
HostManager.hostIsMac -> target in listOf(
KonanTarget.IOS_X64,
KonanTarget.MACOS_X64,
KonanTarget.WATCHOS_X64, KonanTarget.WATCHOS_X86,
KonanTarget.TVOS_X64
)
HostManager.hostIsLinux -> target == KonanTarget.LINUX_X64
HostManager.hostIsMingw -> target in listOf(KonanTarget.MINGW_X86, KonanTarget.MINGW_X64)
else -> false
}
}
return true
}
fun TargetPlatform.providesRunnableTests(): Boolean = componentPlatforms.any { it.providesRunnableTests() }
}
override fun getInfo(element: PsiElement): Info? = calculateIcon(element, false)
override fun getSlowInfo(element: PsiElement): Info? = calculateIcon(element, true)
private fun calculateIcon(
element: PsiElement,
includeSlowProviders: Boolean
): Info? {
val declaration = element.getStrictParentOfType<KtNamedDeclaration>()?.takeIf { it.nameIdentifier == element } ?: return null
val targetPlatform = declaration.module?.platform ?: return null
if (declaration is KtNamedFunction) {
if (declaration.containingClassOrObject == null ||
targetPlatform.isMultiPlatform() && declaration.containingClass() == null) return null
} else {
if (declaration !is KtClassOrObject ||
targetPlatform.isMultiPlatform() && declaration !is KtClass
) return null
}
if (!targetPlatform.providesRunnableTests()) return null
if (!declaration.isUnderKotlinSourceRootTypes()) return null
val icon = targetPlatform.idePlatformKind.tooling.getTestIcon(declaration, includeSlowProviders)
?.takeUnless { declaration.isIgnoredForGradleModule(includeSlowProviders) }
?: return null
return Info(
icon,
Function { KotlinBaseCodeInsightBundle.message("highlighter.tool.tip.text.run.test") },
*ExecutorAction.getActions(getOrder(declaration))
)
}
private fun getOrder(declaration: KtNamedDeclaration): Int {
if (declaration is KtClass && declaration.companionObjects.any { PsiOnlyKotlinMainFunctionDetector.hasMain(it) }) {
return 1
}
if (declaration is KtNamedFunction) {
val containingClass = declaration.containingClassOrObject
return if (containingClass != null && PsiOnlyKotlinMainFunctionDetector.hasMain(containingClass)) 1 else 0
}
return if (PsiOnlyKotlinMainFunctionDetector.hasMain(declaration.containingKtFile)) 1 else 0
}
}
|
apache-2.0
|
b355613e8170ecaf71a5ee681310b489
| 46.171875 | 137 | 0.701391 | 5.241319 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt
|
4
|
13040
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.stubs.StubIndex
import com.intellij.util.ArrayUtil
import com.intellij.util.Processor
import com.intellij.util.Processors
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.indexing.IdFilter
import org.jetbrains.kotlin.analysis.decompiler.psi.KotlinBuiltInFileType
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.defaultImplsChild
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.asJava.getAccessorLightMethods
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() {
companion object {
private val LOG = Logger.getInstance(KotlinShortNamesCache::class.java)
}
//hacky way to avoid searches for Kotlin classes, when looking for Java (from Kotlin)
val disableSearch: ThreadLocal<Boolean> = object : ThreadLocal<Boolean>() {
override fun initialValue(): Boolean = false
}
//region Classes
override fun processAllClassNames(processor: Processor<in String>): Boolean {
if (disableSearch.get()) return true
return KotlinClassShortNameIndex.processAllKeys(project, processor) &&
KotlinFileFacadeShortNameIndex.processAllKeys(project, processor)
}
override fun processAllClassNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean {
if (disableSearch.get()) return true
return processAllClassNames(processor)
}
/**
* Return kotlin class names from project sources which should be visible from java.
*/
override fun getAllClassNames(): Array<String> {
if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY
return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor ->
processAllClassNames(processor)
}
}
override fun processClassesWithName(
name: String,
processor: Processor<in PsiClass>,
scope: GlobalSearchScope,
filter: IdFilter?
): Boolean {
if (disableSearch.get()) return true
val effectiveScope = kotlinDeclarationsVisibleFromJavaScope(scope)
val fqNameProcessor = Processor<FqName> { fqName: FqName? ->
if (fqName == null) return@Processor true
val isInterfaceDefaultImpl = name == JvmAbi.DEFAULT_IMPLS_CLASS_NAME && fqName.shortName().asString() != name
if (fqName.shortName().asString() != name && !isInterfaceDefaultImpl) {
LOG.error(
"A declaration obtained from index has non-matching name:" +
"\nin index: $name" +
"\ndeclared: ${fqName.shortName()}($fqName)"
)
return@Processor true
}
val fqNameToSearch = if (isInterfaceDefaultImpl) fqName.defaultImplsChild() else fqName
val psiClass = JavaElementFinder.getInstance(project).findClass(fqNameToSearch.asString(), effectiveScope)
?: return@Processor true
return@Processor processor.process(psiClass)
}
val allKtClassOrObjectsProcessed = StubIndex.getInstance().processElements(
KotlinClassShortNameIndex.key,
name,
project,
effectiveScope,
filter,
KtClassOrObject::class.java
) { ktClassOrObject ->
fqNameProcessor.process(ktClassOrObject.fqName)
}
if (!allKtClassOrObjectsProcessed) {
return false
}
return StubIndex.getInstance().processElements(
KotlinFileFacadeShortNameIndex.key,
name,
project,
effectiveScope,
filter,
KtFile::class.java
) { ktFile ->
fqNameProcessor.process(ktFile.javaFileFacadeFqName)
}
}
/**
* Return class names form kotlin sources in given scope which should be visible as Java classes.
*/
override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<PsiClass> {
if (disableSearch.get()) return PsiClass.EMPTY_ARRAY
return withArrayProcessor(PsiClass.EMPTY_ARRAY) { processor ->
processClassesWithName(name, processor, scope, null)
}
}
private fun kotlinDeclarationsVisibleFromJavaScope(scope: GlobalSearchScope): GlobalSearchScope {
val noBuiltInsScope: GlobalSearchScope = object : GlobalSearchScope(project) {
override fun isSearchInModuleContent(aModule: Module) = true
override fun compare(file1: VirtualFile, file2: VirtualFile) = 0
override fun isSearchInLibraries() = true
override fun contains(file: VirtualFile) = !FileTypeRegistry.getInstance().isFileOfType(file, KotlinBuiltInFileType)
}
return KotlinSourceFilterScope.projectSourcesAndLibraryClasses(scope, project).intersectWith(noBuiltInsScope)
}
//endregion
//region Methods
override fun processAllMethodNames(
processor: Processor<in String>,
scope: GlobalSearchScope,
filter: IdFilter?
): Boolean {
if (disableSearch.get()) return true
return processAllMethodNames(processor)
}
override fun getAllMethodNames(): Array<String> {
if (disableSearch.get()) ArrayUtil.EMPTY_STRING_ARRAY
return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor ->
processAllMethodNames(processor)
}
}
private fun processAllMethodNames(processor: Processor<in String>): Boolean {
if (disableSearch.get()) return true
if (!KotlinFunctionShortNameIndex.processAllKeys(project, processor)) {
return false
}
return KotlinPropertyShortNameIndex.processAllKeys(project) { name ->
return@processAllKeys processor.process(JvmAbi.setterName(name)) && processor.process(JvmAbi.getterName(name))
}
}
override fun processMethodsWithName(
name: String,
processor: Processor<in PsiMethod>,
scope: GlobalSearchScope,
filter: IdFilter?
): Boolean {
if (disableSearch.get()) return true
val allFunctionsProcessed = StubIndex.getInstance().processElements(
KotlinFunctionShortNameIndex.key,
name,
project,
scope,
filter,
KtNamedFunction::class.java
) { ktNamedFunction ->
val methods = LightClassUtil.getLightClassMethodsByName(ktNamedFunction, name).toList()
methods.all(processor::process)
}
if (!allFunctionsProcessed) {
return false
}
for (propertyName in getPropertyNamesCandidatesByAccessorName(Name.identifier(name))) {
val allProcessed = StubIndex.getInstance().processElements(
KotlinPropertyShortNameIndex.key,
propertyName.asString(),
project,
scope,
filter,
KtNamedDeclaration::class.java
) { ktNamedDeclaration ->
if (ktNamedDeclaration is KtValVarKeywordOwner) {
if (ktNamedDeclaration.isPrivate() || KotlinPsiHeuristics.hasJvmFieldAnnotation(ktNamedDeclaration)) {
return@processElements true
}
}
ktNamedDeclaration.getAccessorLightMethods()
.asSequence()
.filter { it.name == name }
.all(processor::process)
}
if (!allProcessed) {
return false
}
}
return true
}
override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod> {
if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY
return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor ->
processMethodsWithName(name, processor, scope, null)
}
}
override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> {
if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY
require(maxCount >= 0)
return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor ->
processMethodsWithName(
name,
{ psiMethod ->
processor.size != maxCount && processor.process(psiMethod)
},
scope,
null
)
}
}
override fun processMethodsWithName(
name: String,
scope: GlobalSearchScope,
processor: Processor<in PsiMethod>
): Boolean {
if (disableSearch.get()) return true
return ContainerUtil.process(getMethodsByName(name, scope), processor)
}
//endregion
//region Fields
override fun processAllFieldNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean {
if (disableSearch.get()) return true
return processAllFieldNames(processor)
}
override fun getAllFieldNames(): Array<String> {
if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY
return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor ->
processAllFieldNames(processor)
}
}
private fun processAllFieldNames(processor: Processor<in String>): Boolean {
if (disableSearch.get()) return true
return KotlinPropertyShortNameIndex.processAllKeys(project, processor)
}
override fun processFieldsWithName(
name: String,
processor: Processor<in PsiField>,
scope: GlobalSearchScope,
filter: IdFilter?
): Boolean {
if (disableSearch.get()) return true
return StubIndex.getInstance().processElements(
KotlinPropertyShortNameIndex.key,
name,
project,
scope,
filter,
KtNamedDeclaration::class.java
) { ktNamedDeclaration ->
val field = LightClassUtil.getLightClassBackingField(ktNamedDeclaration)
?: return@processElements true
return@processElements processor.process(field)
}
}
override fun getFieldsByName(name: String, scope: GlobalSearchScope): Array<PsiField> {
if (disableSearch.get()) return PsiField.EMPTY_ARRAY
return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor ->
processFieldsWithName(name, processor, scope, null)
}
}
override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> {
if (disableSearch.get()) return PsiField.EMPTY_ARRAY
require(maxCount >= 0)
return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor ->
processFieldsWithName(
name,
{ psiField ->
processor.size != maxCount && processor.process(psiField)
},
scope,
null
)
}
}
//endregion
private inline fun <T> withArrayProcessor(
result: Array<T>,
process: (CancelableArrayCollectProcessor<T>) -> Unit
): Array<T> {
return CancelableArrayCollectProcessor<T>().also { processor ->
process(processor)
}.toArray(result)
}
private class CancelableArrayCollectProcessor<T> : Processor<T> {
private val set = HashSet<T>()
private val processor = Processors.cancelableCollectProcessor<T>(set)
override fun process(value: T): Boolean {
return processor.process(value)
}
val size: Int get() = set.size
fun toArray(a: Array<T>): Array<T> = set.toArray(a)
}
}
|
apache-2.0
|
67796c1b5c41f0219d0a2fba60244975
| 36.797101 | 158 | 0.652991 | 5.359638 | false | false | false | false |
RayBa82/DVBViewerController
|
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/TimerList.kt
|
1
|
15135
|
/*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.appcompat.view.ActionMode.Callback
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import okhttp3.ResponseBody
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.api.ApiResponse
import org.dvbviewer.controller.data.api.ApiStatus
import org.dvbviewer.controller.data.entities.Timer
import org.dvbviewer.controller.data.timer.TimerRepository
import org.dvbviewer.controller.data.timer.TimerViewModel
import org.dvbviewer.controller.data.timer.TimerViewModelFactory
import org.dvbviewer.controller.ui.base.BaseListFragment
import org.dvbviewer.controller.ui.phone.TimerDetailsActivity
import org.dvbviewer.controller.ui.widget.ClickableRelativeLayout
import org.dvbviewer.controller.utils.*
import retrofit2.Call
import retrofit2.Response
import java.util.*
/**
* The Class TimerList.
*
* @author RayBa
* @date 07.04.2013
*/
class TimerList : BaseListFragment(), Callback, OnClickListener, TimerDetails.OnTimerEditedListener, AdapterView.OnItemLongClickListener {
private lateinit var mAdapter: TimerAdapter
private var mode: ActionMode? = null
private var actionMode: Boolean = false
private lateinit var repository: TimerRepository
private lateinit var viewModel: TimerViewModel
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAdapter = TimerAdapter()
setHasOptionsMenu(true)
repository = TimerRepository(getDmsInterface())
val vFac = TimerViewModelFactory(repository)
viewModel = ViewModelProvider(this, vFac)
.get(TimerViewModel::class.java)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
listAdapter = mAdapter
listView!!.choiceMode = ListView.CHOICE_MODE_MULTIPLE
listView!!.onItemLongClickListener = this
setEmptyText(resources.getString(R.string.no_timer))
if (savedInstanceState != null && savedInstanceState.getBoolean(ACTION_MODE, false)) {
val activity = activity as AppCompatActivity?
mode = activity!!.startSupportActionMode(this)
updateActionModeTitle(savedInstanceState.getInt(CHECKED_ITEM_COUNT))
} else {
activity!!.setTitle(R.string.timer)
}
val timerObserver = Observer<ApiResponse<List<Timer>>> { response -> onTimerLoaded(response!!) }
viewModel.getTimerList().observe(this, timerObserver)
setListShown(false)
}
private fun onTimerLoaded(response: ApiResponse<List<Timer>>?) {
if(response?.status == ApiStatus.SUCCESS) {
mAdapter.items = response.data
} else if(response?.status == ApiStatus.ERROR) {
catchException(TAG, response.e)
}
setListShown(true)
}
override fun timerEdited(timer: Timer?) {
timer?.let {
setListShown(false)
repository.saveTimer(it).enqueue(object : retrofit2.Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
refresh()
sendMessage(R.string.timer_saved)
logEvent(EVENT_TIMER_EDITED)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
setListShown(true)
sendMessage(R.string.error_common)
}
})
}
}
/**
* The Class ViewHolder.
*
* @author RayBa
* @date 07.04.2013
*/
private class ViewHolder {
internal var layout: ClickableRelativeLayout? = null
internal var recIndicator: ImageView? = null
internal var title: TextView? = null
internal var channelName: TextView? = null
internal var date: TextView? = null
}
/**
* The Class TimerAdapter.
*
* @author RayBa
* @date 07.04.2013
*/
inner class TimerAdapter
/**
* The Constructor.
*
* @author RayBa
* @date 04.06.2010
* @description Instantiates a new recording adapter.
*/
: ArrayListAdapter<Timer>() {
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val holder: ViewHolder
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_timer, parent, false)
holder = ViewHolder()
holder.layout = convertView as ClickableRelativeLayout?
holder.recIndicator = convertView!!.findViewById(R.id.recIndicator)
holder.title = convertView.findViewById(R.id.title)
holder.channelName = convertView.findViewById(R.id.channelName)
holder.date = convertView.findViewById(R.id.date)
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
val o = getItem(position)
if (o != null) {
holder.title!!.text = o.title
holder.channelName!!.text = o.channelName
var date = DateUtils.getDateInLocalFormat(o.start)
if (DateUtils.isToday(o.start!!.time)) {
date = resources.getString(R.string.today)
} else if (DateUtils.isTomorrow(o.start!!.time)) {
date = resources.getString(R.string.tomorrow)
}
holder.layout!!.isError = o.isFlagSet(Timer.FLAG_EXECUTABLE)
holder.layout!!.isDisabled = o.isFlagSet(Timer.FLAG_DISABLED)
val start = DateUtils.getTimeInLocalFormat(context, o.start)
val end = DateUtils.getTimeInLocalFormat(context, o.end)
holder.date!!.text = "$date $start - $end"
holder.recIndicator!!.visibility = if (o.isFlagSet(Timer.FLAG_RECORDING)) View.VISIBLE else View.GONE
}
return convertView!!
}
}
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.base.BaseListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long)
*/
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
if (actionMode) {
v.isSelected = !v.isSelected
val count = checkedItemCount
updateActionModeTitle(count)
if (checkedItemCount == 0) {
mode!!.finish()
}
} else {
if (UIUtils.isTablet(context!!)) {
onDestroyActionMode(mode)
val timer = mAdapter.getItem(position)
val timerdetails = TimerDetails.newInstance()
val args = TimerDetails.buildBundle(timer)
timerdetails.arguments = args
timerdetails.setTargetFragment(this, 0)
timerdetails.setOnTimerEditedListener(this)
timerdetails.show(activity!!.supportFragmentManager, TimerDetails::class.java.name)
} else {
listView!!.setItemChecked(position, !listView!!.isItemChecked(position))
val timer = mAdapter.getItem(position)
val timerIntent = Intent(context, TimerDetailsActivity::class.java)
val extras = TimerDetails.buildBundle(timer)
timerIntent.putExtras(extras)
startActivityForResult(timerIntent, TimerDetails.TIMER_RESULT)
}
}
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(ACTION_MODE, actionMode)
outState.putInt(CHECKED_ITEM_COUNT, checkedItemCount)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityResult(int, int, android.content.Intent)
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == TimerDetails.RESULT_CHANGED) {
val timer: Timer? = data?.getSerializableExtra("timer") as Timer?
timerEdited(timer)
}
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockFragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.timer_list, menu)
}
/* (non-Javadoc)
* @see com.actionbarsherlock.view.ActionMode.Callback#onCreateActionMode(com.actionbarsherlock.view.ActionMode, com.actionbarsherlock.view.Menu)
*/
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
actionMode = true
activity!!.menuInflater.inflate(R.menu.actionmode_recording, menu)
return true
}
/* (non-Javadoc)
* @see com.actionbarsherlock.view.ActionMode.Callback#onPrepareActionMode(com.actionbarsherlock.view.ActionMode, com.actionbarsherlock.view.Menu)
*/
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
/* (non-Javadoc)
* @see com.actionbarsherlock.view.ActionMode.Callback#onActionItemClicked(com.actionbarsherlock.view.ActionMode, com.actionbarsherlock.view.MenuItem)
*/
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuDelete -> {
/**
* Alertdialog to confirm the delete of Recordings
*/
val builder = AlertDialog.Builder(context!!)
builder.setMessage(resources.getString(R.string.confirmDelete)).setPositiveButton(resources.getString(R.string.yes), this).setNegativeButton(resources.getString(R.string.no), this).show()
}
else -> {
}
}
return true
}
/**
* The Class TimerDeleter.
*
* @author RayBa
* @date 07.04.2013
*/
/* (non-Javadoc)
* @see com.actionbarsherlock.view.ActionMode.Callback#onDestroyActionMode(com.actionbarsherlock.view.ActionMode)
*/
override fun onDestroyActionMode(mode: ActionMode?) {
actionMode = false
clearSelection()
}
/**
* Clear selection.
*
* @author RayBa
* @date 07.04.2013
*/
private fun clearSelection() {
for (i in 0 until listAdapter!!.count) {
listView!!.setItemChecked(i, false)
}
}
/* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
val checkedPositions = listView!!.checkedItemPositions
if (checkedPositions != null && checkedPositions.size() > 0) {
setListShown(false)
val size = checkedPositions.size()
val timers = ArrayList<Timer>()
for (i in 0 until size) {
if (checkedPositions.valueAt(i)) {
timers.add(mAdapter.getItem(checkedPositions.keyAt(i)))
}
}
repository.deleteTimer(timers).enqueue(object : retrofit2.Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
refresh()
sendMessage(R.string.timer_deleted)
logEvent(EVENT_TIMER_DELETED)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
setListShown(true)
sendMessage(R.string.error_common)
}
})
}
mode?.finish()
}
DialogInterface.BUTTON_NEGATIVE -> {
}
}// No button clicked
}
override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
listView!!.setItemChecked(position, true)
val count = checkedItemCount
if (!actionMode) {
actionMode = true
val activty = activity as AppCompatActivity?
mode = activty?.startSupportActionMode(this@TimerList)
}
updateActionModeTitle(count)
return true
}
private fun updateActionModeTitle(count: Int) {
mode?.title = count.toString() + " " + resources.getString(R.string.selected)
}
/**
* Refresh.
*
* @author RayBa
* @date 07.04.2013
*/
private fun refresh() {
viewModel.getTimerList(true)
setListShown(false)
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockFragment#onOptionsItemSelected(android.view.MenuItem)
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuRefresh -> {
refresh()
true
}
else -> false
}
}
companion object {
const val TAG = "TimerList"
const val ACTION_MODE = "action_mode"
const val CHECKED_ITEM_COUNT = "checked_item_count"
}
}
|
apache-2.0
|
c935a5ef262b86a8c64489c6bc8f84dd
| 36.275862 | 203 | 0.627197 | 4.733813 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/request/ApplicationRequestProperties.kt
|
1
|
4753
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package io.ktor.server.request
import io.ktor.http.*
import io.ktor.server.plugins.*
import io.ktor.utils.io.charsets.*
/**
* Gets the first value of a [name] header or returns `null` if missing.
*/
public fun ApplicationRequest.header(name: String): String? = headers[name]
/**
* Gets a request's query string or returns an empty string if missing.
*/
public fun ApplicationRequest.queryString(): String = origin.uri.substringAfter('?', "")
/**
* Gets a request's content type or returns `ContentType.Any`.
*/
public fun ApplicationRequest.contentType(): ContentType =
header(HttpHeaders.ContentType)?.let { ContentType.parse(it) } ?: ContentType.Any
/**
* Gets a request's `Content-Length` header value.
*/
public fun ApplicationRequest.contentLength(): Long? =
header(HttpHeaders.ContentLength)?.toLongOrNull()
/**
* Gets a request's charset.
*/
public fun ApplicationRequest.contentCharset(): Charset? = contentType().charset()
/**
* A document name is a substring after the last slash but before a query string.
*/
public fun ApplicationRequest.document(): String = path().substringAfterLast('/')
/**
* Get a request's URL path without a query string.
*/
public fun ApplicationRequest.path(): String = origin.uri.substringBefore('?')
/**
* Get a request's `Authorization` header value.
*/
public fun ApplicationRequest.authorization(): String? = header(HttpHeaders.Authorization)
/**
* Get a request's `Location` header value.
*/
public fun ApplicationRequest.location(): String? = header(HttpHeaders.Location)
/**
* Get a request's `Accept` header value.
*/
public fun ApplicationRequest.accept(): String? = header(HttpHeaders.Accept)
/**
* Gets the `Accept` header content types sorted according to their qualities.
*/
public fun ApplicationRequest.acceptItems(): List<HeaderValue> =
parseAndSortContentTypeHeader(header(HttpHeaders.Accept))
/**
* Gets a request's `Accept-Encoding` header value.
*/
public fun ApplicationRequest.acceptEncoding(): String? = header(HttpHeaders.AcceptEncoding)
/**
* Gets the `Accept-Encoding` header encoding types sorted according to their qualities.
*/
public fun ApplicationRequest.acceptEncodingItems(): List<HeaderValue> =
parseAndSortHeader(header(HttpHeaders.AcceptEncoding))
/**
* Gets a request's `Accept-Language` header value.
*/
public fun ApplicationRequest.acceptLanguage(): String? = header(HttpHeaders.AcceptLanguage)
/**
* Gets the `Accept-Language` header languages sorted according to their qualities.
*/
public fun ApplicationRequest.acceptLanguageItems(): List<HeaderValue> =
parseAndSortHeader(header(HttpHeaders.AcceptLanguage))
/**
* Gets a request's `Accept-Charset` header value.
*/
public fun ApplicationRequest.acceptCharset(): String? = header(HttpHeaders.AcceptCharset)
/**
* Gets the `Accept-Charset` header charsets sorted according to their qualities.
*/
public fun ApplicationRequest.acceptCharsetItems(): List<HeaderValue> =
parseAndSortHeader(header(HttpHeaders.AcceptCharset))
/**
* Checks whether a request's body is chunk-encoded.
*/
public fun ApplicationRequest.isChunked(): Boolean =
header(HttpHeaders.TransferEncoding)?.compareTo("chunked", ignoreCase = true) == 0
/**
* Checks whether a request body is multipart-encoded.
*/
public fun ApplicationRequest.isMultipart(): Boolean = contentType().match(ContentType.MultiPart.Any)
/**
* Gets a request's `User-Agent` header value.
*/
public fun ApplicationRequest.userAgent(): String? = header(HttpHeaders.UserAgent)
/**
* Gets a request's `Cache-Control` header value.
*/
public fun ApplicationRequest.cacheControl(): String? = header(HttpHeaders.CacheControl)
/**
* Gets a request's host value without a port.
* @see [port]
*/
public fun ApplicationRequest.host(): String = origin.serverHost
/**
* Gets a request's port extracted from the `Host` header value.
* @see [host]
*/
public fun ApplicationRequest.port(): Int = origin.serverPort
/**
* Gets ranges parsed from a request's `Range` header value.
*/
public fun ApplicationRequest.ranges(): RangesSpecifier? =
header(HttpHeaders.Range)?.let { rangesSpec -> parseRangesSpecifier(rangesSpec) }
/**
* Gets a request's URI, including a query string.
*/
public val ApplicationRequest.uri: String get() = origin.uri
/**
* Gets a request HTTP method possibly overridden using the `X-Http-Method-Override` header.
*/
public val ApplicationRequest.httpMethod: HttpMethod get() = origin.method
/**
* Gets a request's HTTP version.
*/
public val ApplicationRequest.httpVersion: String get() = origin.version
|
apache-2.0
|
ba848ebd793e085e30c5cd1458dcfae7
| 29.467949 | 118 | 0.740795 | 4.108038 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaTitlePutResolver.kt
|
2
|
1240
|
package eu.kanade.tachiyomi.data.database.resolvers
import androidx.core.content.contentValuesOf
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 MangaTitlePutResolver : 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) =
contentValuesOf(
MangaTable.COL_TITLE to manga.title
)
}
|
apache-2.0
|
126b04dad4c8d97dfa0fdd2e562b6bed
| 37.75 | 86 | 0.754032 | 4.350877 | false | false | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/static/misc.kt
|
2
|
21591
|
package imgui.static
import gli_.has
import glm_.glm
import glm_.max
import glm_.min
import glm_.vec2.Vec2
import imgui.*
import imgui.ImGui.buttonBehavior
import imgui.ImGui.clearActiveID
import imgui.ImGui.getNavInputAmount2d
import imgui.ImGui.getStyleColorVec4
import imgui.ImGui.io
import imgui.ImGui.isMouseClicked
import imgui.ImGui.isMousePosValid
import imgui.ImGui.loadIniSettingsFromDisk
import imgui.ImGui.mouseCursor
import imgui.ImGui.parseFormatFindEnd
import imgui.ImGui.parseFormatFindStart
import imgui.ImGui.popID
import imgui.ImGui.pushID
import imgui.ImGui.saveIniSettingsToDisk
import imgui.ImGui.setNextWindowBgAlpha
import imgui.ImGui.style
import imgui.ImGui.text
import imgui.ImGui.textColored
import imgui.api.g
import imgui.dsl.tooltip
import imgui.internal.*
import imgui.internal.classes.Rect
import imgui.internal.classes.Window
import imgui.internal.classes.Window.Companion.resizeGripDef
import imgui.internal.sections.*
import kotlin.math.max
import kotlin.math.min
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
/** Called by NewFrame() */
fun updateSettings() {
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.settingsLoaded) {
assert(g.settingsWindows.isEmpty())
io.iniFilename?.let(::loadIniSettingsFromDisk)
g.settingsLoaded = true
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.settingsDirtyTimer > 0f) {
g.settingsDirtyTimer -= io.deltaTime
if (g.settingsDirtyTimer <= 0f) {
io.iniFilename.let {
if (it != null)
saveIniSettingsToDisk(it)
else
io.wantSaveIniSettings = true // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
}
g.settingsDirtyTimer = 0f
}
}
}
fun updateMouseInputs() {
with(io) {
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (isMousePosValid(mousePos)) {
g.lastValidMousePos = floor(mousePos)
mousePos = Vec2(g.lastValidMousePos)
}
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX component) we cancel out movement in MouseDelta
if (isMousePosValid(mousePos) && isMousePosValid(mousePosPrev))
mouseDelta = mousePos - mousePosPrev
else
mouseDelta put 0f
if (mouseDelta.x != 0f || mouseDelta.y != 0f)
g.navDisableMouseHover = false
mousePosPrev put mousePos
for (i in mouseDown.indices) {
mouseClicked[i] = mouseDown[i] && mouseDownDuration[i] < 0f
mouseReleased[i] = !mouseDown[i] && mouseDownDuration[i] >= 0f
mouseDownDurationPrev[i] = mouseDownDuration[i]
mouseDownDuration[i] = when {
mouseDown[i] -> when {
mouseDownDuration[i] < 0f -> 0f
else -> mouseDownDuration[i] + deltaTime
}
else -> -1f
}
mouseDoubleClicked[i] = false
if (mouseClicked[i]) {
if (g.time - mouseClickedTime[i] < mouseDoubleClickTime) {
val deltaFromClickPos = when {
isMousePosValid(io.mousePos) -> io.mousePos - io.mouseClickedPos[i]
else -> Vec2()
}
if (deltaFromClickPos.lengthSqr < io.mouseDoubleClickMaxDist * io.mouseDoubleClickMaxDist)
mouseDoubleClicked[i] = true
mouseClickedTime[i] = -io.mouseDoubleClickTime * 2.0 // Mark as "old enough" so the third click isn't turned into a double-click
} else
mouseClickedTime[i] = g.time
mouseClickedPos[i] put mousePos
mouseDownWasDoubleClick[i] = mouseDoubleClicked[i]
mouseDragMaxDistanceAbs[i] put 0f
mouseDragMaxDistanceSqr[i] = 0f
} else if (mouseDown[i]) {
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
val deltaFromClickPos = when {
isMousePosValid(io.mousePos) -> io.mousePos - io.mouseClickedPos[i]
else -> Vec2()
}
io.mouseDragMaxDistanceSqr[i] = io.mouseDragMaxDistanceSqr[i] max deltaFromClickPos.lengthSqr
io.mouseDragMaxDistanceAbs[i].x = io.mouseDragMaxDistanceAbs[i].x max when {
deltaFromClickPos.x < 0f -> -deltaFromClickPos.x
else -> deltaFromClickPos.x
}
io.mouseDragMaxDistanceAbs[i].y = io.mouseDragMaxDistanceAbs[i].y max when {
deltaFromClickPos.y < 0f -> -deltaFromClickPos.y
else -> deltaFromClickPos.y
}
val mouseDelta = mousePos - mouseClickedPos[i]
mouseDragMaxDistanceAbs[i].x = mouseDragMaxDistanceAbs[i].x max if (mouseDelta.x < 0f) -mouseDelta.x else mouseDelta.x
mouseDragMaxDistanceAbs[i].y = mouseDragMaxDistanceAbs[i].y max if (mouseDelta.y < 0f) -mouseDelta.y else mouseDelta.y
mouseDragMaxDistanceSqr[i] = mouseDragMaxDistanceSqr[i] max mouseDelta.lengthSqr
}
if (!mouseDown[i] && !mouseReleased[i])
mouseDownWasDoubleClick[i] = false
// Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
if (mouseClicked[i])
g.navDisableMouseHover = false
}
}
}
fun updateMouseWheel() {
// Reset the locked window if we move the mouse or after the timer elapses
if (g.wheelingWindow != null) {
g.wheelingWindowTimer -= io.deltaTime
if (isMousePosValid() && (io.mousePos - g.wheelingWindowRefMousePos).lengthSqr > io.mouseDragThreshold * io.mouseDragThreshold)
g.wheelingWindowTimer = 0f
if (g.wheelingWindowTimer <= 0f) {
g.wheelingWindow = null
g.wheelingWindowTimer = 0f
}
}
if (io.mouseWheel == 0f && io.mouseWheelH == 0f)
return
if ((g.activeId != 0 && g.activeIdUsingMouseWheel) || (g.hoveredIdPreviousFrame != 0 && g.hoveredIdPreviousFrameUsingMouseWheel))
return;
var window = g.wheelingWindow ?: g.hoveredWindow
if (window == null || window.collapsed)
return
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (io.mouseWheel != 0f && io.keyCtrl && io.fontAllowUserScaling) {
window.startLockWheeling()
val newFontScale = glm.clamp(window.fontWindowScale + io.mouseWheel * 0.1f, 0.5f, 2.5f)
val scale = newFontScale / window.fontWindowScale
window.fontWindowScale = newFontScale
if (window.flags hasnt WindowFlag._ChildWindow) {
val offset = window.size * (1f - scale) * (io.mousePos - window.pos) / window.size
window.setPos(window.pos + offset)
window.size = floor(window.size * scale)
window.sizeFull = floor(window.sizeFull * scale)
}
return
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
// Vertical Mouse Wheel scrolling
val wheelY = if (io.mouseWheel != 0f && !io.keyShift) io.mouseWheel else 0f
if (wheelY != 0f && !io.keyCtrl) {
window.startLockWheeling()
tailrec fun Window.getParent(): Window = when {
flags has WindowFlag._ChildWindow && (scrollMax.y == 0f || (flags has WindowFlag.NoScrollWithMouse && flags hasnt WindowFlag.NoMouseInputs)) -> parentWindow!!.getParent()
else -> this
}
window = g.hoveredWindow!!.getParent()
if (window.flags hasnt WindowFlag.NoScrollWithMouse && window.flags hasnt WindowFlag.NoMouseInputs) {
val maxStep = window.innerRect.height * 0.67f
val scrollStep = floor((5 * window.calcFontSize()) min maxStep)
window.setScrollY(window.scroll.y - wheelY * scrollStep)
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
val wheelX = when {
io.mouseWheelH != 0f && !io.keyShift -> io.mouseWheelH
io.mouseWheel != 0f && io.keyShift -> io.mouseWheel
else -> 0f
}
if (wheelX != 0f && !io.keyCtrl) {
window.startLockWheeling()
tailrec fun Window.getParent(): Window = when {
flags has WindowFlag._ChildWindow && (scrollMax.x == 0f || (flags has WindowFlag.NoScrollWithMouse && flags hasnt WindowFlag.NoMouseInputs)) -> parentWindow!!.getParent()
else -> this
}
window = g.hoveredWindow!!.getParent()
if (window.flags hasnt WindowFlag.NoScrollWithMouse && window.flags hasnt WindowFlag.NoMouseInputs) {
val maxStep = window.innerRect.width * 0.67f
val scrollStep = floor((2 * window.calcFontSize()) min maxStep)
window.setScrollX(window.scroll.x - wheelX * scrollStep)
}
}
}
/** Handle resize for: Resize Grips, Borders, Gamepad
* @return [JVM] borderHelf to Boolean */
fun updateWindowManualResize(
window: Window, sizeAutoFit: Vec2, borderHeld_: Int, resizeGripCount: Int,
resizeGripCol: IntArray, visibilityRect: Rect,
): Pair<Int, Boolean> {
var borderHeld = borderHeld_
val flags = window.flags
if (flags has WindowFlag.NoResize || flags has WindowFlag.AlwaysAutoResize || window.autoFitFrames anyGreaterThan 0)
return borderHeld to false
if (!window.wasActive) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return borderHeld to false
var retAutoFit = false
val resizeBorderCount = if (io.configWindowsResizeFromEdges) 4 else 0
val gripDrawSize = floor(max(g.fontSize * 1.35f, window.windowRounding + 1f + g.fontSize * 0.2f))
val gripHoverInnerSize = floor(gripDrawSize * 0.75f)
val gripHoverOuterSize = if (io.configWindowsResizeFromEdges) WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS else 0f
val posTarget = Vec2(Float.MAX_VALUE)
val sizeTarget = Vec2(Float.MAX_VALUE)
// Resize grips and borders are on layer 1
window.dc.navLayerCurrent = NavLayer.Menu
// Manual resize grips
pushID("#RESIZE")
for (resizeGripN in 0 until resizeGripCount) {
val grip = resizeGripDef[resizeGripN]
val corner = window.pos.lerp(window.pos + window.size, grip.cornerPosN)
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
val resizeRect = Rect(corner - grip.innerDir * gripHoverOuterSize, corner + grip.innerDir * gripHoverInnerSize)
if (resizeRect.min.x > resizeRect.max.x) swap(resizeRect.min::x, resizeRect.max::x)
if (resizeRect.min.y > resizeRect.max.y) swap(resizeRect.min::y, resizeRect.max::y)
val f = ButtonFlag.FlattenChildren or ButtonFlag.NoNavFocus
val (_, hovered, held) = buttonBehavior(resizeRect, window.getID(resizeGripN), f)
//GetOverlayDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.mouseCursor = if (resizeGripN has 1) MouseCursor.ResizeNESW else MouseCursor.ResizeNWSE
if (held && g.io.mouseDoubleClicked[0] && resizeGripN == 0) {
// Manual auto-fit when double-clicking
sizeTarget put window.calcSizeAfterConstraint(sizeAutoFit)
retAutoFit = true
clearActiveID()
} else if (held) {
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
// Corner of the window corresponding to our corner grip
var cornerTarget = g.io.mousePos - g.activeIdClickOffset + (grip.innerDir * gripHoverOuterSize).lerp(grip.innerDir * -gripHoverInnerSize, grip.cornerPosN)
val clampMin = Vec2 { if (grip.cornerPosN[it] == 1f) visibilityRect.min[it] else -Float.MAX_VALUE }
val clampMax = Vec2 { if (grip.cornerPosN[it] == 0f) visibilityRect.max[it] else Float.MAX_VALUE }
cornerTarget = glm.clamp(cornerTarget, clampMin, clampMax)
window.calcResizePosSizeFromAnyCorner(cornerTarget, grip.cornerPosN, posTarget, sizeTarget)
}
if (resizeGripN == 0 || held || hovered)
resizeGripCol[resizeGripN] = (if (held) Col.ResizeGripActive else if (hovered) Col.ResizeGripHovered else Col.ResizeGrip).u32
}
for (borderN in 0 until resizeBorderCount) {
val borderRect = window.getResizeBorderRect(borderN, gripHoverInnerSize, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)
val (_, hovered, held) = buttonBehavior(borderRect, window.getID((borderN + 4)), ButtonFlag.FlattenChildren)
//GetOverlayDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.hoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) {
g.mouseCursor = if (borderN has 1) MouseCursor.ResizeEW else MouseCursor.ResizeNS
if (held)
borderHeld = borderN
}
if (held) {
var borderTarget = Vec2(window.pos)
val borderPosN = when (borderN) {
0 -> {
borderTarget.y = g.io.mousePos.y - g.activeIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS
Vec2(0, 0)
}
1 -> {
borderTarget.x = g.io.mousePos.x - g.activeIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS
Vec2(1, 0)
}
2 -> {
borderTarget.y = g.io.mousePos.y - g.activeIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS
Vec2(0, 1)
}
3 -> {
borderTarget.x = g.io.mousePos.x - g.activeIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS
Vec2(0, 0)
}
else -> Vec2(0, 0)
}
val clampMin = Vec2 { if (borderN == it + 1) visibilityRect.min[it] else -Float.MAX_VALUE }
val clampMax = Vec2 { if (borderN == (if (it == 0) 3 else 0)) visibilityRect.max[it] else Float.MAX_VALUE }
borderTarget = glm.clamp(borderTarget, clampMin, clampMax)
window.calcResizePosSizeFromAnyCorner(borderTarget, borderPosN, posTarget, sizeTarget)
}
}
popID()
// Restore nav layer
window.dc.navLayerCurrent = NavLayer.Main
// Navigation resize (keyboard/gamepad)
if (g.navWindowingTarget?.rootWindow === window) {
val navResizeDelta = Vec2()
if (g.navInputSource == InputSource.NavKeyboard && g.io.keyShift)
navResizeDelta put getNavInputAmount2d(NavDirSourceFlag.Keyboard.i, InputReadMode.Down)
if (g.navInputSource == InputSource.NavGamepad)
navResizeDelta put getNavInputAmount2d(NavDirSourceFlag.PadDPad.i, InputReadMode.Down)
if (navResizeDelta.x != 0f || navResizeDelta.y != 0f) {
val NAV_RESIZE_SPEED = 600f
navResizeDelta *= floor(NAV_RESIZE_SPEED * g.io.deltaTime * min(g.io.displayFramebufferScale.x, g.io.displayFramebufferScale.y))
navResizeDelta put glm.max(navResizeDelta, visibilityRect.min - window.pos - window.size)
g.navWindowingToggleLayer = false
g.navDisableMouseHover = true
resizeGripCol[0] = Col.ResizeGripActive.u32
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
sizeTarget put window.calcSizeAfterConstraint(window.sizeFull + navResizeDelta)
}
}
// Apply back modified position/size to window
if (sizeTarget.x != Float.MAX_VALUE) {
window.sizeFull put sizeTarget
window.markIniSettingsDirty()
}
if (posTarget.x != Float.MAX_VALUE) {
window.pos = floor(posTarget)
window.markIniSettingsDirty()
}
window.size put window.sizeFull
return borderHeld to retAutoFit
}
fun updateTabFocus() {
// Pressing TAB activate widget focus
g.focusTabPressed = g.navWindow?.let { it.active && it.flags hasnt WindowFlag.NoNavInputs && !io.keyCtrl && Key.Tab.isPressed }
?: false
if (g.activeId == 0 && g.focusTabPressed) {
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.focusRequestNextWindow = g.navWindow
g.focusRequestNextCounterRegular = Int.MAX_VALUE
g.focusRequestNextCounterTabStop = when {
g.navId != 0 && g.navIdTabCounter != Int.MAX_VALUE -> g.navIdTabCounter + 1 + if (io.keyShift) -1 else 1
else -> if (io.keyShift) -1 else 0
}
}
// Turn queued focus request into current one
g.focusRequestCurrWindow = null
g.focusRequestCurrCounterRegular = Int.MAX_VALUE
g.focusRequestCurrCounterTabStop = Int.MAX_VALUE
g.focusRequestNextWindow?.let { window ->
g.focusRequestCurrWindow = window
if (g.focusRequestNextCounterRegular != Int.MAX_VALUE && window.dc.focusCounterRegular != -1)
g.focusRequestCurrCounterRegular = modPositive(g.focusRequestNextCounterRegular, window.dc.focusCounterRegular + 1)
if (g.focusRequestNextCounterTabStop != Int.MAX_VALUE && window.dc.focusCounterTabStop != -1)
g.focusRequestCurrCounterTabStop = modPositive(g.focusRequestNextCounterTabStop, window.dc.focusCounterTabStop + 1)
g.focusRequestNextWindow = null
g.focusRequestNextCounterRegular = Int.MAX_VALUE
g.focusRequestNextCounterTabStop = Int.MAX_VALUE
}
g.navIdTabCounter = Int.MAX_VALUE
}
/** [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. */
fun updateDebugToolItemPicker() {
g.debugItemPickerBreakId = 0
if (g.debugItemPickerActive) {
val hoveredId = g.hoveredIdPreviousFrame
mouseCursor = MouseCursor.Hand
if (Key.Escape.isPressed)
g.debugItemPickerActive = false
if (isMouseClicked(MouseButton.Left) && hoveredId != 0) {
g.debugItemPickerBreakId = hoveredId
g.debugItemPickerActive = false
}
setNextWindowBgAlpha(0.6f)
tooltip {
text("HoveredId: 0x%08X", hoveredId)
text("Press ESC to abort picking.")
textColored(getStyleColorVec4(if (hoveredId != 0) Col.Text else Col.TextDisabled), "Click to break in debugger!")
}
}
}
// truly miscellaneous
// FIXME-OPT O(N)
fun findWindowNavFocusable(iStart: Int, iStop: Int, dir: Int): Window? {
var i = iStart
while (i in g.windowsFocusOrder.indices && i != iStop) {
if (g.windowsFocusOrder[i].isNavFocusable)
return g.windowsFocusOrder[i]
i += dir
}
return null
}
fun navUpdateWindowingHighlightWindow(focusChangeDir: Int) {
val target = g.navWindowingTarget!!
if (target.flags has WindowFlag._Modal) return
val iCurrent = findWindowFocusIndex(target)
val windowTarget = findWindowNavFocusable(iCurrent + focusChangeDir, -Int.MAX_VALUE, focusChangeDir)
?: findWindowNavFocusable(if (focusChangeDir < 0) g.windowsFocusOrder.lastIndex else 0, iCurrent, focusChangeDir)
// Don't reset windowing target if there's a single window in the list
windowTarget?.let {
g.navWindowingTarget = it
g.navWindowingTargetAnim = it
}
g.navWindowingToggleLayer = false
}
/** FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value
* for format was "%.0f".
* Even though we changed the compile-time default, we expect users to have carried %f around, which would break
* the display of DragInt() calls.
* To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled.
* What could possibly go wrong?! */
fun patchFormatStringFloatToInt(fmt: String): String {
if (fmt == "%.0f") // Fast legacy path for "%.0f" which is expected to be the most common case.
return "%d"
val fmtStart = parseFormatFindStart(fmt) // Find % (if any, and ignore %%)
// Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user).
val fmtEnd = parseFormatFindEnd(fmt, fmtStart)
if (fmtEnd > fmtStart && fmt[fmtEnd - 1] == 'f') {
if (fmtStart == 0 && fmtEnd == fmt.length)
return "%d"
return fmt.substring(0, fmtStart) + "%d" + fmt.substring(fmtEnd, fmt.length)
}
return fmt
}
|
mit
|
6d9d52e0f1e4abc7a1d497e6cc1ba181
| 45.735931 | 182 | 0.644667 | 3.991681 | false | false | false | false |
cascheberg/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsRepository.kt
|
1
|
7691
|
package org.thoughtcrime.securesms.components.settings.conversation
import android.content.Context
import android.database.Cursor
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.logging.Log
import org.signal.storageservice.protos.groups.local.DecryptedGroup
import org.signal.storageservice.protos.groups.local.DecryptedPendingMember
import org.thoughtcrime.securesms.contacts.sync.DirectoryHelper
import org.thoughtcrime.securesms.database.DatabaseFactory
import org.thoughtcrime.securesms.database.GroupDatabase
import org.thoughtcrime.securesms.database.IdentityDatabase
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.groups.GroupManager
import org.thoughtcrime.securesms.groups.GroupProtoUtil
import org.thoughtcrime.securesms.groups.LiveGroup
import org.thoughtcrime.securesms.groups.ui.GroupChangeFailureReason
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.recipients.RecipientUtil
import org.thoughtcrime.securesms.util.FeatureFlags
import org.whispersystems.libsignal.util.guava.Optional
import java.io.IOException
private val TAG = Log.tag(ConversationSettingsRepository::class.java)
class ConversationSettingsRepository(
private val context: Context
) {
@WorkerThread
fun getThreadMedia(threadId: Long): Optional<Cursor> {
return if (threadId <= 0) {
Optional.absent()
} else {
Optional.of(DatabaseFactory.getMediaDatabase(context).getGalleryMediaForThread(threadId, MediaDatabase.Sorting.Newest))
}
}
fun getThreadId(recipientId: RecipientId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(DatabaseFactory.getThreadDatabase(context).getThreadIdIfExistsFor(recipientId))
}
}
fun getThreadId(groupId: GroupId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(context, groupId).id
consumer(DatabaseFactory.getThreadDatabase(context).getThreadIdIfExistsFor(recipientId))
}
}
fun isInternalRecipientDetailsEnabled(): Boolean = SignalStore.internalValues().recipientDetails()
fun hasGroups(consumer: (Boolean) -> Unit) {
SignalExecutors.BOUNDED.execute { consumer(DatabaseFactory.getGroupDatabase(context).activeGroupCount > 0) }
}
fun getIdentity(recipientId: RecipientId, consumer: (IdentityDatabase.IdentityRecord?) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(
DatabaseFactory.getIdentityDatabase(context)
.getIdentity(recipientId)
.orNull()
)
}
}
fun getGroupsInCommon(recipientId: RecipientId, consumer: (List<Recipient>) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(
DatabaseFactory
.getGroupDatabase(context)
.getPushGroupsContainingMember(recipientId)
.asSequence()
.filter { it.members.contains(Recipient.self().id) }
.map(GroupDatabase.GroupRecord::getRecipientId)
.map(Recipient::resolved)
.sortedBy { gr -> gr.getDisplayName(context) }
.toList()
)
}
}
fun getGroupMembership(recipientId: RecipientId, consumer: (List<RecipientId>) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupDatabase = DatabaseFactory.getGroupDatabase(context)
val groupRecords = groupDatabase.getPushGroupsContainingMember(recipientId)
val groupRecipients = ArrayList<RecipientId>(groupRecords.size)
for (groupRecord in groupRecords) {
groupRecipients.add(groupRecord.recipientId)
}
consumer(groupRecipients)
}
}
fun refreshRecipient(recipientId: RecipientId) {
SignalExecutors.UNBOUNDED.execute {
try {
DirectoryHelper.refreshDirectoryFor(context, Recipient.resolved(recipientId), false)
} catch (e: IOException) {
Log.w(TAG, "Failed to refresh user after adding to contacts.")
}
}
}
fun setMuteUntil(recipientId: RecipientId, until: Long) {
SignalExecutors.BOUNDED.execute {
DatabaseFactory.getRecipientDatabase(context).setMuted(recipientId, until)
}
}
fun getGroupCapacity(groupId: GroupId, consumer: (GroupCapacityResult) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupRecord: GroupDatabase.GroupRecord = DatabaseFactory.getGroupDatabase(context).getGroup(groupId).get()
consumer(
if (groupRecord.isV2Group) {
val decryptedGroup: DecryptedGroup = groupRecord.requireV2GroupProperties().decryptedGroup
val pendingMembers: List<RecipientId> = decryptedGroup.pendingMembersList
.map(DecryptedPendingMember::getUuid)
.map(GroupProtoUtil::uuidByteStringToRecipientId)
val members = mutableListOf<RecipientId>()
members.addAll(groupRecord.members)
members.addAll(pendingMembers)
GroupCapacityResult(Recipient.self().id, members, FeatureFlags.groupLimits())
} else {
GroupCapacityResult(Recipient.self().id, groupRecord.members, FeatureFlags.groupLimits())
}
)
}
}
fun addMembers(groupId: GroupId, selected: List<RecipientId>, consumer: (GroupAddMembersResult) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(
try {
val groupActionResult = GroupManager.addMembers(context, groupId.requirePush(), selected)
GroupAddMembersResult.Success(groupActionResult.addedMemberCount, Recipient.resolvedList(groupActionResult.invitedMembers))
} catch (e: Exception) {
GroupAddMembersResult.Failure(GroupChangeFailureReason.fromException(e))
}
)
}
}
fun setMuteUntil(groupId: GroupId, until: Long) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(context, groupId).id
DatabaseFactory.getRecipientDatabase(context).setMuted(recipientId, until)
}
}
fun block(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
RecipientUtil.blockNonGroup(context, recipient)
}
}
fun unblock(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
RecipientUtil.unblock(context, recipient)
}
}
fun block(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(context, groupId)
RecipientUtil.block(context, recipient)
}
}
fun unblock(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(context, groupId)
RecipientUtil.unblock(context, recipient)
}
}
fun disableProfileSharing(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
DatabaseFactory.getRecipientDatabase(context).setProfileSharing(recipientId, false)
}
}
@WorkerThread
fun isMessageRequestAccepted(recipient: Recipient): Boolean {
return RecipientUtil.isMessageRequestAccepted(context, recipient)
}
fun getMembershipCountDescription(liveGroup: LiveGroup): LiveData<String> {
return liveGroup.getMembershipCountDescription(context.resources)
}
fun getExternalPossiblyMigratedGroupRecipientId(groupId: GroupId, consumer: (RecipientId) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(Recipient.externalPossiblyMigratedGroup(context, groupId).id)
}
}
}
|
gpl-3.0
|
7f954f28a018d1cb4a69d684ae9bc2b1
| 35.975962 | 133 | 0.745417 | 4.7011 | false | false | false | false |
CarGuo/GSYGithubAppFlutter
|
android/app/src/main/kotlin/com/shuyu/gsygithub/gsygithubappflutter/UpdateAlbumPlugin.kt
|
1
|
2096
|
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry.Registrar
class UpdateAlbumPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
/** Channel名称 **/
private var channel: MethodChannel? = null
private var context: Context? = null
companion object {
private val sChannelName = "com.shuyu.gsygithub.gsygithubflutter/UpdateAlbumPlugin"
fun registerWith(registrar: Registrar) {
val instance = UpdateAlbumPlugin()
instance.channel = MethodChannel(registrar.messenger(), sChannelName)
instance.context = registrar.context()
instance.channel?.setMethodCallHandler(instance)
}
}
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(
binding.flutterEngine.dartExecutor, sChannelName)
context = binding.applicationContext
channel!!.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel?.setMethodCallHandler(null)
channel = null
}
override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
when (methodCall.method) {
"updateAlbum" -> {
val path: String? = methodCall.argument("path")
val name: String? = methodCall.argument("name")
try {
MediaStore.Images.Media.insertImage(context?.contentResolver, path, name, null)
} catch (e: Exception) {
e.printStackTrace()
}
// 最后通知图库更新
context?.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://$path")))
}
}
result.success(null)
}
}
|
apache-2.0
|
867974c5b8fc62205f7dae251f098a5d
| 35.438596 | 112 | 0.661368 | 4.907801 | false | false | false | false |
dahlstrom-g/intellij-community
|
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/ClipboardUtils.kt
|
7
|
4930
|
/*
* Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.plugins.notebooks.visualization.r.inlays
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.plugins.notebooks.visualization.r.VisualizationBundle
import java.awt.Image
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.StringSelection
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import javax.swing.JTable
// TODO: Some problems with getting "event.isControlDown" on component placed on top of Idea Editor content.
/** Clipboard utils to realize Ctrl+C functionality in Table and Plots. */
object ClipboardUtils {
const val LINE_BREAK = "\r"
private const val CELL_BREAK = "\t"
private fun copyAllToString(table: JTable, cellBreak: String = CELL_BREAK, limit: Int = Int.MAX_VALUE): String {
if (table.rowCount == 0 || table.columnCount == 0) {
// The code should be compatible with 193 and 201 so, so we cannot use NotificationGroup.createIdWithTitle yet
Notifications.Bus.notify(Notification("Notebook Table",
VisualizationBundle.message("clipboard.utils.error"),
VisualizationBundle.message("clipboard.utils.no.columns.or.rows"),
NotificationType.ERROR))
return ""
}
val builder = StringBuilder()
for (i in 0 until table.rowCount) {
if (i >= limit) {
builder.append("\n").append(VisualizationBundle.message("clipboard.utils.copy.load.limit", limit))
break
}
for (j in 0 until table.columnCount) {
table.getValueAt(i, j)?.let { builder.append(escape(it, cellBreak)) }
if (j < table.columnCount - 1) {
builder.append(cellBreak)
}
}
if (i != table.rowCount - 1) {
builder.append(LINE_BREAK)
}
}
return builder.toString()
}
fun copyAllToClipboard(table: JTable, cellBreak: String = CELL_BREAK, limit: Int = Int.MAX_VALUE) {
val sel = StringSelection(copyAllToString(table, cellBreak, limit))
Toolkit.getDefaultToolkit().systemClipboard.setContents(sel, sel)
}
fun copySelectedToString(table: JTable, cellBreak: String = CELL_BREAK): String {
val selectedColumnCount = table.selectedColumnCount
val selectedRowCount = table.selectedRowCount
val selectedRows = table.selectedRows
val selectedColumns = table.selectedColumns
if (selectedColumnCount == 0 || selectedRowCount == 0) {
Notifications.Bus.notify(Notification("Notebook Table",
VisualizationBundle.message("clipboard.utils.error"),
VisualizationBundle.message("clipboard.utils.no.selection"),
NotificationType.ERROR))
return ""
}
val builder = StringBuilder()
for (i in 0 until selectedRowCount) {
for (j in 0 until selectedColumnCount) {
table.getValueAt(selectedRows[i], selectedColumns[j])?.let {
val cellString = if (selectedColumnCount > 1) escape(it, cellBreak) else it.toString()
builder.append(cellString)
}
if (j < selectedColumnCount - 1) {
builder.append(cellBreak)
}
}
if (i != selectedRowCount - 1) {
builder.append(LINE_BREAK)
}
}
return builder.toString()
}
fun copySelectedToClipboard(table: JTable, cellBreak: String = CELL_BREAK) {
val sel = StringSelection(copySelectedToString(table, cellBreak))
Toolkit.getDefaultToolkit().systemClipboard.setContents(sel, sel)
}
fun escape(cell: Any, cellBreak: String = CELL_BREAK): String {
val cellString = cell.toString()
return if (cellString.contains(LINE_BREAK) || cellString.contains(cellBreak)) {
"\"${StringUtil.escapeQuotes(cellString)}\""
}
else {
cellString
}
}
fun copyImageToClipboard(image: Image) {
val transferable = ImageTransferable(image)
Toolkit.getDefaultToolkit().systemClipboard.setContents(transferable, null)
}
private class ImageTransferable(private val image: Image) : Transferable {
override fun getTransferDataFlavors(): Array<DataFlavor> {
return arrayOf(DataFlavor.imageFlavor)
}
override fun isDataFlavorSupported(flavor: DataFlavor): Boolean {
return flavor == DataFlavor.imageFlavor
}
override fun getTransferData(flavor: DataFlavor): Any {
if (!isDataFlavorSupported(flavor)) {
throw UnsupportedFlavorException(flavor)
}
return image
}
}
}
|
apache-2.0
|
8994f51d2628891993514b4b964a9332
| 35.798507 | 140 | 0.6714 | 4.489982 | false | false | false | false |
chrhsmt/Sishen
|
app/src/main/java/com/chrhsmt/sisheng/ui/AutoResizeUtils.kt
|
1
|
3880
|
package com.chrhsmt.sisheng.ui
import android.content.Context
import android.graphics.Paint
import android.util.AttributeSet
import android.util.TypedValue
import android.widget.TextView
/**
* フォントサイズ自動調整TextView
*
* ソースコードは以下から借用
* http://aillicepray.blogspot.jp/2015/02/textview.html
*/
object AutoResizeUtils {
class AutoResizeInfo {
internal var modelText: String? = null
internal var numberLine = 1
}
/**
* テキストサイズ調整
*/
fun resize(view: TextView, info: AutoResizeInfo) {
/** 最小のテキストサイズ */
val MIN_TEXT_SIZE = 10f
val viewHeight = view.height // Viewの縦幅
val viewWidth = view.width // Viewの横幅
// テキストサイズ
var textSize = view.textSize
// Paintにテキストサイズ設定
val paint = Paint()
paint.textSize = textSize
// テキスト取得
if (info.modelText == null) {
info.modelText = view.text.toString()
}
// テキストの縦幅取得
var fm = paint.fontMetrics
var textHeight = Math.abs(fm.top) + Math.abs(fm.descent)
val lineNum = view.text!!.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size
// テキストの横幅取得
var textWidth = paint.measureText(info.modelText)
// 縦幅と、横幅が収まるまでループ
while ((viewHeight < (textHeight * lineNum)) or (viewWidth < textWidth)) {
// 調整しているテキストサイズが、定義している最小サイズ以下か。
if (MIN_TEXT_SIZE >= textSize) {
// 最小サイズ以下になる場合は最小サイズ
textSize = MIN_TEXT_SIZE
break
}
// テキストサイズをデクリメント
textSize--
// Paintにテキストサイズ設定
paint.textSize = textSize
// テキストの縦幅を再取得
// 改行を考慮する
fm = paint.fontMetrics
textHeight = Math.abs(fm.top) + Math.abs(fm.descent) * info.numberLine
// テキストの横幅を再取得
textWidth = paint.measureText(info.modelText)
}
// テキストサイズ設定
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
}
/**
* 基準となる改行を含む文字列の最も文字列が大きい部分がViewの枠に収まるようにフォントサイズを調整する.(改行には適応してない模様)
* 文字列に改行を含まない場合、それをそのまま基準にする.
* 表示される文字列の最大数がわかっている時に有効利用できる.
* @param modelText
*/
fun setModelText(modelText: String?, info: AutoResizeInfo) {
if (modelText != null) {
val str = modelText.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
info.numberLine = str.size
var includeLinefeed = false
if (str.size > 1) includeLinefeed = true
if (includeLinefeed) {
var a: String? = null // 一時変数
var model: String? = null
for (i in str.indices) {
if (a == null)
a = str[i]
else {
// 2周目以降
if (a.length >= str[i].length)
model = a
else
model = str[i]
}
}
info.modelText = model
} else {
info.modelText = modelText
}
}
}
}
|
mit
|
4a58cc913c4f41944a9c0e4579d12327
| 27.651786 | 106 | 0.527431 | 3.445757 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/GitLabServerPath.kt
|
5
|
1190
|
// 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.plugins.gitlab.api
import com.intellij.collaboration.api.ServerPath
import com.intellij.openapi.util.NlsSafe
import kotlinx.serialization.Serializable
import java.net.URI
/**
* @property uri should be a normalized server uri like "https://server.com/path"
*/
@Serializable
class GitLabServerPath : ServerPath {
var uri: String = ""
private set
constructor()
constructor(uri: String) {
require(uri.isNotEmpty())
val validation = URI.create(uri)
require(validation.scheme != null)
require(validation.scheme.startsWith("http"))
this.uri = uri
}
val gqlApiUri: URI
get() = URI.create(uri).resolve("/api/graphql")
@NlsSafe
override fun toString() = uri
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GitLabServerPath) return false
if (uri != other.uri) return false
return true
}
override fun hashCode(): Int {
return uri.hashCode()
}
companion object {
val DEFAULT_SERVER = GitLabServerPath("https://gitlab.com")
}
}
|
apache-2.0
|
749e7818664119786f23cf4bf762a4e1
| 22.82 | 120 | 0.701681 | 3.979933 | false | false | false | false |
dkandalov/katas
|
kotlin/src/katas/kotlin/adventofcode/day8/Part1.kt
|
1
|
453
|
package katas.kotlin.adventofcode.day8
import java.io.*
fun main() {
val digits = File("src/katas/kotlin/adventofcode/day8/input.txt").readText().map { it.toString().toInt() }
val width = 25
val height = 6
val layerSize = width * height
val layer = digits.chunked(layerSize)
.minByOrNull { layer: List<Int> -> layer.count { it == 0 } }!!
println(layer)
println(layer.count { it == 1 } * layer.count { it == 2 })
}
|
unlicense
|
9b69c64dca7f4a332b2e442d4a251029
| 27.375 | 110 | 0.626932 | 3.484615 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/features/rounds/EditRoundFragment.kt
|
1
|
6370
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.rounds
import android.content.Intent
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.base.fragments.EditFragmentBase
import de.dreier.mytargets.base.fragments.EditableListFragmentBase.Companion.ITEM_ID
import de.dreier.mytargets.databinding.FragmentEditRoundBinding
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.features.training.target.TargetListFragment
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.utils.ToolbarUtils
import de.dreier.mytargets.utils.Utils
import de.dreier.mytargets.views.selector.DistanceSelector
import de.dreier.mytargets.views.selector.TargetSelector
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar
class EditRoundFragment : EditFragmentBase() {
private var trainingId: Long = 0
private var roundId: Long? = null
private lateinit var binding: FragmentEditRoundBinding
private val trainingDAO = ApplicationInstance.db.trainingDAO()
private val roundDAO = ApplicationInstance.db.roundDAO()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_edit_round, container, false)
trainingId = arguments!!.getLong(ITEM_ID)
if (arguments!!.containsKey(ROUND_ID)) {
roundId = arguments!!.getLong(ROUND_ID)
}
ToolbarUtils.setSupportActionBar(this, binding.toolbar)
ToolbarUtils.showUpAsX(this)
setHasOptionsMenu(true)
binding.arrows.setOnProgressChangeListener(object :
DiscreteSeekBar.OnProgressChangeListener {
override fun onProgressChanged(
seekBar: DiscreteSeekBar,
value: Int,
fromUser: Boolean
) {
updateArrowsLabel()
}
override fun onStartTrackingTouch(seekBar: DiscreteSeekBar) {
}
override fun onStopTrackingTouch(seekBar: DiscreteSeekBar) {}
})
binding.target.setOnClickListener { selectedItem, index ->
val fixedType =
if (roundId == null) TargetListFragment.EFixedType.NONE else TargetListFragment.EFixedType.TARGET
navigationController.navigateToTarget(
selectedItem!!,
index,
TargetSelector.TARGET_REQUEST_CODE,
fixedType
)
}
binding.distance.setOnClickListener { selectedItem, index ->
navigationController.navigateToDistance(
selectedItem!!,
index,
DistanceSelector.DISTANCE_REQUEST_CODE
)
}
if (roundId == null) {
ToolbarUtils.setTitle(this, R.string.new_round)
loadRoundDefaultValues()
} else {
ToolbarUtils.setTitle(this, R.string.edit_round)
val round = roundDAO.loadRound(roundId!!)
binding.distance.setItem(round.distance)
binding.target.setItem(round.target)
binding.notEditable.visibility = View.GONE
if (trainingDAO.loadTraining(round.trainingId!!).standardRoundId != null) {
binding.distanceLayout.visibility = View.GONE
}
}
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Utils.setupFabTransform(activity!!, binding.root)
}
override fun onSave() {
navigationController.finish()
if (roundId == null) {
val round = onSaveRound()
navigationController.navigateToRound(round!!)
.noAnimation()
.start()
navigationController.navigateToCreateEnd(round)
} else {
onSaveRound()
activity!!.overridePendingTransition(R.anim.left_in, R.anim.right_out)
}
}
private fun onSaveRound(): Round? {
val training = trainingDAO.loadTraining(trainingId)
val round: Round
if (roundId == null) {
round = Round()
round.trainingId = trainingId
round.shotsPerEnd = binding.arrows.progress
round.maxEndCount = null
round.index = roundDAO.loadRounds(training.id).size
} else {
round = roundDAO.loadRound(roundId!!)
}
round.distance = binding.distance.selectedItem!!
round.target = binding.target.selectedItem!!
if (roundId == null) {
round.id = roundDAO.insertRound(round)
} else {
roundDAO.updateRound(round)
}
return round
}
private fun updateArrowsLabel() {
binding.arrowsLabel.text = resources
.getQuantityString(
R.plurals.arrow, binding.arrows.progress,
binding.arrows.progress
)
}
private fun loadRoundDefaultValues() {
binding.distance.setItem(SettingsManager.distance)
binding.arrows.progress = SettingsManager.shotsPerEnd
binding.target.setItem(SettingsManager.target)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
binding.target.onActivityResult(requestCode, resultCode, data)
binding.distance.onActivityResult(requestCode, resultCode, data)
}
companion object {
const val ROUND_ID = "round_id"
}
}
|
gpl-2.0
|
84961680816451b92d7ec8942c8a1b35
| 34.988701 | 113 | 0.65887 | 4.915123 | false | false | false | false |
Killian-LeClainche/Java-Base-Application-Engine
|
src/polaris/okapi/gui/GuiScreen.kt
|
1
|
4048
|
package polaris.okapi.gui
import polaris.okapi.App
import polaris.okapi.gui.content.GuiContent
import polaris.okapi.options.WindowMode
import polaris.okapi.util.inBounds
import org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE
import java.util.ArrayList
/**
* Created by Killian Le Clainche on 12/10/2017.
*/
abstract class GuiScreen : Gui {
private var elementList: MutableList<GuiContent> = ArrayList()
private var elementCounter = 0
var focusedElement: GuiContent? = null
protected set
val size: Int
get() = elementList.size
constructor(app: App) : super(app)
constructor(gui: GuiScreen) : super(gui.application, gui, 0.0)
override fun render(delta: Double) {
super.render(delta)
val mouseX = settings.mouse.x
val mouseY = settings.mouse.y
for (element in elementList) {
if (inBounds(mouseX, mouseY, element.bounds)) {
//flag = element.handleInput();
}
element.update(delta)
}
for (element in elementList) {
element.render(delta)
}
}
override fun close() {
this.focusedElement = null
}
fun mouseClick(mouseId: Int): Boolean {
for (element in elementList) {
if (inBounds(settings.mouse.x, settings.mouse.y, element.bounds)) {
val flag = element.nMouseClick(mouseId)
if (flag && element !== focusedElement) {
unbindCurrentElement(element)
}
return flag
}
}
unbindCurrentElement()
return false
}
fun unbindCurrentElement(e: GuiContent) {
unbindCurrentElement()
focusedElement = e
}
fun unbindCurrentElement() {
if (focusedElement != null) {
focusedElement!!.unbind()
focusedElement = null
}
}
fun mouseHeld(mouseId: Int) {
if (focusedElement != null && focusedElement!!.nMouseHeld(mouseId)) {
unbindCurrentElement()
}
}
fun mouseRelease(mouseId: Int) {
if (focusedElement != null && !focusedElement!!.nMouseRelease(mouseId)) {
unbindCurrentElement()
}
}
fun mouseScroll(xOffset: Double, yOffset: Double) {
if (focusedElement != null && focusedElement!!.nMouseScroll(xOffset, yOffset)) {
unbindCurrentElement()
}
}
fun keyPressed(keyId: Int, mods: Int): Int {
if (focusedElement != null) {
return focusedElement!!.nKeyPressed(keyId, mods)
}
if (keyId == GLFW_KEY_ESCAPE) {
if (mods and 1 == 1) {
settings.windowMode = WindowMode.WINDOWED
} else {
if (parent != null) {
parent.reinit()
application.currentScreen = parent
return 0
} else {
application.isRunning = false
}
}
}
return -1
}
fun keyHeld(keyId: Int, called: Int, mods: Int): Int {
return if (focusedElement != null) {
focusedElement!!.nKeyHeld(keyId, called, mods)
} else -1
}
fun keyRelease(keyId: Int, mods: Int) {
if (focusedElement != null && focusedElement!!.nKeyRelease(keyId, mods)) {
unbindCurrentElement()
}
}
fun addElement(e: GuiContent) {
e.init(this, elementCounter)
elementCounter++
elementList.add(e)
}
fun removeElement(i: Int) {
elementList.removeAt(i).close()
}
fun removeElements(i: Int, i1: Int) {
for (j in i1 - 1 downTo i) {
elementList.removeAt(j).close()
}
}
fun elementUpdate(e: GuiContent, actionId: Int) {}
fun clearElements() {
elementList.clear()
}
fun setCurrentElement(id: Int) {
focusedElement = this.getElement(id)
}
fun getElement(i: Int): GuiContent {
return elementList[i]
}
}
|
gpl-2.0
|
b08d7f390654ebf8f32c9955765eb64e
| 24.955128 | 88 | 0.560277 | 4.315565 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/util/DecodeOptions.kt
|
1
|
4047
|
package jp.juggler.subwaytooter.util
import android.content.Context
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ReplacementSpan
import jp.juggler.subwaytooter.api.entity.HostAndDomain
import jp.juggler.subwaytooter.api.entity.NicoProfileEmoji
import jp.juggler.subwaytooter.api.entity.TootAttachmentLike
import jp.juggler.subwaytooter.api.entity.TootMention
import jp.juggler.subwaytooter.emoji.CustomEmoji
import jp.juggler.subwaytooter.table.HighlightWord
import jp.juggler.util.WordTrieTree
import org.jetbrains.anko.collections.forEachReversedByIndex
class DecodeOptions(
val context: Context? = null,
var linkHelper: LinkHelper? = null,
var short: Boolean = false,
var decodeEmoji: Boolean = false,
var attachmentList: ArrayList<TootAttachmentLike>? = null,
var linkTag: Any? = null,
var emojiMapCustom: HashMap<String, CustomEmoji>? = null,
var emojiMapProfile: HashMap<String, NicoProfileEmoji>? = null,
var highlightTrie: WordTrieTree? = null,
var unwrapEmojiImageTag: Boolean = false,
var enlargeCustomEmoji: Float = 1f,
var enlargeEmoji: Float = 1f,
// force use HTML instead of Misskey Markdown
var forceHtml: Boolean = false,
var mentionFullAcct: Boolean = false,
var mentions: ArrayList<TootMention>? = null,
// Account.note などmentionsがない状況でメンションリンクをfull acct化するにはアカウント等からapDomainを補う必要がある
// MFMはメンションのホスト名を補うのに閲覧者ではなく投稿作者のホスト名を必要とする
var authorDomain: HostAndDomain? = null,
) {
internal fun isMediaAttachment(url: String?): Boolean =
url?.let { u -> attachmentList?.any { it.hasUrl(u) } } ?: false
// OUTPUT
var highlightSound: HighlightWord? = null
var highlightSpeech: HighlightWord? = null
var highlightAny: HighlightWord? = null
////////////////////////
// decoder
// AndroidのStaticLayoutはパラグラフ中に絵文字が沢山あると異常に遅いので、絵文字が連続して登場したら改行文字を挿入する
private fun SpannableStringBuilder.workaroundForEmojiLineBreak(): SpannableStringBuilder {
val maxEmojiPerLine = if (linkHelper?.isMisskey == true) 5 else 12
val spans = getSpans(0, length, ReplacementSpan::class.java)
if (spans != null && spans.size > maxEmojiPerLine) {
val insertList = ArrayList<Int>()
var emojiCount = 1
var preEnd: Int? = null
for (span in spans.sortedBy { getSpanStart(it) }) {
val start = getSpanStart(span)
if (preEnd != null) {
// true if specified range includes line feed
fun containsLineFeed(start: Int, end: Int): Boolean {
for (i in start until end) {
if (get(i) == '\n') return true
}
return false
}
if (containsLineFeed(preEnd, start)) {
emojiCount = 1
} else if (++emojiCount > maxEmojiPerLine) {
insertList.add(start)
emojiCount = 1
}
}
preEnd = getSpanEnd(span)
}
// 後ろから順に挿入する
insertList.forEachReversedByIndex { insert(it, "\n") }
}
return this
}
fun decodeHTML(html: String?) =
HTMLDecoder.decodeHTML(this, html).workaroundForEmojiLineBreak()
fun decodeEmoji(s: String?): Spannable =
EmojiDecoder.decodeEmoji(this, s ?: "").workaroundForEmojiLineBreak()
// fun decodeEmojiNullable(s : String?) = when(s) {
// null -> null
// else -> EmojiDecoder.decodeEmoji(this, s)
// }
}
|
apache-2.0
|
10ceb099c27acde4bdc95faccc11f2b6
| 36.958763 | 94 | 0.619476 | 4.024494 | false | false | false | false |
MGaetan89/ShowsRage
|
app/src/main/kotlin/com/mgaetan89/showsrage/fragment/PostProcessingFragment.kt
|
1
|
2413
|
package com.mgaetan89.showsrage.fragment
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.support.v7.widget.SwitchCompat
import android.widget.Spinner
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.extension.inflate
import com.mgaetan89.showsrage.extension.toInt
import com.mgaetan89.showsrage.helper.GenericCallback
import com.mgaetan89.showsrage.network.SickRageApi
class PostProcessingFragment : DialogFragment(), DialogInterface.OnClickListener {
private var forceProcessing: SwitchCompat? = null
private var processingMethod: Spinner? = null
private var replaceFiles: SwitchCompat? = null
override fun onClick(dialog: DialogInterface?, which: Int) {
val force = this.forceProcessing?.isChecked.toInt()
val method = this.getProcessingMethod(this.processingMethod)
val replace = this.replaceFiles?.isChecked.toInt()
SickRageApi.instance.services?.postProcess(replace, force, method, GenericCallback(this.activity))
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = this.context ?: return super.onCreateDialog(savedInstanceState)
val view = context.inflate(R.layout.fragment_post_processing)
this.forceProcessing = view.findViewById(R.id.force_processing) as SwitchCompat?
this.processingMethod = view.findViewById(R.id.processing_method) as Spinner?
this.replaceFiles = view.findViewById(R.id.replace_files) as SwitchCompat?
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.post_processing)
builder.setView(view)
builder.setNegativeButton(android.R.string.cancel, null)
builder.setPositiveButton(R.string.process, this)
return builder.create()
}
override fun onDestroyView() {
this.forceProcessing = null
this.processingMethod = null
this.replaceFiles = null
super.onDestroyView()
}
fun getProcessingMethod(spinner: Spinner?): String? {
val processingMethodIndex = spinner?.selectedItemPosition ?: 0
if (processingMethodIndex > 0) {
val processingMethods = this.resources.getStringArray(R.array.processing_methods_values)
if (processingMethodIndex < processingMethods.size) {
return processingMethods[processingMethodIndex]
}
}
return null
}
companion object {
fun newInstance() = PostProcessingFragment()
}
}
|
apache-2.0
|
01f54dd03fc3806ae4f5cf2b81409f8a
| 33.971014 | 100 | 0.796104 | 3.981848 | false | false | false | false |
orauyeu/SimYukkuri
|
subprojects/messageutil/src/main/kotlin/messageutil/YamlSetting.kt
|
1
|
1474
|
package messageutil
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.AbstractConstruct
import org.yaml.snakeyaml.constructor.Constructor
import org.yaml.snakeyaml.nodes.Node
import org.yaml.snakeyaml.nodes.ScalarNode
import org.yaml.snakeyaml.nodes.Tag
import org.yaml.snakeyaml.representer.Represent
import org.yaml.snakeyaml.representer.Representer
/** [Condition]のyaml上のタグ. */
val condTag = "!condition"
private class TypeConstructor : Constructor() {
init {
yamlConstructors.put(Tag(condTag), ConstructType())
}
private inner class ConstructType : AbstractConstruct() {
override fun construct(node: Node): Any =
Condition.parse(constructScalar(node as ScalarNode) as String)
}
}
private class TypeRepresenter : Representer() {
init {
representers.put(Condition::class.java, RepresentType())
}
private inner class RepresentType : Represent {
override fun representData(data: Any): Node =
representScalar(Tag(condTag), (data as Condition).toSimpleString())
}
}
private val dumperOptions = DumperOptions().apply {
defaultFlowStyle = DumperOptions.FlowStyle.BLOCK
isAllowReadOnlyProperties = true
isAllowUnicode = true
}
/** 適当に設定された[Yaml]インスタンス. */
val myYaml = Yaml(TypeConstructor(), TypeRepresenter(), dumperOptions)
|
apache-2.0
|
8f81289e6605a46af6576a4116e40f4f
| 28.595745 | 79 | 0.71727 | 4.261128 | false | false | false | false |
arnab/adventofcode
|
src/main/kotlin/aoc2018/day1/ChronalCalibration.kt
|
1
|
791
|
package aoc2018.day1
import aoc.extensions.findFirstDuplicate
object ChronalCalibration {
fun calculateFrequencies(frequencyChanges: List<Int>): List<Int> {
return frequencyChanges.fold(mutableListOf(0)) { resultingFrequencies, change ->
resultingFrequencies.add(resultingFrequencies.last() + change)
resultingFrequencies
}
}
fun findFirstDuplicateFrequency(frequencyChanges: List<Int>): Int? {
val currentFrequencyChanges: MutableList<Int> = mutableListOf()
var duplicate: Int? = null
while (duplicate == null) {
currentFrequencyChanges.addAll(frequencyChanges)
duplicate = calculateFrequencies(currentFrequencyChanges).findFirstDuplicate()
}
return duplicate
}
}
|
mit
|
eb40c20cce182f7b05314fcd6cfa7438
| 29.461538 | 90 | 0.69153 | 5.103226 | false | false | false | false |
paplorinc/intellij-community
|
platform/platform-impl/src/com/intellij/ide/actions/RecentLocationsDataModel.kt
|
1
|
12418
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.codeInsight.breadcrumbs.FileBreadcrumbsCollector
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx
import com.intellij.ide.actions.RecentLocationsAction.EMPTY_FILE_TEXT
import com.intellij.ide.ui.UISettings
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorSettings
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
import com.intellij.openapi.editor.highlighter.LightHighlighterClient
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl
import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl.RecentPlacesListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.DocumentUtil
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.containers.ContainerUtil
import java.util.*
import java.util.stream.Collectors
import javax.swing.ScrollPaneConstants
data class RecentLocationsDataModel(val project: Project, val editorsToRelease: ArrayList<Editor> = arrayListOf()) {
val projectConnection = project.messageBus.connect()
init {
projectConnection.subscribe(RecentPlacesListener.TOPIC, object : RecentPlacesListener {
override fun recentPlaceAdded(changePlace: IdeDocumentHistoryImpl.PlaceInfo, isChanged: Boolean) =
resetPlaces(isChanged)
override fun recentPlaceRemoved(changePlace: IdeDocumentHistoryImpl.PlaceInfo, isChanged: Boolean) {
resetPlaces(isChanged)
}
private fun resetPlaces(isChanged: Boolean) {
if (isChanged) changedPlaces.drop() else navigationPlaces.drop()
}
})
}
private val navigationPlaces: SynchronizedClearableLazy<List<RecentLocationItem>> = calculateItems(project, false)
private val changedPlaces: SynchronizedClearableLazy<List<RecentLocationItem>> = calculateItems(project, true)
private val navigationPlacesBreadcrumbsMap: Map<IdeDocumentHistoryImpl.PlaceInfo, String> by lazy {
collectBreadcrumbs(project, navigationPlaces.value)
}
private val changedPlacedBreadcrumbsMap: Map<IdeDocumentHistoryImpl.PlaceInfo, String> by lazy {
collectBreadcrumbs(project, changedPlaces.value)
}
fun getPlaces(changed: Boolean): List<RecentLocationItem> {
return if (changed) changedPlaces.value else navigationPlaces.value
}
fun getBreadcrumbsMap(changed: Boolean): Map<IdeDocumentHistoryImpl.PlaceInfo, String> {
return if (changed) changedPlacedBreadcrumbsMap else navigationPlacesBreadcrumbsMap
}
private fun collectBreadcrumbs(project: Project, items: List<RecentLocationItem>): Map<IdeDocumentHistoryImpl.PlaceInfo, String> {
return items.stream()
.map(RecentLocationItem::info)
.collect(Collectors.toMap({ it }, { getBreadcrumbs(project, it) }))
}
private fun getBreadcrumbs(project: Project, placeInfo: IdeDocumentHistoryImpl.PlaceInfo): String {
val rangeMarker = placeInfo.caretPosition
val fileName = placeInfo.file.name
if (rangeMarker == null) {
return fileName
}
val collector = FileBreadcrumbsCollector.findBreadcrumbsCollector(project, placeInfo.file) ?: return fileName
val crumbs = collector.computeCrumbs(placeInfo.file, rangeMarker.document, rangeMarker.startOffset, true)
if (!crumbs.iterator().hasNext()) {
return fileName
}
val breadcrumbsText = crumbs.joinToString(" > ") { it.text }
return StringUtil.shortenTextWithEllipsis(breadcrumbsText, 50, 0)
}
private fun calculateItems(project: Project, changed: Boolean): SynchronizedClearableLazy<List<RecentLocationItem>> {
return SynchronizedClearableLazy {
val items = createPlaceLinePairs(project, changed)
editorsToRelease.addAll(ContainerUtil.map(items) { item -> item.editor })
items
}
}
private fun createPlaceLinePairs(project: Project, changed: Boolean): List<RecentLocationItem> {
return getPlaces(project, changed)
.mapNotNull { RecentLocationItem(createEditor(project, it) ?: return@mapNotNull null, it) }
.take(UISettings.instance.recentLocationsLimit)
}
private fun getPlaces(project: Project, changed: Boolean): List<IdeDocumentHistoryImpl.PlaceInfo> {
val infos = ContainerUtil.reverse(
if (changed) IdeDocumentHistory.getInstance(project).changePlaces else IdeDocumentHistory.getInstance(project).backPlaces)
val infosCopy = arrayListOf<IdeDocumentHistoryImpl.PlaceInfo>()
for (info in infos) {
if (infosCopy.stream().noneMatch { info1 -> IdeDocumentHistoryImpl.isSame(info, info1) }) {
infosCopy.add(info)
}
}
return infosCopy
}
private fun createEditor(project: Project, placeInfo: IdeDocumentHistoryImpl.PlaceInfo): EditorEx? {
val positionOffset = placeInfo.caretPosition
if (positionOffset == null || !positionOffset.isValid) {
return null
}
assert(positionOffset.startOffset == positionOffset.endOffset)
val fileDocument = positionOffset.document
val lineNumber = fileDocument.getLineNumber(positionOffset.startOffset)
val actualTextRange = getTrimmedRange(fileDocument, lineNumber)
var documentText = fileDocument.getText(actualTextRange)
if (actualTextRange.isEmpty) {
documentText = EMPTY_FILE_TEXT
}
val editorFactory = EditorFactory.getInstance()
val editorDocument = editorFactory.createDocument(documentText)
val editor = editorFactory.createEditor(editorDocument, project) as EditorEx
val gutterComponentEx = editor.gutterComponentEx
val linesShift = fileDocument.getLineNumber(actualTextRange.startOffset)
gutterComponentEx.setLineNumberConvertor { index -> index + linesShift }
gutterComponentEx.setPaintBackground(false)
val scrollPane = editor.scrollPane
scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
fillEditorSettings(editor.settings)
setHighlighting(project, editor, fileDocument, placeInfo, actualTextRange)
return editor
}
private fun fillEditorSettings(settings: EditorSettings) {
settings.isLineNumbersShown = true
settings.isCaretRowShown = false
settings.isLineMarkerAreaShown = false
settings.isFoldingOutlineShown = false
settings.additionalColumnsCount = 0
settings.additionalLinesCount = 0
settings.isRightMarginShown = false
settings.isUseSoftWraps = false
settings.isAdditionalPageAtBottom = false
}
private fun setHighlighting(project: Project,
editor: EditorEx,
document: Document,
placeInfo: IdeDocumentHistoryImpl.PlaceInfo,
textRange: TextRange) {
val colorsScheme = EditorColorsManager.getInstance().globalScheme
applySyntaxHighlighting(project, editor, document, colorsScheme, textRange, placeInfo)
applyHighlightingPasses(project, editor, document, colorsScheme, textRange)
}
private fun applySyntaxHighlighting(project: Project,
editor: EditorEx,
document: Document,
colorsScheme: EditorColorsScheme,
textRange: TextRange,
placeInfo: IdeDocumentHistoryImpl.PlaceInfo) {
val editorHighlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(placeInfo.file, colorsScheme, project)
editorHighlighter.setEditor(LightHighlighterClient(document, project))
editorHighlighter.setText(document.getText(TextRange.create(0, textRange.endOffset)))
val startOffset = textRange.startOffset
val iterator = editorHighlighter.createIterator(startOffset)
while (!iterator.atEnd() && iterator.end <= textRange.endOffset) {
if (iterator.start >= startOffset) {
editor.markupModel.addRangeHighlighter(iterator.start - startOffset,
iterator.end - startOffset,
HighlighterLayer.SYNTAX - 1,
iterator.textAttributes,
HighlighterTargetArea.EXACT_RANGE)
}
iterator.advance()
}
}
private fun applyHighlightingPasses(project: Project,
editor: EditorEx,
document: Document,
colorsScheme: EditorColorsScheme,
rangeMarker: TextRange) {
val startOffset = rangeMarker.startOffset
val endOffset = rangeMarker.endOffset
DaemonCodeAnalyzerEx.processHighlights(document, project, null, startOffset, endOffset) { info ->
if (info.startOffset < startOffset || info.endOffset > endOffset) {
return@processHighlights true
}
when (info.severity) {
HighlightSeverity.ERROR,
HighlightSeverity.WARNING,
HighlightSeverity.WEAK_WARNING,
HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING
-> return@processHighlights true
}
val textAttributes = if (info.forcedTextAttributes != null) info.forcedTextAttributes
else colorsScheme.getAttributes(info.forcedTextAttributesKey)
editor.markupModel.addRangeHighlighter(
info.actualStartOffset - rangeMarker.startOffset, info.actualEndOffset - rangeMarker.startOffset,
HighlighterLayer.SYNTAX,
textAttributes,
HighlighterTargetArea.EXACT_RANGE)
true
}
}
private fun getTrimmedRange(document: Document, lineNumber: Int): TextRange {
val range = getLinesRange(document, lineNumber)
val text = document.getText(TextRange.create(range.startOffset, range.endOffset))
val newLinesBefore = StringUtil.countNewLines(
Objects.requireNonNull<String>(StringUtil.substringBefore(text, StringUtil.trimLeading(text))))
val newLinesAfter = StringUtil.countNewLines(
Objects.requireNonNull<String>(StringUtil.substringAfter(text, StringUtil.trimTrailing(text))))
val firstLine = document.getLineNumber(range.startOffset)
val firstLineAdjusted = firstLine + newLinesBefore
val lastLine = document.getLineNumber(range.endOffset)
val lastLineAdjusted = lastLine - newLinesAfter
val startOffset = document.getLineStartOffset(firstLineAdjusted)
val endOffset = document.getLineEndOffset(lastLineAdjusted)
return TextRange.create(startOffset, endOffset)
}
private fun getLinesRange(document: Document, line: Int): TextRange {
val lineCount = document.lineCount
if (lineCount == 0) {
return TextRange.EMPTY_RANGE
}
val beforeAfterLinesCount = Registry.intValue("recent.locations.lines.before.and.after", 2)
val before = Math.min(beforeAfterLinesCount, line)
val after = Math.min(beforeAfterLinesCount, lineCount - line)
val linesBefore = before + beforeAfterLinesCount - after
val linesAfter = after + beforeAfterLinesCount - before
val startLine = Math.max(line - linesBefore, 0)
val endLine = Math.min(line + linesAfter, lineCount - 1)
val startOffset = document.getLineStartOffset(startLine)
val endOffset = document.getLineEndOffset(endLine)
return if (startOffset <= endOffset)
TextRange.create(startOffset, endOffset)
else
TextRange.create(DocumentUtil.getLineTextRange(document, line))
}
}
data class RecentLocationItem(val editor: EditorEx, val info: IdeDocumentHistoryImpl.PlaceInfo)
|
apache-2.0
|
9a8509d4c2ae0cb27eb81b2f6bdc6949
| 42.423077 | 140 | 0.735304 | 5.003223 | false | false | false | false |
earizon/java-vertx-ledger
|
src/main/java/com/everis/everledger/handlers/TransferHandlers.kt
|
1
|
30884
|
package com.everis.everledger.handlers
import com.everis.everledger.util.Config
import com.everis.everledger.ifaces.account.IfaceLocalAccountManager
import com.everis.everledger.ifaces.transfer.ILocalTransfer
import com.everis.everledger.ifaces.transfer.IfaceTransferManager
import com.everis.everledger.impl.*
import com.everis.everledger.impl.manager.SimpleAccountManager
import com.everis.everledger.impl.manager.SimpleTransferManager
import com.everis.everledger.util.*
import io.netty.handler.codec.http.HttpResponseStatus
import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.LoggerFactory
import io.vertx.ext.web.RoutingContext
import org.interledger.Condition
import org.interledger.Fulfillment
import org.interledger.ilp.InterledgerError
import org.interledger.ledger.model.TransferStatus
import org.javamoney.moneta.Money
import java.net.URI
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.time.ZonedDateTime
import java.util.*
import javax.money.Monetary
import javax.money.MonetaryAmount
private val AM : IfaceLocalAccountManager = SimpleAccountManager;
private val TM : IfaceTransferManager = SimpleTransferManager;
private val currencyUnit /* local ledger currency */ = Monetary.getCurrency(Config.ledgerCurrencyCode)
class TransferHandler
// GET|PUT /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204
private constructor() : RestEndpointHandler(
arrayOf(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST), arrayOf("transfers/:" + transferUUID )) {
override fun handlePut(context: RoutingContext) {
val ai = AuthManager.authenticate(context)
val requestBody = RestEndpointHandler.getBodyAsJson(context)
var transferMatchUser = false
log.trace(this.javaClass.name + "handlePut invoqued ")
log.trace(context.bodyAsString)
/*
* REQUEST: PUT /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204 HTTP/1.1
* Authorization: Basic YWxpY2U6YWxpY2U=
* {"id":"http://localhost/transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204"
* , "ledger":"http://localhost", "debits":[
* {"account":"http://localhost/accounts/alice","amount":"50"},
* {"account":"http://localhost/accounts/candice","amount":"20"}],
* "credits":[
* {"account":"http://localhost/accounts/bob","amount":"30"},
* {"account":"http://localhost/accounts/dave","amount":"40"}],
* "execution_condition"
* :"cc:0:3:Xk14jPQJs7vrbEZ9FkeZPGBr0YqVzkpOYjFp_tIZMgs:7",
* "expires_at":"2015-06-16T00:00:01.000Z", "state":"prepared"} ANSWER:
* HTTP/1.1 201 Created
* {"id":"http://localhost/transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204"
* , "ledger":..., "debits":[ ... ] "credits":[ ... ]
* "execution_condition":"...", "expires_at":..., "state":"proposed",
* "timeline":{"proposed_at":"2015-06-16T00:00:00.000Z"} }
*/
val ilpTransferID: UUID
try {
ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException(
"'" + context.request().getParam(transferUUID) + "' is not a valid UUID")
}
val transferID : ILocalTransfer.LocalTransferID = ILPSpec2LocalTransferID(ilpTransferID)
// TODO: Check requestBody.getString("ledger") match ledger host/port
// TODO: Check state is 'proposed' for new transactions?
// TODO:(?) mark as "Tainted" object
val debits = requestBody.getJsonArray("debits") ?: throw ILPExceptionSupport.createILPBadRequestException("debits not found")
if (debits.size() != 1) {
throw ILPExceptionSupport.createILPBadRequestException("Only one debitor supported by ledger")
}
var totalDebitAmmount = 0.0
val debitList = Array<ILocalTransfer.Debit>(debits.size(), { idx ->
val jsonDebit = debits.getJsonObject(idx)
log.debug("check123 jsonDebit: " + jsonDebit.encode())
// debit0 will be similar to
// {"account":"http://localhost/accounts/alice","amount":"50"}
var account_name = jsonDebit.getString("account")
if (account_name.lastIndexOf('/') > 0) {
account_name = account_name.substring(account_name.lastIndexOf('/') + 1)
}
if (ai.id == account_name) { transferMatchUser = true }
val debit_ammount: MonetaryAmount = try {
val auxDebit = java.lang.Double.parseDouble(jsonDebit.getString("amount"))
totalDebitAmmount += auxDebit
Money.of(auxDebit, currencyUnit)
} catch (e: Exception) {
println(e.toString())
throw ILPExceptionSupport.createILPBadRequestException("unparseable amount")
}
if (debit_ammount.getNumber().toFloat().toDouble() == 0.0) {
throw ILPExceptionSupport.createILPException(422, InterledgerError.ErrorCode.F00_BAD_REQUEST, "debit is zero")
}
val debitor = AM.getAccountByName(account_name)
log.debug("check123 debit_ammount (must match jsonDebit ammount: " + debit_ammount.toString())
Debit(debitor, debit_ammount)
})
if (!ai.isAdmin && !transferMatchUser) {
throw ILPExceptionSupport.createILPForbiddenException()
}
val jsonMemo = requestBody.getJsonObject("memo")
val sMemo = if (jsonMemo == null) "" else jsonMemo.encode()
// REF: JsonArray ussage:
// http://www.programcreek.com/java-api-examples/index.php?api=io.vertx.core.json.JsonArray
val credits = requestBody.getJsonArray("credits")
val sExpiresAt = requestBody.getString("expires_at") // can be null
val DTTM_expires: ZonedDateTime
try {
DTTM_expires = if (sExpiresAt == null) TimeUtils.future else ZonedDateTime.parse(sExpiresAt)
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException("unparseable expires_at")
}
val execution_condition = requestBody.getString("execution_condition")
val URIExecutionCond: Condition = if (execution_condition != null)
ConversionUtil.parseURI(URI.create(execution_condition))
else CC_NOT_PROVIDED
var totalCreditAmmount = 0.0
val creditList = Array<ILocalTransfer.Credit>(credits.size() , { idx ->
val jsonCredit = credits.getJsonObject(idx)
/* { "account":"http://localhost:3002/accounts/ilpconnector",
* "amount":"1.01", "memo":{ "ilp_header":{
* "account":"ledger3.eur.alice.fe773626-81fb-4294-9a60-dc7b15ea841e"
* , "amount":"1", "data":{"expires_at":"2016-11-10T15:51:27.134Z"}
* } } } */
// JsonObject jsonMemoILPHeader = jsonCredit.getJsonObject("memo")
// COMMENTED OLD API .getJsonObject("ilp_header");
var account_name = jsonCredit.getString("account")
if (account_name.lastIndexOf('/') > 0) {
account_name = account_name.substring(account_name.lastIndexOf('/') + 1)
}
val credit_ammount: MonetaryAmount = try {
val auxCredit = java.lang.Double.parseDouble(jsonCredit.getString("amount"))
totalCreditAmmount += auxCredit
Money.of(auxCredit, currencyUnit)
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException("unparseable amount")
}
if (credit_ammount.getNumber().toFloat().toDouble() == 0.0) {
throw ILPExceptionSupport.createILPException(422,
InterledgerError.ErrorCode.F00_BAD_REQUEST, "credit is zero")
}
val creditor = AM.getAccountByName(account_name)
// COMMENTED OLD API String ilp_ph_ilp_dst_address = jsonMemoILPHeader
// COMMENTED OLD API .getString("account");
// COMMENTED OLD API InterledgerAddress dstAddress = InterledgerAddressBuilder.builder()
// COMMENTED OLD API .value(ilp_ph_ilp_dst_address).build();
// COMMENTED OLD API String ilp_ph_amount = jsonMemoILPHeader.getString("amount");
// COMMENTED OLD API BigDecimal ammount = new BigDecimal(ilp_ph_amount);
// COMMENTED OLD API Condition ilp_ph_condition = URIExecutionCond;
// COMMENTED OLD API DTTM ilp_ph_expires = new DTTM(jsonMemoILPHeader.getJsonObject(
// COMMENTED OLD API "data").getString("expires_at"));
// COMMENTED OLD API if (!DTTM_expires.equals(ilp_ph_expires)) {
// COMMENTED OLD API DTTM_expires = ilp_ph_expires;
// COMMENTED OLD API }
// COMMENTED OLD API ZonedDateTime zdt = ZonedDateTime.parse((DTTM_expires.toString()));
// InterledgerPacketHeader(InterledgerAddress destinationAddress,
// BigDecimal amount,
// Condition condition, ZonedDateTime expiry)
// COMMENTED OLD API InterledgerPacketHeader memo_ph = new InterledgerPacketHeader(
// COMMENTED OLD API dstAddress, ammount, ilp_ph_condition, zdt);
// In five-bells-ledger, memo goes into transfer_adjustments table (@ src/sql/pg/...)
Credit(creditor, credit_ammount/*, memo_ph*/) as ILocalTransfer.Credit
})
if (totalCreditAmmount != totalDebitAmmount) {
throw ILPExceptionSupport.createILPException(422,
InterledgerError.ErrorCode.F00_BAD_REQUEST, "total credits do not match total debits")
}
val data = "" // Not yet used
val noteToSelf = "" // Not yet used
val DTTM_proposed = ZonedDateTime.now() // TODO:(?) Add proposed -> prepared support
val DTTM_prepared = ZonedDateTime.now() // TODO:(?) Add proposed -> prepared support
val cancelation_condition = requestBody.getString("cancellation_condition")
val URICancelationCond = if (cancelation_condition != null)
ConversionUtil.parseURI(URI.create(cancelation_condition)) else CC_NOT_PROVIDED
val status = TransferStatus.PROPOSED // By default
// if (requestBody.getString("state") != null) {
// // TODO: Must status change be allowed or must we force it to be
// // 'prepared'?
// // (only Execution|Cancellation Fulfillments will change the state)
// // At this moment it's allowed (to make it compliant with
// // five-bells-ledger tests)
// status = TransferStatus.parse(requestBody.getString("state"));
// log.debug("transfer status " + status);
// }
val receivedTransfer = SimpleTransfer(
transferID as LocalTransferID, debitList, creditList,
URIExecutionCond, URICancelationCond,
DTTM_proposed, DTTM_prepared, DTTM_expires, TimeUtils.future, TimeUtils.future,
data, noteToSelf,
status,
sMemo,
FF_NOT_PROVIDED, FF_NOT_PROVIDED )
// TODO:(0) Next logic must be on the Manager, not in the HTTP-protocol related handler
val isNewTransfer = !TM.doesTransferExists(ilpTransferID)
log.debug("is new transfer?: " + isNewTransfer)
val effectiveTransfer = if (isNewTransfer) receivedTransfer else TM.getTransferById(transferID)
if (!isNewTransfer) {
// Check that received json data match existing transaction.
// TODO: Recheck (Multitransfer active now)
if (effectiveTransfer.credits[0] != receivedTransfer
.credits[0] || effectiveTransfer.debits[0] != receivedTransfer.debits[0]) {
throw ILPExceptionSupport.createILPBadRequestException(
"data for credits and/or debits doesn't match existing registry")
}
} else {
TM.createNewRemoteILPTransfer(receivedTransfer)
}
try { // TODO:(?) Refactor Next code for notification (next two loops) are
// duplicated in FulfillmentHandler
val resource = (effectiveTransfer as SimpleTransfer).toILPJSONStringifiedFormat()
// Notify affected accounts:
val eventType = if (receivedTransfer.transferStatus == TransferStatus.PREPARED)
TransferWSEventHandler.EventType.TRANSFER_CREATE
else TransferWSEventHandler.EventType.TRANSFER_UPDATE
val setAffectedAccounts = HashSet<String>()
for (debit in receivedTransfer.debits) setAffectedAccounts.add((debit as Debit ).account.localID)
for (credit in receivedTransfer.credits) setAffectedAccounts.add((credit as Credit).account.localID)
TransferWSEventHandler.notifyListener(setAffectedAccounts, eventType, resource, null)
} catch (e: Exception) {
log.warn("transaction created correctly but ilp-connector couldn't be notified due to " + e.toString())
}
val response = (effectiveTransfer as SimpleTransfer).toILPJSONStringifiedFormat().encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode( if (isNewTransfer)
HttpResponseStatus.CREATED.code()
else HttpResponseStatus.OK.code()).
end(response)
}
override fun handleGet(context: RoutingContext) {
log.debug(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transfer = TM.getTransferById(ILPSpec2LocalTransferID(ilpTransferID))
val debit0_account = (transfer.debits[0] as Debit).account.localID
val transferMatchUser = ai.id == debit0_account
if (!transferMatchUser && ai.roll != "admin") {
log.error("transferMatchUser false: "
+ "\n ai.id :" + ai.id
+ "\n debit0_account:" + debit0_account)
throw ILPExceptionSupport.createILPForbiddenException()
}
response( context, HttpResponseStatus.OK, (transfer as SimpleTransfer).toILPJSONStringifiedFormat())
}
companion object {
private val log = LoggerFactory.getLogger(AccountsHandler::class.java)
private val transferUUID = "transferUUID";
fun create(): TransferHandler = TransferHandler()
}
}
// GET /transfers/byExecutionCondition/cc:0:3:vmvf6B7EpFalN6RGDx9F4f4z0wtOIgsIdCmbgv06ceI:7
class TransfersHandler : RestEndpointHandler(arrayOf(HttpMethod.GET), arrayOf("transfers/byExecutionCondition/:" + execCondition)) {
override fun handleGet(context: RoutingContext) {
/*
* GET /transfers/byExecutionCondition/cc:0:3:vmvf6B7EpFalN...I:7 HTTP/1.1
* HTTP/1.1 200 OK
* [{"ledger":"http://localhost",
* "execution_condition":"cc:0:3:vmvf6B7EpFalN...I:7",
* "cancellation_condition":"cc:0:3:I3TZF5S3n0-...:6",
* "id":"http://localhost/transfers/9e97a403-f604-44de-9223-4ec36aa466d9",
* "state":"executed",
* "debits":[
* {"account":"http://localhost/accounts/alice","amount":"10","authorized":true}],
* "credits":[{"account":"http://localhost/accounts/bob","amount":"10"}]}]
*/
log.trace(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
var transferMatchUser = false
// Condition condition = CryptoConditionUri.parse(URI.create(testVector.getConditionUri()));
val sExecCond = context.request().getParam(execCondition)
val executionCondition: Condition
executionCondition = ConversionUtil.parseURI(URI.create(sExecCond))
val transferList = TM.getTransfersByExecutionCondition(executionCondition)
val ja = JsonArray()
for (transfer in transferList) {
if (ai.isAdmin
|| (transfer. debits[0] as Debit).account.localID == ai.id
|| (transfer.credits[0] as Credit).account.localID == ai.id) {
ja.add((transfer as SimpleTransfer).toILPJSONStringifiedFormat())
transferMatchUser = true
}
}
if (!ai.isAdmin && !transferMatchUser) {
throw ILPExceptionSupport.createILPForbiddenException()
}
val response = ja.encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code())
.end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(TransfersHandler::class.java)
private val execCondition = "execCondition"
fun create(): TransfersHandler = TransfersHandler()
}
}// REF: https://github.com/interledger/five-bells-ledger/blob/master/src/lib/app.js
// GET /transfers/25644640-d140-450e-b94b-badbe23d3389/state|state?type=sha256
class TransferStateHandler : RestEndpointHandler(
arrayOf(HttpMethod.GET), arrayOf("transfers/:$transferUUID/state")) {
override fun handleGet(context: RoutingContext) {
/* GET transfer by UUID & type
* *****************************
* GET /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204/state?type=sha256 HTTP/1.1
* {"type":"sha256",
* "message":{
* "id":"http:.../transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204",
* "state":"proposed",
* "token":"xy9kB4n......Cg=="
* },
* "signer":"http://localhost",
* "digest":"P6K2HEaZxAthBeGmbjeyPau0BIKjgkaPqW781zmSvf4="
* } */
log.debug(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
val transferId = context.request().getParam(transferUUID)
val transferID = LocalTransferID(transferId)
var status = TransferStatus.PROPOSED // default value
var transferMatchUser = false
if (!TM.doesTransferExists(transferID))
throw ILPExceptionSupport.createILPNotFoundException()
val transfer = TM.getTransferById(transferID)
status = transfer.transferStatus
transferMatchUser = ai.id == (transfer. debits[0] as Debit).account.localID
|| ai.id == (transfer.credits[0] as Credit).account.localID
if (!ai.isAdmin && !transferMatchUser) {
throw ILPExceptionSupport.createILPForbiddenException()
}
// REF: getStateResource @ transfers.js
var receiptType: String? = context.request().getParam("type")
// REF: getTransferStateReceipt(id, receiptType, conditionState) @ five-bells-ledger/src/models/transfers.js
if (receiptType == null) {
receiptType = RECEIPT_TYPE_ED25519
}
if (receiptType != RECEIPT_TYPE_ED25519 &&
receiptType != RECEIPT_TYPE_SHA256 &&
true) {
throw ILPExceptionSupport.createILPBadRequestException(
"type not in := $RECEIPT_TYPE_ED25519* | $RECEIPT_TYPE_SHA256 "
)
}
val jo = JsonObject()
val signer = "" // FIXME: config.getIn(['server', 'base_uri']),
if (receiptType == RECEIPT_TYPE_ED25519) {
// REF: makeEd25519Receipt(transferId, transferState) @
// @ five-bells-ledger/src/models/transfers.js
val message = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_ED25519)
val signature = "" // FIXME: sign(hashJSON(message))
jo.put("type", RECEIPT_TYPE_ED25519)
jo.put("message", message)
jo.put("signer", signer)
jo.put("public_key", DSAPrivPubKeySupport.savePublicKey(Config.ilpLedgerInfo.notificationSignPublicKey))
jo.put("signature", signature)
} else {
// REF: makeSha256Receipt(transferId, transferState, conditionState) @
// @ five-bells-ledger/src/models/transfers.js
val message = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_SHA256)
val digest = sha256(message.encode())
jo.put("type", RECEIPT_TYPE_SHA256)
jo.put("message", message)
jo.put("signer", signer)
jo.put("digest", digest)
val conditionState = context.request().getParam("condition_state")
if (conditionState != null) {
val conditionMessage = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_SHA256)
val condition_digest = sha256(conditionMessage.encode())
jo.put("condition_state", conditionState)
jo.put("condition_digest", condition_digest)
}
}
val response = jo.encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code())
.end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(TransferStateHandler::class.java)
private val transferUUID = "transferUUID"
private val RECEIPT_TYPE_ED25519 = "ed25519-sha512"
private val RECEIPT_TYPE_SHA256 = "sha256"
private val md256: MessageDigest
init {
md256 = MessageDigest.getInstance("SHA-256")
}
fun create(): TransferStateHandler = TransferStateHandler()
private fun makeTransferStateMessage(transferId: LocalTransferID, state: TransferStatus, receiptType: String): JsonObject {
val jo = JsonObject()
// <-- TODO:(0) Move URI logic to Iface ILPTransferSupport and add iface to SimpleLedgerTransferManager
jo.put("id", Config.publicURL.toString() + "transfers/" + transferId.transferID)
jo.put("state", state.toString())
if (receiptType == RECEIPT_TYPE_SHA256) {
val token = "" // FIXME: sign(sha512(transferId + ':' + state))
jo.put("token", token)
}
return jo
}
private fun sha256(input: String): String {
md256.reset()
md256.update(input.toByteArray())
return String(md256.digest())
}
}
}// REF: https://github.com/interledger/five-bells-ledger/blob/master/src/lib/app.js
/*
* GET|PUT /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment
* fulfillment can be execution or cancellation
* Note: Rejection != cancellation. Rejection in five-bells-ledger refers
* to the rejection in the proposed (not-yet prepared) transfer (or part of the
* transfer).
* In the java-vertx-ledger there is not yet (2017-05) concept of proposed
* state.
*/
class FulfillmentHandler : RestEndpointHandler(arrayOf(HttpMethod.GET, HttpMethod.PUT), arrayOf("transfers/:$transferUUID/fulfillment")) {
override fun handlePut(context: RoutingContext) {
val ai = AuthManager.authenticate(context)
log.trace(this.javaClass.name + "handlePut invoqued ")
/* (request from ILP Connector)
* PUT /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment HTTP/1.1 */
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transferID = ILPSpec2LocalTransferID(ilpTransferID)
/*
* REF: https://gitter.im/interledger/Lobby
* Enrique Arizon Benito @earizon 17:51 2016-10-17
* Hi, I'm trying to figure out how the five-bells-ledger implementation validates fulfillments.
* Following the node.js code I see the next route:
*
* router.put('/transfers/:id/fulfillment', transfers.putFulfillment)
*
* I understand the fulfillment is validated at this (PUT) point against the stored condition
* in the existing ":id" transaction.
* Following the stack for this request it looks to me that the method
*
* (/five-bells-condition/index.js)validateFulfillment (serializedFulfillment, serializedCondition, message)
*
* is always being called with an undefined message and so an empty one is being used.
* I'm missing something or is this the expected behaviour?
*
* Stefan Thomas @justmoon 18:00 2016-10-17
* @earizon Yes, this is expected. We're using crypto conditions as a trigger, not to verify the
* authenticity of a message!
* Note that the actual cryptographic signature might still be against a message - via prefix
* conditions (which append a prefix to this empty message)
**/
val transfer = TM.getTransferById(transferID)
if (transfer.executionCondition === CC_NOT_PROVIDED) {
throw ILPExceptionSupport.createILPUnprocessableEntityException(
this.javaClass.name + "Transfer is not conditional")
}
val transferMatchUser = // TODO:(?) Recheck
ai.id == transfer.debits[0].localAccount.localID || ai.id == transfer.credits[0].localAccount.localID
if (!ai.isAdmin && !transferMatchUser) {
throw ILPExceptionSupport.createILPForbiddenException()
}
val sFulfillmentInput = context.bodyAsString
val fulfillmentBytes = Base64.getDecoder().decode(sFulfillmentInput)
// // REF: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
// byte[] fulfillmentBytes = DatatypeConverter.parseHexBinary(sFulfillment);
val inputFF = Fulfillment.of(fulfillmentBytes)
val message = byteArrayOf()
var ffExisted = false // TODO:(0) Recheck usage
log.trace("transfer.getExecutionCondition():" + transfer.executionCondition.toString())
// log.trace("transfer.getCancellationCondition():"+transfer.getCancellationCondition().toString());
log.trace("request hexFulfillment:" + sFulfillmentInput)
log.trace("request ff.getCondition():" + inputFF.condition.toString())
if (transfer.executionCondition == inputFF.condition) {
if (!inputFF.validate(inputFF.condition))
throw ILPExceptionSupport.createILPUnprocessableEntityException("execution fulfillment doesn't validate")
if (transfer.expiresAt.compareTo(ZonedDateTime.now()) < 0 && Config.unitTestsActive == false)
throw ILPExceptionSupport.createILPUnprocessableEntityException("transfer expired")
if (transfer.transferStatus != TransferStatus.EXECUTED)
TM.executeILPTransfer(transfer, inputFF)
// } else if (transfer.getCancellationCondition().equals(inputFF.getCondition()) ){
// if ( transfer.getTransferStatus() == TransferStatus.EXECUTED) {
// throw ILPExceptionSupport.createILPBadRequestException("Already executed");
// }
// ffExisted = transfer.getCancellationFulfillment().equals(inputFF);
// if (!ffExisted) {
// if (!inputFF.verify(inputFF.getCondition(), message)){
// throw ILPExceptionSupport.createILPUnprocessableEntityException("cancelation fulfillment doesn't validate");
// }
// TM.cancelILPTransfer(transfer, inputFF);
// }
} else {
throw ILPExceptionSupport.createILPUnprocessableEntityException(
"Fulfillment does not match any condition")
}
val response = ConversionUtil.fulfillmentToBase64(inputFF)
if (sFulfillmentInput != response) {
throw ILPExceptionSupport.createILPBadRequestException(
"Assert exception. Input '$sFulfillmentInput'doesn't match output '$response' ")
}
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(if (!ffExisted) HttpResponseStatus.CREATED.code() else HttpResponseStatus.OK.code())
.end(response)
}
override fun handleGet(context: RoutingContext) {
// GET /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment
val ai = AuthManager.authenticate(context)
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transferID = ILPSpec2LocalTransferID(ilpTransferID)
val transfer = TM.getTransferById(transferID)
var transferMatchUser =
ai.id == transfer.debits[0].localAccount.localID
|| ai.id == transfer.credits[0].localAccount.localID
if (!ai.isAdmin && !(ai.isConnector && transferMatchUser))
throw ILPExceptionSupport.createILPForbiddenException()
val fulfillment = transfer.executionFulfillment
if (fulfillment === FF_NOT_PROVIDED) {
if (transfer.expiresAt.compareTo(ZonedDateTime.now()) < 0) {
throw ILPExceptionSupport.createILPNotFoundException("This transfer expired before it was fulfilled")
}
throw ILPExceptionSupport.createILPUnprocessableEntityException("Unprocessable Entity")
}
val response = ConversionUtil.fulfillmentToBase64(fulfillment)
context.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code()).end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(FulfillmentHandler::class.java)
private val transferUUID = "transferUUID"
fun create(): FulfillmentHandler = FulfillmentHandler()
}
}
|
apache-2.0
|
48011d9e8f72fbbfbd7b9a9430275284
| 50.302326 | 142 | 0.633726 | 4.175771 | false | false | false | false |
paplorinc/intellij-community
|
platform/usageView/src/com/intellij/usages/UsageViewSettings.kt
|
3
|
3735
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.usages
import com.intellij.openapi.components.*
import com.intellij.util.PathUtil
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
/**
* Passed params will be used as default values, so, do not use constructor if instance will be used as a state (unless you want to change defaults)
*/
@State(name = "UsageViewSettings", storages = [Storage("usageView.xml")])
open class UsageViewSettings(
isGroupByFileStructure: Boolean = true,
isGroupByModule: Boolean = true,
isGroupByPackage: Boolean = true,
isGroupByUsageType: Boolean = true,
isGroupByScope: Boolean = false
) : BaseState(), PersistentStateComponent<UsageViewSettings> {
companion object {
@JvmStatic
val instance: UsageViewSettings
get() = ServiceManager.getService(UsageViewSettings::class.java)
}
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByModule")
var GROUP_BY_MODULE: Boolean = isGroupByModule
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByUsageType")
var GROUP_BY_USAGE_TYPE: Boolean = isGroupByUsageType
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByFileStructure")
var GROUP_BY_FILE_STRUCTURE: Boolean = isGroupByFileStructure
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByScope")
var GROUP_BY_SCOPE: Boolean = isGroupByScope
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByPackage")
var GROUP_BY_PACKAGE: Boolean = isGroupByPackage
@Suppress("MemberVisibilityCanPrivate")
@get:OptionTag("EXPORT_FILE_NAME")
internal var EXPORT_FILE_NAME by property("report.txt")
@get:OptionTag("IS_EXPANDED")
var isExpanded by property(false)
@get:OptionTag("IS_AUTOSCROLL_TO_SOURCE")
var isAutoScrollToSource by property(false)
@get:OptionTag("IS_FILTER_DUPLICATED_LINE")
var isFilterDuplicatedLine by property(true)
@get:OptionTag("IS_SHOW_METHODS")
var isShowModules by property(false)
@get:OptionTag("IS_PREVIEW_USAGES")
var isPreviewUsages by property(false)
@get:OptionTag("IS_REPLACE_PREVIEW_USAGES")
var isReplacePreviewUsages by property(true)
@get:OptionTag("IS_SORT_MEMBERS_ALPHABETICALLY")
var isSortAlphabetically by property(false)
@get:OptionTag("PREVIEW_USAGES_SPLITTER_PROPORTIONS")
var previewUsagesSplitterProportion: Float by property(0.5f)
@get:OptionTag("GROUP_BY_USAGE_TYPE")
var isGroupByUsageType by property(isGroupByUsageType)
@get:OptionTag("GROUP_BY_MODULE")
var isGroupByModule by property(isGroupByModule)
@get:OptionTag("FLATTEN_MODULES")
var isFlattenModules by property(true)
@get:OptionTag("GROUP_BY_PACKAGE")
var isGroupByPackage by property(isGroupByPackage)
@get:OptionTag("GROUP_BY_FILE_STRUCTURE")
var isGroupByFileStructure by property(isGroupByFileStructure)
@get:OptionTag("GROUP_BY_SCOPE")
var isGroupByScope by property(isGroupByScope)
var exportFileName: String?
@Transient
get() = PathUtil.toSystemDependentName(EXPORT_FILE_NAME)
set(value) {
EXPORT_FILE_NAME = PathUtil.toSystemIndependentName(value)
}
override fun getState(): UsageViewSettings = this
@Suppress("DEPRECATION")
override fun loadState(state: UsageViewSettings) {
copyFrom(state)
GROUP_BY_MODULE = isGroupByModule
GROUP_BY_USAGE_TYPE = isGroupByUsageType
GROUP_BY_FILE_STRUCTURE = isGroupByFileStructure
GROUP_BY_SCOPE = isGroupByScope
GROUP_BY_PACKAGE = isGroupByPackage
}
}
|
apache-2.0
|
401f12e62f072ff9b8730cc83e72d3c7
| 30.125 | 148 | 0.755823 | 4.268571 | false | false | false | false |
google/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeMultiparentRootEntityImpl.kt
|
1
|
9489
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class TreeMultiparentRootEntityImpl(val dataSource: TreeMultiparentRootEntityData) : TreeMultiparentRootEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentRootEntity::class.java,
TreeMultiparentLeafEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val children: List<TreeMultiparentLeafEntity>
get() = snapshot.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: TreeMultiparentRootEntityData?) : ModifiableWorkspaceEntityBase<TreeMultiparentRootEntity>(), TreeMultiparentRootEntity.Builder {
constructor() : this(TreeMultiparentRootEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity TreeMultiparentRootEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field TreeMultiparentRootEntity#data should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field TreeMultiparentRootEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field TreeMultiparentRootEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as TreeMultiparentRootEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
// List of non-abstract referenced types
var _children: List<TreeMultiparentLeafEntity>? = emptyList()
override var children: List<TreeMultiparentLeafEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): TreeMultiparentRootEntityData = result ?: super.getEntityData() as TreeMultiparentRootEntityData
override fun getEntityClass(): Class<TreeMultiparentRootEntity> = TreeMultiparentRootEntity::class.java
}
}
class TreeMultiparentRootEntityData : WorkspaceEntityData.WithCalculablePersistentId<TreeMultiparentRootEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeMultiparentRootEntity> {
val modifiable = TreeMultiparentRootEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): TreeMultiparentRootEntity {
return getCached(snapshot) {
val entity = TreeMultiparentRootEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun persistentId(): PersistentEntityId<*> {
return TreeMultiparentPersistentId(data)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return TreeMultiparentRootEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return TreeMultiparentRootEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeMultiparentRootEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeMultiparentRootEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
4c4dd7397a68acce8f831ba3723e6276
| 35.77907 | 157 | 0.707978 | 5.466014 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaMapForEachInspection.kt
|
1
|
2889
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.synthetic.isResolvedWithSamConversions
class JavaMapForEachInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun isApplicable(element: KtCallExpression): Boolean {
val calleeExpression = element.calleeExpression ?: return false
if (calleeExpression.text != "forEach") return false
if (element.valueArguments.size != 1) return false
val lambda = element.lambda() ?: return false
val lambdaParameters = lambda.valueParameters
if (lambdaParameters.size != 2 || lambdaParameters.any { it.destructuringDeclaration != null }) return false
val context = element.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = element.getResolvedCall(context) ?: return false
return resolvedCall.dispatchReceiver?.type?.isMap() == true && resolvedCall.isResolvedWithSamConversions()
}
override fun inspectionHighlightRangeInElement(element: KtCallExpression): TextRange? = element.calleeExpression?.textRangeIn(element)
override fun inspectionText(element: KtCallExpression) =
KotlinBundle.message("java.map.foreach.method.call.should.be.replaced.with.kotlin.s.foreach")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.foreach")
override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambda = element.lambda() ?: return
val valueParameters = lambda.valueParameters
lambda.functionLiteral.valueParameterList?.replace(
KtPsiFactory(project).createLambdaParameterList("(${valueParameters[0].text}, ${valueParameters[1].text})")
)
}
private fun KtCallExpression.lambda(): KtLambdaExpression? {
return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression()
}
}
|
apache-2.0
|
8593ef4d29c409c5174b0b1373c90ef9
| 50.589286 | 138 | 0.778816 | 4.989637 | false | false | false | false |
JetBrains/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/GradleCommandLineProjectConfigurator.kt
|
1
|
10017
|
// 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.plugins.gradle
import com.intellij.ide.CommandLineInspectionProgressReporter
import com.intellij.ide.CommandLineInspectionProjectConfigurator
import com.intellij.ide.CommandLineInspectionProjectConfigurator.ConfiguratorContext
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsProgressNotificationListener
import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsProgressNotificationManager
import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsTaskId
import org.jetbrains.plugins.gradle.service.project.open.createLinkSettings
import org.jetbrains.plugins.gradle.settings.GradleImportHintService
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
private val LOG = logger<GradleCommandLineProjectConfigurator>()
private val gradleLogWriter = BufferedWriter(FileWriter(PathManager.getLogPath() + "/gradle-import.log"))
private const val DISABLE_GRADLE_AUTO_IMPORT = "external.system.auto.import.disabled"
private const val DISABLE_ANDROID_GRADLE_PROJECT_STARTUP_ACTIVITY = "android.gradle.project.startup.activity.disabled"
private const val DISABLE_UPDATE_ANDROID_SDK_LOCAL_PROPERTIES = "android.sdk.local.properties.update.disabled"
class GradleCommandLineProjectConfigurator : CommandLineInspectionProjectConfigurator {
override fun getName() = "gradle"
override fun getDescription(): String = GradleBundle.message("gradle.commandline.description")
override fun configureEnvironment(context: ConfiguratorContext) = context.run {
Registry.get(DISABLE_GRADLE_AUTO_IMPORT).setValue(true)
Registry.get(DISABLE_ANDROID_GRADLE_PROJECT_STARTUP_ACTIVITY).setValue(true)
Registry.get(DISABLE_UPDATE_ANDROID_SDK_LOCAL_PROPERTIES).setValue(true)
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(LoggingNotificationListener(context.logger))
Unit
}
override fun configureProject(project: Project, context: ConfiguratorContext) {
val basePath = project.basePath ?: return
val state = GradleImportHintService.getInstance(project).state
if (state.skip) return
if (GradleSettings.getInstance(project).linkedProjectsSettings.isEmpty()) {
linkProjects(basePath, project)
}
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
val notificationListener = StateNotificationListener(project)
val externalAnnotationsNotificationManager = ExternalAnnotationsProgressNotificationManager.getInstance()
val externalAnnotationsProgressListener = StateExternalAnnotationNotificationListener()
try {
externalAnnotationsNotificationManager.addNotificationListener(externalAnnotationsProgressListener)
progressManager.addNotificationListener(notificationListener)
importProjects(project)
notificationListener.waitForImportEnd()
externalAnnotationsProgressListener.waitForResolveExternalAnnotationEnd()
}
finally {
progressManager.removeNotificationListener(notificationListener)
externalAnnotationsNotificationManager.removeNotificationListener(externalAnnotationsProgressListener)
}
}
private fun linkProjects(basePath: String, project: Project) {
if (linkGradleHintProjects(basePath, project)) {
return
}
linkRootProject(basePath, project)
}
private fun importProjects(project: Project) {
if (!GradleSettings.getInstance(project).linkedProjectsSettings.isEmpty()) {
AutoImportProjectTracker.onceIgnoreDisableAutoReloadRegistry()
AutoImportProjectTracker.getInstance(project).scheduleProjectRefresh()
}
}
private fun linkRootProject(basePath: String, project: Project): Boolean {
val gradleGroovyDslFile = basePath + "/" + GradleConstants.DEFAULT_SCRIPT_NAME
val kotlinDslGradleFile = basePath + "/" + GradleConstants.KOTLIN_DSL_SCRIPT_NAME
if (FileUtil.findFirstThatExist(gradleGroovyDslFile, kotlinDslGradleFile) == null) return false
LOG.info("Link gradle project from root directory")
val settings = createLinkSettings(Paths.get(basePath), project)
ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).linkProject(settings)
return true
}
private fun linkGradleHintProjects(basePath: String, project: Project): Boolean {
val state = GradleImportHintService.getInstance(project).state
if (state.projectsToImport.isNotEmpty()) {
for (projectPath in state.projectsToImport) {
val buildFile = File(basePath).toPath().resolve(projectPath)
if (buildFile.toFile().exists()) {
LOG.info("Link gradle project from intellij.yaml: $projectPath")
val settings = createLinkSettings(buildFile.parent, project)
ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).linkProject(settings)
}
else {
LOG.error("File for linking gradle project doesn't exist: " + buildFile.toAbsolutePath().toString())
return false
}
}
return true
}
return false
}
private class StateExternalAnnotationNotificationListener : ExternalAnnotationsProgressNotificationListener {
private val externalAnnotationsState = ConcurrentHashMap<ExternalAnnotationsTaskId, CompletableFuture<ExternalAnnotationsTaskId>>()
override fun onStartResolve(id: ExternalAnnotationsTaskId) {
externalAnnotationsState[id] = CompletableFuture()
LOG.info("Gradle resolving external annotations started ${id.projectId}")
}
override fun onFinishResolve(id: ExternalAnnotationsTaskId) {
val feature = externalAnnotationsState[id] ?: return
feature.complete(id)
LOG.info("Gradle resolving external annotations completed ${id.projectId}")
}
fun waitForResolveExternalAnnotationEnd() {
externalAnnotationsState.values.forEach { it.get() }
}
}
class StateNotificationListener(private val project: Project) : ExternalSystemTaskNotificationListenerAdapter() {
private val externalSystemState = ConcurrentHashMap<ExternalSystemTaskId, CompletableFuture<ExternalSystemTaskId>>()
override fun onSuccess(id: ExternalSystemTaskId) {
if (!id.isGradleProjectResolveTask()) return
LOG.info("Gradle resolve success: ${id.ideProjectId}")
val connection = project.messageBus.simpleConnect()
connection.subscribe(ProjectDataImportListener.TOPIC, object : ProjectDataImportListener {
override fun onImportFinished(projectPath: String?) {
LOG.info("Gradle import success: ${id.ideProjectId}")
val future = externalSystemState[id] ?: return
future.complete(id)
}
override fun onImportFailed(projectPath: String?, t: Throwable) {
LOG.info("Gradle import failure: ${id.ideProjectId}")
val future = externalSystemState[id] ?: return
future.completeExceptionally(IllegalStateException("Gradle project ${id.ideProjectId} import failed."))
}
})
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
if (!id.isGradleProjectResolveTask()) return
LOG.error("Gradle resolve failure ${id.ideProjectId}", e)
val future = externalSystemState[id] ?: return
future.completeExceptionally(IllegalStateException("Gradle project ${id.ideProjectId} resolve failed.", e))
}
override fun onCancel(id: ExternalSystemTaskId) {
if (!id.isGradleProjectResolveTask()) return
LOG.error("Gradle resolve canceled ${id.ideProjectId}")
val future = externalSystemState[id] ?: return
future.completeExceptionally(IllegalStateException("Resolve of ${id.ideProjectId} was canceled"))
}
override fun onStart(id: ExternalSystemTaskId) {
if (!id.isGradleProjectResolveTask()) return
externalSystemState[id] = CompletableFuture()
LOG.info("Gradle project resolve started ${id.ideProjectId}")
}
fun waitForImportEnd() {
externalSystemState.values.forEach { it.get() }
}
private fun ExternalSystemTaskId.isGradleProjectResolveTask() = this.projectSystemId == GradleConstants.SYSTEM_ID &&
this.type == ExternalSystemTaskType.RESOLVE_PROJECT
}
class LoggingNotificationListener(val logger: CommandLineInspectionProgressReporter) : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
val gradleText = (if (stdOut) "" else "STDERR: ") + text
gradleLogWriter.write(gradleText)
logger.reportMessage(1, gradleText)
}
override fun onEnd(id: ExternalSystemTaskId) {
gradleLogWriter.flush()
}
}
}
|
apache-2.0
|
abf1a8a25a4b83e528eff67c9cb9691d
| 46.473934 | 138 | 0.774184 | 5.198236 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/stage/bg/Background.kt
|
2
|
2842
|
package io.github.chrislo27.rhre3.stage.bg
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import io.github.chrislo27.toolboks.registry.AssetRegistry
abstract class Background(val id: String) {
abstract fun render(camera: OrthographicCamera, batch: SpriteBatch, shapeRenderer: ShapeRenderer, delta: Float)
companion object {
data class BgData(val bg: Background, val name: String)
private val kmStripes2: BgData = BgData(KarateManStripesBackground("karateManStripes2"), "Karate Man GBA 2")
val backgroundsData: List<BgData> by lazy {
listOf(
BgData(TengokuBackground("tengoku"), "GBA Game Select"),
BgData(KarateManBackground("karateMan"), "Karate Man"),
BgData(TilingBackground("rhdsPolkaDots", 5f,
speedX = 3f, speedY = -3f, widthCoeff = 0.5f, heightCoeff = 0.5f)
{ AssetRegistry["bg_polkadot"] }, "DS Game Select"),
BgData(SpaceDanceBackground("spaceDance"), "Space Dance"),
BgData(RetroBackground("retro"), "Retro"),
BgData(TilingBackground("tapTrial", 5f, speedX = 0f, speedY = 1f) { AssetRegistry["bg_tapTrial"] }, "Tap Trial"),
BgData(TilingBackground("tiled", 5f, speedX = 1f, speedY = 1f) { AssetRegistry["bg_tile"] }, "Notes"),
BgData(LaunchPartyBackground("launchParty"), "Launch Party"),
BgData(KittiesBackground("kitties"), "Kitties!"),
BgData(SeesawBackground("seesaw"), "See-Saw"),
BgData(KarateManStripesBackground("karateManStripes1", stripe1 = Color.valueOf("FEC652"),
stripe2 = Color.valueOf("FFE86C")), "Karate Man GBA"),
kmStripes2,
BgData(BTSDSBackground("btsDS"), "Built to Scale DS"),
BgData(BTSDSBackground("btsDS2", Color.valueOf("E1E11FFF")), "Built to Scale DS 2"),
BgData(BTSDSBackground("btsDSBlue", Color.valueOf("2963FFFF")), "Built to Scale DS (Blue)")
// BgData(PolyrhythmBackground("polyrhythm"), "Polyrhythm")
)
}
val backgrounds: List<Background> by lazy { backgroundsData.map { it.bg } }
val backgroundMap: Map<String, Background> by lazy { backgrounds.associateBy(Background::id) }
val backgroundMapByBg: Map<Background, BgData> by lazy { backgroundsData.associateBy { it.bg } }
val defaultBackground: Background
get() = backgroundMap.getValue("tengoku")
}
}
|
gpl-3.0
|
ae917d4f4a8af224ef6ec9c36c1585c4
| 57.020408 | 133 | 0.605208 | 4.136827 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/multipart/RandomCueEntity.kt
|
2
|
3539
|
package io.github.chrislo27.rhre3.entity.model.multipart
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.math.Rectangle
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.entity.Entity
import io.github.chrislo27.rhre3.entity.model.ISoundDependent
import io.github.chrislo27.rhre3.entity.model.IVolumetric
import io.github.chrislo27.rhre3.entity.model.MultipartEntity
import io.github.chrislo27.rhre3.sfxdb.SFXDatabase
import io.github.chrislo27.rhre3.sfxdb.datamodel.Datamodel
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.CuePointer
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.RandomCue
import io.github.chrislo27.rhre3.theme.Theme
import io.github.chrislo27.rhre3.track.Remix
import io.github.chrislo27.toolboks.util.gdxutils.random
class RandomCueEntity(remix: Remix, datamodel: RandomCue)
: MultipartEntity<RandomCue>(remix, datamodel) {
private data class DatamodelPointer(val datamodel: Datamodel, val ptr: CuePointer)
private val possibleObjects: List<DatamodelPointer> = datamodel.cues.mapNotNull { pointer ->
SFXDatabase.data.objectMap[pointer.id]?.let { DatamodelPointer(it, pointer) }
}
private val createdEntities: List<Entity> = possibleObjects.map { it.datamodel.createEntity(remix, it.ptr.copy(beat = 0f)) }
init {
bounds.width = datamodel.cues.map(CuePointer::duration).maxOrNull() ?: error(
"RandomCue datamodel ${datamodel.id} has no internal cues")
}
private fun reroll() {
val thisSemitone = semitone
val thisVolume = volumePercent
// Set semitone and volume to zero, repopulate, and reset it so the setters in MultipartEntity take effect
semitone = 0
volumePercent = IVolumetric.DEFAULT_VOLUME
if (createdEntities.isEmpty()) {
error("No valid entities found from randomization for RandomCue ${datamodel.id}")
}
internal.clear()
internal +=
createdEntities.random().also { ent ->
ent.updateBounds {
ent.bounds.x = this.bounds.x
ent.bounds.width = this.bounds.width
ent.bounds.y = this.bounds.y
}
}
// Re-set semitone and volume so it takes effect in the internals
semitone = thisSemitone
volumePercent = thisVolume
}
override fun getRenderColor(editor: Editor, theme: Theme): Color {
return theme.entities.pattern
}
override fun onPreloadSounds() {
createdEntities
.forEach {
if (it is ISoundDependent) {
it.preloadSounds()
}
}
}
override fun onUnloadSounds() {
createdEntities
.forEach {
if (it is ISoundDependent) {
it.unloadSounds()
}
}
}
override fun updateInternalCache(oldBounds: Rectangle) {
translateInternal(oldBounds)
if (internal.isEmpty())
reroll()
}
override fun onStart() {
reroll()
super.onStart()
}
override fun copy(remix: Remix): RandomCueEntity {
return RandomCueEntity(remix, datamodel).also {
it.updateBounds {
it.bounds.set(this.bounds)
}
it.semitone = this.semitone
it.volumePercent = this.volumePercent
}
}
}
|
gpl-3.0
|
8c6f3e3754977ff0c749dda74a5fd8f0
| 33.368932 | 128 | 0.632665 | 4.258724 | false | false | false | false |
android/wear-os-samples
|
RuntimePermissionsWear/Application/src/main/java/com/example/android/wearable/runtimepermissions/IncomingRequestPhoneService.kt
|
1
|
5995
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.runtimepermissions
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import com.example.android.wearable.runtimepermissions.common.Constants
import com.google.android.gms.wearable.DataMap
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.Wearable
import com.google.android.gms.wearable.WearableListenerService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
/**
* Handles all incoming requests for phone data (and permissions) from wear devices.
*/
class IncomingRequestPhoneService : WearableListenerService() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
override fun onMessageReceived(messageEvent: MessageEvent) {
Log.d(TAG, "onMessageReceived(): $messageEvent")
// Switch to handling the message event asynchronously for any additional work
scope.launch {
handleMessageEvent(messageEvent)
}
}
private suspend fun handleMessageEvent(messageEvent: MessageEvent) {
when (messageEvent.path) {
Constants.MESSAGE_PATH_PHONE -> {
val dataMap = DataMap.fromByteArray(messageEvent.data)
when (dataMap.getInt(Constants.KEY_COMM_TYPE)) {
Constants.COMM_TYPE_REQUEST_PROMPT_PERMISSION -> {
promptUserForPhonePermission(messageEvent.sourceNodeId)
}
Constants.COMM_TYPE_REQUEST_DATA -> {
respondWithPhoneInformation(messageEvent.sourceNodeId)
}
}
}
}
}
private suspend fun promptUserForPhonePermission(nodeId: String) {
val phoneInfoPermissionApproved =
ActivityCompat.checkSelfPermission(
this,
phoneSummaryPermission
) == PackageManager.PERMISSION_GRANTED
if (phoneInfoPermissionApproved) {
sendMessage(
nodeId,
DataMap().apply {
putInt(
Constants.KEY_COMM_TYPE,
Constants.COMM_TYPE_RESPONSE_USER_APPROVED_PERMISSION
)
}
)
} else {
// Launch Phone Activity to grant phone information permissions.
startActivity(
Intent(this, MainPhoneActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
// This extra is included to alert MainPhoneActivity to send back the permission
// results after the user has made their decision in PhonePermissionRequestActivity
// and it finishes.
putExtra(
MainPhoneActivity.EXTRA_PROMPT_PERMISSION_FROM_WEAR,
true
)
}
)
}
}
private suspend fun respondWithPhoneInformation(nodeId: String) {
val phoneInfoPermissionApproved =
ActivityCompat.checkSelfPermission(this, phoneSummaryPermission) ==
PackageManager.PERMISSION_GRANTED
if (!phoneInfoPermissionApproved) {
sendMessage(
nodeId = nodeId,
dataMap = DataMap().apply {
putInt(
Constants.KEY_COMM_TYPE,
Constants.COMM_TYPE_RESPONSE_PERMISSION_REQUIRED
)
}
)
} else {
// Send valid results
sendMessage(
nodeId = nodeId,
dataMap = DataMap().apply {
putInt(
Constants.KEY_COMM_TYPE,
Constants.COMM_TYPE_RESPONSE_DATA
)
// To keep the sample simple, we are just trying to return the phone number.
putString(Constants.KEY_PAYLOAD, getPhoneSummary())
}
)
}
}
private suspend fun sendMessage(nodeId: String, dataMap: DataMap) {
Log.d(TAG, "sendMessage() Node: $nodeId")
try {
// Clients are inexpensive to create, so in this case we aren't creating member
// variables. (They are cached and shared between GoogleApi instances.)
Wearable.getMessageClient(applicationContext)
.sendMessage(
nodeId,
Constants.MESSAGE_PATH_WEAR,
dataMap.toByteArray()
)
.await()
Log.d(TAG, "Message sent successfully")
} catch (cancellationException: CancellationException) {
throw cancellationException
} catch (throwable: Throwable) {
Log.d(TAG, "Message failed.")
}
}
companion object {
private const val TAG = "IncomingRequestService"
}
}
|
apache-2.0
|
a34e3124c0f0783d743f77fb16eb2685
| 36.943038 | 103 | 0.600667 | 5.454959 | false | false | false | false |
Skatteetaten/boober
|
src/test/kotlin/no/skatteetaten/aurora/boober/feature/S3FeatureTest.kt
|
1
|
17557
|
package no.skatteetaten.aurora.boober.feature
import java.time.LocalDateTime
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.springframework.web.client.RestTemplate
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.convertValue
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.containsAll
import assertk.assertions.isEqualTo
import io.fabric8.kubernetes.api.model.Secret
import io.fabric8.openshift.api.model.DeploymentConfig
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import no.skatteetaten.aurora.boober.facade.json
import no.skatteetaten.aurora.boober.model.AuroraResource
import no.skatteetaten.aurora.boober.service.HerkimerService
import no.skatteetaten.aurora.boober.service.ResourceClaimHerkimer
import no.skatteetaten.aurora.boober.service.ResourceHerkimer
import no.skatteetaten.aurora.boober.service.ResourceKind
import no.skatteetaten.aurora.boober.service.resourceprovisioning.FionaRestTemplateWrapper
import no.skatteetaten.aurora.boober.service.resourceprovisioning.S3Provisioner
import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest
import no.skatteetaten.aurora.boober.utils.findResourcesByType
import no.skatteetaten.aurora.boober.utils.singleApplicationError
import no.skatteetaten.aurora.boober.utils.singleApplicationErrorResult
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.HttpMock
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.httpMockServer
class S3FeatureTest : AbstractFeatureTest() {
override val feature: Feature
get() = S3Feature(
s3Provisioner = s3Provisioner,
herkimerService = herkimerService,
cluster = "utv",
booberApplicationdeploymentId = booberAdId,
defaultBucketRegion = "us-east-1"
)
val booberAdId = "abc4567890"
private val s3Provisioner = S3Provisioner(
FionaRestTemplateWrapper(
restTemplate = RestTemplate(),
baseUrl = "http://localhost:5000",
retries = 0
)
)
private val herkimerService: HerkimerService = mockk()
@AfterEach
fun after() {
HttpMock.clearAllHttpMocks()
}
@Test
fun `verify is able to disable s3 when simple config`() {
generateResources(
"""{
"s3": false
}""",
createdResources = 0,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}
@Test
fun `verify is able to disable s3 when expanded config`() {
mockHerkimer(
booberAdId, true,
s3Credentials = listOf(
createS3Credentials("anotherId", "default"),
createS3Credentials("minBucket", "hello-$environment")
)
)
generateResources(
"""{
"s3": {
"not-default" : {
"enabled": false,
"bucketName": "minBucket"
},
"default" : {
"bucketName" : "anotherId"
},
"substitutor":{
"bucketName":"minBucket",
"objectArea":"hello-@env@"
}
}
}""",
createdResources = 2,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}
@Test
fun `verify two objectareas with different bucketnames`() {
val s3Credentials = listOf(
createS3Credentials(bucketName = "minBucket", objectArea = "not-default"),
createS3Credentials(bucketName = "anotherId", objectArea = "default")
)
mockHerkimer(
booberAdId = booberAdId,
claimExistsInHerkimer = true,
s3Credentials = s3Credentials
)
generateResources(
"""{
"s3": {
"not-default" : {
"bucketName": "minBucket"
},
"default" : {
"bucketName" : "anotherId"
}
}
}""",
createdResources = 2,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
).verifyS3SecretsAndEnvs(expectedBucketObjectAreas = listOf("default", "not-default"))
}
@Test
fun `verify creates secrets and supports custom bucketname suffix`() {
val s3Credentials = listOf(
createS3Credentials(),
createS3Credentials(objectArea = "min-andre-bucket")
)
mockFiona()
mockHerkimer(booberAdId = booberAdId, s3Credentials = s3Credentials, claimExistsInHerkimer = false)
val resources = generateResources(
"""{
"s3Defaults": {
"bucketName": "anotherId",
"tenant": "paas-utv"
},
"s3": {
"default": {
"enabled": true
},
"min-andre-bucket": {
"enabled": true
}
}
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig()),
createdResources = 2
)
resources.verifyS3SecretsAndEnvs(expectedBucketObjectAreas = listOf("default", "min-andre-bucket"))
}
@Test
fun `verify fails when no bucket credentials are stored in herkimer`() {
mockHerkimer(booberAdId = booberAdId, bucketIsRegisteredInHerkimer = false, claimExistsInHerkimer = false)
assertThat {
generateResources(
"""{
"s3Defaults": {
"bucketName": "anotherId",
"objectArea": "default"
},
"s3": true
}""",
createdResources = 0,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}.singleApplicationError("Could not find credentials for bucket")
}
@Test
fun `verify fails on validate when two identical objectareas in same bucket`() {
mockFiona()
val s3Credentials = listOf(
createS3Credentials(bucketName = "anotherId", objectArea = "default"),
createS3Credentials(bucketName = "anotherId", objectArea = "default")
)
mockHerkimer(booberAdId = booberAdId, claimExistsInHerkimer = true, s3Credentials = s3Credentials)
assertThat {
generateResources(
"""{
"s3": {
"default" : {
"bucketName": "bucket1"
},
"another":{
"objectArea": "default",
"bucketName": "bucket1"
}
}
}""",
createdResources = 0,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}.singleApplicationError("Duplicated objectArea=default in same bucket=bucket1")
}
@Test
fun `verify fails when tenant is not prefixed with current affiliation`() {
val s3Credentials = listOf(
createS3Credentials(bucketName = "anotherId", objectArea = "default")
)
mockHerkimer(
booberAdId = booberAdId,
claimExistsInHerkimer = true,
s3Credentials = s3Credentials
)
assertThat {
generateResources(
"""{
"s3": {
"default" : {
"bucketName" : "anotherId",
"tenant": "demo-utv"
}
}
}""",
createdResources = 0,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}.singleApplicationError("tenant must contain current affiliation=paas as a prefix, specified value was: demo-utv")
}
@Test
fun `verify fails when tenant is not on required form`() {
val s3Credentials = listOf(
createS3Credentials(bucketName = "anotherId", objectArea = "default")
)
mockHerkimer(
booberAdId = booberAdId,
claimExistsInHerkimer = true,
s3Credentials = s3Credentials
)
assertThat {
generateResources(
"""{
"s3": {
"default" : {
"bucketName" : "anotherId",
"tenant": "paas"
}
}
}""",
createdResources = 0,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
}.singleApplicationError("Config for application simple in environment utv contains errors. s3 tenant must be on the form affiliation-cluster, specified value was: \"paas\".")
}
@Test
fun `Should fail with message when s3 bucketName is missing`() {
assertThat {
createAuroraDeploymentContext(
"""{
"s3Defaults": {
"objectArea": "my-object-area"
},
"s3": true
}"""
)
}.singleApplicationErrorResult("Missing field: bucketName for s3")
}
@Test
fun `Should fail with message when s3 objectArea is not according to required format`() {
assertThat {
createAuroraDeploymentContext(
"""{
"s3Defaults": {
"objectArea": "my-object_Area",
"bucketName": "mybucket"
},
"s3": true
}"""
)
}.singleApplicationErrorResult("s3 objectArea can only contain lower case characters,")
}
@Test
fun `Should fail with message when s3 objectArea is missing`() {
assertThat {
createAuroraDeploymentContext(
"""{
"s3Defaults": {
"bucketName": "anotherId"
},
"s3": true
}"""
)
}.singleApplicationErrorResult("Missing field: objectArea for s3")
}
@Test
fun `verify creates secret with value mappings in dc when claim exists in herkimer`() {
mockFiona()
mockHerkimer(booberAdId = booberAdId, claimExistsInHerkimer = true)
val resources = generateResources(
"""{
"s3": {
"default" : {
"bucketName": "anotherId"
}
}
}""",
createdResources = 1,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
resources.verifyS3SecretsAndEnvs()
}
private fun mockFiona() {
httpMockServer(5000) {
rule {
json(
"""
{
"host": "http://fiona",
"accessKey": "accessKey",
"secretKey": "secretKey"
}
""".trimIndent()
)
}
}
}
private fun mockHerkimer(
booberAdId: String,
claimExistsInHerkimer: Boolean,
s3Credentials: List<S3Credentials> = listOf(createS3Credentials()),
bucketIsRegisteredInHerkimer: Boolean = true
) {
val adId = "1234567890"
val bucketNamesWithCredentials = s3Credentials.groupBy { it.bucketName }
val bucketNames = bucketNamesWithCredentials.keys
every {
herkimerService.getClaimedResources(booberAdId, ResourceKind.MinioPolicy)
} returns if (bucketIsRegisteredInHerkimer) {
bucketNames.map {
createResourceHerkimer(
name = it,
adId = booberAdId,
kind = ResourceKind.MinioPolicy,
claims = listOf(createResourceClaim(booberAdId))
)
}
} else emptyList()
every {
herkimerService.getClaimedResources(
claimOwnerId = adId,
resourceKind = ResourceKind.MinioObjectArea
)
} returns if (claimExistsInHerkimer) s3Credentials.map {
createS3BucketObjectAreaResourceForCredentials(
adId = adId,
s3BucketObjectAreaResourceName = "${it.bucketName}/${it.objectArea}",
credentials = it,
claimOwnerId = adId
)
} else emptyList()
if (!claimExistsInHerkimer) {
every {
herkimerService.createResourceAndClaim(any(), any(), any(), any(), any(), any())
} just Runs
}
}
private fun createS3BucketObjectAreaResourceForCredentials(
adId: String,
s3BucketObjectAreaResourceName: String,
credentials: S3Credentials,
claimOwnerId: String
): ResourceHerkimer {
return createResourceHerkimer(
adId = adId,
kind = ResourceKind.MinioObjectArea,
name = s3BucketObjectAreaResourceName,
claims = listOf(
createResourceClaim(
adId = claimOwnerId,
s3Credentials = jacksonObjectMapper().convertValue(credentials)
)
)
)
}
private fun List<AuroraResource>.verifyS3SecretsAndEnvs(expectedBucketObjectAreas: List<String> = listOf("default")) {
val secrets: List<Secret> = findResourcesByType()
secrets.forEach { secret ->
val bucketObjectArea = secret.metadata.name.substringBefore("-s3").replace("$appName-", "")
assertThat(expectedBucketObjectAreas).contains(bucketObjectArea)
assertThat(secret.data.keys).containsAll(
"serviceEndpoint",
"accessKey",
"secretKey",
"bucketRegion",
"bucketName",
"objectPrefix"
)
val dc = find { it.resource is DeploymentConfig }?.let { it.resource as DeploymentConfig }
?: throw Exception("No dc")
val container = dc.spec.template.spec.containers.first()
val secretName = "$appName-$bucketObjectArea-s3"
val bucketObjectAreaUpper = bucketObjectArea.uppercase()
val actualEnvs = container.env
.map { envVar -> envVar.name to envVar.valueFrom.secretKeyRef.let { "${it.name}/${it.key}" } }
.filter { (name, _) ->
name.startsWith("S3")
}
val expectedEnvs = listOf(
"S3_BUCKETS_${bucketObjectAreaUpper}_SERVICEENDPOINT" to "$secretName/serviceEndpoint",
"S3_BUCKETS_${bucketObjectAreaUpper}_ACCESSKEY" to "$secretName/accessKey",
"S3_BUCKETS_${bucketObjectAreaUpper}_SECRETKEY" to "$secretName/secretKey",
"S3_BUCKETS_${bucketObjectAreaUpper}_BUCKETREGION" to "$secretName/bucketRegion",
"S3_BUCKETS_${bucketObjectAreaUpper}_BUCKETNAME" to "$secretName/bucketName",
"S3_BUCKETS_${bucketObjectAreaUpper}_OBJECTPREFIX" to "$secretName/objectPrefix"
)
assertThat(actualEnvs).containsAll(*expectedEnvs.toTypedArray())
val objectAreaS3EnvVars =
actualEnvs.filter { (name, _) -> name.startsWith("S3_BUCKETS_$bucketObjectAreaUpper") }
assertThat(objectAreaS3EnvVars.size).isEqualTo(expectedEnvs.size)
}
}
private fun createS3Credentials(bucketName: String = "anotherId", objectArea: String = "default") =
S3Credentials(
objectArea,
"http://localhost",
"access",
"secret",
bucketName,
"objectprefix",
"us-east-1"
)
private fun createResourceHerkimer(
adId: String,
kind: ResourceKind,
name: String = "paas-bucket-u-default",
claims: List<ResourceClaimHerkimer> = emptyList()
) = ResourceHerkimer(
id = "0",
name = name,
kind = kind,
ownerId = adId,
claims = claims,
createdDate = LocalDateTime.now(),
modifiedDate = LocalDateTime.now(),
createdBy = "aurora",
modifiedBy = "aurora",
parentId = null
)
private fun createResourceClaim(
adId: String,
s3Credentials: JsonNode = jacksonObjectMapper().createObjectNode()
) =
ResourceClaimHerkimer(
id = "0L",
ownerId = adId,
resourceId = 0L,
credentials = s3Credentials,
name = "ADMIN",
createdDate = LocalDateTime.now(),
modifiedDate = LocalDateTime.now(),
createdBy = "aurora",
modifiedBy = "aurora"
)
}
|
apache-2.0
|
c6600365909a962b578c79c7526f4a48
| 34.397177 | 183 | 0.554138 | 5.129126 | false | false | false | false |
allotria/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/MoveDiffPreviewAction.kt
|
2
|
1855
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions.diff
import com.intellij.diff.editor.DiffContentVirtualFile
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsDataKeys.VIRTUAL_FILES
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.util.containers.JBIterable
import com.intellij.vcsUtil.VcsUtil
internal abstract class MoveDiffPreviewAction(private val openInNewWindow: Boolean) : DumbAwareAction() {
abstract fun isEnabledAndVisible(project: Project): Boolean
override fun update(e: AnActionEvent) {
val project = e.project
val file = JBIterable.from(e.getData(VIRTUAL_FILES)).single()
e.presentation.isEnabledAndVisible = project != null
&& file != null
&& file is DiffContentVirtualFile
&& isEnabledAndVisible(project)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val diffPreviewFile = VcsUtil.getVirtualFiles(e).first()
VcsEditorTabFilesManager.getInstance().openFile(project, diffPreviewFile, true, openInNewWindow, true)
}
}
internal class MoveDiffPreviewToEditorAction : MoveDiffPreviewAction(false) {
override fun isEnabledAndVisible(project: Project): Boolean = VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow
}
internal class MoveDiffPreviewToNewWindowAction : MoveDiffPreviewAction(true) {
override fun isEnabledAndVisible(project: Project): Boolean = !VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow
}
|
apache-2.0
|
a555abbf9d116a70e2340ba33d565244
| 43.166667 | 140 | 0.755256 | 4.830729 | false | false | false | false |
intellij-purescript/intellij-purescript
|
src/main/kotlin/org/purescript/features/PSPairedBraceMatcher.kt
|
1
|
953
|
package org.purescript.features
import com.intellij.lang.BracePair
import com.intellij.lang.PairedBraceMatcher
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.psi.tree.IElementType
import org.purescript.parser.*
class PSPairedBraceMatcher : PairedBraceMatcher {
override fun getPairs(): Array<BracePair> = PAIRS
override fun isPairedBracesAllowedBeforeType(
lbraceType: IElementType,
contextType: IElementType?
): Boolean {
return (contextType == null
|| contextType === WHITE_SPACE)
}
override fun getCodeConstructStart(
file: PsiFile,
openingBraceOffset: Int
): Int {
return openingBraceOffset
}
companion object {
private val PAIRS = arrayOf(
BracePair(LCURLY, RCURLY, true),
BracePair(LBRACK, RBRACK, true),
BracePair(LPAREN, RPAREN, false)
)
}
}
|
bsd-3-clause
|
6626051d0f9f74fc90678b1af168fbe8
| 26.257143 | 53 | 0.67681 | 4.495283 | false | false | false | false |
romannurik/muzei
|
muzei-api/src/main/java/com/google/android/apps/muzei/api/internal/ProtocolConstants.kt
|
2
|
2623
|
/*
* Copyright 2014 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.android.apps.muzei.api.internal
/**
* Internal intent constants for sources.
*/
public object ProtocolConstants {
private const val PREFIX = "com.google.android.apps.muzei.api."
public const val METHOD_GET_VERSION: String = PREFIX + "GET_VERSION"
public const val KEY_VERSION: String = PREFIX + "VERSION"
public const val DEFAULT_VERSION: Int = 310000
public const val METHOD_REQUEST_LOAD: String = PREFIX + "REQUEST_LOAD"
public const val METHOD_MARK_ARTWORK_INVALID: String = PREFIX + "MARK_ARTWORK_INVALID"
public const val METHOD_MARK_ARTWORK_LOADED: String = PREFIX + "MARK_ARTWORK_LOADED"
public const val METHOD_GET_LOAD_INFO: String = PREFIX + "GET_LOAD_INFO"
public const val KEY_MAX_LOADED_ARTWORK_ID: String = PREFIX + "MAX_LOADED_ARTWORK_ID"
public const val KEY_LAST_LOADED_TIME: String = PREFIX + "LAST_LOAD_TIME"
public const val KEY_RECENT_ARTWORK_IDS: String = PREFIX + "RECENT_ARTWORK_IDS"
public const val METHOD_GET_DESCRIPTION: String = PREFIX + "GET_DESCRIPTION"
public const val KEY_DESCRIPTION: String = PREFIX + "DESCRIPTION"
public const val METHOD_GET_COMMANDS: String = PREFIX + "GET_COMMANDS"
public const val GET_COMMAND_ACTIONS_MIN_VERSION: Int = 340000
public const val KEY_COMMANDS: String = PREFIX + "COMMANDS"
public const val METHOD_TRIGGER_COMMAND: String = PREFIX + "TRIGGER_COMMAND"
public const val KEY_COMMAND_AUTHORITY: String = PREFIX + "AUTHORITY"
public const val KEY_COMMAND_ARTWORK_ID: String = PREFIX + "ARTWORK_ID"
public const val KEY_COMMAND: String = PREFIX + "COMMAND"
public const val METHOD_OPEN_ARTWORK_INFO: String = PREFIX + "OPEN_ARTWORK_INFO"
public const val KEY_OPEN_ARTWORK_INFO_SUCCESS: String = PREFIX + "ARTWORK_INFO_SUCCESS"
public const val GET_ARTWORK_INFO_MIN_VERSION: Int = 320000
public const val METHOD_GET_ARTWORK_INFO: String = PREFIX + "GET_ARTWORK_INFO"
public const val KEY_GET_ARTWORK_INFO: String = PREFIX + "ARTWORK_INFO"
}
|
apache-2.0
|
590be67e429ee987a1a5bc768be6ac96
| 53.645833 | 92 | 0.728174 | 3.897474 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.