repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
youdonghai/intellij-community | platform/lang-impl/src/com/intellij/openapi/module/impl/moduleFileListener.kt | 1 | 3388 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module.impl
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.impl.storage.ClasspathStorage
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
/**
* Why this class is required if we have StorageVirtualFileTracker?
* Because StorageVirtualFileTracker doesn't detect (intentionally) parent file changes —
*
* If module file is foo/bar/hello.iml and directory foo is renamed to oof then we must update module path. And StorageVirtualFileTracker doesn't help us here (and is not going to help by intention).
*/
internal class ModuleFileListener(private val moduleManager: ModuleManagerComponent) : BulkFileListener.Adapter() {
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> propertyChanged(event)
is VFileMoveEvent -> fileMoved(event)
}
}
}
private fun propertyChanged(event: VFilePropertyChangeEvent) {
if (event.requestor is StateStorage || VirtualFile.PROP_NAME != event.propertyName) {
return
}
val parentPath = event.file.parent?.path ?: return
for (module in moduleManager.modules) {
if (!module.isLoaded) {
continue
}
val ancestorPath = "$parentPath/${event.oldValue}"
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "$parentPath/${event.newValue}/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
}
}
}
private fun fileMoved(event: VFileMoveEvent) {
if (!event.file.isDirectory) {
return
}
val dirName = event.file.nameSequence
val ancestorPath = "${event.oldParent.path}/$dirName"
for (module in moduleManager.modules) {
if (!module.isLoaded) {
continue
}
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "${event.newParent.path}/$dirName/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
}
}
}
private fun setModuleFilePath(module: Module, newFilePath: String) {
ClasspathStorage.modulePathChanged(module, newFilePath)
module.stateStore.setPath(FileUtilRt.toSystemIndependentName(newFilePath))
}
} | apache-2.0 | 105c6dee5950db7f9cfed6ec4efe6164 | 37.488636 | 199 | 0.738925 | 4.461133 | false | false | false | false |
lovehuang/RangeDownload | app/src/main/java/downloader/wxy/com/rangedownloader/DownLoadList.kt | 1 | 1086 | package downloader.wxy.com.rangedownloader
import android.content.Context
import org.json.JSONArray
/**
* Created by wangxiaoyan on 2017/8/20.
*/
// TODO 此处应该用数据库
private val PREFERENCE_NAME = "DOWNLOAD_LIST"
val SAVE_NAME = "download_list_name"
fun saveDownLoadList(context: Context, entitys: MutableList<DownLoadEntity>) {
val pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
val jsonArray = JSONArray()
entitys.forEach { jsonArray.put(it.toString()) }
pref.edit().putString(SAVE_NAME, jsonArray.toString()).apply()
}
fun getDownLoadList(context: Context): MutableList<DownLoadEntity> {
val pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
val jsonArrayString = pref.getString(SAVE_NAME, "")
var list = mutableListOf<DownLoadEntity>()
if (!jsonArrayString.isEmpty()) {
val jsonArray = JSONArray(jsonArrayString)
for (i in 0..(jsonArray.length() - 1)) {
list.add(DownLoadEntity.getEntity(jsonArray.getString(i)))
}
}
return list
} | apache-2.0 | 6604e1d824a82b028580b76ecfa79ac0 | 28.75 | 82 | 0.714019 | 3.807829 | false | false | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/scoreboard/ScoreboardActivity.kt | 1 | 3977 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.scoreboard
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sbgapps.scoreit.app.R
import com.sbgapps.scoreit.app.databinding.ActivityScoreboardBinding
import com.sbgapps.scoreit.app.databinding.DialogEditNameBinding
import com.sbgapps.scoreit.app.ui.prefs.PreferencesViewModel
import com.sbgapps.scoreit.core.ext.onImeActionDone
import com.sbgapps.scoreit.core.ui.BaseActivity
import com.sbgapps.scoreit.data.model.PlayerPosition
import io.uniflow.androidx.flow.onStates
import org.koin.androidx.viewmodel.ext.android.viewModel
class ScoreboardActivity : BaseActivity() {
private lateinit var binding: ActivityScoreboardBinding
private val scoreBoarViewModel by viewModel<ScoreBoardViewModel>()
private val prefsViewModel by viewModel<PreferencesViewModel>()
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setDefaultNightMode(prefsViewModel.getThemeMode())
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
binding = ActivityScoreboardBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.back.setOnClickListener { onBackPressed() }
bindButton(binding.minusScoreOne, -1, PlayerPosition.ONE)
bindButton(binding.plusScoreOne, +1, PlayerPosition.ONE)
bindButton(binding.minusScoreTwo, -1, PlayerPosition.TWO)
bindButton(binding.plusScoreTwo, +1, PlayerPosition.TWO)
binding.reset.setOnClickListener { scoreBoarViewModel.reset() }
binding.nameOne.setOnClickListener { displayNameDialog(PlayerPosition.ONE) }
binding.nameTwo.setOnClickListener { displayNameDialog(PlayerPosition.TWO) }
onStates(scoreBoarViewModel) { state ->
when (state) {
is Content -> {
binding.scoreOne.text = state.scoreBoard.scoreOne.toString()
binding.scoreTwo.text = state.scoreBoard.scoreTwo.toString()
binding.nameOne.text = state.scoreBoard.nameOne
binding.nameTwo.text = state.scoreBoard.nameTwo
}
}
}
}
private fun bindButton(button: MaterialButton, increment: Int, player: PlayerPosition) {
button.setOnClickListener { scoreBoarViewModel.incrementScore(increment, player) }
}
private fun displayNameDialog(position: PlayerPosition) {
val action = { name: String ->
if (name.isNotEmpty()) scoreBoarViewModel.setPlayerName(name, position)
}
val view = DialogEditNameBinding.inflate(layoutInflater)
val dialog = MaterialAlertDialogBuilder(this)
.setView(view.root)
.setPositiveButton(R.string.button_action_ok) { _, _ ->
action(view.name.text.toString())
}
.create()
view.name.apply {
requestFocus()
onImeActionDone {
action(text.toString())
dialog.dismiss()
}
}
dialog.show()
}
}
| apache-2.0 | fbcc2b63e9c8871dd1ca92ea22168cf3 | 40.416667 | 92 | 0.710765 | 4.607184 | false | false | false | false |
sakki54/RLGdx | src/main/kotlin/com/brekcel/RLGdx/console/Console.kt | 1 | 9345 | //=====Copyright 2017 Clayton Breckel=====//
package com.brekcel.RLGdx.console
import com.badlogic.gdx.graphics.Color
/** The base class of the console. Used to blit things onto the RootConsole. Has no inherit way of displaying content onto the screen. */
open class Console {
/**
* If true, checks before each set call whether or not the given coords are in bound. If true, and a given coord is out of bounds, it will just not draw it, otherwise it will naturally throw an array out of bounds exception.
* *FOR THE LOOPS ONLY*.
*/
var safe: Boolean
/** The 2d array containing all of the cells */
val cells: Array<Array<Cell>>
/** The width of the console */
val width: Int
/** The height of the console */
val height: Int
/** Range of [0,width) */
val widthRange: IntRange
/** Range of [0,height) */
val heightRange: IntRange
/**
* Creates a new console that. Used to create "subconsoles" to be copied onto the main RootConsole to draw.
* @param width The width of this console
* @param height The height of this console
* @param safe Whether or not it uses the [safe] check
*/
constructor(width: Int, height: Int, safe: Boolean) {
this.width = width
this.height = height
this.widthRange = 0 until width
this.heightRange = 0 until height
this.safe = safe
cells = Array(width, { Array(height, { Cell() }) })
}
/**
* Sets the entire console to the given Cell
* @param symbol The symbol to set the console to
* @param foreColor The Forecolor to set the console to
* @param backColor The backcolor to set the console to
*/
fun clear(symbol: Char, foreColor: Color, backColor: Color) = clear(Cell(symbol, foreColor, backColor))
/**
* Sets the entire console to the given Cell
* @param cell The Cell to set each cell to
*/
@JvmOverloads
fun clear(cell: Cell = Cell()) {
widthRange.forEach { x ->
heightRange.forEach { y ->
cells[x][y].set(cell)
}
}
}
/**
* Sets the cell from the given x,y coord to the given Cell
* @param x The x coord of the cell to be set
* @param y The y coord of the cell to be set
* @param cell The Cell to set each cell to
*/
fun set(x: Int, y: Int, cell: Cell) {
cells[x][y].set(cell)
}
/**
* Sets the cells beginning from the given x,y to the x+width and y+height coord's to the given Cell
* @param x The beginning x coord of the cells to be set
* @param y The beginning y coord of the cells to be set
* @param width The amount of cells in the x direction to be set
* @param height The amount of cells in the given y direction to be set
* @param c The character to set each cell to
* @param foreColor The ForeColor to set each cell to
* @param backColor The BackColor to set each cell to
*/
fun set(x: Int, y: Int, width: Int, height: Int, c: Char, foreColor: Color, backColor: Color) = set(x, y, width, height, Cell(c, foreColor, backColor))
/**
* Sets the cells beginning from the given x,y to the x+width and y+height coord's to the given Cell
* @param x The beginning x coord of the cells to be set
* @param y The beginning y coord of the cells to be set
* @param width The amount of cells in the x direction to be set
* @param height The amount of cells in the given y direction to be set
* @param cell The Cell to set each cell to
*/
fun set(x: Int, y: Int, width: Int, height: Int, cell: Cell) {
x.until(x + width).forEach x@ { x1 ->
if (safe && x1 > this.width)
return@x
y.until(y + height).forEach y@ { y1 ->
if (safe && y1 > this.height)
return@y
cells[x1][y1].set(cell)
}
}
}
//CHARACTER BASED SET
/**
* Sets the char at the given (x,y) coord to the given character
* @param x The x position of the cell to be changed
* @param y The y positon of the cell to be changed
* @param c The character to set
*/
fun set(x: Int, y: Int, c: Char) {
cells[x][y].char = c
}
/**
* Sets the cell's chars beginning from the given x,y to x+width,y+height coord's to the given character
* @param x The beginning x coord of the cells to be set
* @param y The beginning y coord of the cells to be set
* @param width The amount of cells in the x direction to be set
* @param height The amount of cells in the given y direction to be set
* @param c The character to set each cell to
*/
fun set(x: Int, y: Int, width: Int, height: Int, c: Char) {
x.until(x + width).forEach x@ { x1 ->
if (safe && x1 > this.width)
return@x
y.until(y + height).forEach y@ { y1 ->
if (safe && y1 > this.height)
return@y
cells[x1][y1].char = c
}
}
}
/**
* Prints a string starting at the given x,y coord
* @param x The x coord to start the message at
* @param y The y coord of the message
* @param s The String to be printed
* @param foreColor *OPTIONAL* The Forecolor to be printed
* @param backColor *OPTIONAL* The Backcolor to be printed
* @param w *OPTIONAL* The width, in chars, of the string that's printed. If w < s.length, will break after printing w chars. If w > s.length, will fill remaining chars with 0. Defaults to w = s.length.
*/
@JvmOverloads
fun print(x: Int, y: Int, s: String, foreColor: Color? = null, backColor: Color? = null, w: Int = s.length) {
0.until(w).forEach i@ { i ->
if ((safe && x + i > width) || i > w)
return@i
cells[x + i][y].char = if (i < s.length) s[i] else 0.toChar()
if (foreColor != null)
cells[x + i][y].foreColor = foreColor
if (backColor != null)
cells[x + i][y].backColor = backColor
}
}
//FORECOLOR BASED SET
/**
* Sets the ForeColor at the given (x,y) coord to the given Color
* @param x The x position of the cell to be changed
* @param y The y positon of the cell to be changed
* @param c The ForeColor to set
*/
fun setForeColor(x: Int, y: Int, c: Color) {
cells[x][y].foreColor = c.cpy()
}
/**
* Sets the cell's Forecolors beginning from the given x,y to x+width,y+height coord's to the given Color
* @param x The beginning x coord of the cells to be set
* @param y The beginning y coord of the cells to be set
* @param width The amount of cells in the x direction to be set
* @param height The amount of cells in the given y direction to be set
* @param foreColor The ForeColor to set each cell to
*/
fun setForeColor(x: Int, y: Int, width: Int, height: Int, foreColor: Color) {
x.until(x + width).forEach x@ { x1 ->
if (safe && x1 > this.width)
return@x
y.until(y + height).forEach y@ { y1 ->
if (safe && y1 > this.height)
return@y
cells[x1][y1].foreColor = foreColor
}
}
}
//BACKCOLOR BASED SET
/**
* Sets the BackColor at the given (x,y) coord to the given Color
* @param x The x position of the cell to be changed
* @param y The y positon of the cell to be changed
* @param c The BackColor to set
*/
fun setBackColor(x: Int, y: Int, c: Color) {
cells[x][y].backColor = c
}
/**
* Sets the cell's BackColor beginning from the given x,y to x+width,y+height coord's to the given Color
* @param x The beginning x coord of the cells to be set
* @param y The beginning y coord of the cells to be set
* @param width The amount of cells in the x direction to be set
* @param height The amount of cells in the given y direction to be set
* @param backColor The BackColor to set each cell to
*/
fun setBackColor(x: Int, y: Int, width: Int, height: Int, backColor: Color) {
x.until(x + width).forEach x@ { x1 ->
if (safe && x1 > this.width)
return@x
y.until(y + height).forEach y@ { y1 ->
if (safe && y1 > this.height)
return@y
cells[x1][y1].backColor = backColor
}
}
}
//BLIT
/** Blit's (<a href="https://en.wikipedia.org/wiki/Bit_blit">Bit Blit - Wikipedia</a>) this console to the given console at the destination's destX and destY coords
* Equivalent to console.blit(0, 0, console.width, console.height, destConsole,destX,destY)
* @param dest The destination console to receive the blit
* @param destX The X coord of the destination where the blit will begin
* @param destY The Y coord of the destination where the blit will begin
*/
fun blit(dest: Console, destX: Int, destY: Int) = blit(0, 0, width, height, dest, destX, destY)
/**
* Blit's (<a href="https://en.wikipedia.org/wiki/Bit_blit">Bit Blit - Wikipedia</a>) this console to the given console beginning from the Source's X,Y coords for width,height to the dest's X,Y Coords
* @param srcX The X coord of where the blit will begin from this console
* @param srcY The Y coord of where the blit will begin from this console
* @param width The number of cells to be copied in the X direction
* @param height The number of cells to be copied in the Y direction
* @param dest The destination console to receive the blit
* @param destX The X coord of the destination where the blit will begin
* @param destY The Y coord of the destination where the blit will begin
*/
fun blit(srcX: Int, srcY: Int, width: Int, height: Int, dest: Console, destX: Int, destY: Int) {
widthRange.forEach { x ->
heightRange.forEach { y ->
val dx = x + destX
val dy = y + destY
val sx = x + srcX
val sy = y + srcY
if (!safe || (dx >= 0 && dy >= 0 && dx < dest.width && dy < dest.height && sx >= 0 && sy >= 0 && sx < width && sy < height))
dest.cells[dx][dy] = cells[sx][sy]
}
}
}
} | mit | 5b2e78cbde2a390a3f0654faf57cdb41 | 35.224806 | 225 | 0.663456 | 3.226865 | false | false | false | false |
exercism/xkotlin | exercises/practice/rotational-cipher/src/test/kotlin/RotationalCipherTest.kt | 1 | 1940 | import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
class RotationalCipherTest {
@Test
fun testRotateLowercaseABy0() {
val cipher = RotationalCipher(0)
assertEquals("a", cipher.encode("a"))
}
@Ignore
@Test
fun testRotateLowercaseABy1NoWrapAround() {
val cipher = RotationalCipher(1)
assertEquals("b", cipher.encode("a"))
}
@Ignore
@Test
fun testRotateLowercaseABy26SingleWrapAround() {
val cipher = RotationalCipher(26)
assertEquals("a", cipher.encode("a"))
}
@Ignore
@Test
fun testRotateLowercaseMBy13NoWrapAround() {
val cipher = RotationalCipher(13)
assertEquals("z", cipher.encode("m"))
}
@Ignore
@Test
fun testRotateLowercaseNBy1SingleWrapAround() {
val cipher = RotationalCipher(13)
assertEquals("a", cipher.encode("n"))
}
@Ignore
@Test
fun testRotateCapitalLettersNoWrapAround() {
val cipher = RotationalCipher(5)
assertEquals("TRL", cipher.encode("OMG"))
}
@Ignore
@Test
fun testSpacesAreUnalteredByRotation() {
val cipher = RotationalCipher(5)
assertEquals("T R L", cipher.encode("O M G"))
}
@Ignore
@Test
fun testNumbersAreUnalteredByRotation() {
val cipher = RotationalCipher(4)
assertEquals("Xiwxmrk 1 2 3 xiwxmrk", cipher.encode("Testing 1 2 3 testing"))
}
@Ignore
@Test
fun testPunctuationIsUnalteredByRotation() {
val cipher = RotationalCipher(21)
assertEquals("Gzo'n zvo, Bmviyhv!", cipher.encode("Let's eat, Grandma!"))
}
@Ignore
@Test
fun testAllLettersRotateCorrectly() {
val cipher = RotationalCipher(13)
assertEquals(
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt.",
cipher.encode("The quick brown fox jumps over the lazy dog."))
}
}
| mit | c87e98d435fc44043187b8ccdf78a6da | 23.871795 | 85 | 0.625258 | 3.895582 | false | true | false | false |
vvv1559/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/server/JUnitServerImpl.kt | 1 | 6730 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.server
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.apache.log4j.Logger
import java.io.InvalidClassException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.ServerSocket
import java.net.Socket
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
class JUnitServerImpl: JUnitServer {
private val SEND_THREAD = "JUnit Server Send Thread"
private val RECEIVE_THREAD = "JUnit Server Receive Thread"
private val postingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val receivingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val handlers: ArrayList<ServerHandler> = ArrayList()
private var failHandler: ((Throwable) -> Unit)? = null
private val LOG = Logger.getLogger("#com.intellij.testGuiFramework.remote.server.JUnitServerImpl")
private val serverSocket = ServerSocket(0)
lateinit private var serverSendThread: ServerSendThread
lateinit private var serverReceiveThread: ServerReceiveThread
lateinit private var connection: Socket
lateinit private var objectInputStream: ObjectInputStream
lateinit private var objectOutputStream: ObjectOutputStream
private val port: Int
init {
port = serverSocket.localPort
serverSocket.soTimeout = 180000
}
override fun start() {
execOnParallelThread {
try {
connection = serverSocket.accept()
LOG.info("Server accepted client on port: ${connection.port}")
objectOutputStream = ObjectOutputStream(connection.getOutputStream())
serverSendThread = ServerSendThread(connection, objectOutputStream)
serverSendThread.start()
objectInputStream = ObjectInputStream(connection.getInputStream())
serverReceiveThread = ServerReceiveThread(connection, objectInputStream)
serverReceiveThread.start()
} catch (e: Exception) {
failHandler?.invoke(e)
}
}
}
override fun send(message: TransportMessage) {
postingMessages.put(message)
LOG.info("Add message to send pool: $message ")
}
override fun receive(): TransportMessage =
receivingMessages.take()
override fun sendAndWaitAnswer(message: TransportMessage)
= sendAndWaitAnswerBase(message)
override fun sendAndWaitAnswer(message: TransportMessage, timeout: Long, timeUnit: TimeUnit)
= sendAndWaitAnswerBase(message, timeout, timeUnit)
fun sendAndWaitAnswerBase(message: TransportMessage, timeout: Long = 0L, timeUnit: TimeUnit = TimeUnit.SECONDS): Unit {
val countDownLatch = CountDownLatch(1)
val waitHandler = createCallbackServerHandler({ countDownLatch.countDown() }, message.id)
addHandler(waitHandler)
send(message)
if (timeout == 0L)
countDownLatch.await()
else
countDownLatch.await(timeout, timeUnit)
removeHandler(waitHandler)
}
override fun addHandler(serverHandler: ServerHandler) {
handlers.add(serverHandler)
}
override fun removeHandler(serverHandler: ServerHandler) {
handlers.remove(serverHandler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun setFailHandler(failHandler: (Throwable) -> Unit) {
this.failHandler = failHandler
}
override fun isConnected(): Boolean {
try {
return connection.isConnected
} catch (lateInitException: UninitializedPropertyAccessException) {
return false
}
}
override fun getPort() = port
override fun stopServer() {
serverSendThread.objectOutputStream.close()
LOG.info("Object output stream closed")
serverSendThread.interrupt()
LOG.info("Server Send Thread joined")
serverReceiveThread.objectInputStream.close()
LOG.info("Object input stream closed")
serverReceiveThread.interrupt()
LOG.info("Server Receive Thread joined")
connection.close()
}
private fun execOnParallelThread(body: () -> Unit) {
(object: Thread("JUnitServer: Exec On Parallel Thread") { override fun run() { body(); Thread.currentThread().join() } }).start()
}
private fun createCallbackServerHandler(handler: (TransportMessage) -> Unit, id: Long)
= object : ServerHandler() {
override fun acceptObject(message: TransportMessage) = message.id == id
override fun handleObject(message: TransportMessage) { handler(message) }
}
inner class ServerSendThread(val connection: Socket, val objectOutputStream: ObjectOutputStream) : Thread(SEND_THREAD) {
override fun run() {
LOG.info("Server Send Thread started")
try {
while (connection.isConnected) {
val message = postingMessages.take()
LOG.info("Sending message: $message ")
objectOutputStream.writeObject(message)
}
}
catch(e: InterruptedException) {
Thread.currentThread().interrupt()
}
catch (e: Exception) {
if (e is InvalidClassException) LOG.error("Probably client is down:", e)
failHandler?.invoke(e)
}
finally {
objectOutputStream.close()
}
}
}
inner class ServerReceiveThread(val connection: Socket, val objectInputStream: ObjectInputStream) : Thread(RECEIVE_THREAD) {
override fun run() {
try {
LOG.info("Server Receive Thread started")
while (connection.isConnected) {
val obj = objectInputStream.readObject()
LOG.info("Receiving message: $obj")
assert(obj is TransportMessage)
val message = obj as TransportMessage
receivingMessages.put(message)
val copied: Array<ServerHandler> = handlers.toTypedArray().copyOf()
copied
.filter { it.acceptObject(message) }
.forEach { it.handleObject(message) }
}
} catch (e: Exception) {
if (e is InvalidClassException) LOG.error("Probably serialization error:", e)
failHandler?.invoke(e)
}
}
}
} | apache-2.0 | 2ed2291a976c759d45514e5428e3147e | 32.487562 | 133 | 0.715305 | 4.81402 | false | false | false | false |
customerly/Customerly-Android-SDK | customerly-android-sdk/src/main/java/io/customerly/activity/chat/ClyChatViewHolder.kt | 1 | 55886 | package io.customerly.activity.chat
/*
* Copyright (C) 2017 Customerly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.DatePickerDialog
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.util.Patterns
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import io.customerly.Customerly
import io.customerly.R
import io.customerly.activity.fullscreen.startClyFullScreenImageActivity
import io.customerly.activity.startClyWebViewActivity
import io.customerly.api.ClyApiRequest
import io.customerly.api.ClyApiResponse
import io.customerly.api.ENDPOINT_FORM_ATTRIBUTE
import io.customerly.api.ENDPOINT_PING
import io.customerly.entity.chat.ClyMessage
import io.customerly.entity.iamAnonymous
import io.customerly.entity.iamUser
import io.customerly.entity.ping.ClyFormCast
import io.customerly.entity.ping.ClyFormDetails
import io.customerly.entity.urlImageAccount
import io.customerly.sxdependencies.*
import io.customerly.sxdependencies.annotations.SXIntRange
import io.customerly.sxdependencies.annotations.SXLayoutRes
import io.customerly.utils.download.imagehandler.ClyImageRequest
import io.customerly.utils.ggkext.*
import io.customerly.utils.shortDateFomatter
import kotlinx.android.synthetic.main.io_customerly__li_bubble_accountinfos.view.*
import java.text.DecimalFormat
import java.util.*
/**
* Created by Gianni on 24/04/18.
* Project: Customerly-KAndroid-SDK
*/
@MSTimestamp private const val TYPING_DOTS_SPEED = 500L
internal sealed class ClyChatViewHolder (
recyclerView: SXRecyclerView,
@SXLayoutRes layoutRes: Int,
@SXIntRange(from = 1, to = Long.MAX_VALUE) iconResId: Int = R.id.io_customerly__icon)
: SXRecyclerViewViewHolder(recyclerView.activity!!.inflater().inflate(layoutRes, recyclerView, false)) {
val icon: ImageView? = this.itemView.findViewById(iconResId)
internal open fun onViewRecycled() {}
internal sealed class Bubble(recyclerView: SXRecyclerView, @SXLayoutRes layoutRes: Int,
@SXIntRange(from = 1, to = Long.MAX_VALUE) contentResId: Int = R.id.io_customerly__content
) : ClyChatViewHolder(recyclerView = recyclerView, layoutRes = layoutRes) {
val content: TextView = this.itemView.findViewById<TextView>(contentResId).apply { this.movementMethod = LinkMovementMethod.getInstance() }
protected val iconSize = recyclerView.resources.getDimensionPixelSize(R.dimen.io_customerly__chat_li_icon_size).also { iconSize ->
this.icon?.layoutParams?.also {
it.height = iconSize
it.width = iconSize
}
}
abstract fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean)
internal class Typing(recyclerView: SXRecyclerView): ClyChatViewHolder.Bubble(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_account_typing) {
init {
val weakContentTv = this.content.weak()
object : Runnable {
override fun run() {
weakContentTv.get()?.also { tv ->
tv.text = when (tv.text.toString()) {
". " -> ". . "
". . " -> ". . ."
else /* "" or ". . ." */ -> ". "
}
tv.postInvalidate()
tv.postDelayed(this, TYPING_DOTS_SPEED)
}
}
}.run()
}
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
val typingAccountID = chatActivity.typingAccountId
this.content.text = ". "
this.icon?.also { icon ->
icon.visibility = if (isFirstMessageOfSender && typingAccountID != TYPING_NO_ONE) {
ClyImageRequest(context = chatActivity, url = urlImageAccount(accountId = typingAccountID, sizePX = this.iconSize, name = chatActivity.typingAccountName))
.fitCenter()
.transformCircle()
.resize(width = this.iconSize)
.placeholder(placeholder = R.drawable.io_customerly__ic_default_admin)
.into(imageView = icon)
.start()
View.VISIBLE
} else {
View.INVISIBLE
}
}
}
}
internal sealed class Message(
recyclerView: SXRecyclerView,
@SXLayoutRes layoutRes: Int,
val sendingProgressBarResId: Int = 0,
val pendingMessageResId: Int = 0,
@SXIntRange(from = 1, to = Long.MAX_VALUE) attachmentLayoutResId: Int = R.id.io_customerly__attachment_layout,
@SXIntRange(from = 1, to = Long.MAX_VALUE) dateResId: Int = R.id.io_customerly__date,
@SXIntRange(from = 1, to = Long.MAX_VALUE) timeResId: Int = R.id.io_customerly__time,
@SXIntRange(from = 1, to = Long.MAX_VALUE) val iconAttachment: Int
) : ClyChatViewHolder.Bubble(recyclerView = recyclerView, layoutRes = layoutRes) {
private val attachmentLayout: LinearLayout? = this.itemView.findViewById(attachmentLayoutResId)
private var sendingProgressBar: View? = null
private var pendingMessageLabel: View? = null
private val date: TextView = this.itemView.findViewById(dateResId)
private val time: TextView? = this.itemView.findViewById(timeResId)
private fun progressBarVisibility(show: Boolean) {
when(show) {
true -> {
if(this.sendingProgressBar == null) {
this.sendingProgressBar = this.itemView.findViewById(this.sendingProgressBarResId)
}
this.sendingProgressBar?.visibility = View.VISIBLE
}
false -> {
this.sendingProgressBar?.visibility = View.GONE
}
}
}
private fun pendingMessageLabelVisibility(show: Boolean) {
when(show) {
true -> {
if(this.pendingMessageLabel == null) {
this.pendingMessageLabel = this.itemView.findViewById(this.pendingMessageResId)
}
this.pendingMessageLabel?.visibility = View.VISIBLE
}
false -> {
this.pendingMessageLabel?.visibility = View.GONE
}
}
}
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
if(message == null) {
//Always != null for this ViewHolder
this.icon?.visibility = View.INVISIBLE
this.content.apply {
this.text = null
this.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
this.setOnClickListener(null)
}
this.progressBarVisibility(show = false)
this.pendingMessageLabelVisibility(show = false)
this.itemView.setOnClickListener(null)
this.attachmentLayout?.apply {
this.removeAllViews()
this.visibility = View.GONE
}
return
}
//assert(message != null)
this.date.visibility = dateToDisplay?.let {
this.date.text = it
View.VISIBLE
} ?: View.GONE
this.time?.apply {
if(message.writer.isBot) {
this.visibility = View.GONE
} else {
this.text = message.timeString
this.visibility = View.VISIBLE
}
}
this.icon?.also { icon ->
icon.visibility = if (isFirstMessageOfSender) {
message.writer.loadUrl(into = icon, sizePx = this.iconSize)
View.VISIBLE
} else {
View.INVISIBLE
}
}
if (message.content.isNotEmpty()) {
this.content.text = message.getContentSpanned(tv = this.content, pImageClickableSpan = { activity, imageUrl -> activity.startClyFullScreenImageActivity(imageUrl = imageUrl) })
this.content.visibility = View.VISIBLE
} else {
this.onEmptyContent()
}
if(message.isStateFailed) {
this.content.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.io_customerly__ic_error, 0)
this.content.visibility = View.VISIBLE
({ v : View ->
Customerly.checkConfigured {
message.setStateSending()
(v.activity as? ClyChatActivity)?.let {
it.notifyItemChangedInList(message = message)
it.startSendMessageRequest(message = message)
}
}
}).also {
this.content.setOnClickListener(it)
this.itemView.setOnClickListener(it)
}
} else {
this.content.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
this.content.setOnClickListener(null)
this.itemView.setOnClickListener(null)
}
this.progressBarVisibility(show = message.isStateSending)
this.pendingMessageLabelVisibility(show = message.isStatePending)
this.attachmentLayout?.also { attachmentLayout ->
attachmentLayout.removeAllViews()
attachmentLayout.visibility = if(message.attachments.isNotEmpty()) {
message.attachments.forEach { attachment ->
val ll = LinearLayout(chatActivity).apply {
layoutParams = SXRecyclerViewLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
orientation = LinearLayout.VERTICAL
gravity = Gravity.CENTER_HORIZONTAL
minimumWidth = 150.dp2px
}
val iv = ImageView(chatActivity)
when {
attachment.isImage() -> {
//Image attachment
iv.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 80.dp2px)
val path = attachment.path
if(path?.isNotEmpty() == true) {
ClyImageRequest(context = chatActivity, url = path)
.centerCrop()
.placeholder(placeholder = R.drawable.io_customerly__pic_placeholder)
.into(imageView = iv)
.start()
ll.setOnClickListener { it.activity?.startClyFullScreenImageActivity(imageUrl = path) }
} else {
iv.scaleType = ImageView.ScaleType.CENTER_CROP
try {
attachment.loadBase64FromMemory(context = chatActivity)?.let { Base64.decode(it, Base64.DEFAULT) }?.also {
iv.setImageBitmap(BitmapFactory.decodeByteArray(it, 0, it.size))
} ?: iv.setImageResource(R.drawable.io_customerly__pic_placeholder)
} catch (outOfMemoryError: OutOfMemoryError) {
iv.setImageResource(R.drawable.io_customerly__pic_placeholder)
}
}
}
else -> {
ll.setBackgroundResource(if (message.writer.isUser) R.drawable.io_customerly__attachmentfile_border_user else R.drawable.io_customerly__attachmentfile_border_account)
ll.setPadding(10.dp2px, 0, 10.dp2px, 10.dp2px)
iv.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 40.dp2px)
iv.setPadding(0, 15.dp2px, 0, 0)
iv.setImageResource(this.iconAttachment)
val name = attachment.name
val path = attachment.path
val weakChatActivity = chatActivity.weak()
if(path?.isNotEmpty() == true) {
ll.setOnClickListener {
SXAlertDialogBuilder(chatActivity)
.setTitle(R.string.io_customerly__download)
.setMessage(R.string.io_customerly__download_the_file_)
.setPositiveButton(android.R.string.ok) { _, _ -> weakChatActivity.get()?.startAttachmentDownload(name, path) }
.setNegativeButton(android.R.string.cancel, null)
.setCancelable(true)
.show()
}
}
}
}
val tv = TextView(chatActivity).apply {
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
setTextColor(SXContextCompat.getColorStateList(chatActivity, if (message.writer.isUser) R.color.io_customerly__textcolor_white_grey else R.color.io_customerly__textcolor_malibu_grey))
setLines(1)
setSingleLine()
ellipsize = TextUtils.TruncateAt.MIDDLE
text = attachment.name
setPadding(0, 10.dp2px, 0, 0)
setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)
}
this.attachmentLayout.addView(ll.apply {
this.addView(iv)
this.addView(tv)
})
(ll.layoutParams as LinearLayout.LayoutParams).topMargin = 10.dp2px
}
View.VISIBLE
} else {
View.GONE
}
}
}
internal open fun onEmptyContent() {
this.content.apply {
text = null
visibility = View.GONE
}
}
internal class User(recyclerView: SXRecyclerView)
: Message(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_user, sendingProgressBarResId = R.id.io_customerly__content_sending_progressspinner,
pendingMessageResId = R.id.io_customerly__pending_message_label, iconAttachment = R.drawable.io_customerly__ic_attach_user) {
init {
(this.itemView.findViewById<View>(R.id.bubble).background as? GradientDrawable)?.setColor(Customerly.lastPing.widgetColor)
}
}
internal sealed class Account(recyclerView: SXRecyclerView, @SXLayoutRes layoutRes: Int)
: Message(recyclerView = recyclerView, layoutRes = layoutRes, iconAttachment = R.drawable.io_customerly__ic_attach_account_40dp) {
internal class Text(recyclerView: SXRecyclerView) : Account(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_account_text) {
private val accountName: TextView = this.itemView.findViewById(R.id.io_customerly__name)
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = isFirstMessageOfSender)
this.accountName.visibility = message?.takeIf { isFirstMessageOfSender }?.writer?.getName(context = chatActivity)?.takeIf { it.isNotEmpty() }?.let {
this.accountName.text = it
View.VISIBLE
} ?: View.GONE
}
}
internal class Rich(recyclerView: SXRecyclerView) : Account(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_account_rich) {
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = isFirstMessageOfSender)
this.content.setText(Customerly.currentUser.email?.let { R.string.io_customerly__rich_message_text_via_email } ?: R.string.io_customerly__rich_message_text_no_email)
({ v : View -> message?.richMailLink?.let { v.activity?.startClyWebViewActivity(targetUrl = it) } ?: Unit }
).also {
this.content.setOnClickListener(it)
this.itemView.setOnClickListener(it)
}
}
override fun onEmptyContent() {}
}
}
internal sealed class Bot(recyclerView: SXRecyclerView, @SXLayoutRes layoutRes: Int)
: Message(recyclerView = recyclerView, layoutRes = layoutRes, iconAttachment = R.drawable.io_customerly__ic_attach_account_40dp) {
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = true)
}
internal class Text(recyclerView: SXRecyclerView)
: Bot(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_bot_text)
internal sealed class Form(recyclerView: SXRecyclerView, @SXLayoutRes layoutRes: Int, @SXIntRange(from = 1, to = Long.MAX_VALUE) privacyPolicyResId: Int = R.id.io_customerly__botform_privacy_policy)
: Bot(recyclerView = recyclerView, layoutRes = layoutRes) {
private val privacyPolicy: TextView = this.itemView.findViewById(privacyPolicyResId)
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = true)
val privacyUrl = Customerly.lastPing.privacyUrl
if(privacyUrl?.isNotEmpty() == true && !Customerly.currentUser.privacyPolicyAlreadyChecked()) {
this.privacyPolicy.also { policy ->
policy.setOnClickListener {
it.activity?.startClyWebViewActivity(targetUrl = privacyUrl, showClearInsteadOfBack = true)
}
val textIAccept = policy.context.getString(R.string.io_customerly__i_accept_the_)
val textPrivacyPolicy = policy.context.getString(R.string.io_customerly__privacy_policy)
policy.text = SpannableString(textIAccept + textPrivacyPolicy).apply {
this.setSpan(
ForegroundColorSpan(Color.parseColor("#38b9ff")),
textIAccept.length,
textIAccept.length + textPrivacyPolicy.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
policy.visibility = View.VISIBLE
}
} else {
this.privacyPolicy.visibility = View.GONE
}
}
internal class Profiling(recyclerView: SXRecyclerView)
: Bot.Form(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_bot_profilingform) {
private val containerInput: LinearLayout = this.itemView.findViewById(R.id.io_customerly__profilingform_container_input)
private val formInputInput: EditText = this.containerInput.findViewById(R.id.io_customerly__profilingform_input)
private val formInputSubmit: ImageButton = this.containerInput.findViewById(R.id.io_customerly__profilingform_button_submit_input)
private val containerTruefalse: LinearLayout = this.itemView.findViewById(R.id.io_customerly__profilingform_container_truefalse)
private val containerDate: LinearLayout = this.itemView.findViewById(R.id.io_customerly__profilingform_container_date)
private val sendingSpinner: View = this.itemView.findViewById(R.id.io_customerly__content_sending_progressspinner)
init {
this.formInputInput.apply {
this.addTextChangedListener(object : TextWatcher {
val weakBotVH = [email protected]()
override fun afterTextChanged(s: Editable?) {
this.weakBotVH.get()?.currentForm?.apply {
this.answer = when (this.cast) {
ClyFormCast.NUMERIC -> s?.toString()?.toDoubleOrNull()
ClyFormCast.STRING -> s?.toString()
else -> null
}
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
})
}
val weakBotForm = this.weak()
this.formInputSubmit.setOnClickListener { btnSendInput ->
weakBotForm.reference { vh ->
val form = vh.currentForm
if (form?.answer != null && ((form.answer as? String)?.isEmpty() != true)) {
btnSendInput.dismissKeyboard()
btnSendInput.isEnabled = false
vh.formInputInput.apply {
this.isEnabled = false
this.isFocusable = false
this.isFocusableInTouchMode = false
this.clearFocus()
}
form.answerConfirmed = true
vh.sendingSpinner.visibility = View.VISIBLE
form.sendAnswer(chatActivity = btnSendInput.activity as? ClyChatActivity) {
weakBotForm.get()?.sendingSpinner?.visibility = View.GONE
}
}
}
}
}
private var currentForm: ClyFormDetails? = null
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = true)
if(message is ClyMessage.Bot.Form.Profiling) {
val form = message.form
this.currentForm = form
when (form.cast) {
ClyFormCast.STRING, ClyFormCast.NUMERIC -> {
this.containerTruefalse.visibility = View.GONE
this.containerDate.visibility = View.GONE
this.containerInput.visibility = View.VISIBLE
this.formInputInput.also { inputEditText ->
when (form.cast) {
ClyFormCast.NUMERIC -> {
inputEditText.inputType = InputType.TYPE_CLASS_NUMBER
inputEditText.setText((form.answer as? Double)?.let {
DecimalFormat("#################.################").format(it)
})
}
else /* ClyFormCast.STRING */ -> {
inputEditText.inputType = InputType.TYPE_CLASS_TEXT
inputEditText.setText(form.answer as? String)
}
}
inputEditText.hint = form.hint
inputEditText.isEnabled = !form.answerConfirmed
inputEditText.isFocusable = !form.answerConfirmed
inputEditText.isFocusableInTouchMode = !form.answerConfirmed
this.formInputSubmit.isEnabled = !form.answerConfirmed
}
}
ClyFormCast.DATE -> {
this.containerTruefalse.visibility = View.GONE
this.containerInput.visibility = View.GONE
this.formInputInput.also { inputEditText ->
inputEditText.isEnabled = false
inputEditText.isFocusable = false
inputEditText.isFocusableInTouchMode = false
inputEditText.clearFocus()
}
this.containerDate.visibility = View.VISIBLE
if (!form.answerConfirmed) {
this.containerDate.findViewById<TextView>(R.id.io_customerly__profilingform_date).apply {
this.hint = form.hint?.takeIf { it.isNotEmpty() } ?: "--/--/----"
this.text = (form.answer as? Long)?.nullOnException { shortDateFomatter?.format(it.asDate) }
this.setOnClickListener {
val now = Calendar.getInstance().apply {
(form.answer as? Long)?.also { answer ->
this.timeInMillis = answer
}
}
DatePickerDialog(it.context,
DatePickerDialog.OnDateSetListener { _, year, month, day ->
(it.parent as? View)?.findViewById<TextView>(R.id.io_customerly__profilingform_date)?.apply {
this.text = Calendar.getInstance().apply {
this.set(Calendar.YEAR, year)
this.set(Calendar.MONTH, month)
this.set(Calendar.DAY_OF_MONTH, day)
}.time.nullOnException { date ->
form.answer = date.time
shortDateFomatter?.format(date)
}
}
},
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)).show()
}
}
this.containerDate.findViewById<View>(R.id.io_customerly__profilingform_button_submit_date).apply {
this.isEnabled = true
val weakSendingSpinner = sendingSpinner.weak()
this.setOnClickListener { submitDate ->
if (form.answer != null) {
(submitDate.parent as? View)?.findViewById<TextView>(R.id.io_customerly__profilingform_date)?.apply {
this.isEnabled = false
submitDate.isEnabled = false
form.answerConfirmed = true
weakSendingSpinner.get()?.visibility = View.VISIBLE
form.sendAnswer(chatActivity = this.activity as? ClyChatActivity) {
weakSendingSpinner.get()?.visibility = View.GONE
}
}
}
}
}
} else {
this.containerDate.findViewById<TextView>(R.id.io_customerly__profilingform_date).apply {
this.hint = form.hint?.takeIf { it.isNotEmpty() } ?: "--/--/----"
this.isEnabled = false
this.text = (form.answer as? Long)?.nullOnException { shortDateFomatter?.format(it.asDate) }
}
this.containerDate.findViewById<View>(R.id.io_customerly__profilingform_button_submit_date).isEnabled = false
}
}
ClyFormCast.BOOL -> {
this.containerDate.visibility = View.GONE
this.containerInput.visibility = View.GONE
this.formInputInput.also { inputEditText ->
inputEditText.isEnabled = false
inputEditText.isFocusable = false
inputEditText.isFocusableInTouchMode = false
inputEditText.clearFocus()
}
this.containerTruefalse.visibility = View.VISIBLE
this.containerTruefalse.findViewById<View>(R.id.io_customerly__profilingform_button_true).isSelected = form.answer == true
this.containerTruefalse.findViewById<View>(R.id.io_customerly__profilingform_button_false).isSelected = form.answer == false
val weakSendingSpinner = this.sendingSpinner.weak()
this.containerTruefalse.findViewById<View>(R.id.io_customerly__profilingform_button_true).setOnClickListener { btnTrue ->
btnTrue.isSelected = true
(btnTrue.parent as? View)?.findViewById<View>(R.id.io_customerly__profilingform_button_false)?.isSelected = false
form.answer = true
form.answerConfirmed = true
weakSendingSpinner.get()?.visibility = View.VISIBLE
form.sendAnswer(chatActivity = btnTrue.activity as? ClyChatActivity) {
weakSendingSpinner.get()?.visibility = View.GONE
}
}
this.containerTruefalse.findViewById<View>(R.id.io_customerly__profilingform_button_false).setOnClickListener { btnFalse ->
btnFalse.isSelected = true
(btnFalse.parent as? View)?.findViewById<View>(R.id.io_customerly__profilingform_button_true)?.isSelected = false
form.answer = false
form.answerConfirmed = true
weakSendingSpinner.get()?.visibility = View.VISIBLE
form.sendAnswer(chatActivity = btnFalse.activity as? ClyChatActivity) {
weakSendingSpinner.get()?.visibility = View.GONE
}
}
}
}
} else {
this.currentForm = null
this.containerTruefalse.visibility = View.GONE
this.containerDate.visibility = View.GONE
this.containerInput.visibility = View.GONE
}
}
}
internal class AskEmail(recyclerView: SXRecyclerView)
: Bot.Form(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_bot_askemail) {
private val input: EditText = this.itemView.findViewById(R.id.io_customerly__askemail_input)
private val submit: View = this.itemView.findViewById(R.id.io_customerly__askemail_submit)
private val sendingSpinner: View = this.itemView.findViewById(R.id.io_customerly__content_sending_progressspinner)
private var pendingMessage: ClyMessage.Human.UserLocal? = null
init {
val weakInput = this.input.weak()
val weakSendingSpinner = this.sendingSpinner.weak()
this.submit.setOnClickListener { btn ->
val weakActivity = btn.activity?.weak()
val weakSubmit = btn.weak()
weakInput.get()?.let { input ->
val email = input.text.toString().trim().toLowerCase(Locale.ITALY)
if (Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
btn.dismissKeyboard()
weakSendingSpinner.get()?.visibility = View.VISIBLE
if(Customerly.iamAnonymous()) {
ClyApiRequest(
context = input.context,
endpoint = ENDPOINT_PING,
jsonObjectConverter = { Unit },
callback = { response ->
weakSendingSpinner.get()?.visibility = View.GONE
weakInput.get()?.apply {
this.isEnabled = false
this.isFocusable = false
this.isFocusableInTouchMode = false
this.clearFocus()
}
weakSubmit.get()?.isEnabled = false
this.pendingMessage?.also { pendingMessage ->
Customerly.jwtToken?.userID?.apply { pendingMessage.writer.id = this }
pendingMessage.setStateSending()
(weakActivity?.get() as? ClyChatActivity)?.notifyItemChangedInList(message = pendingMessage)
when (response) {
is ClyApiResponse.Success -> {
(weakActivity?.get() as? ClyChatActivity)?.startSendMessageRequest(message = pendingMessage)
}
is ClyApiResponse.Failure -> {
weakInput.reference { input ->
if (input.tag == null) {
input.tag = Unit
val originalColor = input.textColors.defaultColor
input.setTextColor(Color.RED)
input.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
weakInput.reference {
it.setTextColor(originalColor)
it.removeTextChangedListener(this)
it.tag = null
}
}
})
}
}
}
}
}
})
.p(key = "lead_email", value = email)
.start()
} else {
ClyApiRequest(
context = input.context,
endpoint = ENDPOINT_FORM_ATTRIBUTE,
jsonObjectConverter = { jo -> jo },
callback = { response ->
weakSendingSpinner.get()?.visibility = View.GONE
weakInput.get()?.apply {
this.isEnabled = false
this.isFocusable = false
this.isFocusableInTouchMode = false
this.clearFocus()
}
weakSubmit.get()?.isEnabled = false
when (response) {
is ClyApiResponse.Success -> {
Customerly.clySocket.sendAttributeSet(name = "email", value = email, cast = ClyFormCast.STRING, userData = response.result)
Customerly.currentUser.updateUser(
isUser = Customerly.iamUser(),
contactEmail = email,
contactName = response.result.optJSONObject("data")?.optTyped<String>(name = "name"),
userId = response.result.optJSONObject("data")?.optTyped<String>(name = "user_id"))
(weakActivity?.get() as? ClyChatActivity)?.tryLoadForm()
}
is ClyApiResponse.Failure -> {
weakInput.reference { input ->
if (input.tag == null) {
input.tag = Unit
val originalColor = input.textColors.defaultColor
input.setTextColor(Color.RED)
input.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
weakInput.reference {
it.setTextColor(originalColor)
it.removeTextChangedListener(this)
it.tag = null
}
}
})
}
}
}
}
})
.p(key = "name", value = "email")
.p(key = "value", value = email)
.start()
}
} else {
if (input.tag == null) {
input.tag = Unit
val originalColor = input.textColors.defaultColor
input.setTextColor(Color.RED)
input.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
weakInput.reference {
it.setTextColor(originalColor)
it.removeTextChangedListener(this)
it.tag = null
}
}
})
}
}
}
}
}
override fun apply(chatActivity: ClyChatActivity, message: ClyMessage?, dateToDisplay: String?, isFirstMessageOfSender: Boolean) {
super.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = true)
this.pendingMessage = (message as? ClyMessage.Bot.Form.AskEmail)?.pendingMessage
this.itemView.findViewById<TextView>(R.id.io_customerly__title)?.also { title ->
if (this.pendingMessage != null) {
title.setText(R.string.io_customerly__botaskemail_title)
title.setTypeface(null, Typeface.BOLD)
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
} else {
title.setText(R.string.io_customerly__botaskemail_title_nopending)
title.setTypeface(null, Typeface.NORMAL)
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
}
}
( Customerly.currentUser.email?.let { it to false } ?: null to true )
.also { (email,formEnabled) ->
this.input.isEnabled = formEnabled
this.input.isFocusable = formEnabled
this.input.isFocusableInTouchMode = formEnabled
this.submit.isEnabled = formEnabled
this.input.setText(email)
}
}
}
}
}
}
}
internal class AccountInfos(recyclerView: SXRecyclerView)
: ClyChatViewHolder(recyclerView = recyclerView, layoutRes = R.layout.io_customerly__li_bubble_accountinfos) {
init {
(this.itemView as? SXCardView)?.apply {
this.setCardBackgroundColor(Color.WHITE)
this.radius = 5f.dp2px
this.cardElevation = 5f.dp2px
}
}
fun apply(chatActivity: ClyChatActivity) {
val clyAdminFull = chatActivity.conversationFullAdmin
if(clyAdminFull != null) {
this.itemView.io_customerly__cardaccount_job.apply {
this.visibility = clyAdminFull.jobTitle?.let { jobTitle ->
this.text = jobTitle
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_motto.apply {
this.visibility = clyAdminFull.description?.let { description ->
this.text = description
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_location_layout.apply {
this.visibility = clyAdminFull.location?.let { location ->
this.io_customerly__cardaccount_location.text = location
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_fb.apply {
this.visibility = clyAdminFull.socialProfileFacebook?.let { fbUrl ->
this.setOnClickListener { it.activity?.startUrl(url = fbUrl) }
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_twitter.apply {
this.visibility = clyAdminFull.socialProfileTwitter?.let { twitterUrl ->
this.setOnClickListener { it.activity?.startUrl(url = twitterUrl) }
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_linkedin.apply {
this.visibility = clyAdminFull.socialProfileLinkedin?.let { linkedinUrl ->
this.setOnClickListener { it.activity?.startUrl(url = linkedinUrl) }
View.VISIBLE
} ?: View.GONE
}
this.itemView.io_customerly__cardaccount_instagram.apply {
this.visibility = clyAdminFull.socialProfileInstagram?.let { instagramUrl ->
this.setOnClickListener { it.activity?.startUrl(url = instagramUrl) }
View.VISIBLE
} ?: View.GONE
}
ClyImageRequest(context = chatActivity, url = clyAdminFull.getImageUrl(sizePx = 80.dp2px))
.fitCenter()
.transformCircle()
.resize(width = 80.dp2px)
.placeholder(placeholder = R.drawable.io_customerly__ic_default_admin)
.into(imageView = this.itemView.io_customerly__icon)
.start()
this.itemView.io_customerly__cardaccount_name.apply {
this.text = clyAdminFull.name
}
this.itemView.io_customerly__cardaccount_cardlayout.visibility = View.VISIBLE
} else {
this.itemView.io_customerly__cardaccount_cardlayout.visibility = View.GONE
}
}
}
} | apache-2.0 | f08950209c36f4f897b5d42ad7c44aa8 | 62.870857 | 215 | 0.430108 | 6.709809 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/base/EmptyTypeDescriptor.kt | 1 | 480 | package com.aemtools.analysis.htl.callchain.typedescriptor.base
import com.intellij.codeInsight.lookup.LookupElement
/**
* @author Dmytro Troynikov
*/
open class EmptyTypeDescriptor : TypeDescriptor {
override fun isArray(): Boolean = false
override fun isIterable(): Boolean = false
override fun isMap(): Boolean = false
override fun myVariants(): List<LookupElement> = listOf()
override fun subtype(identifier: String): TypeDescriptor = TypeDescriptor.empty()
}
| gpl-3.0 | 6e5412f5ef721cce0a6cbb7df5b05037 | 29 | 83 | 0.766667 | 4.8 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/elements/CallChain.kt | 1 | 1216 | package com.aemtools.analysis.htl.callchain.elements
import com.aemtools.analysis.htl.callchain.elements.segment.CallChainSegment
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.intellij.psi.PsiElement
/**
* @author Dmytro_Troynikov
*/
class CallChain(val callChainSegments: List<CallChainSegment>) {
/**
* Find call chain element containing given [PsiElement].
* @param element the psi element to look for
* @return call chain element which contains given psi element, _null_ if no such element found
*/
fun findChainElement(element: PsiElement): CallChainElement? {
callChainSegments.forEach {
it.chainElements().forEach {
if (it.element == element) {
return it
}
}
}
return null
}
/**
* Return last output type of this call chain.
*
* @return last output type descriptor
*/
fun getLastOutputType(): TypeDescriptor? =
callChainSegments.lastOrNull()?.outputType()
companion object {
private val EMPTY_CHAIN = CallChain(listOf())
/**
* Create empty call chain instance.
*
* @return empty call chain instance
*/
fun empty() = EMPTY_CHAIN
}
}
| gpl-3.0 | 3c3d288fd065856c36ae0c694f11267e | 25.434783 | 97 | 0.686678 | 4.405797 | false | false | false | false |
android/wear-os-samples | WatchFaceKotlin/app/src/main/java/com/example/android/wearable/alpha/utils/UserStyleSchemaUtils.kt | 1 | 3980 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.alpha.utils
import android.content.Context
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting
import androidx.wear.watchface.style.WatchFaceLayer
import com.example.android.wearable.alpha.R
import com.example.android.wearable.alpha.data.watchface.ColorStyleIdAndResourceIds
import com.example.android.wearable.alpha.data.watchface.DRAW_HOUR_PIPS_DEFAULT
import com.example.android.wearable.alpha.data.watchface.MINUTE_HAND_LENGTH_FRACTION_DEFAULT
import com.example.android.wearable.alpha.data.watchface.MINUTE_HAND_LENGTH_FRACTION_MAXIMUM
import com.example.android.wearable.alpha.data.watchface.MINUTE_HAND_LENGTH_FRACTION_MINIMUM
// Keys to matched content in the the user style settings. We listen for changes to these
// values in the renderer and if new, we will update the database and update the watch face
// being rendered.
const val COLOR_STYLE_SETTING = "color_style_setting"
const val DRAW_HOUR_PIPS_STYLE_SETTING = "draw_hour_pips_style_setting"
const val WATCH_HAND_LENGTH_STYLE_SETTING = "watch_hand_length_style_setting"
/*
* Creates user styles in the settings activity associated with the watch face, so users can
* edit different parts of the watch face. In the renderer (after something has changed), the
* watch face listens for a flow from the watch face API data layer and updates the watch face.
*/
fun createUserStyleSchema(context: Context): UserStyleSchema {
// 1. Allows user to change the color styles of the watch face (if any are available).
val colorStyleSetting =
UserStyleSetting.ListUserStyleSetting(
UserStyleSetting.Id(COLOR_STYLE_SETTING),
context.resources,
R.string.colors_style_setting,
R.string.colors_style_setting_description,
null,
ColorStyleIdAndResourceIds.toOptionList(context),
listOf(
WatchFaceLayer.BASE,
WatchFaceLayer.COMPLICATIONS,
WatchFaceLayer.COMPLICATIONS_OVERLAY
)
)
// 2. Allows user to toggle on/off the hour pips (dashes around the outer edge of the watch
// face).
val drawHourPipsStyleSetting = UserStyleSetting.BooleanUserStyleSetting(
UserStyleSetting.Id(DRAW_HOUR_PIPS_STYLE_SETTING),
context.resources,
R.string.watchface_pips_setting,
R.string.watchface_pips_setting_description,
null,
listOf(WatchFaceLayer.BASE),
DRAW_HOUR_PIPS_DEFAULT
)
// 3. Allows user to change the length of the minute hand.
val watchHandLengthStyleSetting = UserStyleSetting.DoubleRangeUserStyleSetting(
UserStyleSetting.Id(WATCH_HAND_LENGTH_STYLE_SETTING),
context.resources,
R.string.watchface_hand_length_setting,
R.string.watchface_hand_length_setting_description,
null,
MINUTE_HAND_LENGTH_FRACTION_MINIMUM.toDouble(),
MINUTE_HAND_LENGTH_FRACTION_MAXIMUM.toDouble(),
listOf(WatchFaceLayer.COMPLICATIONS_OVERLAY),
MINUTE_HAND_LENGTH_FRACTION_DEFAULT.toDouble()
)
// 4. Create style settings to hold all options.
return UserStyleSchema(
listOf(
colorStyleSetting,
drawHourPipsStyleSetting,
watchHandLengthStyleSetting
)
)
}
| apache-2.0 | feb21a9e0c7ba93f70859f5c771f313f | 42.736264 | 95 | 0.727387 | 4.335512 | false | false | false | false |
sdeleuze/mixit | src/main/kotlin/mixit/web/routes/WebsiteRoutes.kt | 1 | 5719 | package mixit.web
import mixit.MixitProperties
import mixit.repository.EventRepository
import mixit.util.MarkdownConverter
import mixit.util.locale
import mixit.web.handler.*
import org.slf4j.LoggerFactory
import org.springframework.context.MessageSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
import org.springframework.core.io.ClassPathResource
import org.springframework.http.MediaType
import org.springframework.http.MediaType.*
import org.springframework.web.reactive.function.server.*
import org.springframework.web.reactive.function.server.RouterFunctions.resources
import org.springframework.web.reactive.function.server.ServerResponse.ok
import reactor.core.publisher.toMono
import java.util.*
@Configuration
class WebsiteRoutes(val adminHandler: AdminHandler,
val authenticationHandler: AuthenticationHandler,
val blogHandler: BlogHandler,
val globalHandler: GlobalHandler,
val newsHandler: NewsHandler,
val talkHandler: TalkHandler,
val sponsorHandler: SponsorHandler,
val ticketingHandler: TicketingHandler,
val messageSource: MessageSource,
val properties: MixitProperties,
val eventRepository: EventRepository,
val markdownConverter: MarkdownConverter) {
private val logger = LoggerFactory.getLogger(WebsiteRoutes::class.java)
@Bean
@DependsOn("databaseInitializer")
fun websiteRouter() = router {
GET("/blog/feed", blogHandler::feed)
accept(TEXT_HTML).nest {
GET("/") { sponsorHandler.viewWithSponsors("home", null, it) }
GET("/about", globalHandler::findAboutView)
GET("/news", newsHandler::newsView)
GET("/ticketing", ticketingHandler::ticketing)
GET("/sponsors") { sponsorHandler.viewWithSponsors("sponsors", "sponsors.title", it) }
GET("/mixteen", globalHandler::mixteenView)
GET("/faq", globalHandler::faqView)
GET("/come", globalHandler::comeToMixitView)
GET("/schedule", globalHandler::scheduleView)
// Authentication
GET("/login", authenticationHandler::loginView)
// Talks
eventRepository.findAll().toIterable().map { it.year }.forEach { year ->
GET("/$year") { talkHandler.findByEventView(year, it) }
GET("/$year/makers") { talkHandler.findByEventView(year, it, "makers") }
GET("/$year/aliens") { talkHandler.findByEventView(year, it, "aliens") }
GET("/$year/tech") { talkHandler.findByEventView(year, it, "tech") }
GET("/$year/design") { talkHandler.findByEventView(year, it, "design") }
GET("/$year/hacktivism") { talkHandler.findByEventView(year, it, "hacktivism") }
GET("/$year/learn") { talkHandler.findByEventView(year, it, "learn") }
GET("/$year/{slug}") { talkHandler.findOneView(year, it) }
}
"/admin".nest {
GET("/", adminHandler::admin)
GET("/ticketing", adminHandler::adminTicketing)
GET("/talks", adminHandler::adminTalks)
DELETE("/")
GET("/talks/edit/{slug}", adminHandler::editTalk)
GET("/talks/create", adminHandler::createTalk)
GET("/users", adminHandler::adminUsers)
GET("/users/edit/{login}", adminHandler::editUser)
GET("/users/create", adminHandler::createUser)
GET("/blog", adminHandler::adminBlog)
GET("/post/edit/{id}", adminHandler::editPost)
GET("/post/create", adminHandler::createPost)
}
"/blog".nest {
GET("/", blogHandler::findAllView)
GET("/{slug}", blogHandler::findOneView)
}
}
accept(TEXT_EVENT_STREAM).nest {
GET("/news/sse", newsHandler::newsSse)
}
contentType(APPLICATION_FORM_URLENCODED).nest {
POST("/login", authenticationHandler::login)
//POST("/ticketing", ticketingHandler::submit)
"/admin".nest {
POST("/talks", adminHandler::adminSaveTalk)
POST("/talks/delete", adminHandler::adminDeleteTalk)
POST("/users", adminHandler::adminSaveUser)
POST("/users/delete", adminHandler::adminDeleteUser)
POST("/post", adminHandler::adminSavePost)
POST("/post/delete", adminHandler::adminDeletePost)
}
}
if (properties.baseUri != "https://mixitconf.org") {
logger.warn("SEO disabled via robots.txt because ${properties.baseUri} baseUri is not the production one (https://mixitconf.org)")
GET("/robots.txt") {
ok().contentType(TEXT_PLAIN).syncBody("User-agent: *\nDisallow: /")
}
}
}.filter { request, next ->
val locale : Locale = request.locale()
val session = request.session().block()
val path = request.uri().path
val model = generateModel(properties.baseUri!!, path, locale, session, messageSource, markdownConverter)
next.handle(request).flatMap { if (it is RenderingResponse) RenderingResponse.from(it).modelAttributes(model).build() else it.toMono() }
}
@Bean
@DependsOn("websiteRouter")
fun resourceRouter() = resources("/**", ClassPathResource("static/"))
}
| apache-2.0 | 6a6997dd8c398511e823795f933d7545 | 44.031496 | 152 | 0.613219 | 4.664763 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/library/KonanLibrary.kt | 1 | 1926 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.library
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.util.visibleName
// This scheme describes the Konan Library (klib) layout.
interface KonanLibraryLayout {
val libDir: File
val target: KonanTarget?
// This is a default implementation. Can't make it an assignment.
get() = null
val manifestFile
get() = File(libDir, "manifest")
val resourcesDir
get() = File(libDir, "resources")
val targetsDir
get() = File(libDir, "targets")
val targetDir
get() = File(targetsDir, target!!.visibleName)
val kotlinDir
get() = File(targetDir, "kotlin")
val nativeDir
get() = File(targetDir, "native")
val includedDir
get() = File(targetDir, "included")
val linkdataDir
get() = File(libDir, "linkdata")
val moduleHeaderFile
get() = File(linkdataDir, "module")
val dataFlowGraphFile
get() = File(linkdataDir, "module_data_flow_graph")
fun packageFile(packageName: String)
= File(linkdataDir, if (packageName == "") "root_package.knm" else "package_$packageName.knm")
}
interface KonanLibrary: KonanLibraryLayout {
val libraryName: String
}
| apache-2.0 | cb0499fc51618ff40b040583b088cae4 | 33.392857 | 102 | 0.688993 | 4.097872 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/advanced/AdvancedFragment.kt | 1 | 6590 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.advanced
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavDirections
import androidx.navigation.fragment.findNavController
import model.TunnelStatus
import org.blokada.R
import service.EnvironmentService
import ui.TunnelViewModel
import ui.app
import utils.Links
class AdvancedFragment : Fragment() {
private lateinit var tunnelVM: TunnelViewModel
private data class Section(
val name: String,
val slugline: String,
val iconResId: Int,
val destination: NavDirections
)
private val sections by lazy {
listOf(
if (EnvironmentService.isSlim()) null
else {
Section(
name = getString(R.string.advanced_section_header_packs),
slugline = getString(R.string.advanced_section_slugline_packs),
iconResId = R.drawable.ic_shield,
destination = AdvancedFragmentDirections.actionAdvancedFragmentToNavigationPacks()
)
},
if (EnvironmentService.isSlim()) null
else {
Section(
name = getString(R.string.userdenied_section_header),
slugline = getString(R.string.userdenied_section_slugline),
iconResId = R.drawable.ic_baseline_admin_panel_settings_24,
destination = AdvancedFragmentDirections.actionAdvancedFragmentToUserDeniedFragment()
)
},
if (EnvironmentService.isSlim() || !EnvironmentService.isLibre()) null
else {
Section(
name = getString(R.string.apps_section_header),
slugline = getString(R.string.advanced_section_slugline_apps),
iconResId = R.drawable.ic_baseline_apps_24,
destination = AdvancedFragmentDirections.actionAdvancedFragmentToAppsFragment()
)
},
if (!EnvironmentService.isLibre()) null
else {
Section(
name = getString(R.string.networks_section_header),
slugline = getString(R.string.networks_section_label),
iconResId = R.drawable.ic_baseline_wifi_lock_24,
destination = AdvancedFragmentDirections.actionAdvancedFragmentToSettingsNetworksFragment()
)
}
).filterNotNull()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
activity?.let {
tunnelVM = ViewModelProvider(it.app()).get(TunnelViewModel::class.java)
}
val root = inflater.inflate(R.layout.fragment_advanced, container, false)
val sectionsContainer = root.findViewById<ViewGroup>(R.id.advanced_container)
sectionsContainer.removeAllViews()
for (section in sections) {
val (name, slugline, iconResId, destination) = section
val sectionView = inflater.inflate(R.layout.item_advanced_section, sectionsContainer, false)
sectionView.setOnClickListener {
val nav = findNavController()
nav.navigate(destination)
}
sectionsContainer.addView(sectionView)
val nameView = sectionView.findViewById<TextView>(R.id.advanced_name)
nameView.text = name
val sluglineView = sectionView.findViewById<TextView>(R.id.advanced_slugline)
sluglineView.text = slugline
val iconView = sectionView.findViewById<ImageView>(R.id.advanced_icon)
iconView.setImageResource(iconResId)
}
// val encryptionView = root.findViewById<View>(R.id.advanced_level)
// val encryptionIcon = root.findViewById<ImageView>(R.id.advanced_level_icon)
// val encryptionLevel = root.findViewById<TextView>(R.id.advanced_level_status)
//
// tunnelVM.tunnelStatus.observe(viewLifecycleOwner, Observer { status ->
// val level = statusToLevel(status)
// val ctx = requireContext()
// val color = when (level) {
// -1 -> ctx.getColorFromAttr(android.R.attr.textColorSecondary)
// 1 -> ctx.getColor(R.color.orange)
// 2 -> ctx.getColor(R.color.green)
// else -> ctx.getColor(R.color.red)
// }
//
// encryptionIcon.setColorFilter(color)
// encryptionIcon.setImageResource(when (level) {
// 2 -> R.drawable.ic_baseline_lock_24
// 1 -> R.drawable.ic_baseline_lock_open_24
// else -> R.drawable.ic_baseline_no_encryption_24
// })
//
// encryptionLevel.setTextColor(color)
// encryptionLevel.text = ctx.levelToText(level)
// })
val migrateSlim = root.findViewById<View>(R.id.advanced_migrateslim)
migrateSlim.visibility = if (EnvironmentService.isSlim()) View.VISIBLE else View.GONE
migrateSlim.setOnClickListener {
val nav = findNavController()
nav.navigate(
AdvancedFragmentDirections.actionAdvancedFragmentToWebFragment(
Links.updated, getString(R.string.universal_action_learn_more)
)
)
}
return root
}
}
internal fun statusToLevel(status: TunnelStatus): Int {
return when {
status.inProgress -> -1
status.gatewayId != null -> 2
status.active && status.isUsingDnsOverHttps -> 1
status.active -> 0
else -> 0
}
}
private fun Context.levelToText(level: Int): String {
return when (level) {
-1 -> "..."
1 -> getString(R.string.account_encrypt_label_level_medium)
2 -> getString(R.string.account_encrypt_label_level_high)
else -> getString(R.string.account_encrypt_label_level_low)
}
} | mpl-2.0 | 9ba898e36d76676d8d1a3dd8374e1f8a | 35.815642 | 111 | 0.616937 | 4.578874 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/analysis/DependencyGraphBuilder.kt | 1 | 33706 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.analysis
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.IntRef
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiElement
import com.intellij.util.castSafelyTo
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastVisitor
internal class DependencyGraphBuilder private constructor(
private val currentScope: LocalScopeContext = LocalScopeContext(null),
private var currentDepth: Int,
val dependents: MutableMap<UElement, MutableSet<Dependent>> = mutableMapOf(),
val dependencies: MutableMap<UElement, MutableSet<Dependency>> = mutableMapOf(),
private val implicitReceivers: MutableMap<UCallExpression, UThisExpression> = mutableMapOf(),
val scopesStates: MutableMap<UElement, UScopeObjectsState> = mutableMapOf(),
private val inlinedVariables: MutableMap<ULambdaExpression, Pair<String, String>> = mutableMapOf()
) : AbstractUastVisitor() {
constructor() : this(currentDepth = 0)
private val elementsProcessedAsReceiver: MutableSet<UExpression> = mutableSetOf()
private fun createVisitor(scope: LocalScopeContext) =
DependencyGraphBuilder(scope, currentDepth, dependents, dependencies, implicitReceivers, scopesStates, inlinedVariables)
inline fun <T> checkedDepthCall(node: UElement, body: () -> T): T {
currentDepth++
try {
if (currentDepth > maxBuildDepth) {
thisLogger().info("build overflow in $node because depth is greater than $maxBuildDepth")
throw BuildOverflowException
}
return body()
}
finally {
currentDepth--
}
}
override fun visitLambdaExpression(node: ULambdaExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val parent = (node.uastParent as? UCallExpression)
val isInlined = parent?.let { KotlinExtensionConstants.isExtensionFunctionToIgnore(it) } == true
val child = currentScope.createChild(isInlined)
for (parameter in node.parameters) {
child.declareFakeVariable(parameter, parameter.name)
child[parameter.name] = setOf(parameter)
}
parent
?.takeIf { KotlinExtensionConstants.isExtensionFunctionToIgnore(it) }
?.let { parent.valueArguments.getOrNull(0) as? ULambdaExpression }
?.let {
it.parameters.getOrNull(0)?.name
}?.let {
(parent.receiver ?: parent.getImplicitReceiver())?.let receiverHandle@{ receiver ->
val initElements = setOf(receiver)
child[it] = initElements
updatePotentialEqualReferences(it, initElements, child)
val inlined = currentScope.declareInlined(receiver) ?: return@receiverHandle
child.setPotentialEquality(inlined, it, DependencyEvidence())
child[inlined] = initElements
inlinedVariables[node] = it to inlined
}
}
node.body.accept(createVisitor(child))
scopesStates[node] = child.toUScopeObjectsState()
if (isInlined) {
currentScope.updateForInlined(child)
}
return@checkedDepthCall true
}
override fun visitBinaryExpressionWithType(node: UBinaryExpressionWithType): Boolean = checkedDepthCall(node) {
if (node.operationKind != UastBinaryExpressionWithTypeKind.TypeCast.INSTANCE) {
return@checkedDepthCall super.visitBinaryExpressionWithType(node)
}
registerDependency(Dependent.CommonDependent(node), node.operand.extractBranchesResultAsDependency())
return@checkedDepthCall super.visitBinaryExpressionWithType(node)
}
override fun visitCallExpression(node: UCallExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val resolvedMethod = node.resolve() ?: return@checkedDepthCall super.visitCallExpression(node)
val receiver = (node.uastParent as? UQualifiedReferenceExpression)?.receiver
for ((i, parameter) in resolvedMethod.parameterList.parameters.withIndex()) {
val argument = node.getArgumentForParameter(i) ?: continue
if (argument is UExpressionList && argument.kind == UastSpecialExpressionKind.VARARGS) {
argument.expressions.forEach {
registerDependency(
Dependent.CallExpression(i, node, (parameter.type as PsiArrayType).componentType),
Dependency.ArgumentDependency(it, node)
)
}
}
else {
registerDependency(Dependent.CallExpression(i, node, parameter.type), Dependency.ArgumentDependency(argument, node))
}
// TODO: implicit this as receiver argument
argument.takeIf { it == receiver }?.let { elementsProcessedAsReceiver.add(it) }
}
node.getImplicitReceiver()?.accept(this)
return@checkedDepthCall super.visitCallExpression(node)
}
override fun afterVisitCallExpression(node: UCallExpression) {
node.getImplicitReceiver()?.let { implicitReceiver ->
val inlinedCall = inlineCall(node, node.uastParent)
if (inlinedCall.isNotEmpty()) {
registerDependency(Dependent.CommonDependent(node), Dependency.BranchingDependency(inlinedCall).unwrapIfSingle())
}
else {
registerDependency(Dependent.CommonDependent(node), Dependency.CommonDependency(implicitReceiver))
if (node.uastParent !is UReferenceExpression) {
currentScope.setLastPotentialUpdate(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME, node)
}
}
}
}
override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.receiver.accept(this)
node.selector.accept(this)
if (node.receiver !in elementsProcessedAsReceiver) {
registerDependency(Dependent.CommonDependent(node.selector), Dependency.CommonDependency(node.receiver))
}
else {
// this element unnecessary now, remove it to avoid memory leaks
elementsProcessedAsReceiver.remove(node.receiver)
}
val inlinedExpressions = inlineCall(node.selector, node.uastParent)
if (inlinedExpressions.isNotEmpty()) {
registerDependency(Dependent.CommonDependent(node), Dependency.BranchingDependency(inlinedExpressions).unwrapIfSingle())
}
else {
registerDependency(Dependent.CommonDependent(node), Dependency.CommonDependency(node.selector))
}
if (inlinedExpressions.isEmpty() && node.getOutermostQualified() == node) {
node.getQualifiedChainWithImplicits().first().referenceOrThisIdentifier?.takeIf { it in currentScope }?.let {
currentScope.setLastPotentialUpdate(it, node)
}
}
return@checkedDepthCall true
}
override fun visitParenthesizedExpression(node: UParenthesizedExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
registerDependency(Dependent.CommonDependent(node), node.expression.extractBranchesResultAsDependency())
return@checkedDepthCall super.visitParenthesizedExpression(node)
}
override fun visitReturnExpression(node: UReturnExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.returnExpression?.extractBranchesResultAsDependency()?.let { registerDependency(Dependent.CommonDependent(node), it) }
return@checkedDepthCall super.visitReturnExpression(node)
}
override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.uastParent is UReferenceExpression && (node.uastParent as? UQualifiedReferenceExpression)?.receiver != node)
return@checkedDepthCall true
registerDependenciesForIdentifier(node.identifier, node)
return@checkedDepthCall super.visitSimpleNameReferenceExpression(node)
}
override fun visitThisExpression(node: UThisExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
registerDependenciesForIdentifier(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME, node)
return@checkedDepthCall super.visitThisExpression(node)
}
private fun registerDependenciesForIdentifier(identifier: String, node: UExpression) {
val referenceInfo = DependencyOfReference.ReferenceInfo(identifier, currentScope.getReferencedValues(identifier))
currentScope[identifier]?.let {
registerDependency(
Dependent.CommonDependent(node),
Dependency.BranchingDependency(
it,
referenceInfo
).unwrapIfSingle()
)
}
val potentialDependenciesCandidates = currentScope.getLastPotentialUpdate(identifier)
if (potentialDependenciesCandidates != null) {
registerDependency(Dependent.CommonDependent(node),
Dependency.PotentialSideEffectDependency(potentialDependenciesCandidates, referenceInfo))
}
}
override fun visitVariable(node: UVariable): Boolean = checkedDepthCall(node) {
if (node !is ULocalVariable && !(node is UParameter && node.uastParent is UMethod)) {
return@checkedDepthCall super.visitVariable(node)
}
ProgressManager.checkCanceled()
node.uastInitializer?.accept(this)
val name = node.name ?: return@checkedDepthCall super.visitVariable(node)
currentScope.declare(node)
val initializer = node.uastInitializer ?: return@checkedDepthCall super.visitVariable(node)
val initElements = initializer.extractBranchesResultAsDependency().inlineElementsIfPossible().elements
currentScope[name] = initElements
updatePotentialEqualReferences(name, initElements)
currentScope.setLastPotentialUpdateAsAssignment(name, initElements)
return@checkedDepthCall true
}
override fun visitBinaryExpression(node: UBinaryExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.operator == UastBinaryOperator.ASSIGN &&
(node.leftOperand is UReferenceExpression || node.leftOperand is UArrayAccessExpression)
) {
node.rightOperand.accept(this)
val extractedBranchesResult = node.rightOperand.extractBranchesResultAsDependency().inlineElementsIfPossible()
(node.leftOperand as? USimpleNameReferenceExpression)
?.takeIf { it.identifier in currentScope }
?.let {
currentScope[it.identifier] = extractedBranchesResult.elements
updatePotentialEqualReferences(it.identifier, extractedBranchesResult.elements)
currentScope.setLastPotentialUpdateAsAssignment(it.identifier, extractedBranchesResult.elements)
}
registerDependency(Dependent.Assigment(node.leftOperand), extractedBranchesResult)
return@checkedDepthCall true
}
registerDependency(
Dependent.BinaryOperatorDependent(node, isDependentOfLeftOperand = true),
Dependency.CommonDependency(node.leftOperand)
)
registerDependency(
Dependent.BinaryOperatorDependent(node, isDependentOfLeftOperand = false),
Dependency.CommonDependency(node.rightOperand)
)
return@checkedDepthCall super.visitBinaryExpression(node)
}
private fun Dependency.inlineElementsIfPossible(): Dependency {
val newElements = elements.flatMap { element ->
when (element) {
is UQualifiedReferenceExpression -> inlineCall(element.selector, element.uastParent)
is UCallExpression -> inlineCall(element, element.uastParent)
else -> listOf()
}.takeUnless { it.isEmpty() } ?: listOf(element)
}.toSet()
return Dependency.BranchingDependency(newElements).unwrapIfSingle()
}
override fun visitIfExpression(node: UIfExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.condition.accept(this)
val left = currentScope.createChild()
val right = currentScope.createChild()
node.thenExpression?.accept(createVisitor(left))
node.elseExpression?.accept(createVisitor(right))
currentScope.mergeWith(right, left)
return@checkedDepthCall true
}
override fun visitExpressionList(node: UExpressionList) = checkedDepthCall(node) {
ProgressManager.checkCanceled()
if (node.kind.name != UAST_KT_ELVIS_NAME) {
return super.visitExpressionList(node)
}
val firstExpression = (node.expressions.first() as? UDeclarationsExpression)
?.declarations
?.first()
?.castSafelyTo<ULocalVariable>()
?.uastInitializer
?.extractBranchesResultAsDependency() ?: return@checkedDepthCall super.visitExpressionList(node)
val ifExpression = node.expressions.getOrNull(1)
?.extractBranchesResultAsDependency() ?: return@checkedDepthCall super.visitExpressionList(node)
registerDependency(Dependent.CommonDependent(node), firstExpression.and(ifExpression))
return@checkedDepthCall super.visitExpressionList(node)
}
override fun visitSwitchExpression(node: USwitchExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
node.expression?.accept(this)
val childrenScopes = mutableListOf<LocalScopeContext>()
for (clause in node.body.expressions.filterIsInstance<USwitchClauseExpressionWithBody>()) {
val childScope = currentScope.createChild()
clause.accept(createVisitor(childScope))
childrenScopes.add(childScope)
}
currentScope.mergeWith(childrenScopes)
return@checkedDepthCall true
}
override fun visitForEachExpression(node: UForEachExpression): Boolean {
ProgressManager.checkCanceled()
node.iteratedValue.accept(this)
return visitLoopExpression(node)
}
override fun visitForExpression(node: UForExpression): Boolean {
ProgressManager.checkCanceled()
node.declaration?.accept(this)
node.condition?.accept(this)
node.update?.accept(this)
return visitLoopExpression(node)
}
override fun visitDoWhileExpression(node: UDoWhileExpression): Boolean {
ProgressManager.checkCanceled()
node.condition.accept(this)
return visitLoopExpression(node)
}
override fun visitWhileExpression(node: UWhileExpression): Boolean {
ProgressManager.checkCanceled()
node.condition.accept(this)
return visitLoopExpression(node)
}
private fun visitLoopExpression(node: ULoopExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val child = currentScope.createChild()
node.body.accept(createVisitor(child))
currentScope.mergeWith(currentScope, child)
return@checkedDepthCall true
}
override fun visitBlockExpression(node: UBlockExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
when (node.uastParent) {
is ULoopExpression, is UIfExpression, is USwitchExpression, is ULambdaExpression ->
return@checkedDepthCall super.visitBlockExpression(node)
}
val child = currentScope.createChild()
val visitor = createVisitor(child)
for (expression in node.expressions) {
if (expression.getExpressionType() != null) { // it is real expression, not statement
registerEmptyDependency(expression)
}
expression.accept(visitor)
}
currentScope.update(child)
return@checkedDepthCall true
}
override fun visitTryExpression(node: UTryExpression): Boolean = checkedDepthCall(node) {
ProgressManager.checkCanceled()
val tryChild = currentScope.createChild()
node.tryClause.accept(createVisitor(tryChild))
val scopeChildren = mutableListOf(tryChild)
node.catchClauses.mapTo(scopeChildren) { clause ->
currentScope.createChild().also { clause.accept(createVisitor(it)) }
}
currentScope.mergeWith(scopeChildren)
node.finallyClause?.accept(this)
return@checkedDepthCall true
}
// Ignore class nodes
override fun visitClass(node: UClass): Boolean = true
override fun afterVisitMethod(node: UMethod) {
scopesStates[node] = currentScope.toUScopeObjectsState()
}
private fun inlineCall(selector: UExpression, parent: UElement?): Set<UExpression> {
val call = selector as? UCallExpression ?: return emptySet()
if (KotlinExtensionConstants.isLetOrRunCall(call)) {
val lambda = call.getArgumentForParameter(1) ?: return emptySet()
return mutableSetOf<UExpression>().apply {
lambda.accept(object : AbstractUastVisitor() {
override fun visitReturnExpression(node: UReturnExpression): Boolean {
if (node.jumpTarget != lambda) return super.visitReturnExpression(node)
node.returnExpression?.let {
val inlinedCall = inlineCall(it, node)
if (inlinedCall.isNotEmpty()) {
addAll(inlinedCall)
}
else {
add(it)
}
}
return super.visitReturnExpression(node)
}
})
}
}
if (KotlinExtensionConstants.isAlsoOrApplyCall(call)) {
val lambda = call.getArgumentForParameter(1) as? ULambdaExpression ?: return emptySet()
val paramName = lambda.parameters.singleOrNull()?.name ?: return emptySet()
val inlinedVarName = inlinedVariables[lambda]?.takeIf { it.first == paramName }?.second ?: return emptySet()
val scopesState = scopesStates[lambda] ?: return emptySet()
val candidates = scopesState.lastVariablesUpdates[paramName] ?: return emptySet()
val values = scopesState.variableToValueMarks[paramName] ?: return emptySet()
val fakeReferenceExpression = UFakeSimpleNameReferenceExpression(parent, inlinedVarName, inlinedVarName)
currentScope[inlinedVarName]?.let {
registerDependency(
Dependent.CommonDependent(fakeReferenceExpression),
Dependency.BranchingDependency(it).unwrapIfSingle()
)
}
registerDependency(
Dependent.CommonDependent(fakeReferenceExpression),
Dependency.PotentialSideEffectDependency(candidates, DependencyOfReference.ReferenceInfo(paramName, values))
)
return setOf(fakeReferenceExpression)
}
return emptySet()
}
private fun updatePotentialEqualReferences(name: String, initElements: Set<UElement>, scope: LocalScopeContext = currentScope) {
scope.clearPotentialReferences(TEMP_VAR_NAME)
fun getInlined(element: UElement, id: String): String? =
element.getParentOfType<ULambdaExpression>()
?.let { inlinedVariables[it] }
?.takeIf { it.first == id }
?.second
fun identToReferenceInfo(element: UElement, identifier: String): Pair<String, UReferenceExpression?>? {
return (identifier.takeIf { id -> id in scope } ?: getInlined(element, identifier))
?.let { id -> id to null } // simple reference => same references
}
val potentialEqualReferences = initElements
.mapNotNull {
when (it) {
is UQualifiedReferenceExpression -> it.getQualifiedChainWithImplicits().firstOrNull()?.referenceOrThisIdentifier?.let { identifier ->
(identifier.takeIf { id -> id in scope } ?: getInlined(it, identifier))?.let { id -> id to it }
}
is USimpleNameReferenceExpression -> identToReferenceInfo(it, it.identifier)
is UThisExpression -> identToReferenceInfo(it, KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME)
is UCallExpression -> {
it.getImplicitReceiver()
?.takeIf { KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME in scope }
?.let { implicitThis ->
KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME to UFakeQualifiedReferenceExpression(implicitThis, it, it.uastParent)
}
}
else -> null
}
}
for ((potentialEqualReference, evidence) in potentialEqualReferences) {
scope.setPotentialEquality(TEMP_VAR_NAME, potentialEqualReference, DependencyEvidence(evidence))
}
scope.clearPotentialReferences(name)
scope.setPotentialEquality(name, TEMP_VAR_NAME, DependencyEvidence())
scope.clearPotentialReferences(TEMP_VAR_NAME)
}
private fun registerEmptyDependency(element: UElement) {
dependents.putIfAbsent(element, mutableSetOf())
}
private fun registerDependency(dependent: Dependent, dependency: Dependency) {
if (dependency !is Dependency.PotentialSideEffectDependency) {
for (el in dependency.elements) {
dependents.getOrPut(el) { mutableSetOf() }.add(dependent)
}
}
dependencies.getOrPut(dependent.element) { mutableSetOf() }.add(dependency)
}
private fun UCallExpression.getImplicitReceiver(): UExpression? {
return if (
hasImplicitReceiver(this) &&
(KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME in currentScope || this in implicitReceivers)
) {
implicitReceivers.getOrPut(this) { UFakeThisExpression(uastParent) }
}
else {
null
}
}
private fun UQualifiedReferenceExpression.getQualifiedChainWithImplicits(): List<UExpression> {
val chain = getQualifiedChain()
val firstElement = chain.firstOrNull()
return if (firstElement is UCallExpression) {
listOfNotNull(firstElement.getImplicitReceiver()) + chain
}
else {
chain
}
}
companion object {
val maxBuildDepth = Registry.intValue("uast.usage.graph.default.recursion.depth.limit", 30)
object BuildOverflowException : RuntimeException("graph building is overflowed", null, false, false)
}
}
private typealias SideEffectChangeCandidate = Dependency.PotentialSideEffectDependency.SideEffectChangeCandidate
private typealias DependencyEvidence = Dependency.PotentialSideEffectDependency.DependencyEvidence
private typealias CandidatesTree = Dependency.PotentialSideEffectDependency.CandidatesTree
private const val INLINED_PREFIX = "inlined/"
private class LocalScopeContext(
private val parent: LocalScopeContext?,
private val inlinedId: IntRef = IntRef(),
private val isInlined: Boolean = false
) {
private val definedInScopeVariables = mutableSetOf<UElement>()
private val definedInScopeVariablesNames = mutableSetOf<String>()
private val lastAssignmentOf = mutableMapOf<UElement, Set<UElement>>()
private val lastDeclarationOf = mutableMapOf<String?, UElement>()
private val lastPotentialUpdatesOf = mutableMapOf<String, CandidatesTree>()
private val referencesModel: ReferencesModel = ReferencesModel(parent?.referencesModel)
operator fun set(variable: String, values: Set<UElement>) {
getDeclaration(variable)?.let { lastAssignmentOf[it] = values }
}
operator fun set(variable: UElement, values: Set<UElement>) {
lastAssignmentOf[variable] = values
}
operator fun get(variable: String): Set<UElement>? = getDeclaration(variable)?.let { lastAssignmentOf[it] ?: parent?.get(variable) }
operator fun get(variable: UElement): Set<UElement>? = lastAssignmentOf[variable] ?: parent?.get(variable)
fun declare(variable: UVariable) {
definedInScopeVariables.add(variable)
variable.name?.let {
definedInScopeVariablesNames.add(it)
referencesModel.assignValueIfNotAssigned(it)
lastDeclarationOf[it] = variable
}
}
fun declareFakeVariable(element: UElement, name: String) {
definedInScopeVariablesNames.add(name)
referencesModel.assignValueIfNotAssigned(name)
lastDeclarationOf[name] = element
}
fun declareInlined(element: UElement): String? {
if (!isInlined) {
val name = "$INLINED_PREFIX${inlinedId.get()}"
inlinedId.inc()
declareFakeVariable(element, name)
return name
}
return parent?.declareInlined(element)
}
fun getDeclaration(variable: String): UElement? = lastDeclarationOf[variable] ?: parent?.getDeclaration(variable)
operator fun contains(variable: String): Boolean = variable in definedInScopeVariablesNames || parent?.let { variable in it } == true
fun createChild(isInlined: Boolean = false) = LocalScopeContext(this, inlinedId, isInlined)
fun setLastPotentialUpdate(variable: String, updateElement: UElement) {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidate(
SideEffectChangeCandidate(
updateElement,
DependencyEvidence(),
dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable)
)
)
for ((reference, evidenceAndWitness) in referencesModel.getAllPossiblyEqualReferences(variable)) {
val (evidence, witness) = evidenceAndWitness
val newCandidate = SideEffectChangeCandidate(updateElement, evidence, witness)
val candidatesForReference = lastPotentialUpdatesOf[reference]
lastPotentialUpdatesOf[reference] = candidatesForReference?.addToBegin(newCandidate) ?: CandidatesTree.fromCandidate(newCandidate)
}
}
fun setLastPotentialUpdateAsAssignment(variable: String, updateElements: Collection<UElement>) {
if (updateElements.size == 1) {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidate(
SideEffectChangeCandidate(
updateElements.first(),
DependencyEvidence(),
dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable))
)
}
else {
lastPotentialUpdatesOf[variable] = CandidatesTree.fromCandidates(
updateElements.mapTo(mutableSetOf()) {
SideEffectChangeCandidate(it, DependencyEvidence(), dependencyWitnessValues = referencesModel.getAllTargetsForReference(variable))
}
)
}
}
fun getLastPotentialUpdate(variable: String): CandidatesTree? =
lastPotentialUpdatesOf[variable] ?: parent?.getLastPotentialUpdate(variable)
fun setPotentialEquality(assigneeReference: String, targetReference: String, evidence: DependencyEvidence) {
referencesModel.setPossibleEquality(assigneeReference, targetReference, evidence)
}
fun clearPotentialReferences(reference: String) {
referencesModel.clearReference(reference)
}
val variables: Iterable<UElement>
get() {
return generateSequence(this) { it.parent }
.flatMap { it.definedInScopeVariables.asSequence() }
.asIterable()
}
val variablesNames: Iterable<String>
get() = generateSequence(this) { it.parent }
.flatMap { it.definedInScopeVariablesNames }
.asIterable()
fun mergeWith(others: Iterable<LocalScopeContext>) {
for (variable in variables) {
this[variable] = mutableSetOf<UElement>().apply {
for (other in others) {
other[variable]?.let { addAll(it) }
}
}
}
for (variableName in variablesNames) {
mutableSetOf<CandidatesTree>().apply {
for (other in others) {
other.getLastPotentialUpdate(variableName)?.let {
add(it)
}
}
}.takeUnless { it.isEmpty() }?.let { candidates ->
lastPotentialUpdatesOf[variableName] = CandidatesTree.merge(candidates)
}
}
}
fun mergeWith(vararg others: LocalScopeContext) {
mergeWith(others.asIterable())
}
fun update(other: LocalScopeContext) {
mergeWith(other)
}
fun updateForInlined(other: LocalScopeContext) {
update(other)
referencesModel.updateForReferences(other.referencesModel, variablesNames.filter { it.startsWith(INLINED_PREFIX) })
}
fun getReferencedValues(identifier: String): Collection<UValueMark> {
return referencesModel.getAllTargetsForReference(identifier)
}
fun toUScopeObjectsState(): UScopeObjectsState {
val variableValueMarks = definedInScopeVariablesNames.associateWith { referencesModel.getAllTargetsForReference(it) }
val lastUpdates = definedInScopeVariablesNames.mapNotNull { getLastPotentialUpdate(it)?.let { tree -> it to tree } }.toMap()
return UScopeObjectsState(lastUpdates, variableValueMarks)
}
private class ReferencesModel(private val parent: ReferencesModel?) {
private val referencesTargets = mutableMapOf<String, MutableMap<UValueMark, DependencyEvidence>>()
private val targetsReferences = mutableMapOf<UValueMark, MutableMap<String, DependencyEvidence>>()
private fun getAllReferences(referencedValue: UValueMark): Map<String, DependencyEvidence> =
parent?.getAllReferences(referencedValue).orEmpty() + targetsReferences[referencedValue].orEmpty()
private fun getAllTargets(reference: String): Map<UValueMark, DependencyEvidence> =
listOfNotNull(referencesTargets[reference], parent?.getAllTargets(reference)).fold(emptyMap()) { result, current ->
(result.keys + current.keys).associateWith { (result[it] ?: current[it])!! }
}
fun assignValueIfNotAssigned(reference: String) {
if (getAllTargets(reference).isNotEmpty()) return
val evidence = DependencyEvidence()
val newTarget = UValueMark()
referencesTargets[reference] = mutableMapOf(newTarget to evidence)
targetsReferences[newTarget] = mutableMapOf(reference to evidence)
}
fun setPossibleEquality(assigneeReference: String, targetReference: String, evidence: DependencyEvidence) {
val targets = getAllTargets(targetReference).toMutableMap()
if (targets.isEmpty()) {
val newTarget = UValueMark()
val targetEvidence = DependencyEvidence()
referencesTargets[targetReference] = mutableMapOf(newTarget to targetEvidence) // equal by default
referencesTargets.getOrPut(assigneeReference) { mutableMapOf() }[newTarget] = evidence
targetsReferences[newTarget] = mutableMapOf(
assigneeReference to evidence,
targetReference to targetEvidence
)
return
}
referencesTargets.getOrPut(assigneeReference) { mutableMapOf() }
.putAll(targets.mapValues { (_, evidenceForTarget) -> evidence.copy(requires = listOf(evidenceForTarget)) })
for (target in targets.keys) {
targetsReferences.getOrPut(target) { mutableMapOf() }[assigneeReference] = evidence
}
}
fun clearReference(reference: String) {
val targets = referencesTargets[reference] ?: return
referencesTargets.remove(reference)
for (target in targets.keys) {
targetsReferences[target]?.let { references ->
references.remove(reference)
if (references.isEmpty()) {
targetsReferences.remove(target)
}
}
}
}
fun getAllPossiblyEqualReferences(reference: String): Map<String, Pair<DependencyEvidence, Collection<UValueMark>>> {
val allTargets = getAllTargets(reference)
return allTargets
.map { (target, evidence) ->
getAllReferences(target).map { (currentReference, referenceEvidence) ->
currentReference to (combineEvidences(evidence, referenceEvidence) to allTargets.keys)
}
}
.flatten()
.filter { it.first != reference }
.toMap()
}
fun getAllTargetsForReference(reference: String): Collection<UValueMark> {
return getAllTargets(reference).keys
}
private val references: Sequence<String>
get() = generateSequence(this) { it.parent }
.flatMap { it.referencesTargets.keys }
.distinct()
// For now works only for inlined variables
fun updateForReferences(other: ReferencesModel, references: List<String>) {
check(other.parent == this)
val newTargets = mutableSetOf<UValueMark>()
for (reference in references) {
other.referencesTargets[reference]?.let {
clearReference(reference)
referencesTargets[reference] = it
newTargets += it.keys
}
}
val ownReferences = this.references.toSet()
for (target in newTargets) {
other.targetsReferences[target]?.filterKeys { it in ownReferences }?.takeUnless { it.isEmpty() }?.let {
targetsReferences[target] = it.toMutableMap()
}
}
}
}
}
private fun combineEvidences(ownEvidence: DependencyEvidence, otherEvidence: DependencyEvidence): DependencyEvidence =
ownEvidence.copy(requires = ownEvidence.requires + otherEvidence)
private const val UAST_KT_ELVIS_NAME = "elvis"
private const val TEMP_VAR_NAME = "@$,()"
private fun hasImplicitReceiver(callExpression: UCallExpression): Boolean =
callExpression.receiver == null && callExpression.receiverType != null
private val UExpression?.referenceOrThisIdentifier: String?
get() = when (this) {
is USimpleNameReferenceExpression -> identifier
is UThisExpression -> KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME
else -> null
}
private class UFakeThisExpression(override val uastParent: UElement?) : UThisExpression, UFakeExpression {
override val label: String?
get() = null
override val labelIdentifier: UIdentifier?
get() = null
}
private class UFakeQualifiedReferenceExpression(
override val receiver: UExpression,
override val selector: UExpression,
override val uastParent: UElement?
) : UQualifiedReferenceExpression, UFakeExpression {
override val accessType: UastQualifiedExpressionAccessType
get() = UastQualifiedExpressionAccessType.SIMPLE
override val resolvedName: String?
get() = null
}
private interface UFakeExpression : UExpression, UResolvable {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiElement?
get() = null
@JvmDefault
override val uAnnotations: List<UAnnotation>
get() = emptyList()
override fun resolve(): PsiElement? = null
}
private class UFakeSimpleNameReferenceExpression(
override val uastParent: UElement?,
override val resolvedName: String?,
override val identifier: String
) : USimpleNameReferenceExpression, UFakeExpression | apache-2.0 | a58cef7662d4391b66945bb02e4916e6 | 38.84279 | 143 | 0.726369 | 4.826174 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt | 3 | 1765 | // 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.
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInspection.reference.EntryPoint
import com.intellij.codeInspection.reference.RefElement
import com.intellij.openapi.util.DefaultJDOMExternalizer
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jdom.Element
import org.jetbrains.kotlin.idea.KotlinBundle
class KotlinJUnitStaticEntryPoint(@JvmField var wasSelected: Boolean = true) : EntryPoint() {
override fun getDisplayName() = KotlinBundle.message("junit.static.methods")
override fun isSelected() = wasSelected
override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement)
private val staticJUnitAnnotations = listOf(
"org.junit.BeforeClass",
"org.junit.AfterClass",
"org.junit.runners.Parameterized.Parameters"
)
override fun isEntryPoint(psiElement: PsiElement) = psiElement is PsiMethod &&
AnnotationUtil.isAnnotated(psiElement, staticJUnitAnnotations, AnnotationUtil.CHECK_TYPE) &&
AnnotationUtil.isAnnotated(psiElement, listOf("kotlin.jvm.JvmStatic"), AnnotationUtil.CHECK_TYPE)
override fun readExternal(element: Element) {
DefaultJDOMExternalizer.readExternal(this, element)
}
override fun setSelected(selected: Boolean) {
this.wasSelected = selected
}
override fun writeExternal(element: Element) {
if (!wasSelected) {
DefaultJDOMExternalizer.writeExternal(this, element)
}
}
} | apache-2.0 | 3878cea7add2e745cd032b543ddb6c64 | 37.391304 | 158 | 0.754674 | 4.77027 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/ProjectUpdatesActivity.kt | 1 | 3396 | package com.kickstarter.ui.activities
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.kickstarter.R
import com.kickstarter.databinding.ActivityUpdatesBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.RecyclerViewPaginator
import com.kickstarter.libs.SwipeRefresher
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.TransitionUtils
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.models.Project
import com.kickstarter.models.Update
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.adapters.UpdatesAdapter
import com.kickstarter.viewmodels.ProjectUpdatesViewModel
import rx.android.schedulers.AndroidSchedulers
@RequiresActivityViewModel(ProjectUpdatesViewModel.ViewModel::class)
class ProjectUpdatesActivity : BaseActivity<ProjectUpdatesViewModel.ViewModel>(), UpdatesAdapter.Delegate {
private val adapter: UpdatesAdapter = UpdatesAdapter(this)
private lateinit var recyclerViewPaginator: RecyclerViewPaginator
private lateinit var swipeRefresher: SwipeRefresher
private lateinit var binding: ActivityUpdatesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUpdatesBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.updatesRecyclerView.adapter = adapter
binding.updatesRecyclerView.layoutManager = LinearLayoutManager(this)
recyclerViewPaginator = RecyclerViewPaginator(
binding.updatesRecyclerView,
{ viewModel.inputs.nextPage() },
viewModel.outputs.isFetchingUpdates()
)
swipeRefresher = SwipeRefresher(
this, binding.updatesSwipeRefreshLayout, { viewModel.inputs.refresh() }
) { viewModel.outputs.isFetchingUpdates() }
binding.updatesToolbar.commentsToolbar.setTitle(getString(R.string.project_subpages_menu_buttons_updates))
viewModel.outputs.horizontalProgressBarIsGone()
.compose(bindToLifecycle())
.compose(Transformers.observeForUI())
.subscribe(ViewUtils.setGone(binding.updatesProgressBar))
viewModel.outputs.startUpdateActivity()
.compose(bindToLifecycle())
.compose(Transformers.observeForUI())
.subscribe { startUpdateActivity(it.first, it.second) }
viewModel.outputs.projectAndUpdates()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { adapter.takeData(it) }
}
override fun onDestroy() {
super.onDestroy()
recyclerViewPaginator.stop()
binding.updatesRecyclerView.adapter = null
}
override fun updateCardClicked(update: Update) {
viewModel.inputs.updateClicked(update)
}
private fun startUpdateActivity(project: Project, update: Update) {
val intent = Intent(this, UpdateActivity::class.java)
.putExtra(IntentKey.PROJECT, project)
.putExtra(IntentKey.UPDATE, update)
startActivityWithTransition(intent, R.anim.slide_in_right, R.anim.fade_out_slide_out_left)
}
override fun exitTransition() = TransitionUtils.slideInFromLeft()
}
| apache-2.0 | cd5aaec6d8ed604804b0344d2c30610b | 39.428571 | 114 | 0.749117 | 5.145455 | false | false | false | false |
idea4bsd/idea4bsd | platform/credential-store/src/kdbx/KdbxHeader.kt | 13 | 6084 | /*
* Copyright 2015 Jo Rabin
*
* 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.credentialStore.kdbx
import org.bouncycastle.crypto.engines.AESEngine
import org.bouncycastle.crypto.engines.AESFastEngine
import org.bouncycastle.crypto.io.CipherInputStream
import org.bouncycastle.crypto.io.CipherOutputStream
import org.bouncycastle.crypto.modes.CBCBlockCipher
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.ParametersWithIV
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.*
/**
* This class represents the header portion of a KeePass KDBX file or stream. The header is received in
* plain text and describes the encryption and compression of the remainder of the file.
* It is a factory for encryption and decryption streams and contains a hash of its own serialization.
* While KDBX streams are Little-Endian, data is passed to and from this class in standard Java byte order.
* @author jo
*/
/**
* This UUID denotes that AES Cipher is in use. No other values are known.
*/
private val AES_CIPHER = UUID.fromString("31C1F2E6-BF71-4350-BE58-05216AFC5AFF")
internal class KdbxHeader {
/**
* The ordinal 0 represents uncompressed and 1 GZip compressed
*/
enum class CompressionFlags {
NONE, GZIP
}
/**
* The ordinals represent various types of encryption that may be applied to fields within the unencrypted data
*/
enum class ProtectedStreamAlgorithm {
NONE, ARC_FOUR, SALSA_20
}
/* the cipher in use */
var cipherUuid = AES_CIPHER
private set
/* whether the data is compressed */
var compressionFlags = CompressionFlags.GZIP
private set
var masterSeed: ByteArray
var transformSeed: ByteArray
var transformRounds: Long = 6000
var encryptionIv: ByteArray
var protectedStreamKey: ByteArray
var protectedStreamAlgorithm = ProtectedStreamAlgorithm.SALSA_20
private set
/* these bytes appear in cipher text immediately following the header */
var streamStartBytes = ByteArray(32)
/* not transmitted as part of the header, used in the XML payload, so calculated
* on transmission or receipt */
var headerHash: ByteArray? = null
init {
val random = SecureRandom()
masterSeed = random.generateSeed(32)
transformSeed = random.generateSeed(32)
encryptionIv = random.generateSeed(16)
protectedStreamKey = random.generateSeed(32)
}
/**
* Create a decrypted input stream using supplied digest and this header
* apply decryption to the passed encrypted input stream
*/
fun createDecryptedStream(digest: ByteArray, inputStream: InputStream): InputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getDecryptedInputStream(inputStream, finalKeyDigest, encryptionIv)
}
/**
* Create an unencrypted output stream using the supplied digest and this header
* and use the supplied output stream to write encrypted data.
*/
fun createEncryptedStream(digest: ByteArray, outputStream: OutputStream): OutputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getEncryptedOutputStream(outputStream, finalKeyDigest, encryptionIv)
}
fun setCipherUuid(uuid: ByteArray) {
val b = ByteBuffer.wrap(uuid)
val incoming = UUID(b.long, b.getLong(8))
if (incoming != AES_CIPHER) {
throw IllegalStateException("Unknown Cipher UUID ${incoming.toString()}")
}
this.cipherUuid = incoming
}
fun setCompressionFlags(flags: Int) {
this.compressionFlags = CompressionFlags.values()[flags]
}
fun setInnerRandomStreamId(innerRandomStreamId: Int) {
this.protectedStreamAlgorithm = ProtectedStreamAlgorithm.values()[innerRandomStreamId]
}
}
private fun getFinalKeyDigest(key: ByteArray, masterSeed: ByteArray, transformSeed: ByteArray, transformRounds: Long): ByteArray {
val engine = AESEngine()
engine.init(true, KeyParameter(transformSeed))
// copy input key
val transformedKey = ByteArray(key.size)
System.arraycopy(key, 0, transformedKey, 0, transformedKey.size)
// transform rounds times
for (rounds in 0..transformRounds - 1) {
engine.processBlock(transformedKey, 0, transformedKey, 0)
engine.processBlock(transformedKey, 16, transformedKey, 16)
}
val md = sha256MessageDigest()
val transformedKeyDigest = md.digest(transformedKey)
md.update(masterSeed)
return md.digest(transformedKeyDigest)
}
fun sha256MessageDigest() = MessageDigest.getInstance("SHA-256")
/**
* Create a decrypted input stream from an encrypted one
*/
private fun getDecryptedInputStream(encryptedInputStream: InputStream, keyData: ByteArray, ivData: ByteArray): InputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val pbbc = PaddedBufferedBlockCipher(CBCBlockCipher(AESFastEngine()))
pbbc.init(false, keyAndIV)
return CipherInputStream(encryptedInputStream, pbbc)
}
/**
* Create an encrypted output stream from an unencrypted output stream
*/
private fun getEncryptedOutputStream(decryptedOutputStream: OutputStream, keyData: ByteArray, ivData: ByteArray): OutputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val pbbc = PaddedBufferedBlockCipher(CBCBlockCipher(AESFastEngine()))
pbbc.init(true, keyAndIV)
return CipherOutputStream(decryptedOutputStream, pbbc)
} | apache-2.0 | 7dc189882d19bedc99afb15165813956 | 35.656627 | 130 | 0.767258 | 4.29661 | false | false | false | false |
androidx/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ScaffoldSample.kt | 3 | 3994 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import android.annotation.SuppressLint
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.Vignette
import androidx.wear.compose.material.VignettePosition
import androidx.wear.compose.material.rememberScalingLazyListState
@SuppressLint("UnrememberedMutableState")
@Sampled
@Composable
fun SimpleScaffoldWithScrollIndicator() {
val listState = rememberScalingLazyListState()
val vignetteState = mutableStateOf(VignettePosition.TopAndBottom)
val showVignette = mutableStateOf(true)
Scaffold(
positionIndicator = {
PositionIndicator(
scalingLazyListState = listState,
modifier = Modifier
)
},
vignette = {
if (showVignette.value) {
Vignette(vignettePosition = vignetteState.value)
}
},
timeText = {
TimeText()
}
) {
ScalingLazyColumn(
contentPadding = PaddingValues(top = 40.dp),
state = listState,
modifier = Modifier.fillMaxWidth()
) {
item {
Chip(
onClick = { showVignette.value = false },
label = { Text("No Vignette") },
colors = ChipDefaults.secondaryChipColors()
)
}
item {
Chip(
onClick = {
showVignette.value = true
vignetteState.value = VignettePosition.Top
},
label = { Text("Top Vignette only") },
colors = ChipDefaults.secondaryChipColors()
)
}
item {
Chip(
onClick = {
showVignette.value = true
vignetteState.value = VignettePosition.Bottom
},
label = { Text("Bottom Vignette only") },
colors = ChipDefaults.secondaryChipColors()
)
}
item {
Chip(
onClick = {
showVignette.value = true
vignetteState.value = VignettePosition.TopAndBottom
},
label = { Text("Top and Bottom Vignette") },
colors = ChipDefaults.secondaryChipColors()
)
}
items(20) {
Chip(
onClick = { },
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
}
| apache-2.0 | 0611c7c9dea15b84fa090f9976754808 | 34.035088 | 75 | 0.582874 | 5.166882 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontMatcher.kt | 3 | 6439 | /*
* Copyright 2018 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.text.font
import androidx.compose.ui.text.fastFilter
/**
* Given a [FontFamily], [FontWeight] and [FontStyle], matches the best font in the [FontFamily]
* that satisfies the requirements of [FontWeight] and [FontStyle].
*
* For the case without font synthesis, applies the rules at
* [CSS 4 Font Matching](https://www.w3.org/TR/css-fonts-4/#font-style-matching).
*/
internal class FontMatcher {
/**
* Given a [FontFamily], [FontWeight] and [FontStyle], matches the best font in the
* [FontFamily] that satisfies the requirements of [FontWeight] and [FontStyle]. If there is
* not a font that exactly satisfies the given constraints of [FontWeight] and [FontStyle], the
* best match will be returned. The rules for the best match are defined in
* [CSS 4 Font Matching](https://www.w3.org/TR/css-fonts-4/#font-style-matching).
*
* If no fonts match, an empty list is returned.
*
* @param fontList iterable of fonts to choose the [Font] from
* @param fontWeight desired [FontWeight]
* @param fontStyle desired [FontStyle]
*/
fun matchFont(
fontList: List<Font>,
fontWeight: FontWeight,
fontStyle: FontStyle
): List<Font> {
// check for exact match first
fontList.fastFilter { it.weight == fontWeight && it.style == fontStyle }.let {
// TODO(b/130797349): IR compiler bug was here
if (it.isNotEmpty()) {
return it
}
}
// if no exact match, filter with style
val fontsToSearch = fontList.fastFilter { it.style == fontStyle }.ifEmpty { fontList }
val result = when {
fontWeight < FontWeight.W400 -> {
// If the desired weight is less than 400
// - weights less than or equal to the desired weight are checked in descending order
// - followed by weights above the desired weight in ascending order
fontsToSearch.filterByClosestWeight(fontWeight, preferBelow = true)
}
fontWeight > FontWeight.W500 -> {
// If the desired weight is greater than 500
// - weights greater than or equal to the desired weight are checked in ascending order
// - followed by weights below the desired weight in descending order
fontsToSearch.filterByClosestWeight(fontWeight, preferBelow = false)
}
else -> {
// If the desired weight is inclusively between 400 and 500
// - weights greater than or equal to the target weight are checked in ascending order
// until 500 is hit and checked,
// - followed by weights less than the target weight in descending order,
// - followed by weights greater than 500
fontsToSearch
.filterByClosestWeight(
fontWeight,
preferBelow = false,
minSearchRange = null,
maxSearchRange = FontWeight.W500
)
.ifEmpty {
fontsToSearch.filterByClosestWeight(
fontWeight,
preferBelow = false,
minSearchRange = FontWeight.W500,
maxSearchRange = null
)
}
}
}
return result
}
@Suppress("NOTHING_TO_INLINE")
// @VisibleForTesting
internal inline fun List<Font>.filterByClosestWeight(
fontWeight: FontWeight,
preferBelow: Boolean,
minSearchRange: FontWeight? = null,
maxSearchRange: FontWeight? = null,
): List<Font> {
var bestWeightAbove: FontWeight? = null
var bestWeightBelow: FontWeight? = null
for (index in indices) {
val font = get(index)
val possibleWeight = font.weight
if (minSearchRange != null && possibleWeight < minSearchRange) { continue }
if (maxSearchRange != null && possibleWeight > maxSearchRange) { continue }
if (possibleWeight < fontWeight) {
if (bestWeightBelow == null || possibleWeight > bestWeightBelow) {
bestWeightBelow = possibleWeight
}
} else if (possibleWeight > fontWeight) {
if (bestWeightAbove == null || possibleWeight < bestWeightAbove) {
bestWeightAbove = possibleWeight
}
} else {
// exact weight match, we can exit now
bestWeightAbove = possibleWeight
bestWeightBelow = possibleWeight
break
}
}
val bestWeight = if (preferBelow) {
bestWeightBelow ?: bestWeightAbove
} else {
bestWeightAbove ?: bestWeightBelow
}
return fastFilter { it.weight == bestWeight }
}
/**
* @see matchFont
*/
fun matchFont(
fontFamily: FontFamily,
fontWeight: FontWeight,
fontStyle: FontStyle
): List<Font> {
if (fontFamily !is FontListFontFamily) throw IllegalArgumentException(
"Only FontFamily instances that presents a list of Fonts can be used"
)
return matchFont(fontFamily, fontWeight, fontStyle)
}
/**
* Required to disambiguate matchFont(fontListFontFamilyInstance).
*
* @see matchFont
*/
fun matchFont(
fontFamily: FontListFontFamily,
fontWeight: FontWeight,
fontStyle: FontStyle
): List<Font> {
return matchFont(fontFamily.fonts, fontWeight, fontStyle)
}
} | apache-2.0 | 78416b8784b730451d3896b1933c1bbc | 38.030303 | 103 | 0.59093 | 5.06609 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/pager/PagerStateTest.kt | 3 | 16855 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.pager
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.StateRestorationTester
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@OptIn(ExperimentalFoundationApi::class)
@LargeTest
@RunWith(Parameterized::class)
internal class PagerStateTest(val config: ParamConfig) : BasePagerTest(config) {
@Test
fun scrollToPage_shouldPlacePagesCorrectly() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act and Assert
repeat(DefaultPageCount) {
assertThat(state.currentPage).isEqualTo(it)
rule.runOnIdle {
scope.launch {
state.scrollToPage(state.currentPage + 1)
}
}
confirmPageIsInCorrectPosition(state.currentPage)
}
}
@Test
fun scrollToPage_longSkipShouldNotPlaceIntermediatePages() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act
assertThat(state.currentPage).isEqualTo(0)
rule.runOnIdle {
scope.launch {
state.scrollToPage(DefaultPageCount - 1)
}
}
// Assert
rule.runOnIdle {
assertThat(state.currentPage).isEqualTo(DefaultPageCount - 1)
assertThat(placed).doesNotContain(DefaultPageCount / 2 - 1)
assertThat(placed).doesNotContain(DefaultPageCount / 2)
assertThat(placed).doesNotContain(DefaultPageCount / 2 + 1)
}
confirmPageIsInCorrectPosition(state.currentPage)
}
@Test
fun animateScrollToPage_shouldPlacePagesCorrectly() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act and Assert
repeat(DefaultPageCount) {
assertThat(state.currentPage).isEqualTo(it)
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(state.currentPage + 1)
}
}
rule.waitForIdle()
confirmPageIsInCorrectPosition(state.currentPage)
}
}
@Test
fun animateScrollToPage_longSkipShouldNotPlaceIntermediatePages() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act
assertThat(state.currentPage).isEqualTo(0)
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(DefaultPageCount - 1)
}
}
// Assert
rule.runOnIdle {
assertThat(state.currentPage).isEqualTo(DefaultPageCount - 1)
assertThat(placed).doesNotContain(DefaultPageCount / 2 - 1)
assertThat(placed).doesNotContain(DefaultPageCount / 2)
assertThat(placed).doesNotContain(DefaultPageCount / 2 + 1)
}
confirmPageIsInCorrectPosition(state.currentPage)
}
@Test
fun scrollToPage_shouldCoerceWithinRange() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act
assertThat(state.currentPage).isEqualTo(0)
rule.runOnIdle {
scope.launch {
state.scrollToPage(DefaultPageCount)
}
}
// Assert
rule.runOnIdle { assertThat(state.currentPage).isEqualTo(DefaultPageCount - 1) }
// Act
rule.runOnIdle {
scope.launch {
state.scrollToPage(-1)
}
}
// Assert
rule.runOnIdle { assertThat(state.currentPage).isEqualTo(0) }
}
@Test
fun animateScrollToPage_shouldCoerceWithinRange() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
// Act
assertThat(state.currentPage).isEqualTo(0)
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(DefaultPageCount)
}
}
// Assert
rule.runOnIdle { assertThat(state.currentPage).isEqualTo(DefaultPageCount - 1) }
// Act
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(-1)
}
}
// Assert
rule.runOnIdle { assertThat(state.currentPage).isEqualTo(0) }
}
@Test
fun animateScrollToPage_withPassedAnimation() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
val differentAnimation: AnimationSpec<Float> = tween()
// Act and Assert
repeat(DefaultPageCount) {
assertThat(state.currentPage).isEqualTo(it)
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(state.currentPage + 1, differentAnimation)
}
}
rule.waitForIdle()
confirmPageIsInCorrectPosition(state.currentPage)
}
}
@Test
fun currentPage_shouldChangeWhenClosestPageToSnappedPositionChanges() {
// Arrange
val state = PagerState()
createPager(state = state, modifier = Modifier.fillMaxSize())
var previousCurrentPage = state.currentPage
// Act
// Move less than half an item
val firstDelta = (pagerSize * 0.4f) * scrollForwardSign
onPager().performTouchInput {
down(layoutStart)
if (isVertical) {
moveBy(Offset(0f, firstDelta))
} else {
moveBy(Offset(firstDelta, 0f))
}
}
// Assert
rule.runOnIdle {
assertThat(state.currentPage).isEqualTo(previousCurrentPage)
}
// Release pointer
onPager().performTouchInput { up() }
rule.runOnIdle {
previousCurrentPage = state.currentPage
}
confirmPageIsInCorrectPosition(state.currentPage)
// Arrange
// Pass closest to snap position threshold (over half an item)
val secondDelta = (pagerSize * 0.6f) * scrollForwardSign
// Act
onPager().performTouchInput {
down(layoutStart)
if (isVertical) {
moveBy(Offset(0f, secondDelta))
} else {
moveBy(Offset(secondDelta, 0f))
}
}
// Assert
rule.runOnIdle {
assertThat(state.currentPage).isEqualTo(previousCurrentPage + 1)
}
onPager().performTouchInput { up() }
rule.waitForIdle()
confirmPageIsInCorrectPosition(state.currentPage)
}
@Test
fun targetPage_performScroll_shouldShowNextPage() {
// Arrange
val state = PagerState()
createPager(
state = state,
modifier = Modifier.fillMaxSize(),
snappingPage = PagerSnapDistance.atMost(3)
)
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.mainClock.autoAdvance = false
// Act
// Moving forward
val forwardDelta = pagerSize * 0.4f * scrollForwardSign.toFloat()
onPager().performTouchInput {
down(layoutStart)
moveBy(Offset(forwardDelta, forwardDelta))
}
// Assert
assertThat(state.targetPage).isEqualTo(state.currentPage + 1)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
// Reset
rule.mainClock.autoAdvance = true
onPager().performTouchInput { up() }
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.runOnIdle {
runBlocking { state.scrollToPage(5) }
}
rule.mainClock.autoAdvance = false
// Act
// Moving backward
val backwardDelta = -pagerSize * 0.4f * scrollForwardSign.toFloat()
onPager().performTouchInput {
down(layoutEnd)
moveBy(Offset(backwardDelta, backwardDelta))
}
// Assert
assertThat(state.targetPage).isEqualTo(state.currentPage - 1)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
rule.mainClock.autoAdvance = true
onPager().performTouchInput { up() }
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
}
@Test
fun targetPage_performingFling_shouldGoToPredictedPage() {
// Arrange
val state = PagerState()
createPager(
state = state,
modifier = Modifier.fillMaxSize(),
snappingPage = PagerSnapDistance.atMost(3)
)
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.mainClock.autoAdvance = false
// Act
// Moving forward
var previousTarget = state.targetPage
val forwardDelta = pagerSize * scrollForwardSign.toFloat()
onPager().performTouchInput {
swipeWithVelocityAcrossMainAxis(20000f, forwardDelta)
}
rule.mainClock.advanceTimeUntil { state.targetPage != previousTarget }
// Assert
assertThat(state.targetPage).isEqualTo(state.currentPage + 3)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
rule.mainClock.autoAdvance = true
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.mainClock.autoAdvance = false
// Act
// Moving backward
previousTarget = state.targetPage
val backwardDelta = -pagerSize * scrollForwardSign.toFloat()
onPager().performTouchInput {
swipeWithVelocityAcrossMainAxis(20000f, backwardDelta)
}
rule.mainClock.advanceTimeUntil { state.targetPage != previousTarget }
// Assert
assertThat(state.targetPage).isEqualTo(state.currentPage - 3)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
rule.mainClock.autoAdvance = true
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
}
@Test
fun targetPage_shouldReflectTargetWithAnimation() {
// Arrange
val state = PagerState()
createPager(
state = state,
modifier = Modifier.fillMaxSize()
)
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.mainClock.autoAdvance = false
// Act
// Moving forward
var previousTarget = state.targetPage
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(DefaultPageCount - 1)
}
}
rule.mainClock.advanceTimeUntil { state.targetPage != previousTarget }
// Assert
assertThat(state.targetPage).isEqualTo(DefaultPageCount - 1)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
rule.mainClock.autoAdvance = true
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
rule.mainClock.autoAdvance = false
// Act
// Moving backward
previousTarget = state.targetPage
rule.runOnIdle {
scope.launch {
state.animateScrollToPage(0)
}
}
rule.mainClock.advanceTimeUntil { state.targetPage != previousTarget }
// Assert
assertThat(state.targetPage).isEqualTo(0)
assertThat(state.targetPage).isNotEqualTo(state.currentPage)
rule.mainClock.autoAdvance = true
rule.runOnIdle { assertThat(state.targetPage).isEqualTo(state.currentPage) }
}
@Test
fun currentPageOffset_shouldReflectScrollingOfCurrentPage() {
// Arrange
val state = PagerState(DefaultPageCount / 2)
createPager(state = state, modifier = Modifier.fillMaxSize())
// No offset initially
rule.runOnIdle {
assertThat(state.currentPageOffset).isWithin(0.01f).of(0f)
}
// Act
// Moving forward
onPager().performTouchInput {
down(layoutStart)
if (isVertical) {
moveBy(Offset(0f, scrollForwardSign * pagerSize / 4f))
} else {
moveBy(Offset(scrollForwardSign * pagerSize / 4f, 0f))
}
}
rule.runOnIdle {
assertThat(state.currentPageOffset).isWithin(0.1f).of(0.25f)
}
onPager().performTouchInput { up() }
rule.waitForIdle()
// Reset
rule.runOnIdle {
scope.launch {
state.scrollToPage(DefaultPageCount / 2)
}
}
// No offset initially (again)
rule.runOnIdle {
assertThat(state.currentPageOffset).isWithin(0.01f).of(0f)
}
// Act
// Moving backward
onPager().performTouchInput {
down(layoutStart)
if (isVertical) {
moveBy(Offset(0f, -scrollForwardSign * pagerSize / 4f))
} else {
moveBy(Offset(-scrollForwardSign * pagerSize / 4f, 0f))
}
}
rule.runOnIdle {
assertThat(state.currentPageOffset).isWithin(0.1f).of(-0.25f)
}
}
@Test
fun initialPageOnPagerState_shouldDisplayThatPageFirst() {
// Arrange
val state = PagerState(5)
// Act
createPager(state = state, modifier = Modifier.fillMaxSize())
// Assert
rule.onNodeWithTag("4").assertDoesNotExist()
rule.onNodeWithTag("5").assertIsDisplayed()
rule.onNodeWithTag("6").assertDoesNotExist()
confirmPageIsInCorrectPosition(state.currentPage)
}
@Test
fun testStateRestoration() {
// Arrange
val tester = StateRestorationTester(rule)
val state = PagerState()
tester.setContent {
scope = rememberCoroutineScope()
HorizontalOrVerticalPager(
state = state,
pageCount = DefaultPageCount,
modifier = Modifier.fillMaxSize()
) {
Page(it)
}
}
// Act
rule.runOnIdle {
scope.launch {
state.scrollToPage(5)
}
runBlocking {
state.scroll {
scrollBy(50f)
}
}
}
// TODO(levima) Update to assert offset as well
val previousPage = state.currentPage
tester.emulateSavedInstanceStateRestore()
// Assert
rule.runOnIdle {
assertThat(state.currentPage).isEqualTo(previousPage)
}
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun params() = mutableListOf<ParamConfig>().apply {
for (orientation in TestOrientation) {
for (reverseLayout in TestReverseLayout) {
for (layoutDirection in TestLayoutDirection) {
add(
ParamConfig(
orientation = orientation,
reverseLayout = reverseLayout,
layoutDirection = layoutDirection
)
)
}
}
}
}
}
} | apache-2.0 | 2aa0ded8140bbb117ea21b5005a85321 | 30.803774 | 88 | 0.598279 | 5.115326 | false | true | false | false |
androidx/androidx | wear/wear-samples-ambient/src/main/java/androidx/wear/samples/ambient/MainViewModel.kt | 3 | 2811 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.samples.ambient
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
internal enum class Status {
ACTIVE, AMBIENT
}
internal class MainViewModel : ViewModel() {
/** The last time the activity was resumed. */
private var resumeTime: MutableLiveData<Long> = MutableLiveData<Long>(0)
/** The current status of the activity, either active or ambient. */
private var status: MutableLiveData<Status> = MutableLiveData<Status>(Status.ACTIVE)
/** The number of updates received within the current status. */
private var updates: MutableLiveData<Int> = MutableLiveData<Int>(0)
/** The timestamp of the last update. */
private var updateTimestamp: MutableLiveData<Long> = MutableLiveData<Long>(0)
fun observeStartTime(owner: LifecycleOwner, observer: Observer<Long>) =
resumeTime.observe(owner, observer)
fun observeStatus(owner: LifecycleOwner, observer: Observer<Status>) =
status.observe(owner, observer)
fun observeUpdates(owner: LifecycleOwner, observer: Observer<Int>) =
updates.observe(owner, observer)
fun observeUpdateTimestamp(owner: LifecycleOwner, observer: Observer<Long>) =
updateTimestamp.observe(owner, observer)
/** Returns the amount of time between the last resume and the last update. */
fun getTimer(): Long = updateTimestamp.value!! - resumeTime.value!!
/** Publishes a new update. */
fun publishUpdate() {
updateWith(updates.value!! + 1)
}
/** Updates the status. */
fun setStatus(status: Status) {
if (this.status.value == status) {
return
}
this.status.value = status
resetUpdates()
}
/** Updates the result time. */
fun updateResumeTime() {
resumeTime.value = System.currentTimeMillis()
resetUpdates()
}
/** Resets the number of updates. */
private fun resetUpdates() {
updateWith(0)
}
private fun updateWith(value: Int) {
updates.value = value
updateTimestamp.value = System.currentTimeMillis()
}
} | apache-2.0 | 76b348bd364dba233a95c55979d9629c | 32.082353 | 88 | 0.695838 | 4.600655 | false | false | false | false |
androidx/androidx | text/text/src/main/java/androidx/compose/ui/text/android/PaintExtensions.kt | 3 | 3648 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.android
import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.text.Spanned
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import kotlin.math.max
import kotlin.math.min
internal fun TextPaint.getCharSequenceBounds(
text: CharSequence,
startInclusive: Int,
endExclusive: Int
): Rect {
val metricSpanClass = MetricAffectingSpan::class.java
if (text !is Spanned || !text.hasSpan(metricSpanClass, startInclusive, endExclusive)) {
return getStringBounds(text, startInclusive, endExclusive)
}
val finalRect = Rect()
val tmpRect = Rect()
val tmpPaint = TextPaint()
var tmpStart = startInclusive
while (tmpStart < endExclusive) {
val tmpEnd = text.nextSpanTransition(tmpStart, endExclusive, metricSpanClass)
val spans = text.getSpans(tmpStart, tmpEnd, metricSpanClass)
tmpPaint.set(this)
for (span in spans) {
val spanStart = text.getSpanStart(span)
val spanEnd = text.getSpanEnd(span)
// TODO handle replacement
// skip 0 length spans
if (spanStart != spanEnd) {
span.updateMeasureState(tmpPaint)
}
}
tmpPaint.fillStringBounds(text, tmpStart, tmpEnd, tmpRect)
finalRect.extendWith(tmpRect)
tmpStart = tmpEnd
}
return finalRect
}
/**
* For use only in getCharSequenceBounds.
*
* Afaik the coordinate space of StaticLayout always start from 0,0, regardless of
* LTR, RTL or BiDi.
*
* - Every string is calculated on its own, and their coordinate space will start from 0,0
* - assume the rect horizontal coordinates are [0, 20], [0, 40]
* - this should return [0, 20 + 40] = [0, 60]
* - left stays the same, right adds the *width*.
* - assume the rect vertical coordinates are [10, 20], [0, 30]
* - this should return [0, 30].
* - the min of top (0), and max of bottom (30).
*/
private fun Rect.extendWith(rect: Rect) {
// this.left stays the same
this.right += rect.width()
this.top = min(this.top, rect.top)
this.bottom = max(this.bottom, rect.bottom)
}
@VisibleForTesting
internal fun Paint.getStringBounds(text: CharSequence, start: Int, end: Int): Rect {
val rect = Rect()
fillStringBounds(text, start, end, rect)
return rect
}
private fun Paint.fillStringBounds(text: CharSequence, start: Int, end: Int, rect: Rect) {
if (Build.VERSION.SDK_INT >= 29) {
Paint29.getTextBounds(this, text, start, end, rect)
} else {
this.getTextBounds(text.toString(), start, end, rect)
}
}
@RequiresApi(29)
private object Paint29 {
@JvmStatic
@DoNotInline
fun getTextBounds(paint: Paint, text: CharSequence, start: Int, end: Int, rect: Rect) {
paint.getTextBounds(text, start, end, rect)
}
} | apache-2.0 | af2a25c5d8411f20be1658ca2625dc31 | 32.172727 | 91 | 0.688048 | 3.939525 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/appearance/AppearanceSettingsViewModel.kt | 2 | 1414 | package org.thoughtcrime.securesms.components.settings.app.appearance
import android.app.Activity
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import org.thoughtcrime.securesms.jobs.EmojiSearchIndexDownloadJob
import org.thoughtcrime.securesms.keyvalue.SettingsValues.Theme
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.SplashScreenUtil
import org.thoughtcrime.securesms.util.livedata.Store
class AppearanceSettingsViewModel : ViewModel() {
private val store: Store<AppearanceSettingsState>
init {
val initialState = AppearanceSettingsState(
SignalStore.settings().theme,
SignalStore.settings().messageFontSize,
SignalStore.settings().language
)
store = Store(initialState)
}
val state: LiveData<AppearanceSettingsState> = store.stateLiveData
fun setTheme(activity: Activity?, theme: Theme) {
store.update { it.copy(theme = theme) }
SignalStore.settings().theme = theme
SplashScreenUtil.setSplashScreenThemeIfNecessary(activity, theme)
}
fun setLanguage(language: String) {
store.update { it.copy(language = language) }
SignalStore.settings().language = language
EmojiSearchIndexDownloadJob.scheduleImmediately()
}
fun setMessageFontSize(size: Int) {
store.update { it.copy(messageFontSize = size) }
SignalStore.settings().messageFontSize = size
}
}
| gpl-3.0 | 6909db7f73bd53f917c7fb5cb512ac71 | 31.883721 | 69 | 0.777935 | 4.620915 | false | false | false | false |
holisticon/ranked | test/h2/src/main/kotlin/H2Application.kt | 1 | 2612 | @file:Suppress("PackageDirectoryMismatch", "unused")
package de.holisticon.ranked.h2
import de.holisticon.ranked.extension.runApplicationExpr
import org.axonframework.eventhandling.saga.repository.jpa.AssociationValueEntry
import org.axonframework.eventhandling.saga.repository.jpa.SagaEntry
import org.axonframework.eventhandling.tokenstore.jpa.TokenEntry
import org.axonframework.eventsourcing.eventstore.AbstractSnapshotEventEntry
import org.axonframework.eventsourcing.eventstore.jpa.DomainEventEntry
import org.axonframework.eventsourcing.eventstore.jpa.SnapshotEventEntry
import org.h2.tools.Server
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import springfox.documentation.builders.PathSelectors
import springfox.documentation.builders.RequestHandlerSelectors
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2
fun main(args: Array<String>) = runApplicationExpr<H2Application>(*args)
@SpringBootApplication
@EnableSwagger2
@RestController // should be data-rest, but see https://github.com/springfox/springfox/issues/1957
class H2Application(
@Value("\${ranked.h2.port:9092}") val port: String,
val domainEventRepository: DomainEventRepository,
val tokenRepository: TokenRepository
) {
@Bean(initMethod = "start", destroyMethod = "stop")
fun h2Server(): Server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", port)
@GetMapping("/domain")
fun domainEvents() = domainEventRepository.findAll()
@GetMapping("/token")
fun tokens() = tokenRepository.findAll()
@Bean
fun swagger(): Docket = Docket(DocumentationType.SWAGGER_2)
.groupName("H2 Repositories")
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
}
interface AssociationValueRepository : PagingAndSortingRepository<AssociationValueEntry, Long>
interface DomainEventRepository : PagingAndSortingRepository<DomainEventEntry, Long>
interface SagaRepository : PagingAndSortingRepository<SagaEntry<Any>,String>
interface TokenRepository : PagingAndSortingRepository<TokenEntry, TokenEntry.PK>
interface SnapshotEventRepository : PagingAndSortingRepository<SnapshotEventEntry, AbstractSnapshotEventEntry.PK>
| bsd-3-clause | 52d31c616a678f18772a30e1d2cecada | 44.034483 | 113 | 0.833844 | 4.606702 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt | 1 | 5875 | // 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.actions.internal
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import javax.swing.SwingUtilities
class CheckComponentsUsageSearchAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return
val selectedKotlinFiles = selectedKotlinFiles(e).toList()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
runReadAction { process(selectedKotlinFiles, project) }
},
KotlinBundle.message("checking.data.classes"),
true,
project
)
}
private fun process(files: Collection<KtFile>, project: Project) {
val dataClasses = files.asSequence()
.flatMap { it.declarations.asSequence() }
.filterIsInstance<KtClass>()
.filter { it.isData() }
.toList()
val progressIndicator = ProgressManager.getInstance().progressIndicator
for ((i, dataClass) in dataClasses.withIndex()) {
progressIndicator?.text = KotlinBundle.message("checking.data.class.0.of.1", i + 1, dataClasses.size)
@NlsSafe val fqName = dataClass.fqName?.asString() ?: ""
progressIndicator?.text2 = fqName
val parameter = dataClass.primaryConstructor?.valueParameters?.firstOrNull()
if (parameter != null) {
try {
var smartRefsCount = 0
var goldRefsCount = 0
ProgressManager.getInstance().runProcess(
{
ExpressionsOfTypeProcessor.mode =
ExpressionsOfTypeProcessor.Mode.ALWAYS_SMART
smartRefsCount = ReferencesSearch.search(parameter).findAll().size
ExpressionsOfTypeProcessor.mode =
ExpressionsOfTypeProcessor.Mode.ALWAYS_PLAIN
goldRefsCount = ReferencesSearch.search(parameter).findAll().size
}, EmptyProgressIndicator()
)
if (smartRefsCount != goldRefsCount) {
SwingUtilities.invokeLater {
Messages.showInfoMessage(
project,
KotlinBundle.message(
"difference.found.for.data.class.0.found.1.2",
dataClass.fqName?.asString().toString(),
smartRefsCount,
goldRefsCount
),
KotlinBundle.message("title.error")
)
}
return
}
} finally {
ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.PLAIN_WHEN_NEEDED
}
}
progressIndicator?.fraction = (i + 1) / dataClasses.size.toDouble()
}
SwingUtilities.invokeLater {
Messages.showInfoMessage(
project,
KotlinBundle.message("analyzed.0.classes.no.difference.found", dataClasses.size),
KotlinBundle.message("title.success")
)
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isApplicationInternalMode()
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 | bf7b44405b40b5ec503203beba08db9b | 41.883212 | 158 | 0.61566 | 5.649038 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/testSources/dsl/GradleManagedPropertyTest.kt | 2 | 4574 | // 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.dsl
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.use
import org.jetbrains.plugins.gradle.codeInspection.GradleDisablerTestUtils
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.jetbrains.plugins.groovy.codeInspection.assignment.GroovyAssignabilityCheckInspection
import org.jetbrains.plugins.groovy.codeInspection.bugs.GroovyAccessibilityInspection
import org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GrUnresolvedAccessInspection
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROVIDER_PROPERTY
import org.jetbrains.plugins.gradle.testFramework.GradleCodeInsightTestCase
import org.jetbrains.plugins.gradle.testFramework.GradleTestFixtureBuilder
import org.jetbrains.plugins.gradle.testFramework.annotations.AllGradleVersionsSource
import org.jetbrains.plugins.gradle.testFramework.util.withBuildFile
import org.jetbrains.plugins.gradle.testFramework.util.withSettingsFile
import org.junit.jupiter.params.ParameterizedTest
class GradleManagedPropertyTest : GradleCodeInsightTestCase() {
@ParameterizedTest
@TargetVersions("6.0+")
@AllGradleVersionsSource("""
"<caret>myExt" : pkg.MyExtension,
"myExt.<caret>stringProperty" : $GRADLE_API_PROVIDER_PROPERTY<$JAVA_LANG_STRING>,
"myExt.getStringProperty(<caret>)" : $GRADLE_API_PROVIDER_PROPERTY<$JAVA_LANG_STRING>,
"myExt.getStringProperty().get(<caret>)" : $JAVA_LANG_STRING,
"myExt { <caret>delegate }" : pkg.MyExtension,
"myExt { <caret>stringProperty }" : $GRADLE_API_PROVIDER_PROPERTY<$JAVA_LANG_STRING>,
"myExt { getStringProperty(<caret>) }" : $GRADLE_API_PROVIDER_PROPERTY<$JAVA_LANG_STRING>,
"myExt { getStringProperty().get(<caret>) }" : $JAVA_LANG_STRING
""")
fun types(gradleVersion: GradleVersion, expression: String, type: String) {
test(gradleVersion, FIXTURE_BUILDER) {
testBuildscript(expression) {
typingTest(elementUnderCaret(GrExpression::class.java), type)
}
}
}
@ParameterizedTest
@TargetVersions("6.0+")
@AllGradleVersionsSource
fun highlighting(gradleVersion: GradleVersion) {
Disposer.newDisposable().use { parentDisposable ->
test(gradleVersion, FIXTURE_BUILDER) {
GradleDisablerTestUtils.enableAllDisableableInspections(parentDisposable)
fixture.enableInspections(
GrUnresolvedAccessInspection::class.java,
GroovyAssignabilityCheckInspection::class.java,
GroovyAccessibilityInspection::class.java
)
updateProjectFile("""
|myExt.integerProperty = 42
|<warning descr="Cannot assign 'Object' to 'Integer'">myExt.integerProperty</warning> = new Object()
|myExt.setIntegerProperty(69)
|myExt.setIntegerProperty<warning descr="'setIntegerProperty' in 'pkg.MyExtension' cannot be applied to '(java.lang.Object)'">(new Object())</warning>
|myExt {
| integerProperty = 42
| <warning descr="Cannot assign 'Object' to 'Integer'">integerProperty</warning> = new Object()
| setIntegerProperty(69)
| setIntegerProperty<warning descr="'setIntegerProperty' in 'pkg.MyExtension' cannot be applied to '(java.lang.Object)'">(new Object())</warning>
|}
""".trimMargin())
fixture.checkHighlighting()
}
}
}
companion object {
private val FIXTURE_BUILDER = GradleTestFixtureBuilder.create("GradleManagedPropertyTest") {
withFile("buildSrc/build.gradle", "")
withFile("buildSrc/src/main/java/pkg/MyExtension.java", """
|package pkg;
|
|import org.gradle.api.provider.Property;
|
|public abstract class MyExtension {
| abstract Property<String> getStringProperty();
| Property<Integer> getIntegerProperty() {
| throw new RuntimeException();
| }
|}
""".trimMargin())
withBuildFile(content = "project.extensions.create('myExt', pkg.MyExtension)")
withSettingsFile {
setProjectName("GradleManagedPropertyTest")
}
}
}
} | apache-2.0 | fe57880a22bc98bc56e5c873f1ecb005 | 47.670213 | 160 | 0.71185 | 4.569431 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/evaluator.kt | 4 | 2772 | // 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.debugger.coroutine.proxy.mirror
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext
import java.lang.IllegalArgumentException
sealed class MethodEvaluator<T>(val method: Method?) {
fun value(value: ObjectReference?, context: DefaultExecutionContext, vararg values: Value): T? {
return method?.let {
return when {
method.isStatic -> {
// pass extension methods like the usual ones.
val args = if (value != null) {
listOf(value) + values.toList()
} else
values.toList()
@Suppress("UNCHECKED_CAST")
context.invokeMethod(method.declaringType() as ClassType, method, args) as T?
}
value != null ->
@Suppress("UNCHECKED_CAST")
context.invokeMethod(value, method, values.toList()) as T?
else -> throw IllegalArgumentException("Exception while calling method " + method.signature() + " with an empty value.")
}
}
}
class DefaultMethodEvaluator<T>(method: Method?) : MethodEvaluator<T>(method)
class MirrorMethodEvaluator<T, F>(method: Method?, private val mirrorProvider: MirrorProvider<T, F>): MethodEvaluator<T>(method) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext, vararg values: Value): F? {
return mirrorProvider.mirror(value(ref, context, *values), context)
}
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
sealed class FieldEvaluator<T>(val field: Field?, val thisRef: ReferenceTypeProvider) {
@Suppress("UNCHECKED_CAST")
fun value(value: ObjectReference): T? =
field?.let { value.getValue(it) as T? }
@Suppress("UNCHECKED_CAST")
fun staticValue(): T? = thisRef.getCls().let { it.getValue(field) as? T }
class DefaultFieldEvaluator<T>(field: Field?, thisRef: ReferenceTypeProvider) : FieldEvaluator<T>(field, thisRef)
class MirrorFieldEvaluator<T, F>(field: Field?, thisRef: ReferenceTypeProvider, private val mirrorProvider: MirrorProvider<T, F>) : FieldEvaluator<T>(field, thisRef) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext): F? =
mirrorProvider.mirror(value(ref), context)
fun mirrorOnly(value: T, context: DefaultExecutionContext) = mirrorProvider.mirror(value, context)
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
| apache-2.0 | 8edd03ab4760d329fdfeb64a1cbc24b3 | 46.793103 | 171 | 0.655844 | 4.529412 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/util/PageLinks.kt | 1 | 3584 | /*
* Copyright (c) 2017 Lizhaotailang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.tonnyl.mango.util
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*/
import retrofit2.Response
/**
* Created by lizhaotailang on 2017/8/10.
*
* Parse links from executed method
*/
class PageLinks(response: Response<*>) {
var next: String? = null
private set
var prev: String? = null
private set
companion object {
private val DELIM_LINKS = "," //$NON-NLS-1$
private val DELIM_LINK_PARAM = ";" //$NON-NLS-1$
private val HEAD_LINK = "Link"
private val META_REL = "rel" //$NON-NLS-1$
private val META_NEXT = "next" //$NON-NLS-1$
private val META_PREV = "prev" //$NON-NLS-1$
}
init {
val linkHeader = response.headers().get(HEAD_LINK)
if (linkHeader != null) {
val links = linkHeader.split(DELIM_LINKS)
for (link in links) {
val segments = link.split(DELIM_LINK_PARAM)
if (segments.size < 2) {
continue
}
var linkPart = segments[0].trim()
if (!linkPart.startsWith("<") || !linkPart.endsWith(">")) { //$NON-NLS-1$ //$NON-NLS-2$
continue
}
linkPart = linkPart.substring(1, linkPart.length - 1)
for (i in 1 until segments.size) {
val rel = segments[i].trim { it <= ' ' }.split("=") //$NON-NLS-1$
if (rel.size < 2 || META_REL != rel[0]) {
continue
}
var relValue = rel[1]
if (relValue.startsWith("\"") && relValue.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
relValue = relValue.substring(1, relValue.length - 1)
}
if (META_NEXT == relValue) {
next = linkPart
} else if (META_PREV == relValue) {
prev = linkPart
}
}
}
}
}
}
| mit | 88e10cddce1bad5f5cbd82f4ee577292 | 33.796117 | 107 | 0.570871 | 4.3548 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineNamedDeclarationProcessor.kt | 4 | 6787 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.inline
import com.intellij.lang.Language
import com.intellij.lang.refactoring.InlineHandler
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.refactoring.OverrideMethodsProcessor
import com.intellij.refactoring.inline.GenericInlineHandler
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.replaceUsages
import org.jetbrains.kotlin.idea.findUsages.ReferencesSearchScopeHelper
import org.jetbrains.kotlin.idea.refactoring.pullUp.deleteWithCompanion
import org.jetbrains.kotlin.idea.search.declarationsSearch.findSuperMethodsNoWrapping
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingElement
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtReferenceExpression
abstract class AbstractKotlinInlineNamedDeclarationProcessor<TDeclaration : KtNamedDeclaration>(
declaration: TDeclaration,
private val reference: PsiReference?,
private val inlineThisOnly: Boolean,
private val deleteAfter: Boolean,
editor: Editor?,
project: Project,
) : AbstractKotlinDeclarationInlineProcessor<TDeclaration>(declaration, editor, project) {
private lateinit var inliners: Map<Language, InlineHandler.Inliner>
abstract fun createReplacementStrategy(): UsageReplacementStrategy?
open fun postAction() = Unit
open fun postDeleteAction() = Unit
final override fun findUsages(): Array<UsageInfo> {
if (inlineThisOnly && reference != null) return arrayOf(UsageInfo(reference))
val usages = hashSetOf<UsageInfo>()
for (usage in ReferencesSearchScopeHelper.search(declaration, myRefactoringScope)) {
usages += UsageInfo(usage)
}
if (shouldDeleteAfter) {
declaration.forEachOverridingElement(scope = myRefactoringScope) { _, overridingMember ->
val superMethods = findSuperMethodsNoWrapping(overridingMember)
if (superMethods.singleOrNull()?.unwrapped == declaration) {
usages += OverrideUsageInfo(overridingMember)
return@forEachOverridingElement true
}
true
}
}
return usages.toArray(UsageInfo.EMPTY_ARRAY)
}
open fun additionalPreprocessUsages(usages: Array<out UsageInfo>, conflicts: MultiMap<PsiElement, String>) = Unit
final override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
val usagesInfo = refUsages.get()
if (inlineThisOnly) {
val element = usagesInfo.singleOrNull()?.element
if (element != null && !CommonRefactoringUtil.checkReadOnlyStatus(myProject, element)) return false
}
val conflicts = MultiMap<PsiElement, String>()
additionalPreprocessUsages(usagesInfo, conflicts)
for (usage in usagesInfo) {
val element = usage.element ?: continue
val callableConflict = findCallableConflictForUsage(element) ?: continue
conflicts.putValue(element, callableConflict)
}
if (shouldDeleteAfter) {
for (superDeclaration in findSuperMethodsNoWrapping(declaration)) {
val fqName = superDeclaration.kotlinFqName?.asString() ?: KotlinBundle.message("fix.change.signature.error")
val message = KotlinBundle.message("text.inlined.0.overrides.0.1", kind, fqName)
conflicts.putValue(superDeclaration, message)
}
}
inliners = GenericInlineHandler.initInliners(
declaration,
usagesInfo,
InlineHandler.Settings { inlineThisOnly },
conflicts,
KotlinLanguage.INSTANCE
)
return showConflicts(conflicts, usagesInfo)
}
private val shouldDeleteAfter: Boolean get() = deleteAfter && isWritable
private fun postActions() {
if (shouldDeleteAfter) {
declaration.deleteWithCompanion()
postDeleteAction()
}
postAction()
}
override fun performRefactoring(usages: Array<out UsageInfo>) {
if (usages.isEmpty()) {
if (!shouldDeleteAfter) {
val message = KotlinBundle.message("0.1.is.never.used", kind.capitalize(), declaration.name.toString())
CommonRefactoringUtil.showErrorHint(myProject, editor, message, commandName, null)
} else {
postActions()
}
return
}
val replacementStrategy = createReplacementStrategy() ?: return
val (kotlinReferenceUsages, nonKotlinReferenceUsages) = usages.partition { it !is OverrideUsageInfo && it.element is KtReferenceExpression }
for (usage in nonKotlinReferenceUsages) {
val element = usage.element ?: continue
when {
usage is OverrideUsageInfo -> for (processor in OverrideMethodsProcessor.EP_NAME.extensionList) {
if (processor.removeOverrideAttribute(element)) break
}
element.language == KotlinLanguage.INSTANCE -> LOG.error("Found unexpected Kotlin usage $element")
else -> GenericInlineHandler.inlineReference(usage, declaration, inliners)
}
}
replacementStrategy.replaceUsages(
usages = kotlinReferenceUsages.mapNotNull { it.element as? KtReferenceExpression }
)
postActions()
}
private val isWritable: Boolean
get() = declaration.isWritable
override fun getElementsToWrite(descriptor: UsageViewDescriptor): Collection<PsiElement?> = when {
inlineThisOnly -> listOfNotNull(reference?.element)
isWritable -> listOfNotNull(reference?.element, declaration)
else -> emptyList()
}
companion object {
private val LOG = Logger.getInstance(AbstractKotlinInlineNamedDeclarationProcessor::class.java)
}
}
private class OverrideUsageInfo(element: PsiElement) : UsageInfo(element)
| apache-2.0 | 5779f2bb3839012cec89fff934e425d8 | 40.384146 | 148 | 0.703993 | 5.224788 | false | false | false | false |
raniejade/spek-idea-plugin | tooling/src/main/kotlin/org/jetbrains/spek/tooling/adapter/sm/ServiceMessageAdapter.kt | 1 | 2802 | package org.jetbrains.spek.tooling.adapter.sm
import org.jetbrains.spek.tooling.adapter.Adapter
import org.jetbrains.spek.tooling.runner.TestExecutionResult
import org.jetbrains.spek.tooling.runner.TestIdentifier
import java.io.CharArrayWriter
import java.io.PrintWriter
/**
* @author Ranie Jade Ramiso
*/
class ServiceMessageAdapter: Adapter() {
override fun executionFinished(test: TestIdentifier, result: TestExecutionResult) {
val name = test.displayName.toTcSafeString()
if (test.container) {
if (result.status != TestExecutionResult.Status.Success) {
val exceptionDetails = getExceptionDetails(result)
// fake a child test
out("testStarted name='$name'")
out("testFailed name='$name' message='${exceptionDetails.first}' details='${exceptionDetails.second}'")
out("testFinished name='$name'")
}
out("testSuiteFinished name='$name'")
} else {
val duration = result.duration
if (result.status != TestExecutionResult.Status.Success) {
val exceptionDetails = getExceptionDetails(result)
out("testFailed name='$name' message='${exceptionDetails.first}' details='${exceptionDetails.second}'")
}
out("testFinished name='$name' duration='$duration'")
}
}
override fun executionStarted(testIdentifier: TestIdentifier) {
val name = testIdentifier.displayName.toTcSafeString()
if (testIdentifier.container) {
out("testSuiteStarted name='$name'")
} else {
out("testStarted name='$name'")
}
}
override fun executionSkipped(testIdentifier: TestIdentifier, reason: String) {
val name = testIdentifier.displayName.toTcSafeString()
out("testIgnored name='$name' ignoreComment='$reason'")
out("testFinished name='$name'")
}
private fun getExceptionDetails(result: TestExecutionResult): Pair<String?, String> {
val throwable = result.throwable!!
val writer = CharArrayWriter()
throwable.printStackTrace(PrintWriter(writer))
val details = writer.toString()
.toTcSafeString()
val message = throwable.message?.toTcSafeString()
return message to details
}
}
private fun String.toTcSafeString(): String {
return this.replace("|", "||")
.replace("\n", "|n")
.replace("\r", "|r")
.replace("'", "|'")
.replace("[", "|[")
.replace("]", "|]")
.replace(Regex("""\\u(\d\d\d\d)""")) {
"|0x${it.groupValues[1]}"
}
}
private fun out(event: String) {
/* ensure ##teamcity has it's own line*/
println()
println("##teamcity[$event]")
}
| mit | 16f61762b0af766d93ec73cc395593d4 | 33.592593 | 119 | 0.614918 | 4.797945 | false | true | false | false |
vickychijwani/kotlin-koans-android | app/src/main/code/me/vickychijwani/kotlinkoans/network/ProductionHttpClientFactory.kt | 1 | 2121 | package me.vickychijwani.kotlinkoans.network
import android.os.Build
import android.os.StatFs
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.util.concurrent.TimeUnit
open class ProductionHttpClientFactory : HttpClientFactory {
/**
* @param cacheDir - directory for the HTTP cache, disabled if null
* *
* @return an HTTP client intended for production use
*/
override fun create(cacheDir: File?): OkHttpClient {
val builder = OkHttpClient.Builder()
if (cacheDir != null) {
val size = calculateDiskCacheSize(cacheDir)
builder.cache(Cache(cacheDir, size))
}
return builder
.connectTimeout(CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
.build()
}
companion object {
private val MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024 // in bytes
private val MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024 // in bytes
private val CONNECT_TIMEOUT = 20
private val READ_TIMEOUT = 30
private val WRITE_TIMEOUT = 30
private fun calculateDiskCacheSize(dir: File): Long {
var size = MIN_DISK_CACHE_SIZE.toLong()
try {
val statFs = StatFs(dir.absolutePath)
val available: Long
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
available = statFs.blockCountLong * statFs.blockSizeLong
} else {
// checked at runtime
available = (statFs.blockCount * statFs.blockSize).toLong()
}
// Target 2% of the total space.
size = available / 50
} catch (ignored: IllegalArgumentException) {
}
// Bound inside min/max size for disk cache.
return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE.toLong()), MIN_DISK_CACHE_SIZE.toLong())
}
}
}
| mit | f6f2b905f6de32b368b8e127b24af3e6 | 33.770492 | 103 | 0.591231 | 4.671806 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/shadowlayout/ShadowLayoutDemoActivity.kt | 1 | 6106 | package com.zeke.demo.shadowlayout
import android.graphics.Color
import android.os.Bundle
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import com.zeke.demo.R
import kotlinx.android.synthetic.main.page_shadowlayout_demo.*
class ShadowLayoutDemoActivity : AppCompatActivity() {
private var shadowAlpha :Int = 0
private var red :Int = 0
private var green:Int = 0
private var blue:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.page_shadowlayout_demo)
red = shadow_color_red_seekbar.progress
green = shadow_color_green_seekbar.progress
blue = shadow_color_blue_seekbar.progress
radio_left.setOnCheckedChangeListener { _, isChecked ->
shadowLayout.setShadowHiddenLeft(isChecked)
}
radio_top.setOnCheckedChangeListener { _, isChecked ->
shadowLayout.setShadowHiddenTop(isChecked)
}
radio_right.setOnCheckedChangeListener { _, isChecked ->
shadowLayout.setShadowHiddenRight(isChecked)
}
radio_buttom.setOnCheckedChangeListener { _, isChecked ->
shadowLayout.setShadowHiddenBottom(isChecked)
}
//-----------> 阴影颜色
shadow_color_red_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
red = progress
shadowLayout.setShadowColor(Color.argb(shadowAlpha, red, green, blue))
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
shadow_color_green_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
green = progress
shadowLayout.setShadowColor(Color.argb(shadowAlpha, red, green, blue))
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
shadow_color_blue_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
blue = progress
shadowLayout.setShadowColor(Color.argb(shadowAlpha, red, green, blue))
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
//<----------- 阴影颜色
//阴影扩散程度
shadow_limit_seekbar.apply {
progress = shadowLayout.shadowLimit.toInt()
shadow_limit_tip.text = String.format("阴影扩撒程度:%s", progress)
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
shadow_limit_tip.text = String.format("阴影扩撒程度:%s", progress)
shadowLayout.setShadowLimit(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
}
//阴影X|Y偏移量
shadow_color_offsetx_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
shadow_offsetx_tip.text = String.format("阴影X偏移量:%s",progress)
shadowLayout.setShadowOffsetX(progress.toFloat())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
shadow_color_offsety_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
shadow_offsety_tip.text = String.format("阴影Y偏移量:%s",progress)
shadowLayout.setShadowOffsetY(progress.toFloat())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
//圆角效果
shadow_round_rect_seekbar.apply {
progress = shadowLayout.cornerRadius.toInt()
shadow_round_rect_tip.text = String.format("圆角大小:%s",progress)
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
shadow_round_rect_tip.text = String.format("圆角大小:%s",progress)
shadowLayout.setCornerRadius(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
}
//透明度设置
shadow_alpha_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
shadowAlpha = progress
shadow_alpha_tip.text = String.format("透明度:%.0f %%",progress.toFloat() * 100 / 255)
shadowLayout.setShadowColor(Color.argb(shadowAlpha, red, green, blue))
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
}
}
| gpl-2.0 | fd7d0323c2fc16420a717c8c5233261e | 38.629139 | 106 | 0.620655 | 5.198957 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenHelper.kt | 1 | 1876 | package eu.kanade.tachiyomi.data.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import eu.kanade.tachiyomi.data.database.tables.*
class DbOpenHelper(context: Context)
: SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
/**
* Name of the database file.
*/
const val DATABASE_NAME = "tachiyomi.db"
/**
* Version of the database.
*/
const val DATABASE_VERSION = 3
}
override fun onCreate(db: SQLiteDatabase) = with(db) {
execSQL(MangaTable.createTableQuery)
execSQL(ChapterTable.createTableQuery)
execSQL(MangaSyncTable.createTableQuery)
execSQL(CategoryTable.createTableQuery)
execSQL(MangaCategoryTable.createTableQuery)
execSQL(HistoryTable.createTableQuery)
// DB indexes
execSQL(MangaTable.createUrlIndexQuery)
execSQL(MangaTable.createFavoriteIndexQuery)
execSQL(ChapterTable.createMangaIdIndexQuery)
execSQL(HistoryTable.createChapterIdIndexQuery)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 2) {
db.execSQL(ChapterTable.sourceOrderUpdateQuery)
// Fix kissmanga covers after supporting cloudflare
db.execSQL("""UPDATE mangas SET thumbnail_url =
REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""")
}
if (oldVersion < 3) {
// Initialize history tables
db.execSQL(HistoryTable.createTableQuery)
db.execSQL(HistoryTable.createChapterIdIndexQuery)
}
}
override fun onConfigure(db: SQLiteDatabase) {
db.setForeignKeyConstraintsEnabled(true)
}
}
| gpl-3.0 | 317ddd65191ef6804215ea7b55f9c3bc | 31.912281 | 97 | 0.670576 | 4.737374 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/note/actions/NoteOptionsBottomSheet.kt | 1 | 19416 | package com.maubis.scarlet.base.note.actions
import android.app.Dialog
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.graphics.drawable.Icon
import android.view.View
import android.widget.GridLayout
import android.widget.LinearLayout
import android.widget.LinearLayout.VERTICAL
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.github.bijoysingh.starter.util.RandomHelper
import com.maubis.markdown.Markdown
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface
import com.maubis.scarlet.base.core.note.NoteBuilder
import com.maubis.scarlet.base.core.note.NoteState
import com.maubis.scarlet.base.core.note.getNoteState
import com.maubis.scarlet.base.database.room.note.Note
import com.maubis.scarlet.base.main.sheets.InstallProUpsellBottomSheet
import com.maubis.scarlet.base.main.sheets.openDeleteNotePermanentlySheet
import com.maubis.scarlet.base.note.activity.INoteOptionSheetActivity
import com.maubis.scarlet.base.note.copy
import com.maubis.scarlet.base.note.creation.activity.NoteIntentRouterActivity
import com.maubis.scarlet.base.note.edit
import com.maubis.scarlet.base.note.folder.sheet.FolderChooserBottomSheet
import com.maubis.scarlet.base.note.getFullText
import com.maubis.scarlet.base.note.getTagString
import com.maubis.scarlet.base.note.getTitleForSharing
import com.maubis.scarlet.base.note.hasImages
import com.maubis.scarlet.base.note.reminders.sheet.ReminderBottomSheet
import com.maubis.scarlet.base.note.save
import com.maubis.scarlet.base.note.selection.activity.KEY_SELECT_EXTRA_MODE
import com.maubis.scarlet.base.note.selection.activity.KEY_SELECT_EXTRA_NOTE_ID
import com.maubis.scarlet.base.note.selection.activity.SelectNotesActivity
import com.maubis.scarlet.base.note.share
import com.maubis.scarlet.base.note.shareImages
import com.maubis.scarlet.base.note.tag.sheet.TagChooserBottomSheet
import com.maubis.scarlet.base.notification.NotificationConfig
import com.maubis.scarlet.base.notification.NotificationHandler
import com.maubis.scarlet.base.security.sheets.openUnlockSheet
import com.maubis.scarlet.base.settings.sheet.ColorPickerBottomSheet
import com.maubis.scarlet.base.settings.sheet.ColorPickerDefaultController
import com.maubis.scarlet.base.support.addShortcut
import com.maubis.scarlet.base.support.option.OptionsItem
import com.maubis.scarlet.base.support.sheets.GridBottomSheetBase
import com.maubis.scarlet.base.support.sheets.openSheet
import com.maubis.scarlet.base.support.ui.ThemedActivity
import com.maubis.scarlet.base.support.utils.FlavorUtils
import com.maubis.scarlet.base.support.utils.OsVersionUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class NoteOptionsBottomSheet() : GridBottomSheetBase() {
var noteFn: () -> Note? = { null }
override fun setupViewWithDialog(dialog: Dialog) {
val note = noteFn()
if (note === null) {
dismiss()
return
}
setOptionTitle(dialog, R.string.choose_action)
setupGrid(dialog, note)
setupCardViews(note)
makeBackgroundTransparent(dialog, R.id.root_layout)
}
private fun setupGrid(dialog: Dialog, note: Note) {
val gridLayoutIds = arrayOf(
R.id.quick_actions_properties,
R.id.note_properties,
R.id.grid_layout)
val gridOptionFunctions = arrayOf(
{ noteForAction: Note -> getQuickActions(noteForAction) },
{ noteForAction: Note -> getNotePropertyOptions(noteForAction) },
{ noteForAction: Note -> getOptions(noteForAction) })
gridOptionFunctions.forEachIndexed { index, function ->
GlobalScope.launch(Dispatchers.Main) {
val items = GlobalScope.async(Dispatchers.IO) { function(note) }
setOptions(dialog.findViewById<GridLayout>(gridLayoutIds[index]), items.await())
}
}
}
private fun setupCardViews(note: Note) {
val activity = context as ThemedActivity
val dlg = dialog
if (activity !is INoteOptionSheetActivity || dlg === null) {
return
}
val groupCardLayout = dlg.findViewById<LinearLayout>(R.id.group_card_layout)
val tagCardLayout = dlg.findViewById<View>(R.id.tag_card_layout)
val selectCardLayout = dlg.findViewById<View>(R.id.select_notes_layout)
val selectCardTitle = dlg.findViewById<TextView>(R.id.select_notes_title)
selectCardTitle.typeface = sAppTypeface.title()
val selectCardSubtitle = dlg.findViewById<TextView>(R.id.select_notes_subtitle)
selectCardSubtitle.typeface = sAppTypeface.title()
val tags = tagCardLayout.findViewById<TextView>(R.id.tags_content)
tags.typeface = sAppTypeface.title()
val tagSubtitle = tagCardLayout.findViewById<TextView>(R.id.tags_subtitle)
tagSubtitle.typeface = sAppTypeface.title()
val tagContent = note.getTagString()
if (tagContent.isNotBlank()) {
GlobalScope.launch(Dispatchers.Main) {
val text = GlobalScope.async(Dispatchers.IO) { Markdown.renderSegment(tagContent, true) }
tags.visibility = View.VISIBLE
tagSubtitle.visibility = View.GONE
tags.text = text.await()
groupCardLayout.orientation = VERTICAL
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val margin = activity.resources.getDimension(R.dimen.spacing_xxsmall).toInt()
params.setMargins(margin, margin, margin, margin)
tagCardLayout.layoutParams = params
selectCardLayout.layoutParams = params
}
}
tagCardLayout.setOnClickListener {
openSheet(activity, TagChooserBottomSheet().apply {
this.note = note
dismissListener = { activity.notifyTagsChanged(note) }
})
dismiss()
}
selectCardLayout.setOnClickListener {
val intent = Intent(context, SelectNotesActivity::class.java)
intent.putExtra(KEY_SELECT_EXTRA_MODE, activity.getSelectMode(note))
intent.putExtra(KEY_SELECT_EXTRA_NOTE_ID, note.uid)
activity.startActivity(intent)
dismiss()
}
selectCardLayout.visibility = View.VISIBLE
}
private fun getQuickActions(note: Note): List<OptionsItem> {
val activity = context as ThemedActivity
if (activity !is INoteOptionSheetActivity) {
return emptyList()
}
val options = ArrayList<OptionsItem>()
options.add(
OptionsItem(
title = R.string.restore_note,
subtitle = R.string.tap_for_action_not_trash,
icon = R.drawable.ic_restore,
listener = View.OnClickListener {
activity.markItem(note, NoteState.DEFAULT)
dismiss()
},
visible = note.getNoteState() == NoteState.TRASH
))
options.add(OptionsItem(
title = R.string.edit_note,
subtitle = R.string.tap_for_action_edit,
icon = R.drawable.ic_edit_white_48dp,
listener = View.OnClickListener {
note.edit(activity)
dismiss()
}
))
options.add(
OptionsItem(
title = R.string.not_favourite_note,
subtitle = R.string.tap_for_action_not_favourite,
icon = R.drawable.ic_favorite_white_48dp,
listener = View.OnClickListener {
activity.markItem(note, NoteState.DEFAULT)
dismiss()
},
visible = note.getNoteState() == NoteState.FAVOURITE
))
options.add(
OptionsItem(
title = R.string.favourite_note,
subtitle = R.string.tap_for_action_favourite,
icon = R.drawable.ic_favorite_border_white_48dp,
listener = View.OnClickListener {
activity.markItem(note, NoteState.FAVOURITE)
dismiss()
},
visible = note.getNoteState() != NoteState.FAVOURITE
))
options.add(
OptionsItem(
title = R.string.unarchive_note,
subtitle = R.string.tap_for_action_not_archive,
icon = R.drawable.ic_archive_white_48dp,
listener = View.OnClickListener {
activity.markItem(note, NoteState.DEFAULT)
dismiss()
},
visible = note.getNoteState() == NoteState.ARCHIVED
))
options.add(
OptionsItem(
title = R.string.archive_note,
subtitle = R.string.tap_for_action_archive,
icon = R.drawable.ic_archive_white_48dp,
listener = View.OnClickListener {
activity.markItem(note, NoteState.ARCHIVED)
dismiss()
},
visible = note.getNoteState() != NoteState.ARCHIVED
))
options.add(
OptionsItem(
title = R.string.send_note,
subtitle = R.string.tap_for_action_share,
icon = R.drawable.ic_share_white_48dp,
listener = View.OnClickListener {
note.share(activity)
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.copy_note,
subtitle = R.string.tap_for_action_copy,
icon = R.drawable.ic_content_copy_white_48dp,
listener = View.OnClickListener {
note.copy(activity)
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.delete_note_permanently,
subtitle = R.string.tap_for_action_delete,
icon = R.drawable.ic_delete_permanently,
listener = View.OnClickListener {
activity.moveItemToTrashOrDelete(note)
dismiss()
},
visible = note.getNoteState() == NoteState.TRASH,
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.trash_note,
subtitle = R.string.tap_for_action_trash,
icon = R.drawable.ic_delete_white_48dp,
listener = View.OnClickListener {
activity.moveItemToTrashOrDelete(note)
dismiss()
},
visible = note.getNoteState() != NoteState.TRASH,
invalid = activity.lockedContentIsHidden() && note.locked
))
return options
}
private fun getNotePropertyOptions(note: Note): List<OptionsItem> {
val activity = context as ThemedActivity
if (activity !is INoteOptionSheetActivity) {
return emptyList()
}
val options = ArrayList<OptionsItem>()
options.add(OptionsItem(
title = R.string.choose_note_color,
subtitle = R.string.tap_for_action_color,
icon = R.drawable.ic_action_color,
listener = View.OnClickListener {
val config = ColorPickerDefaultController(
title = R.string.choose_note_color,
colors = listOf(
activity.resources.getIntArray(R.array.bright_colors), activity.resources.getIntArray(R.array.bright_colors_accent)),
selectedColor = note.color,
onColorSelected = { color ->
note.color = color
activity.updateNote(note)
}
)
com.maubis.scarlet.base.support.sheets.openSheet(activity, ColorPickerBottomSheet().apply { this.config = config })
dismiss()
}
))
options.add(OptionsItem(
title = if (note.folder.isBlank()) R.string.folder_option_add_to_notebook else R.string.folder_option_change_notebook,
subtitle = R.string.folder_option_add_to_notebook,
icon = R.drawable.ic_folder,
listener = View.OnClickListener {
com.maubis.scarlet.base.support.sheets.openSheet(activity, FolderChooserBottomSheet().apply {
this.note = note
this.dismissListener = {
activity.notifyResetOrDismiss()
}
})
dismiss()
}
))
options.add(
OptionsItem(
title = R.string.lock_note,
subtitle = R.string.lock_note,
icon = R.drawable.ic_action_lock,
listener = View.OnClickListener {
note.locked = true
activity.updateNote(note)
dismiss()
},
visible = !note.locked
))
options.add(
OptionsItem(
title = R.string.unlock_note,
subtitle = R.string.unlock_note,
icon = R.drawable.ic_action_unlock,
listener = View.OnClickListener {
openUnlockSheet(
activity = activity,
onUnlockSuccess = {
note.locked = false
activity.updateNote(note)
dismiss()
},
onUnlockFailure = { })
},
visible = note.locked
))
return options
}
private fun getOptions(note: Note): List<OptionsItem> {
val activity = context as ThemedActivity
if (activity !is INoteOptionSheetActivity) {
return emptyList()
}
val options = ArrayList<OptionsItem>()
options.add(OptionsItem(
title = if (note.pinned) R.string.unpin_note else R.string.pin_note,
subtitle = if (note.pinned) R.string.unpin_note else R.string.pin_note,
icon = R.drawable.ic_pin,
listener = View.OnClickListener {
note.pinned = !note.pinned
activity.updateNote(note)
dismiss()
}
))
options.add(
OptionsItem(
title = R.string.share_images,
subtitle = R.string.share_images,
icon = R.drawable.icon_share_image,
listener = View.OnClickListener {
note.shareImages(activity)
dismiss()
},
visible = note.hasImages(),
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.open_in_notification,
subtitle = R.string.open_in_notification,
icon = R.drawable.ic_action_notification,
listener = View.OnClickListener {
val handler = NotificationHandler(themedContext())
handler.openNotification(NotificationConfig(note = note))
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.delete_note_permanently,
subtitle = R.string.delete_note_permanently,
icon = R.drawable.ic_delete_permanently,
listener = View.OnClickListener {
openDeleteNotePermanentlySheet(activity, note, { activity.notifyResetOrDismiss() })
dismiss()
},
visible = note.getNoteState() !== NoteState.TRASH,
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.pin_to_launcher,
subtitle = R.string.pin_to_launcher,
icon = R.drawable.icon_shortcut,
listener = View.OnClickListener {
if (!FlavorUtils.isLite() && OsVersionUtils.canAddLauncherShortcuts()) {
var title = note.getTitleForSharing()
if (title.isBlank()) {
title = note.getFullText().split("\n").firstOrNull() ?: "Note"
}
val shortcut = ShortcutInfo.Builder(activity, "scarlet_notes___${note.uuid}")
.setShortLabel(title)
.setLongLabel(title)
.setIcon(Icon.createWithResource(activity, R.mipmap.open_note_launcher))
.setIntent(NoteIntentRouterActivity.view(note))
.build()
addShortcut(activity, shortcut)
return@OnClickListener
}
openSheet(activity, InstallProUpsellBottomSheet())
},
visible = OsVersionUtils.canAddLauncherShortcuts(),
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.reminder,
subtitle = R.string.reminder,
icon = R.drawable.ic_action_reminder_icon,
listener = View.OnClickListener {
ReminderBottomSheet.openSheet(activity, note)
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.duplicate,
subtitle = R.string.duplicate,
icon = R.drawable.ic_duplicate,
listener = View.OnClickListener {
val copiedNote = NoteBuilder().copy(note)
copiedNote.uid = null
copiedNote.uuid = RandomHelper.getRandomString(24)
copiedNote.save(activity)
activity.notifyResetOrDismiss()
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.voice_action_title,
subtitle = R.string.voice_action_title,
icon = R.drawable.ic_action_speak_aloud,
listener = View.OnClickListener {
TextToSpeechBottomSheet.openSheet(activity, note)
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.view_distraction_free,
subtitle = R.string.view_distraction_free,
icon = R.drawable.ic_action_distraction_free,
listener = View.OnClickListener {
if (!FlavorUtils.isLite()) {
activity.startActivity(NoteIntentRouterActivity.view(activity, note, isDistractionFree = true))
return@OnClickListener
}
openSheet(activity, InstallProUpsellBottomSheet())
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.open_in_popup,
subtitle = R.string.tap_for_action_popup,
icon = R.drawable.ic_bubble_chart_white_48dp,
listener = View.OnClickListener {
ApplicationBase.instance.noteActions(note).popup(activity)
dismiss()
},
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.backup_note_enable,
subtitle = R.string.backup_note_enable,
icon = R.drawable.ic_action_backup,
listener = View.OnClickListener {
ApplicationBase.instance.noteActions(note).enableBackup(activity)
activity.updateNote(note)
dismiss()
},
visible = note.disableBackup && FlavorUtils.isPlayStore(),
invalid = activity.lockedContentIsHidden() && note.locked
))
options.add(
OptionsItem(
title = R.string.backup_note_disable,
subtitle = R.string.backup_note_disable,
icon = R.drawable.ic_action_backup_no,
listener = View.OnClickListener {
ApplicationBase.instance.noteActions(note).disableBackup(activity)
activity.updateNote(note)
dismiss()
},
visible = !note.disableBackup && FlavorUtils.isPlayStore(),
invalid = activity.lockedContentIsHidden() && note.locked
))
return options
}
override fun getLayout(): Int = R.layout.bottom_sheet_note_options
override fun getBackgroundCardViewIds(): Array<Int> = emptyArray()
override fun getOptionsTitleColor(selected: Boolean): Int {
return ContextCompat.getColor(themedContext(), R.color.light_primary_text)
}
companion object {
fun openSheet(activity: ThemedActivity, note: Note) {
val sheet = NoteOptionsBottomSheet()
sheet.noteFn = { note }
sheet.show(activity.supportFragmentManager, sheet.tag)
}
}
} | gpl-3.0 | d48c7a37cb2b6be9d617440eb18b0f57 | 35.774621 | 129 | 0.663113 | 4.229144 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKCodeBuilder.kt | 1 | 35292 | // 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.nj2k.printing
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.symbols.getDisplayFqName
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitorWithCommentsPrinting
import org.jetbrains.kotlin.nj2k.types.JKContextType
import org.jetbrains.kotlin.nj2k.types.isInterface
import org.jetbrains.kotlin.nj2k.types.isUnit
import org.jetbrains.kotlin.nj2k.types.updateNullability
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class JKCodeBuilder(context: NewJ2kConverterContext) {
private val elementInfoStorage = context.elementsInfoStorage
private val printer = JKPrinter(context.project, context.importStorage, elementInfoStorage)
private val commentPrinter = JKCommentPrinter(printer)
fun printCodeOut(root: JKTreeElement): String {
Visitor().also { root.accept(it) }
return printer.toString().replace("\r\n", "\n")
}
private inner class Visitor : JKVisitorWithCommentsPrinting() {
override fun printLeftNonCodeElements(element: JKFormattingOwner) {
commentPrinter.printTrailingComments(element)
}
override fun printRightNonCodeElements(element: JKFormattingOwner) {
commentPrinter.printLeadingComments(element)
}
private fun renderTokenElement(tokenElement: JKTokenElement) {
printLeftNonCodeElements(tokenElement)
printer.print(tokenElement.text)
printRightNonCodeElements(tokenElement)
}
private fun renderExtraTypeParametersUpperBounds(typeParameterList: JKTypeParameterList) {
val extraTypeBounds = typeParameterList.typeParameters
.filter { it.upperBounds.size > 1 }
if (extraTypeBounds.isNotEmpty()) {
printer.print(" where ")
val typeParametersWithBounds =
extraTypeBounds.flatMap { typeParameter ->
typeParameter.upperBounds.map { bound ->
typeParameter.name to bound
}
}
printer.renderList(typeParametersWithBounds) { (name, bound) ->
name.accept(this)
printer.print(" : ")
bound.accept(this)
}
}
}
private fun renderModifiersList(modifiersList: JKModifiersListOwner) {
val hasOverrideModifier = modifiersList
.safeAs<JKOtherModifiersOwner>()
?.hasOtherModifier(OtherModifier.OVERRIDE) == true
modifiersList.forEachModifier { modifierElement ->
if (modifierElement.modifier == Modality.FINAL || modifierElement.modifier == Visibility.PUBLIC) {
if (hasOverrideModifier) {
modifierElement.accept(this)
} else {
printLeftNonCodeElements(modifierElement)
printRightNonCodeElements(modifierElement)
}
} else {
modifierElement.accept(this)
}
printer.print(" ")
}
}
override fun visitTreeElementRaw(treeElement: JKElement) {
printer.print("/* !!! Hit visitElement for element type: ${treeElement::class} !!! */")
}
override fun visitModifierElementRaw(modifierElement: JKModifierElement) {
if (modifierElement.modifier != Modality.FINAL) {
printer.print(modifierElement.modifier.text)
}
}
override fun visitTreeRootRaw(treeRoot: JKTreeRoot) {
treeRoot.element.accept(this)
}
override fun visitKtTryExpressionRaw(ktTryExpression: JKKtTryExpression) {
printer.print("try ")
ktTryExpression.tryBlock.accept(this)
ktTryExpression.catchSections.forEach { it.accept(this) }
if (ktTryExpression.finallyBlock != JKBodyStub) {
printer.print("finally ")
ktTryExpression.finallyBlock.accept(this)
}
}
override fun visitKtTryCatchSectionRaw(ktTryCatchSection: JKKtTryCatchSection) {
printer.print("catch ")
printer.par {
ktTryCatchSection.parameter.accept(this)
}
ktTryCatchSection.block.accept(this)
}
override fun visitForInStatementRaw(forInStatement: JKForInStatement) {
printer.print("for (")
forInStatement.declaration.accept(this)
printer.print(" in ")
forInStatement.iterationExpression.accept(this)
printer.print(") ")
if (forInStatement.body.isEmpty()) {
printer.print(";")
} else {
forInStatement.body.accept(this)
}
}
override fun visitKtThrowExpressionRaw(ktThrowExpression: JKKtThrowExpression) {
printer.print("throw ")
ktThrowExpression.exception.accept(this)
}
override fun visitDoWhileStatementRaw(doWhileStatement: JKDoWhileStatement) {
printer.print("do ")
doWhileStatement.body.accept(this)
printer.print(" while (")
doWhileStatement.condition.accept(this)
printer.print(")")
}
override fun visitClassAccessExpressionRaw(classAccessExpression: JKClassAccessExpression) {
printer.renderSymbol(classAccessExpression.identifier, classAccessExpression)
}
override fun visitMethodAccessExpression(methodAccessExpression: JKMethodAccessExpression) {
printer.renderSymbol(methodAccessExpression.identifier, methodAccessExpression)
}
override fun visitTypeQualifierExpression(typeQualifierExpression: JKTypeQualifierExpression) {
printer.renderType(typeQualifierExpression.type, typeQualifierExpression)
}
override fun visitFileRaw(file: JKFile) {
if (file.packageDeclaration.name.value.isNotEmpty()) {
file.packageDeclaration.accept(this)
}
file.importList.accept(this)
file.declarationList.forEach { it.accept(this) }
}
override fun visitPackageDeclarationRaw(packageDeclaration: JKPackageDeclaration) {
printer.print("package ")
val packageNameEscaped = packageDeclaration.name.value.escapedAsQualifiedName()
printer.print(packageNameEscaped)
printer.println()
}
override fun visitImportListRaw(importList: JKImportList) {
importList.imports.forEach { it.accept(this) }
}
override fun visitImportStatementRaw(importStatement: JKImportStatement) {
printer.print("import ")
val importNameEscaped =
importStatement.name.value.escapedAsQualifiedName()
printer.print(importNameEscaped)
printer.println()
}
override fun visitBreakStatementRaw(breakStatement: JKBreakStatement) {
printer.print("break")
breakStatement.label.accept(this)
}
override fun visitClassRaw(klass: JKClass) {
klass.annotationList.accept(this)
if (klass.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(klass)
printer.print(" ")
printer.print(klass.classKind.text)
printer.print(" ")
klass.name.accept(this)
klass.typeParameterList.accept(this)
printer.print(" ")
val primaryConstructor = klass.primaryConstructor()
primaryConstructor?.accept(this)
if (klass.inheritance.present()) {
printer.print(" : ")
klass.inheritance.accept(this)
}
renderExtraTypeParametersUpperBounds(klass.typeParameterList)
klass.classBody.accept(this)
}
override fun visitInheritanceInfoRaw(inheritanceInfo: JKInheritanceInfo) {
val parentClass = inheritanceInfo.parentOfType<JKClass>()!!
val isInInterface = parentClass.classKind == JKClass.ClassKind.INTERFACE
inheritanceInfo.extends.forEach { it.type = it.type.updateNullability(Nullability.NotNull) }
inheritanceInfo.implements.forEach { it.type = it.type.updateNullability(Nullability.NotNull) }
if (isInInterface) {
printer.renderList(inheritanceInfo.extends) {
it.annotationList.accept(this)
printer.renderType(it.type, null)
}
} else {
inheritanceInfo.extends.singleOrNull()?.also { superTypeElement ->
superTypeElement.annotationList.accept(this)
printer.renderType(superTypeElement.type, null)
val primaryConstructor = parentClass.primaryConstructor()
val delegationCall =
primaryConstructor
?.delegationCall
?.let { it as? JKDelegationConstructorCall }
if (delegationCall != null) {
printer.par { delegationCall.arguments.accept(this) }
} else if (!superTypeElement.type.isInterface() && (primaryConstructor != null || parentClass.isObjectOrCompanionObject)) {
printer.print("()")
}
}
}
if (inheritanceInfo.implements.isNotEmpty() && inheritanceInfo.extends.size == 1) {
printer.print(", ")
}
printer.renderList(inheritanceInfo.implements) {
it.annotationList.accept(this)
printer.renderType(it.type, null)
}
}
private fun renderEnumConstants(enumConstants: List<JKEnumConstant>) {
printer.renderList(enumConstants) {
it.accept(this)
}
}
private fun renderNonEnumClassDeclarations(declarations: List<JKDeclaration>) {
printer.renderList(declarations, { printer.println() }) {
it.accept(this)
}
}
override fun visitFieldRaw(field: JKField) {
field.annotationList.accept(this)
if (field.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(field)
printer.print(" ")
field.name.accept(this)
if (field.type.present()) {
printer.print(":")
field.type.accept(this)
}
if (field.initializer !is JKStubExpression) {
printer.print(" = ")
field.initializer.accept(this)
}
}
override fun visitEnumConstantRaw(enumConstant: JKEnumConstant) {
enumConstant.annotationList.accept(this)
enumConstant.name.accept(this)
if (enumConstant.arguments.arguments.isNotEmpty()) {
printer.par {
enumConstant.arguments.accept(this)
}
}
if (enumConstant.body.declarations.isNotEmpty()) {
enumConstant.body.accept(this)
}
}
override fun visitKtInitDeclarationRaw(ktInitDeclaration: JKKtInitDeclaration) {
if (ktInitDeclaration.block.statements.isNotEmpty()) {
printer.print("init ")
ktInitDeclaration.block.accept(this)
}
}
override fun visitIsExpressionRaw(isExpression: JKIsExpression) {
isExpression.expression.accept(this)
printer.print(" is ")
isExpression.type.accept(this)
}
override fun visitParameterRaw(parameter: JKParameter) {
renderModifiersList(parameter)
printer.print(" ")
parameter.annotationList.accept(this)
if (parameter.isVarArgs) {
printer.print("vararg ")
}
if (parameter.parent is JKKtPrimaryConstructor
&& (parameter.parent?.parent?.parent as? JKClass)?.classKind == JKClass.ClassKind.ANNOTATION
) {
printer.print(" val ")
}
parameter.name.accept(this)
if (parameter.type.present() && parameter.type.type !is JKContextType) {
printer.print(":")
parameter.type.accept(this)
}
if (parameter.initializer !is JKStubExpression) {
printer.print(" = ")
parameter.initializer.accept(this)
}
}
override fun visitKtAnnotationArrayInitializerExpressionRaw(
ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression
) {
printer.print("[")
printer.renderList(ktAnnotationArrayInitializerExpression.initializers) {
it.accept(this)
}
printer.print("]")
}
override fun visitForLoopVariableRaw(forLoopVariable: JKForLoopVariable) {
forLoopVariable.annotationList.accept(this)
forLoopVariable.name.accept(this)
if (forLoopVariable.type.present() && forLoopVariable.type.type !is JKContextType) {
printer.print(": ")
forLoopVariable.type.accept(this)
}
}
override fun visitMethodRaw(method: JKMethod) {
method.annotationList.accept(this)
renderModifiersList(method)
printer.print(" fun ")
method.typeParameterList.accept(this)
elementInfoStorage.getOrCreateInfoForElement(method).let {
printer.print(it.render())
}
method.name.accept(this)
renderTokenElement(method.leftParen)
printer.renderList(method.parameters) {
it.accept(this)
}
renderTokenElement(method.rightParen)
if (!method.returnType.type.isUnit()) {
printer.print(": ")
method.returnType.accept(this)
}
renderExtraTypeParametersUpperBounds(method.typeParameterList)
method.block.accept(this)
}
override fun visitIfElseExpressionRaw(ifElseExpression: JKIfElseExpression) {
printer.print("if (")
ifElseExpression.condition.accept(this)
printer.print(")")
ifElseExpression.thenBranch.accept(this)
if (ifElseExpression.elseBranch !is JKStubExpression) {
printer.print(" else ")
ifElseExpression.elseBranch.accept(this)
}
}
override fun visitIfElseStatementRaw(ifElseStatement: JKIfElseStatement) {
printer.print("if (")
ifElseStatement.condition.accept(this)
printer.print(")")
if (ifElseStatement.thenBranch.isEmpty()) {
printer.print(";")
} else {
ifElseStatement.thenBranch.accept(this)
}
if (!ifElseStatement.elseBranch.isEmpty()) {
printer.print(" else ")
ifElseStatement.elseBranch.accept(this)
}
}
override fun visitBinaryExpressionRaw(binaryExpression: JKBinaryExpression) {
binaryExpression.left.accept(this)
printer.print(" ")
printer.print(binaryExpression.operator.token.text)
printer.print(" ")
binaryExpression.right.accept(this)
}
override fun visitTypeParameterListRaw(typeParameterList: JKTypeParameterList) {
if (typeParameterList.typeParameters.isNotEmpty()) {
printer.par(JKPrinterBase.ParenthesisKind.ANGLE) {
printer.renderList(typeParameterList.typeParameters) {
it.accept(this)
}
}
}
}
override fun visitTypeParameterRaw(typeParameter: JKTypeParameter) {
typeParameter.annotationList.accept(this)
typeParameter.name.accept(this)
if (typeParameter.upperBounds.size == 1) {
printer.print(" : ")
typeParameter.upperBounds.single().accept(this)
}
}
override fun visitLiteralExpressionRaw(literalExpression: JKLiteralExpression) {
printer.print(literalExpression.literal)
}
override fun visitPrefixExpressionRaw(prefixExpression: JKPrefixExpression) {
printer.print(prefixExpression.operator.token.text)
prefixExpression.expression.accept(this)
}
override fun visitThisExpressionRaw(thisExpression: JKThisExpression) {
printer.print("this")
thisExpression.qualifierLabel.accept(this)
}
override fun visitSuperExpressionRaw(superExpression: JKSuperExpression) {
printer.print("super")
superExpression.qualifierLabel.accept(this)
}
override fun visitContinueStatementRaw(continueStatement: JKContinueStatement) {
printer.print("continue")
continueStatement.label.accept(this)
printer.print(" ")
}
override fun visitLabelEmptyRaw(labelEmpty: JKLabelEmpty) {}
override fun visitLabelTextRaw(labelText: JKLabelText) {
printer.print("@")
labelText.label.accept(this)
printer.print(" ")
}
override fun visitLabeledExpressionRaw(labeledExpression: JKLabeledExpression) {
for (label in labeledExpression.labels) {
label.accept(this)
printer.print("@")
}
labeledExpression.statement.accept(this)
}
override fun visitNameIdentifierRaw(nameIdentifier: JKNameIdentifier) {
printer.print(nameIdentifier.value.escaped())
}
override fun visitPostfixExpressionRaw(postfixExpression: JKPostfixExpression) {
postfixExpression.expression.accept(this)
printer.print(postfixExpression.operator.token.text)
}
override fun visitQualifiedExpressionRaw(qualifiedExpression: JKQualifiedExpression) {
qualifiedExpression.receiver.accept(this)
printer.print(".")
qualifiedExpression.selector.accept(this)
}
override fun visitArgumentListRaw(argumentList: JKArgumentList) {
printer.renderList(argumentList.arguments) { it.accept(this) }
}
override fun visitArgumentRaw(argument: JKArgument) {
argument.value.accept(this)
}
override fun visitNamedArgumentRaw(namedArgument: JKNamedArgument) {
namedArgument.name.accept(this)
printer.print(" = ")
namedArgument.value.accept(this)
}
override fun visitCallExpressionRaw(callExpression: JKCallExpression) {
printer.renderSymbol(callExpression.identifier, callExpression)
callExpression.typeArgumentList.accept(this)
printer.par {
callExpression.arguments.accept(this)
}
}
override fun visitTypeArgumentListRaw(typeArgumentList: JKTypeArgumentList) {
if (typeArgumentList.typeArguments.isNotEmpty()) {
printer.par(JKPrinterBase.ParenthesisKind.ANGLE) {
printer.renderList(typeArgumentList.typeArguments) {
it.accept(this)
}
}
}
}
override fun visitParenthesizedExpressionRaw(parenthesizedExpression: JKParenthesizedExpression) {
printer.par {
parenthesizedExpression.expression.accept(this)
}
}
override fun visitDeclarationStatementRaw(declarationStatement: JKDeclarationStatement) {
printer.renderList(declarationStatement.declaredStatements, { printer.println() }) {
it.accept(this)
}
}
override fun visitTypeCastExpressionRaw(typeCastExpression: JKTypeCastExpression) {
typeCastExpression.expression.accept(this)
printer.print(" as ")
typeCastExpression.type.accept(this)
}
override fun visitWhileStatementRaw(whileStatement: JKWhileStatement) {
printer.print("while (")
whileStatement.condition.accept(this)
printer.print(")")
if (whileStatement.body.isEmpty()) {
printer.print(";")
} else {
whileStatement.body.accept(this)
}
}
override fun visitLocalVariableRaw(localVariable: JKLocalVariable) {
printer.print(" ")
localVariable.annotationList.accept(this)
renderModifiersList(localVariable)
printer.print(" ")
localVariable.name.accept(this)
if (localVariable.type.present() && localVariable.type.type != JKContextType) {
printer.print(": ")
localVariable.type.accept(this)
}
if (localVariable.initializer !is JKStubExpression) {
printer.print(" = ")
localVariable.initializer.accept(this)
}
}
override fun visitEmptyStatementRaw(emptyStatement: JKEmptyStatement) {}
override fun visitStubExpressionRaw(stubExpression: JKStubExpression) {}
override fun visitKtConvertedFromForLoopSyntheticWhileStatementRaw(
ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement
) {
printer.renderList(
ktConvertedFromForLoopSyntheticWhileStatement.variableDeclarations,
{ printer.println() }) {
it.accept(this)
}
printer.println()
ktConvertedFromForLoopSyntheticWhileStatement.whileStatement.accept(this)
}
override fun visitNewExpressionRaw(newExpression: JKNewExpression) {
if (newExpression.isAnonymousClass) {
printer.print("object : ")
}
printer.renderSymbol(newExpression.classSymbol, newExpression)
newExpression.typeArgumentList.accept(this)
if (!newExpression.classSymbol.isInterface() || newExpression.arguments.arguments.isNotEmpty()) {
printer.par(JKPrinterBase.ParenthesisKind.ROUND) {
newExpression.arguments.accept(this)
}
}
if (newExpression.isAnonymousClass) {
newExpression.classBody.accept(this)
}
}
override fun visitKtItExpressionRaw(ktItExpression: JKKtItExpression) {
printer.print("it")
}
override fun visitClassBodyRaw(classBody: JKClassBody) {
val declarationsToPrint = classBody.declarations.filterNot { it is JKKtPrimaryConstructor }
renderTokenElement(classBody.leftBrace)
if (declarationsToPrint.isNotEmpty()) {
printer.indented {
printer.println()
val enumConstants = declarationsToPrint.filterIsInstance<JKEnumConstant>()
val otherDeclarations = declarationsToPrint.filterNot { it is JKEnumConstant }
renderEnumConstants(enumConstants)
if ((classBody.parent as? JKClass)?.classKind == JKClass.ClassKind.ENUM
&& otherDeclarations.isNotEmpty()
) {
printer.print(";")
printer.println()
}
if (enumConstants.isNotEmpty() && otherDeclarations.isNotEmpty()) {
printer.println()
}
renderNonEnumClassDeclarations(otherDeclarations)
}
printer.println()
}
renderTokenElement(classBody.rightBrace)
}
override fun visitTypeElementRaw(typeElement: JKTypeElement) {
typeElement.annotationList.accept(this)
printer.renderType(typeElement.type, typeElement)
}
override fun visitBlockRaw(block: JKBlock) {
renderTokenElement(block.leftBrace)
if (block.statements.isNotEmpty()) {
printer.indented {
printer.println()
printer.renderList(block.statements, { printer.println() }) {
it.accept(this)
}
}
printer.println()
}
renderTokenElement(block.rightBrace)
}
override fun visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) {
printer.renderList(blockStatementWithoutBrackets.statements, { printer.println() }) {
it.accept(this)
}
}
override fun visitExpressionStatementRaw(expressionStatement: JKExpressionStatement) {
expressionStatement.expression.accept(this)
}
override fun visitReturnStatementRaw(returnStatement: JKReturnStatement) {
printer.print("return")
returnStatement.label.accept(this)
printer.print(" ")
returnStatement.expression.accept(this)
}
override fun visitFieldAccessExpressionRaw(fieldAccessExpression: JKFieldAccessExpression) {
printer.renderSymbol(fieldAccessExpression.identifier, fieldAccessExpression)
}
override fun visitPackageAccessExpressionRaw(packageAccessExpression: JKPackageAccessExpression) {
printer.renderSymbol(packageAccessExpression.identifier, packageAccessExpression)
}
override fun visitMethodReferenceExpressionRaw(methodReferenceExpression: JKMethodReferenceExpression) {
methodReferenceExpression.qualifier.accept(this)
printer.print("::")
val needFqName = methodReferenceExpression.qualifier is JKStubExpression
val displayName =
if (needFqName) methodReferenceExpression.identifier.getDisplayFqName()
else methodReferenceExpression.identifier.name
printer.print(displayName.escapedAsQualifiedName())
}
override fun visitDelegationConstructorCallRaw(delegationConstructorCall: JKDelegationConstructorCall) {
delegationConstructorCall.expression.accept(this)
printer.par {
delegationConstructorCall.arguments.accept(this)
}
}
private fun renderParameterList(parameters: List<JKParameter>) {
printer.par(JKPrinterBase.ParenthesisKind.ROUND) {
printer.renderList(parameters) {
it.accept(this)
}
}
}
override fun visitConstructorRaw(constructor: JKConstructor) {
constructor.annotationList.accept(this)
if (constructor.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(constructor)
printer.print(" constructor")
renderParameterList(constructor.parameters)
if (constructor.delegationCall !is JKStubExpression) {
printer.print(" : ")
constructor.delegationCall.accept(this)
}
constructor.block.accept(this)
}
override fun visitKtPrimaryConstructorRaw(ktPrimaryConstructor: JKKtPrimaryConstructor) {
ktPrimaryConstructor.annotationList.accept(this)
renderModifiersList(ktPrimaryConstructor)
printer.print(" constructor ")
if (ktPrimaryConstructor.parameters.isNotEmpty()) {
renderParameterList(ktPrimaryConstructor.parameters)
} else {
printer.print("()")
}
}
override fun visitLambdaExpressionRaw(lambdaExpression: JKLambdaExpression) {
val printLambda = {
printer.par(JKPrinterBase.ParenthesisKind.CURVED) {
if (lambdaExpression.statement.statements.size > 1)
printer.println()
printer.renderList(lambdaExpression.parameters) {
it.accept(this)
}
if (lambdaExpression.parameters.isNotEmpty()) {
printer.print(" -> ")
}
val statement = lambdaExpression.statement
if (statement is JKBlockStatement) {
printer.renderList(statement.block.statements, { printer.println() }) { it.accept(this) }
} else {
statement.accept(this)
}
if (lambdaExpression.statement.statements.size > 1) {
printer.println()
}
}
}
if (lambdaExpression.functionalType.present()) {
printer.renderType(lambdaExpression.functionalType.type, lambdaExpression)
printer.print(" ")
printer.par(JKPrinterBase.ParenthesisKind.ROUND, printLambda)
} else {
printLambda()
}
}
override fun visitBlockStatementRaw(blockStatement: JKBlockStatement) {
blockStatement.block.accept(this)
}
override fun visitKtAssignmentStatementRaw(ktAssignmentStatement: JKKtAssignmentStatement) {
ktAssignmentStatement.field.accept(this)
printer.print(" ")
printer.print(ktAssignmentStatement.token.text)
printer.print(" ")
ktAssignmentStatement.expression.accept(this)
}
override fun visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) {
assignmentChainAlsoLink.receiver.accept(this)
printer.print(".also({ ")
assignmentChainAlsoLink.assignmentStatement.accept(this)
printer.print(" })")
}
override fun visitAssignmentChainLetLinkRaw(assignmentChainLetLink: JKAssignmentChainLetLink) {
assignmentChainLetLink.receiver.accept(this)
printer.print(".let({ ")
assignmentChainLetLink.assignmentStatement.accept(this)
printer.print("; ")
assignmentChainLetLink.field.accept(this)
printer.print(" })")
}
override fun visitKtWhenBlockRaw(ktWhenBlock: JKKtWhenBlock) {
printer.print("when(")
ktWhenBlock.expression.accept(this)
printer.print(")")
printer.block {
printer.renderList(ktWhenBlock.cases, { printer.println() }) {
it.accept(this)
}
}
}
override fun visitKtWhenExpression(ktWhenExpression: JKKtWhenExpression) {
visitKtWhenBlockRaw(ktWhenExpression)
}
override fun visitKtWhenStatement(ktWhenStatement: JKKtWhenStatement) {
visitKtWhenBlockRaw(ktWhenStatement)
}
override fun visitAnnotationListRaw(annotationList: JKAnnotationList) {
printer.renderList(annotationList.annotations, " ") {
it.accept(this)
}
if (annotationList.annotations.isNotEmpty()) {
printer.print(" ")
}
}
override fun visitAnnotationRaw(annotation: JKAnnotation) {
printer.print("@")
printer.renderSymbol(annotation.classSymbol, annotation)
if (annotation.arguments.isNotEmpty()) {
printer.par {
printer.renderList(annotation.arguments) { it.accept(this) }
}
}
}
override fun visitAnnotationNameParameterRaw(annotationNameParameter: JKAnnotationNameParameter) {
annotationNameParameter.name.accept(this)
printer.print(" = ")
annotationNameParameter.value.accept(this)
}
override fun visitAnnotationParameterRaw(annotationParameter: JKAnnotationParameter) {
annotationParameter.value.accept(this)
}
override fun visitClassLiteralExpressionRaw(classLiteralExpression: JKClassLiteralExpression) {
if (classLiteralExpression.literalType == JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE) {
printer.print("Void.TYPE")
} else {
printer.renderType(classLiteralExpression.classType.type, classLiteralExpression)
printer.print("::")
when (classLiteralExpression.literalType) {
JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS -> printer.print("class")
JKClassLiteralExpression.ClassLiteralType.JAVA_CLASS -> printer.print("class.java")
JKClassLiteralExpression.ClassLiteralType.JAVA_PRIMITIVE_CLASS -> printer.print("class.javaPrimitiveType")
JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE -> Unit
}
}
}
override fun visitKtWhenCaseRaw(ktWhenCase: JKKtWhenCase) {
printer.renderList(ktWhenCase.labels) {
it.accept(this)
}
printer.print(" -> ")
ktWhenCase.statement.accept(this)
}
override fun visitKtElseWhenLabelRaw(ktElseWhenLabel: JKKtElseWhenLabel) {
printer.print("else")
}
override fun visitKtValueWhenLabelRaw(ktValueWhenLabel: JKKtValueWhenLabel) {
ktValueWhenLabel.expression.accept(this)
}
override fun visitErrorStatement(errorStatement: JKErrorStatement) {
visitErrorElement(errorStatement)
}
private fun visitErrorElement(errorElement: JKErrorElement) {
val message = buildString {
append("Cannot convert element: ${errorElement.reason}")
errorElement.psi?.let { append("\nWith text:\n${it.text}") }
}
printer.print("TODO(")
printer.indented {
printer.print("\"\"\"")
printer.println()
message.split('\n').forEach { line ->
printer.print("|")
printer.print(line.replace("$", "\\$"))
printer.println()
}
printer.print("\"\"\"")
}
printer.print(").trimMargin()")
}
}
}
| apache-2.0 | 2f616c472c9fc46b477fc958bad1c6a5 | 39.287671 | 143 | 0.596962 | 5.846918 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/KotlinSearchUsagesSupport.kt | 2 | 8426 | // 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.search
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DataClassResolver
import org.jetbrains.kotlin.resolve.ImportPath
interface KotlinSearchUsagesSupport {
interface ConstructorCallHandle {
fun referencedTo(element: KtElement): Boolean
}
companion object {
fun getInstance(project: Project): KotlinSearchUsagesSupport = project.service()
val KtParameter.dataClassComponentMethodName: String?
get() = getInstance(project).dataClassComponentMethodName(this)
val KtExpression.hasType: Boolean
get() = getInstance(project).hasType(this)
val PsiClass.isSamInterface: Boolean
get() = getInstance(project).isSamInterface(this)
fun <T : PsiNamedElement> List<T>.filterDataClassComponentsIfDisabled(kotlinOptions: KotlinReferencesSearchOptions): List<T> {
fun PsiNamedElement.isComponentElement(): Boolean {
if (this !is PsiMethod) return false
val dataClassParent = ((parent as? KtLightClass)?.kotlinOrigin as? KtClass)?.isData() == true
if (!dataClassParent) return false
if (!Name.isValidIdentifier(name)) return false
val nameIdentifier = Name.identifier(name)
if (!DataClassResolver.isComponentLike(nameIdentifier)) return false
return true
}
return if (kotlinOptions.searchForComponentConventions) this else filter { !it.isComponentElement() }
}
fun PsiReference.isCallableOverrideUsage(declaration: KtNamedDeclaration): Boolean =
getInstance(declaration.project).isCallableOverrideUsage(this, declaration)
fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration): Boolean =
getInstance(declaration.project).isUsageInContainingDeclaration(this, declaration)
fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclaration): Boolean =
getInstance(declaration.project).isExtensionOfDeclarationClassUsage(this, declaration)
fun PsiElement.getReceiverTypeSearcherInfo(isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? =
getInstance(project).getReceiverTypeSearcherInfo(this, isDestructionDeclarationSearch)
fun KtFile.forceResolveReferences(elements: List<KtElement>) =
getInstance(project).forceResolveReferences(this, elements)
fun PsiFile.scriptDefinitionExists(): Boolean =
getInstance(project).scriptDefinitionExists(this)
fun KtFile.getDefaultImports(): List<ImportPath> =
getInstance(project).getDefaultImports(this)
fun forEachKotlinOverride(
ktClass: KtClass,
members: List<KtNamedDeclaration>,
scope: SearchScope,
searchDeeply: Boolean,
processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean
): Boolean = getInstance(ktClass.project).forEachKotlinOverride(ktClass, members, scope, searchDeeply, processor)
fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> =
getInstance(method.project).findDeepestSuperMethodsNoWrapping(method)
fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> =
getInstance(project).findTypeAliasByShortName(shortName, project, scope)
fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean =
getInstance(element.project).isInProjectSource(element, includeScriptsOutsideSourceRoots)
fun KtDeclaration.isOverridable(): Boolean =
getInstance(project).isOverridable(this)
fun KtClass.isInheritable(): Boolean =
getInstance(project).isInheritable(this)
@NlsSafe
fun formatJavaOrLightMethod(method: PsiMethod): String =
getInstance(method.project).formatJavaOrLightMethod(method)
@NlsSafe
fun formatClass(classOrObject: KtClassOrObject): String =
getInstance(classOrObject.project).formatClass(classOrObject)
fun KtDeclaration.expectedDeclarationIfAny(): KtDeclaration? =
getInstance(project).expectedDeclarationIfAny(this)
fun KtDeclaration.isExpectDeclaration(): Boolean =
getInstance(project).isExpectDeclaration(this)
fun KtDeclaration.actualsForExpected(module: Module? = null): Set<KtDeclaration> =
getInstance(project).actualsForExpected(this, module)
fun PsiElement.canBeResolvedWithFrontEnd(): Boolean =
getInstance(project).canBeResolvedWithFrontEnd(this)
fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle =
getInstance(ktDeclaration.project).createConstructorHandle(ktDeclaration)
fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle =
getInstance(psiMethod.project).createConstructorHandle(psiMethod)
}
fun actualsForExpected(declaration: KtDeclaration, module: Module? = null): Set<KtDeclaration>
fun dataClassComponentMethodName(element: KtParameter): String?
fun hasType(element: KtExpression): Boolean
fun isSamInterface(psiClass: PsiClass): Boolean
fun isCallableOverrideUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean
fun isCallableOverride(subDeclaration: KtDeclaration, superDeclaration: PsiNamedElement): Boolean
fun isUsageInContainingDeclaration(reference: PsiReference, declaration: KtNamedDeclaration): Boolean
fun isExtensionOfDeclarationClassUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean
/**
*
* Extract the PSI class for the receiver type of [psiElement] assuming it is an _operator_.
* Additionally compute an occurence check for uses of the type in another, used to
* conservatively discard search candidates in which the type does not occur at all.
*
* TODO: rename to something more apt? The FE1.0 implementation requires that the target
* be an operator.
*/
fun getReceiverTypeSearcherInfo(psiElement: PsiElement, isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo?
fun forceResolveReferences(file: KtFile, elements: List<KtElement>)
fun scriptDefinitionExists(file: PsiFile): Boolean
fun getDefaultImports(file: KtFile): List<ImportPath>
fun forEachKotlinOverride(
ktClass: KtClass,
members: List<KtNamedDeclaration>,
scope: SearchScope,
searchDeeply: Boolean,
processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean
): Boolean
fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement>
fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement>
fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias>
fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean
fun isOverridable(declaration: KtDeclaration): Boolean
fun isInheritable(ktClass: KtClass): Boolean
fun formatJavaOrLightMethod(method: PsiMethod): String
fun formatClass(classOrObject: KtClassOrObject): String
fun expectedDeclarationIfAny(declaration: KtDeclaration): KtDeclaration?
fun isExpectDeclaration(declaration: KtDeclaration): Boolean
fun canBeResolvedWithFrontEnd(element: PsiElement): Boolean
fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle
fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle
}
| apache-2.0 | d4a720ed6366d33a9b2737f720cc2f05 | 43.115183 | 134 | 0.743651 | 5.875872 | false | false | false | false |
GunoH/intellij-community | platform/testFramework/ui/src/com/intellij/uiTests/robot/RobotRestService.kt | 3 | 14385 | // 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.uiTests.robot
import com.intellij.remoterobot.client.FindByXpathRequest
import com.intellij.remoterobot.data.*
import com.intellij.remoterobot.data.js.ExecuteScriptRequest
import com.intellij.remoterobot.encryption.Encryptor
import com.intellij.remoterobot.encryption.EncryptorFactory
import com.intellij.remoterobot.fixtures.dataExtractor.server.TextToKeyCache
import com.intellij.remoterobot.services.IdeRobot
import com.intellij.remoterobot.services.LambdaLoader
import com.intellij.remoterobot.services.js.RhinoJavaScriptExecutor
import com.intellij.remoterobot.services.xpath.XpathDataModelCreator
import com.intellij.remoterobot.services.xpath.convertToHtml
import com.intellij.remoterobot.utils.serializeToBytes
import com.intellij.uiTests.robot.routing.CantFindRouteException
import com.intellij.uiTests.robot.routing.StaticFile
import com.intellij.uiTests.robot.routing.route
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.util.CharsetUtil
import org.jetbrains.ide.RestService
import org.jetbrains.io.response
internal class RobotRestService : RestService() {
private val encryptor: Encryptor by lazy { EncryptorFactory().getInstance() }
init {
TextToKeyCache.init(javaClass.classLoader)
}
private val ideRobot: IdeRobot by lazy {
IdeRobot(TextToKeyCache, RhinoJavaScriptExecutor(), LambdaLoader())
}
override fun getServiceName(): String {
return "robot"
}
override fun isMethodSupported(method: HttpMethod): Boolean {
return method in listOf(HttpMethod.GET, HttpMethod.POST)
}
private val routing = route("/${PREFIX}/${getServiceName()}") {
get("/hello") {
CommonResponse(ResponseStatus.SUCCESS, "Hello", 0L)
}
static()
post("/component") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
ideRobot.find(lambdaContainer = lambda)
}) { result ->
FindComponentsResponse(
elementList = listOf(result.data!!), log = result.logs, time = result.time
)
}
}
post("/{id}/component") {
val lambda = request.receive<ObjectContainer>()
dataResultRequest({
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.find(
containerId = id,
lambdaContainer = lambda
)
}) { result ->
FindComponentsResponse(
elementList = listOf(result.data!!),
log = result.logs,
time = result.time
)
}
}
post("/xpath/component") {
val request = request.receive<FindByXpathRequest>()
dataResultRequest({ ideRobot.findByXpath(request.xpath) }) { result ->
FindComponentsResponse(
elementList = listOf(result.data!!), log = result.logs, time = result.time
)
}
}
post("/xpath/{id}/component") {
dataResultRequest({
val req = request.receive<FindByXpathRequest>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.findByXpath(
containerId = id,
xpath = req.xpath
)
}) { result ->
FindComponentsResponse(
elementList = listOf(result.data!!),
log = result.logs,
time = result.time
)
}
}
post("/xpath/components") {
dataResultRequest({
val request = request.receive<FindByXpathRequest>()
ideRobot.findAllByXpath(request.xpath)
}) { result ->
FindComponentsResponse(
elementList = result.data!!, log = result.logs, time = result.time
)
}
}
post("/xpath/{id}/components") {
dataResultRequest({
val req = request.receive<FindByXpathRequest>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.findAllByXpath(
containerId = id,
xpath = req.xpath
)
}) { result ->
FindComponentsResponse(elementList = result.data!!, log = result.logs, time = result.time)
}
}
post("/{id}/parentOfComponent") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.findParentOf(
containerId = id,
lambdaContainer = lambda
)
}) { result ->
FindComponentsResponse(
elementList = listOf(result.data!!),
log = result.logs,
time = result.time
)
}
}
post("/components") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
ideRobot.findAll(lambdaContainer = lambda)
}) { result ->
FindComponentsResponse(
elementList = result.data!!, log = result.logs, time = result.time
)
}
}
post("/{id}/components") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.findAll(
containerId = id,
lambdaContainer = lambda
)
}) { result ->
FindComponentsResponse(elementList = result.data!!, log = result.logs, time = result.time)
}
}
get("") {
hierarchy()
}
get("/") {
hierarchy()
}
get("/hierarchy") {
hierarchy()
}
get("/highlight") {
val parameters = QueryStringDecoder(request.uri()).parameters()
fun intParameter(name: String): Int = parameters[name]?.firstOrNull()?.toInt() ?: throw IllegalArgumentException("$name is missed")
val x = intParameter("x")
val y = intParameter("y")
val width = intParameter("width")
val height = intParameter("height")
ideRobot.highlight(x, y, width, height)
"ok"
}
post("/execute") {
commonRequest {
val lambda = request.receive<ObjectContainer>()
ideRobot.doAction(lambda)
}
}
post("/js/execute") {
commonRequest {
val req = request.receive<ExecuteScriptRequest>()
val decryptedRequest = req.decrypt(encryptor)
ideRobot.doAction(decryptedRequest.script, decryptedRequest.runInEdt)
}
}
post("/{id}/execute") {
commonRequest {
val lambda = request.receive<ObjectContainer>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.doAction(id, lambda)
}
}
post("/{id}/retrieveText") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.retrieveText(id, lambda)
}) { result ->
CommonResponse(message = result.data!!, log = result.logs, time = result.time)
}
}
post("/retrieveAny") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
ideRobot.retrieveAny(lambda)
}) { result ->
ByteResponse(
className = "",
bytes = result.data?.serializeToBytes() ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
post("/js/retrieveAny") {
dataResultRequest({
val req = request.receive<ExecuteScriptRequest>()
val decryptedRequest = req.decrypt(encryptor)
ideRobot.retrieveAny(decryptedRequest.script, decryptedRequest.runInEdt)
}) { result ->
println(result)
ByteResponse(
className = "",
bytes = result.data?.serializeToBytes() ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
post("/{id}/retrieveAny") {
dataResultRequest({
val lambda = request.receive<ObjectContainer>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.retrieveAny(id, lambda)
}) { result ->
ByteResponse(
className = "",
bytes = result.data?.serializeToBytes() ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
post("/{id}/data") {
dataResultRequest({
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
ideRobot.extractComponentData(id)
}) { result ->
ComponentDataResponse(componentData = result.data!!, log = result.logs, time = result.time)
}
}
get("/screenshot") {
dataResultRequest({ ideRobot.makeScreenshot() }) { result ->
ByteResponse(
className = "",
bytes = result.data ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
get("/{componentId}/screenshot") {
dataResultRequest({
val componentId =
pathParameters["componentId"] ?: throw IllegalArgumentException("empty componentId")
val isPaintingMode = urlDecoder.parameters()["isPaintingMode"]?.firstOrNull() ?: "false"
if (isPaintingMode.toBoolean())
ideRobot.makeScreenshotWithPainting(componentId)
else
ideRobot.makeScreenshot(componentId)
}) { result ->
ByteResponse(
className = "",
bytes = result.data ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
post("/{id}/js/execute") {
commonRequest {
val req = request.receive<ExecuteScriptRequest>()
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
val decryptedRequest = req.decrypt(encryptor)
ideRobot.doAction(id, decryptedRequest.script, decryptedRequest.runInEdt)
}
}
post("/{id}/js/retrieveAny") {
val req = request.receive<ExecuteScriptRequest>()
dataResultRequest({
val id = pathParameters["id"] ?: throw IllegalArgumentException("empty id")
val decryptedRequest = req.decrypt(encryptor)
ideRobot.retrieveAny(id, decryptedRequest.script, decryptedRequest.runInEdt)
}) { result ->
ByteResponse(
className = "",
bytes = result.data?.serializeToBytes() ?: ByteArray(0),
log = result.logs,
time = result.time
)
}
}
}
override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? {
try {
val response = when (val result = routing.handleRequest(urlDecoder, request, context)) {
is Response -> response("application/json", Unpooled.wrappedBuffer(gson.toJson(result).toByteArray()))
is String -> response("text/html", Unpooled.wrappedBuffer(result.toByteArray()))
is StaticFile -> response(result.type, Unpooled.wrappedBuffer(result.byteArray))
else -> throw NotImplementedError("${result::class.java} type is not supported")
}
sendResponse(request, context, response)
}
catch (e: CantFindRouteException) {
e.printStackTrace()
sendStatus(HttpResponseStatus.BAD_REQUEST, HttpUtil.isKeepAlive(request), context.channel())
}
return null
}
private inline fun <reified T> FullHttpRequest.receive(): T {
//return mapper.readValue(content().toString(CharsetUtil.US_ASCII), T::class.java)
return gson.fromJson(content().toString(CharsetUtil.US_ASCII), T::class.java)
}
private fun hierarchy(): String {
val doc = XpathDataModelCreator(TextToKeyCache).create(null)
return doc.convertToHtml()
.replace("src=\"", "src=\"${getServiceName()}/")
.replace("href=\"styles.css\"", "href=\"${getServiceName()}/styles.css\"")
}
private fun <T> dataResultRequest(
code: () -> IdeRobot.Result<T>,
responseMapper: (IdeRobot.Result<T>) -> Response
): Response {
return try {
val result = code()
if (result.exception == null) {
responseMapper(result)
}
else {
CommonResponse(
ResponseStatus.ERROR,
result.exception!!.message,
result.time,
result.exception,
result.logs
)
}
}
catch (e: Throwable) {
e.printStackTrace()
CommonResponse(ResponseStatus.ERROR, e.message ?: "", 0L, e)
}.apply { println(this) }
}
private fun commonRequest(code: () -> IdeRobot.Result<Unit>): Response {
return try {
val result = code()
if (result.exception == null) {
CommonResponse(log = result.logs, time = result.time)
}
else {
CommonResponse(
ResponseStatus.ERROR,
result.exception!!.message,
result.time,
result.exception,
result.logs
)
}
}
catch (e: Throwable) {
e.printStackTrace()
CommonResponse(ResponseStatus.ERROR, e.message, 0L, e)
}
}
} | apache-2.0 | 7208a2349d7d79f3675a8e40c1772469 | 33.66506 | 137 | 0.56399 | 4.974066 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SoftLinkReferencedChildImpl.kt | 2 | 9181 | 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.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.annotations.Open
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SoftLinkReferencedChildImpl(val dataSource: SoftLinkReferencedChildData) : SoftLinkReferencedChild, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(EntityWithSoftLinks::class.java,
SoftLinkReferencedChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: EntityWithSoftLinks
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SoftLinkReferencedChildData?) : ModifiableWorkspaceEntityBase<SoftLinkReferencedChild, SoftLinkReferencedChildData>(
result), SoftLinkReferencedChild.Builder {
constructor() : this(SoftLinkReferencedChildData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SoftLinkReferencedChild is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// 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 (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field SoftLinkReferencedChild#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field SoftLinkReferencedChild#parentEntity 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 SoftLinkReferencedChild
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<EntityWithSoftLinks>().single()
if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: EntityWithSoftLinks
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityClass(): Class<SoftLinkReferencedChild> = SoftLinkReferencedChild::class.java
}
}
class SoftLinkReferencedChildData : WorkspaceEntityData<SoftLinkReferencedChild>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SoftLinkReferencedChild> {
val modifiable = SoftLinkReferencedChildImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SoftLinkReferencedChild {
return getCached(snapshot) {
val entity = SoftLinkReferencedChildImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SoftLinkReferencedChild::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SoftLinkReferencedChild(entitySource) {
this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(EntityWithSoftLinks::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SoftLinkReferencedChildData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SoftLinkReferencedChildData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 7fba3c1599194f073b3ab9b3ebb2ae0d | 37.57563 | 157 | 0.702647 | 5.577764 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/DemoBinding.kt | 1 | 3127 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.ui.uiDslShowcase
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.dsl.builder.*
import com.intellij.util.Alarm
import org.jetbrains.annotations.ApiStatus
import java.awt.Font
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.SwingUtilities
@Suppress("DialogTitleCapitalization")
@Demo(title = "Binding",
description = "It is possible to bind component values to properties. Such properties are applied only when DialogPanel.apply is invoked. " +
"Methods DialogPanel.isModified and DialogPanel.reset are also supported automatically for bound properties",
scrollbar = true)
fun demoBinding(parentDisposable: Disposable): DialogPanel {
lateinit var lbIsModified: JLabel
lateinit var lbModel: JLabel
lateinit var panel: DialogPanel
val alarm = Alarm(parentDisposable)
val model = Model()
fun initValidation() {
alarm.addRequest(Runnable {
val modified = panel.isModified()
lbIsModified.text = "isModified: $modified"
lbIsModified.bold(modified)
lbModel.text = "<html>$model"
initValidation()
}, 1000)
}
panel = panel {
row {
checkBox("Checkbox")
.bindSelected(model::checkbox)
}
row("textField:") {
textField()
.bindText(model::textField)
}
row("intTextField(0..100):") {
intTextField()
.bindIntText(model::intTextField)
}
row("comboBox:") {
comboBox(Color.values().toList())
.bindItem(model::comboBoxColor)
}
row("slider:") {
slider(0, 100, 10, 50)
.bindValue(model::slider)
}
row("spinner:") {
spinner(0..100)
.bindIntValue(model::spinner)
}
buttonsGroup(title = "radioButton:") {
for (value in Color.values()) {
row {
radioButton(value.name, value)
}
}
}.bind(model::radioButtonColor)
group("DialogPanel Control") {
row {
button("Reset") {
panel.reset()
}
button("Apply") {
panel.apply()
}
lbIsModified = label("").component
}
row {
lbModel = label("").component
}
}
}
val disposable = Disposer.newDisposable()
panel.registerValidators(disposable)
Disposer.register(parentDisposable, disposable)
SwingUtilities.invokeLater {
initValidation()
}
return panel
}
private fun JComponent.bold(isBold: Boolean) {
font = font.deriveFont(if (isBold) Font.BOLD else Font.PLAIN)
}
@ApiStatus.Internal
internal data class Model(
var checkbox: Boolean = false,
var textField: String = "",
var intTextField: Int = 0,
var comboBoxColor: Color = Color.GREY,
var slider: Int = 0,
var spinner: Int = 0,
var radioButtonColor: Color = Color.GREY,
)
@ApiStatus.Internal
internal enum class Color {
WHITE,
GREY,
BLACK
}
| apache-2.0 | 4fe34659ecf8200885749c8aca9a9eaa | 25.5 | 158 | 0.663256 | 4.242877 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnlabeledReturnInsideLambdaInspection.kt | 4 | 1976 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.quickfix.ChangeToLabeledReturnFix
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.returnExpressionVisitor
class UnlabeledReturnInsideLambdaInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
returnExpressionVisitor(fun(returnExpression: KtReturnExpression) {
if (returnExpression.labelQualifier != null) return
val lambda = returnExpression.getParentOfType<KtLambdaExpression>(true, KtNamedFunction::class.java) ?: return
val parentFunction = lambda.getStrictParentOfType<KtNamedFunction>() ?: return
if (returnExpression.analyze().diagnostics.forElement(returnExpression).any { it.severity == Severity.ERROR }) return
holder.registerProblem(
returnExpression.returnKeyword,
KotlinBundle.message("unlabeled.return.inside.lambda"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(ChangeToLabeledReturnFix(returnExpression, labeledReturn = "return@${parentFunction.name}"))
)
})
} | apache-2.0 | e17df62f1e44e3c403a38d6836303320 | 57.147059 | 158 | 0.782389 | 5.21372 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/utils/StatisticsCachedConfigTest.kt | 12 | 1867 | // 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.internal.statistics.utils
import com.intellij.internal.statistic.eventLog.connection.StatisticsCachingSupplier
import junit.framework.TestCase
import org.junit.Test
import kotlin.test.assertEquals
class StatisticsCachedConfigTest {
@Test
fun `test cached value`() {
var counter = 0
val supplier = StatisticsCachingSupplier<Int>({ ++counter }, 50)
assertEquals(1, supplier.get())
assertEquals(1, supplier.get())
assertEquals(1, supplier.get())
assertEquals(1, supplier.get())
Thread.sleep(50)
assertEquals(2, supplier.get())
assertEquals(2, supplier.get())
assertEquals(2, supplier.get())
}
@Test
fun `test value re-calculated on short timeout`() {
var counter = 0
val supplier = StatisticsCachingSupplier<Int>({ ++counter }, 4)
assertEquals(1, supplier.get())
Thread.sleep(5)
assertEquals(2, supplier.get())
Thread.sleep(5)
assertEquals(3, supplier.get())
Thread.sleep(5)
assertEquals(4, supplier.get())
}
@Test
fun `test value re-calculated on exception`() {
var counter = 0
val supplier = StatisticsCachingSupplier<Int>(
{ ++counter; if (counter % 2 == 0) throw RuntimeException() else counter },
4
)
assertEquals(1, supplier.get())
Thread.sleep(5)
assertExceptionThrown(Runnable { supplier.get() })
assertEquals(3, supplier.get())
Thread.sleep(5)
assertExceptionThrown(Runnable { supplier.get() })
assertEquals(5, supplier.get())
}
private fun assertExceptionThrown(runnable: Runnable) {
var thrown = false
try {
runnable.run()
}
catch (e: RuntimeException) {
thrown = true
}
TestCase.assertTrue(thrown)
}
} | apache-2.0 | dc96db997539d4cb0329499710152d5c | 26.880597 | 140 | 0.681307 | 4.058696 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinPackageEntryTableAccessor.kt | 6 | 2150 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.formatter
import com.intellij.application.options.codeStyle.properties.CodeStylePropertiesUtil
import com.intellij.application.options.codeStyle.properties.ValueListPropertyAccessor
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntry
import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntryTable
import java.lang.reflect.Field
class KotlinPackageEntryTableAccessor(kotlinCodeStyle: KotlinCodeStyleSettings, field: Field) :
ValueListPropertyAccessor<KotlinPackageEntryTable>(kotlinCodeStyle, field) {
override fun valueToString(value: List<String>): String = CodeStylePropertiesUtil.toCommaSeparatedString(value)
override fun fromExternal(extVal: List<String>): KotlinPackageEntryTable = KotlinPackageEntryTable(
extVal.asSequence().map(String::trim).map(::readPackageEntry).toMutableList()
)
override fun isEmptyListAllowed(): Boolean = false
override fun toExternal(value: KotlinPackageEntryTable): List<String> = value.getEntries().map(::writePackageEntry)
companion object {
private const val ALIAS_CHAR = "^"
private const val OTHER_CHAR = "*"
private fun readPackageEntry(string: String): KotlinPackageEntry = when {
string == ALIAS_CHAR -> KotlinPackageEntry.ALL_OTHER_ALIAS_IMPORTS_ENTRY
string == OTHER_CHAR -> KotlinPackageEntry.ALL_OTHER_IMPORTS_ENTRY
string.endsWith("**") -> KotlinPackageEntry(string.substring(0, string.length - 1), true)
else -> KotlinPackageEntry(string, false)
}
private fun writePackageEntry(entry: KotlinPackageEntry): String = when (entry) {
KotlinPackageEntry.ALL_OTHER_ALIAS_IMPORTS_ENTRY -> ALIAS_CHAR
KotlinPackageEntry.ALL_OTHER_IMPORTS_ENTRY -> OTHER_CHAR
else -> "${entry.packageName}.*" + if (entry.withSubpackages) "*" else ""
}
}
}
| apache-2.0 | e79cfa6f1ce89f9741caa4054091f77b | 50.190476 | 158 | 0.744186 | 4.423868 | false | false | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/irc/message/rfc1459/rpl/Rpl353Message.kt | 2 | 1613 | package chat.willow.kale.irc.message.rfc1459.rpl
import chat.willow.kale.core.ICommand
import chat.willow.kale.core.message.*
import chat.willow.kale.irc.CharacterCodes
object Rpl353Message : ICommand {
override val command = "353"
data class Message(val source: String, val target: String, val visibility: String, val channel: String, val names: List<String>) {
object Descriptor : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = Parser)
object Parser : MessageParser<Message>() {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 4) {
return null
}
val source = components.prefix ?: ""
val target = components.parameters[0]
val visibility = components.parameters[1]
val channel = components.parameters[2]
val names = components.parameters[3].split(delimiters = CharacterCodes.SPACE).filterNot(String::isEmpty)
return Message(source, target, visibility, channel, names)
}
}
object Serialiser : MessageSerialiser<Message>(command) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val names = message.names.joinToString(separator = CharacterCodes.SPACE.toString())
return IrcMessageComponents(prefix = message.source, parameters = listOf(message.target, message.visibility, message.channel, names))
}
}
}
} | isc | 2e35f445294835f40ced453adfff9b9e | 34.866667 | 149 | 0.647241 | 5.040625 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/locks.kt | 3 | 1502 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.util
import com.intellij.openapi.progress.ProgressManager
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
internal inline fun <T> ReentrantReadWriteLock.writeWithCheckCanceled(action: () -> T): T {
val rl = readLock()
val readCount = if (writeHoldCount == 0) readHoldCount else 0
repeat(readCount) { rl.unlock() }
val wl = writeLock()
while (!wl.tryLock(100, TimeUnit.MILLISECONDS)) {
ProgressManager.checkCanceled()
}
try {
return action()
} finally {
repeat(readCount) { rl.lock() }
wl.unlock()
}
}
/**
* It is preferable to use [CheckCanceledLock] instead of [ReentrantLock] in case of mix of
* [IntelliJ Read-Write locks](https://plugins.jetbrains.com/docs/intellij/general-threading-rules.html) and regular locks.
*
* To acquire lock has to be cancellable action as read actions.
*/
class CheckCanceledLock {
private val lock = ReentrantLock()
internal inline fun <T> withLock(action: () -> T): T {
while (!lock.tryLock(100, TimeUnit.MILLISECONDS)) {
ProgressManager.checkCanceled()
}
try {
return action()
} finally {
lock.unlock()
}
}
} | apache-2.0 | 077972ba78d838eac968fe18060c433c | 31.673913 | 158 | 0.676431 | 4.207283 | false | false | false | false |
TimePath/launcher | src/main/kotlin/com/timepath/launcher/ui/swing/LauncherFrame.kt | 1 | 19792 | package com.timepath.launcher.ui.swing
import com.timepath.IOUtils
import com.timepath.SwingUtils
import com.timepath.launcher.Launcher
import com.timepath.launcher.LauncherUtils
import com.timepath.launcher.data.DownloadManager.DownloadMonitor
import com.timepath.launcher.data.Program
import com.timepath.launcher.data.Repository
import com.timepath.launcher.data.RepositoryManager
import com.timepath.maven.Package
import com.timepath.maven.PersistentCache
import com.timepath.swing.ThemeSelector
import java.awt.*
import java.awt.event.*
import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
import java.util.concurrent.ExecutionException
import java.util.concurrent.atomic.AtomicInteger
import java.util.logging.Level
import java.util.logging.Logger
import java.util.prefs.BackingStoreException
import java.util.regex.Pattern
import javax.swing.*
import javax.swing.event.TreeSelectionEvent
import javax.swing.event.TreeSelectionListener
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreePath
import kotlin.properties.Delegates
public class LauncherFrame(protected var launcher: Launcher) : JFrame() {
protected var repositoryManager: RepositoryManagerPanel = object : RepositoryManagerPanel() {
override fun addActionPerformed(evt: ActionEvent) {
// FIXME: showInternalInputDialog returns immediately
val `in` = JOptionPane.showInputDialog([email protected](), "Enter URL")
if (`in` == null) return
val r = Repository.fromIndex(`in`)
if (r == null) {
JOptionPane.showInternalMessageDialog([email protected](), "Invalid repository", "Invalid repository", JOptionPane.WARNING_MESSAGE)
} else {
RepositoryManager.addRepository(r)
updateList()
}
}
override fun removeActionPerformed(evt: ActionEvent) {
var i = 0
val selection = jTable1!!.getSelectedRows()
selection.sort()
val rows = model!!.getRows()
for (r in rows.toTypedArray()) {
val selected = selection.binarySearch(i++) >= 0
if (selected) RepositoryManager.removeRepository(r)
}
updateList()
}
}
protected var aboutPanel: JPanel by Delegates.notNull()
protected var downloadPanel: DownloadPanel by Delegates.notNull()
protected var launchButton: JButton by Delegates.notNull()
protected var newsScroll: JScrollPane by Delegates.notNull()
protected var programList: JTree? = null
protected var programSplit: JSplitPane by Delegates.notNull()
protected var tabs: JTabbedPane by Delegates.notNull()
init {
// Has to be here to catch exceptions occurring on the EDT
Thread.setDefaultUncaughtExceptionHandler(object : Thread.UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
val msg = "Uncaught Exception in $t:"
Logger.getLogger(t.getName()).log(Level.SEVERE, msg, e)
val sw = StringWriter()
e.printStackTrace(PrintWriter(sw))
JOptionPane.showInternalMessageDialog([email protected](), object : JScrollPane(object : JTextArea("$msg\n${sw.toString()}") {
init {
setEditable(false)
setTabSize(4)
}
}) {
init {
val size = [email protected]()
size.width /= 2
size.height /= 2
setPreferredSize(size)
}
}, "Uncaught Exception", JOptionPane.ERROR_MESSAGE)
}
})
}
init {
launcher.downloadManager.addListener(object : DownloadMonitor {
var c = AtomicInteger()
override fun onSubmit(pkgFile: Package) {
downloadPanel.tableModel!!.add(pkgFile)
updateTitle(c.incrementAndGet())
}
fun updateTitle(i: Int) {
setTitle("Downloads${if (i > 0) " ($i)" else ""}")
}
fun setTitle(title: String) {
val index = tabs.indexOfComponent(downloadPanel)
tabs.setTitleAt(index, title)
}
override fun onUpdate(pkgFile: Package) {
downloadPanel.tableModel!!.update(pkgFile)
}
override fun onFinish(pkgFile: Package) {
updateTitle(c.decrementAndGet())
}
})
this.initComponents()
this.updateList()
this.setTitle("TimePath's program hub")
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
val mid = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint()
this.setSize(Dimension(mid.x, mid.y))
this.setLocationRelativeTo(null)
LOG.log(Level.INFO, "Created UI at {0}ms", System.currentTimeMillis() - LauncherUtils.START_TIME)
}
/**
* Schedule a listing update
*/
protected fun updateList() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))
object : SwingWorker<MutableList<Repository>, Void>() {
override fun doInBackground(): MutableList<Repository> {
return launcher.getRepositories(true)
}
override fun done() {
try {
LOG.log(Level.INFO, "Listing at {0}ms", System.currentTimeMillis() - LauncherUtils.START_TIME)
val repos = get()
repositoryManager.setRepositories(repos)
// Update the program list
val rootNode = DefaultMutableTreeNode()
for (repo in repos) {
var repoNode = rootNode
// Create a new pseudo root node if there are multiple repositories
if (repos.size() > 1) {
repoNode = DefaultMutableTreeNode(repo.getName())
rootNode.add(repoNode)
}
for (p in repo.getExecutions()) {
repoNode.add(DefaultMutableTreeNode(p))
}
}
val newModel = DefaultTreeModel(rootNode)
programList!!.setModel(newModel)
val firstLeaf = rootNode.getFirstLeaf()
val path = TreePath(firstLeaf.getPath())
programList!!.expandPath(path)
programList!!.setSelectionPath(path)
pack(programSplit)
if (!LauncherUtils.DEBUG && launcher.updateRequired()) {
// Show update notification
JOptionPane.showInternalMessageDialog([email protected](), "Please update", "A new version is available", JOptionPane.INFORMATION_MESSAGE, null)
}
} catch (e: InterruptedException) {
LOG.log(Level.SEVERE, null, e)
} catch (e: ExecutionException) {
LOG.log(Level.SEVERE, null, e)
} finally {
[email protected](Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR))
}
}
}.execute()
}
/**
* Hack to pack the SplitPane
*/
protected fun pack(programSplit: JSplitPane) {
val pcl = object : PropertyChangeListener {
/** Flag to ignore the first event */
var ignore = true
override fun propertyChange(evt: PropertyChangeEvent) {
if (ignore) {
ignore = false
return
}
programSplit.removePropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, this)
programSplit.setDividerLocation(Math.max(evt.getNewValue() as Int, programList!!.getPreferredScrollableViewportSize().width))
}
}
programSplit.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, pcl)
programSplit.setDividerLocation(-1)
}
protected fun initComponents() {
aboutPanel = object : JPanel(BorderLayout()) {
init {
add(initAboutPanel(), BorderLayout.CENTER)
}
}
setContentPane(object : JTabbedPane() {
init {
addTab("Programs", object : JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true) {
init {
setLeftComponent(JScrollPane(with(JTree()) {
setModel(null)
setRootVisible(false)
setShowsRootHandles(true)
getSelectionModel().addTreeSelectionListener(object : TreeSelectionListener {
override fun valueChanged(e: TreeSelectionEvent) {
news(getSelected(getLastSelectedPathComponent()))
}
})
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) start(getSelected(getLastSelectedPathComponent()))
}
})
val adapter = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
if (select(e) == -1) return
if (SwingUtilities.isLeftMouseButton(e) && (e.getClickCount() >= 2)) {
val p = getSelected(getLastSelectedPathComponent())
start(p)
}
}
override fun mousePressed(e: MouseEvent) {
select(e)
}
override fun mouseDragged(e: MouseEvent) {
select(e)
}
private fun select(e: MouseEvent): Int {
val selRow = getClosestRowForLocation(e.getX(), e.getY())
setSelectionRow(selRow)
return selRow
}
}
addMouseMotionListener(adapter)
addMouseListener(adapter)
this
}.let {
programList = it
it
}))
setRightComponent(object : JPanel(BorderLayout()) {
init {
add(object : JScrollPane() {
init {
getVerticalScrollBar().setUnitIncrement(16)
}
}.let {
newsScroll = it
it
}, BorderLayout.CENTER)
add(JButton(object : AbstractAction("Launch") {
override fun actionPerformed(e: ActionEvent) {
start(getSelected(programList!!.getLastSelectedPathComponent()))
}
}).let {
launchButton = it
it
}, BorderLayout.SOUTH)
launchButton.setEnabled(false)
}
})
}
}.let {
programSplit = it
it
})
addTab("Downloads", DownloadPanel().let {
downloadPanel = it
it
})
}
}.let {
tabs = it
it
})
setJMenuBar(object : JMenuBar() {
init {
add(object : JMenu("Tools") {
init {
add(JMenuItem(object : AbstractAction("Repository management") {
override fun actionPerformed(e: ActionEvent) {
JOptionPane.showInternalMessageDialog([email protected](), repositoryManager, "Repository manager", JOptionPane.PLAIN_MESSAGE)
}
}))
add(JMenuItem(object : AbstractAction("Clear cache") {
override fun actionPerformed(event: ActionEvent) {
try {
PersistentCache.drop()
JOptionPane.showInternalMessageDialog([email protected](), "Restart to check for updates", "Cleared cache", JOptionPane.INFORMATION_MESSAGE)
} catch (e: BackingStoreException) {
LOG.log(Level.WARNING, "Unable to drop caches", e)
JOptionPane.showInternalMessageDialog([email protected](), "Unable to clear cache", "Error", JOptionPane.ERROR_MESSAGE)
}
}
}))
add(JMenuItem(object : AbstractAction("Preferences") {
override fun actionPerformed(e: ActionEvent) {
JOptionPane.showInternalMessageDialog([email protected](), ThemeSelector(), "Select theme", JOptionPane.PLAIN_MESSAGE)
}
}))
}
})
add(object : JMenu("Help") {
init {
add(JMenuItem(object : AbstractAction("About") {
override fun actionPerformed(e: ActionEvent) {
JOptionPane.showInternalMessageDialog([email protected](), aboutPanel)
}
}))
}
})
}
})
}
/**
* Display the news for a program
*/
protected fun news(p: Program?) {
if (p == null) {
// Handle things other than programs
newsScroll.setViewportView(null)
launchButton.setEnabled(false)
} else {
newsScroll.setViewportView(p.getPanel())
launchButton.setEnabled(!Launcher.isLocked(p.`package`))
}
}
protected fun start(program: Program?) {
if (program == null) return // Handle things other than programs
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))
launchButton.setEnabled(false)
object : SwingWorker<Set<Package>, Void>() {
override fun doInBackground(): Set<Package>? {
return launcher.update(program)
}
override fun done() {
try {
val updates = get()
if (updates != null) {
// Ready to start
val parent = program.`package`
var run = true
if (!LauncherUtils.DEBUG && parent.isSelf()) {
// Alert on self update
if (parent in updates) {
run = false
JOptionPane.showInternalMessageDialog([email protected](), "Restart to apply", "Update downloaded", JOptionPane.INFORMATION_MESSAGE, null)
} else {
run = false
JOptionPane.showInternalMessageDialog([email protected](), "Launcher is up to date", "Launcher is up to date", JOptionPane.INFORMATION_MESSAGE, null)
}
}
if (run) {
launcher.start(program)
}
}
} catch (e: InterruptedException) {
LOG.log(Level.SEVERE, null, e)
} catch (e: ExecutionException) {
LOG.log(Level.SEVERE, null, e)
} finally {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR))
launchButton.setEnabled(true)
}
}
}.execute()
}
protected fun initAboutPanel(): JEditorPane {
val pane = object : JEditorPane("text/html", "") {
init {
setEditable(false)
setOpaque(false)
setBackground(Color(255, 255, 255, 0))
addHyperlinkListener(SwingUtils.HYPERLINK_LISTENER)
}
}
var buildDate = "unknown"
val time = LauncherUtils.CURRENT_VERSION
val df = SimpleDateFormat("EEE dd MMM yyyy, hh:mm:ss a z")
if (time != 0L) buildDate = df.format(Date(time))
val aboutText = IOUtils.requestPage(javaClass.getResource("/com/timepath/launcher/ui/swing/about.html").toString())!!
.replace("\${buildDate}", buildDate)
.replace("\${steamGroup}", "http://steamcommunity.com/gid/103582791434775526")
.replace("\${steamChat}", "steam://friends/joinchat/103582791434775526")
val split = aboutText.splitBy("\${localtime}")
pane.setText("${split[0]}calculating...${split[1]}")
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"))
val timer = Timer(1000, object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
SwingUtilities.invokeLater {
val i = pane.getSelectionStart()
val j = pane.getSelectionEnd()
pane.setText("${split[0]}${df.format(System.currentTimeMillis())}${split[1]}")
pane.select(i, j)
}
}
})
timer.setInitialDelay(0)
addHierarchyListener(object : HierarchyListener {
override fun hierarchyChanged(e: HierarchyEvent) {
if ((e.getChangeFlags() and HierarchyEvent.DISPLAYABILITY_CHANGED.toLong()) == 0L) return
if (isDisplayable()) {
timer.start()
} else {
timer.stop()
}
}
})
return pane
}
companion object {
private val LOG = Logger.getLogger(javaClass<LauncherFrame>().getName())
/**
* Get a program from a TreeNode
*/
protected fun getSelected(selected: Any): Program? {
return (selected as? DefaultMutableTreeNode)?.getUserObject() as? Program
}
}
}
| artistic-2.0 | f0658845f301ff7de4ffd09a95225cf3 | 43.376682 | 197 | 0.506568 | 5.845245 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/App.kt | 1 | 2689 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity
import android.content.Context
import androidx.multidex.MultiDex
import com.blankj.utilcode.util.Utils
import com.facebook.stetho.Stetho
import com.squareup.leakcanary.LeakCanary
import com.tencent.bugly.crashreport.CrashReport
import com.zwq65.unity.di.component.DaggerApplicationComponent
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
/**
* ================================================
* unity Application
* <p>
* Created by NIRVANA on 2017/06/28.
* Contact with <[email protected]>
* ================================================
*/
class App : DaggerApplication() {
override fun onCreate() {
super.onCreate()
instance = this
Utils.init(this)
initBugly()
initStetho()
initLeakCanary()
}
/**
* return an [AndroidInjector] for the concrete [ ]. Typically, that injector is a [dagger.Component].
*/
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerApplicationComponent.builder().application(this).build()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
/**
* 初始化bugly
*/
private fun initBugly() {
CrashReport.initCrashReport(applicationContext, "d60b53237b", false)
}
/**
* 初始化Stetho(可以在chrome中方便地查看app数据库等信息,release版本关闭)
*/
private fun initStetho() {
Stetho.initializeWithDefaults(this)
}
/**
* 初始化LeakCanary(内存泄漏检测工具)
*/
private fun initLeakCanary() {
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return
}
LeakCanary.install(this)
}
companion object {
var instance: App? = null
private set
}
} | apache-2.0 | 5a34f563c8c690ec2bdef78ea2fb2d2d | 28.088889 | 106 | 0.64616 | 4.46587 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/variables/editor/VariableEditorViewModel.kt | 1 | 9928 | package ch.rmy.android.http_shortcuts.activities.variables.editor
import android.app.Application
import androidx.lifecycle.viewModelScope
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.framework.utils.UUIDUtils.newUUID
import ch.rmy.android.framework.utils.localization.StringResLocalizable
import ch.rmy.android.framework.viewmodel.BaseViewModel
import ch.rmy.android.framework.viewmodel.WithDialog
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.variables.VariableTypeMappings
import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.TemporaryVariableRepository
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.enums.VariableType
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.extensions.createDialogState
import ch.rmy.android.http_shortcuts.variables.Variables
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import javax.inject.Inject
class VariableEditorViewModel(
application: Application,
) : BaseViewModel<VariableEditorViewModel.InitData, VariableEditorViewState>(application), WithDialog {
@Inject
lateinit var variableRepository: VariableRepository
@Inject
lateinit var temporaryVariableRepository: TemporaryVariableRepository
init {
getApplicationComponent().inject(this)
}
private val variableId: VariableId?
get() = initData.variableId
private val variableType: VariableType
get() = initData.variableType
private var oldVariable: VariableModel? = null
private lateinit var variable: VariableModel
private lateinit var variableKeysInUse: List<VariableKey>
private var isSaving = false
private var variableKeyInputErrorRes: Int? = null
set(value) {
if (field != value) {
field = value
updateViewState {
copy(variableKeyInputError = value?.let { StringResLocalizable(it) })
}
if (value != null) {
emitEvent(VariableEditorEvent.FocusVariableKeyInput)
}
}
}
override var dialogState: DialogState?
get() = currentViewState?.dialogState
set(value) {
updateViewState {
copy(dialogState = value)
}
}
override fun onInitializationStarted(data: InitData) {
viewModelScope.launch {
try {
if (data.variableId != null) {
variableRepository.createTemporaryVariableFromVariable(data.variableId)
} else {
temporaryVariableRepository.createNewTemporaryVariable(variableType)
}
onTemporaryVariableCreated()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
handleInitializationError(e)
}
}
viewModelScope.launch {
variableRepository.getObservableVariables()
.collect { variables ->
variableKeysInUse = variables
.filter { variable ->
variable.id != variableId
}
.map { variable ->
variable.key
}
}
}
}
private fun onTemporaryVariableCreated() {
viewModelScope.launch {
temporaryVariableRepository.getObservableTemporaryVariable()
.collect { variable ->
[email protected] = variable
if (oldVariable == null) {
oldVariable = variable
finalizeInitialization(silent = true)
}
updateViewState {
copy(
variableKey = variable.key,
variableTitle = variable.title,
variableMessage = variable.message,
urlEncodeChecked = variable.urlEncode,
jsonEncodeChecked = variable.jsonEncode,
allowShareChecked = variable.isShareText || variable.isShareTitle,
shareSupport = variable.getShareSupport(),
)
}
}
}
}
private fun handleInitializationError(error: Throwable) {
handleUnexpectedError(error)
finish()
}
override fun initViewState() = VariableEditorViewState(
title = StringResLocalizable(if (variableId == null) R.string.create_variable else R.string.edit_variable),
subtitle = StringResLocalizable(VariableTypeMappings.getTypeName(variableType)),
dialogTitleVisible = variableType.supportsDialogTitle,
dialogMessageVisible = variableType.supportsDialogMessage,
)
fun onSaveButtonClicked() {
trySave()
}
private fun trySave() {
if (isSaving) {
return
}
isSaving = true
viewModelScope.launch {
waitForOperationsToFinish()
if (validate()) {
if (variableType.hasFragment) {
emitEvent(VariableEditorEvent.Validate)
} else {
onValidated(valid = true)
}
} else {
isSaving = false
}
}
}
fun onValidated(valid: Boolean) {
if (valid) {
save()
} else {
isSaving = false
}
}
private fun save() {
viewModelScope.launch {
try {
variableRepository.copyTemporaryVariableToVariable(variableId ?: newUUID())
finish()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
isSaving = false
showSnackbar(R.string.error_generic)
logException(e)
}
}
}
private fun validate(): Boolean {
if (variable.key.isEmpty()) {
variableKeyInputErrorRes = R.string.validation_key_non_empty
return false
}
if (!Variables.isValidVariableKey(variable.key)) {
variableKeyInputErrorRes = R.string.warning_invalid_variable_key
return false
}
if (variableKeysInUse.contains(variable.key)) {
variableKeyInputErrorRes = R.string.validation_key_already_exists
return false
}
return true
}
fun onBackPressed() {
if (hasChanges()) {
showDiscardDialog()
} else {
finish()
}
}
private fun hasChanges() =
oldVariable?.isSameAs(variable) == false
private fun showDiscardDialog() {
dialogState = createDialogState {
message(R.string.confirm_discard_changes_message)
.positive(R.string.dialog_discard) { onDiscardDialogConfirmed() }
.negative(R.string.dialog_cancel)
.build()
}
}
private fun onDiscardDialogConfirmed() {
finish()
}
fun onVariableKeyChanged(key: String) {
updateVariableKey(key)
launchWithProgressTracking {
temporaryVariableRepository.setKey(key)
}
}
private fun updateVariableKey(key: String) {
variableKeyInputErrorRes = if (key.isEmpty() || Variables.isValidVariableKey(key)) {
null
} else {
R.string.warning_invalid_variable_key
}
}
fun onVariableTitleChanged(title: String) {
launchWithProgressTracking {
temporaryVariableRepository.setTitle(title)
}
}
fun onVariableMessageChanged(message: String) {
launchWithProgressTracking {
temporaryVariableRepository.setMessage(message)
}
}
fun onUrlEncodeChanged(enabled: Boolean) {
launchWithProgressTracking {
temporaryVariableRepository.setUrlEncode(enabled)
}
}
fun onJsonEncodeChanged(enabled: Boolean) {
launchWithProgressTracking {
temporaryVariableRepository.setJsonEncode(enabled)
}
}
fun onAllowShareChanged(enabled: Boolean) {
doWithViewState { viewState ->
launchWithProgressTracking {
temporaryVariableRepository.setSharingSupport(
shareText = enabled && viewState.shareSupport.text,
shareTitle = enabled && viewState.shareSupport.title,
)
}
}
}
fun onShareSupportChanged(shareSupport: VariableEditorViewState.ShareSupport) {
launchWithProgressTracking {
temporaryVariableRepository.setSharingSupport(
shareText = shareSupport.text,
shareTitle = shareSupport.title,
)
}
}
private fun VariableModel.getShareSupport(): VariableEditorViewState.ShareSupport {
if (isShareTitle) {
if (isShareText) {
return VariableEditorViewState.ShareSupport.TITLE_AND_TEXT
}
return VariableEditorViewState.ShareSupport.TITLE
}
return VariableEditorViewState.ShareSupport.TEXT
}
data class InitData(
val variableId: VariableId?,
val variableType: VariableType,
)
}
| mit | 90d5876b47f0d56e362dfcedccd46f9e | 32.427609 | 115 | 0.600524 | 5.329039 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/usecase/LinkFindTarget.kt | 1 | 1488 | package com.orgzly.android.usecase
import com.orgzly.android.App
import com.orgzly.android.BookName
import com.orgzly.android.data.DataRepository
import com.orgzly.android.prefs.AppPreferences
import java.io.File
class LinkFindTarget(val path: String) : UseCase() {
val context = App.getAppContext();
override fun run(dataRepository: DataRepository): UseCaseResult {
val target = openLink(dataRepository, path)
return UseCaseResult(
userData = target
)
}
private fun openLink(dataRepository: DataRepository, path: String): Any {
return if (isAbsolute(path)) {
File(AppPreferences.fileAbsoluteRoot(context), path)
} else {
isMaybeBook(path)?.let { bookName ->
dataRepository.getBook(bookName.name)?.let {
return it
}
}
File(AppPreferences.fileRelativeRoot(context), path)
}
}
private fun isAbsolute(path: String): Boolean {
return path.startsWith('/')
}
private fun isMaybeBook(path: String): BookName? {
val file = File(path)
return if (!hasParent(file) && BookName.isSupportedFormatFileName(file.name)) {
BookName.fromFileName(file.name)
} else {
null
}
}
private fun hasParent(file: File): Boolean {
val parentFile = file.parentFile
return parentFile != null && parentFile.name != "."
}
} | gpl-3.0 | 6fe63f50c51100d6b200d7d1a398d197 | 27.634615 | 87 | 0.617608 | 4.664577 | false | false | false | false |
Litote/kmongo | kmongo-rxjava2-core-tests/src/main/kotlin/org/litote/kmongo/rxjava2/ReplaceTest.kt | 1 | 1708 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.rxjava2
import org.junit.Test
import org.litote.kmongo.model.Friend
import kotlin.test.assertEquals
/**
*
*/
class ReplaceTest : KMongoRxBaseTest<Friend>() {
@Test
fun canReplaceWithId() {
val friend = Friend("Peter", "31 rue des Lilas")
col.insertOne(friend).blockingAwait()
col.replaceOneById(friend._id ?: Any(), Friend("John")).blockingGet()
val replacedFriend = col.findOne("{name:'John'}}").blockingGet() ?: throw AssertionError("Value must not null!")
assertEquals("John", replacedFriend.name)
}
@Test
fun canReplaceTheSameDocument() {
val friend = Friend("John", "123 Wall Street")
col.insertOne(friend).blockingAwait()
friend.name = "Johnny"
col.replaceOne(friend).blockingGet()
val replacedFriend = col.findOne("{name:'Johnny'}").blockingGet() ?: throw AssertionError("Value must not null!")
assertEquals("Johnny", replacedFriend.name)
assertEquals("123 Wall Street", replacedFriend.address)
assertEquals(friend._id, replacedFriend._id)
}
} | apache-2.0 | 3497f2e791cc6205feb7019dce979cff | 33.18 | 121 | 0.689696 | 4.248756 | false | true | false | false |
TheContext/podcast-ci | src/main/kotlin/io/thecontext/podcaster/Main.kt | 1 | 1385 | package io.thecontext.podcaster
import io.thecontext.podcaster.context.Context
import java.io.File
import kotlin.system.exitProcess
enum class ResultCode(val value: Int) {
Success(0),
Failure(1),
}
fun main(args: Array<String>) {
val argumentsResult = Arguments.from(args)
val resultCode = when (argumentsResult) {
is ArgumentsResult.Success -> {
val arguments = argumentsResult.arguments
val inputDirectory = File(arguments.inputPath)
val outputFeedFile = File(arguments.outputFeedPath)
val outputWebsiteDirectory = File(arguments.outputWebsitePath)
val runner = Runner.Impl(Context.Impl())
val result = runner.run(inputDirectory, outputFeedFile, outputWebsiteDirectory).blockingGet()
when (result) {
is Runner.Result.Success -> {
println(":: Success!")
ResultCode.Success
}
is Runner.Result.Failure -> {
println(":: Failure.")
println(result.message)
ResultCode.Failure
}
}
}
is ArgumentsResult.Failure -> {
println(":: Failure.")
println(argumentsResult.message)
ResultCode.Failure
}
}
exitProcess(resultCode.value)
} | apache-2.0 | b70738034ba2ab948312338036822c1e | 26.176471 | 105 | 0.577617 | 5.036364 | false | false | false | false |
Jire/Acelta | src/main/kotlin/com/acelta/util/tools/stresser/Stresser.kt | 1 | 998 | package com.acelta.util.tools.stresser
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufAllocator
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel
import java.net.InetSocketAddress
const val CONNECTIONS = 2000
const val HOST = "localhost"
const val PORT = 43594
inline fun stresser(crossinline supplyByteBuf: ByteBufAllocator.(repeatN: Int) -> ByteBuf) {
val addr = InetSocketAddress(HOST, PORT)
val group = NioEventLoopGroup(Runtime.getRuntime().availableProcessors())
repeat(CONNECTIONS) {
Bootstrap()
.group(group)
.channel(NioSocketChannel::class.java)
.handler(object : ChannelInboundHandlerAdapter() {
override fun channelActive(ctx: ChannelHandlerContext) {
ctx.writeAndFlush(ctx.alloc().supplyByteBuf(it), ctx.voidPromise())
}
})
.connect(addr)
}
} | gpl-3.0 | ec2d5dfc7ee4f84881148baf16449bdb | 31.225806 | 92 | 0.779559 | 4.008032 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/LocalFileDependencyBackedArtifactSetCodec.kt | 2 | 16272 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.Action
import org.gradle.api.artifacts.FileCollectionDependency
import org.gradle.api.artifacts.component.ComponentIdentifier
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.artifacts.type.ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE
import org.gradle.api.attributes.Attribute
import org.gradle.api.attributes.AttributeContainer
import org.gradle.api.capabilities.CapabilitiesMetadata
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.CollectionCallbackActionDecorator
import org.gradle.api.internal.artifacts.ArtifactTransformRegistration
import org.gradle.api.internal.artifacts.VariantTransformRegistry
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.LocalFileDependencyBackedArtifactSet
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvableArtifact
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedVariant
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedVariantSet
import org.gradle.api.internal.artifacts.transform.ArtifactTransformDependencies
import org.gradle.api.internal.artifacts.transform.DefaultArtifactTransformDependencies
import org.gradle.api.internal.artifacts.transform.ExtraExecutionGraphDependenciesResolverFactory
import org.gradle.api.internal.artifacts.transform.TransformUpstreamDependencies
import org.gradle.api.internal.artifacts.transform.TransformUpstreamDependenciesResolver
import org.gradle.api.internal.artifacts.transform.Transformation
import org.gradle.api.internal.artifacts.transform.TransformationStep
import org.gradle.api.internal.artifacts.transform.TransformedVariantFactory
import org.gradle.api.internal.artifacts.transform.VariantDefinition
import org.gradle.api.internal.artifacts.transform.VariantSelector
import org.gradle.api.internal.artifacts.type.DefaultArtifactTypeRegistry
import org.gradle.api.internal.attributes.AttributeContainerInternal
import org.gradle.api.internal.attributes.AttributesSchemaInternal
import org.gradle.api.internal.attributes.EmptySchema
import org.gradle.api.internal.attributes.ImmutableAttributes
import org.gradle.api.internal.attributes.ImmutableAttributesFactory
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.internal.tasks.TaskDependencyResolveContext
import org.gradle.api.specs.Spec
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingSharedIdentity
import org.gradle.configurationcache.serialization.encodePreservingSharedIdentityOf
import org.gradle.configurationcache.serialization.readCollection
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.internal.Describables
import org.gradle.internal.DisplayName
import org.gradle.internal.Try
import org.gradle.internal.component.external.model.ImmutableCapabilities
import org.gradle.internal.component.local.model.LocalFileDependencyMetadata
import org.gradle.internal.component.model.VariantResolveMetadata
import org.gradle.internal.model.CalculatedValueContainerFactory
import org.gradle.internal.reflect.Instantiator
class LocalFileDependencyBackedArtifactSetCodec(
private val instantiator: Instantiator,
private val attributesFactory: ImmutableAttributesFactory,
private val fileCollectionFactory: FileCollectionFactory,
private val calculatedValueContainerFactory: CalculatedValueContainerFactory
) : Codec<LocalFileDependencyBackedArtifactSet> {
override suspend fun WriteContext.encode(value: LocalFileDependencyBackedArtifactSet) {
// TODO - When the set of files is fixed (eg `gradleApi()` or some hard-coded list of files):
// - calculate the attributes for each of the files eagerly rather than writing the mappings
// - when the selector would not apply a transform, then write only the files and nothing else
// - otherwise, write only the transform and attributes for each file rather than writing the transform registry
val noRequestedAttributes = value.selector.requestedAttributes.isEmpty
writeBoolean(noRequestedAttributes)
write(value.dependencyMetadata.componentId)
write(value.dependencyMetadata.files)
write(value.componentFilter)
// Write the file extension -> attributes mappings
// TODO - move this to an encoder
encodePreservingSharedIdentityOf(value.artifactTypeRegistry) {
val mappings = value.artifactTypeRegistry.create()!!
writeCollection(mappings) {
writeString(it.name)
write(it.attributes)
}
}
if (!noRequestedAttributes) {
// Write the file extension -> transformation mappings
// This currently uses a dummy set of variants to calculate the mappings.
// Do not write this if it will not be used
// TODO - simplify extracting the mappings
// TODO - deduplicate this data, as the mapping is project scoped and almost always the same across all projects of a given type
val matchingOnArtifactFormat = value.selector.requestedAttributes.keySet().contains(ARTIFACT_TYPE_ATTRIBUTE)
writeBoolean(matchingOnArtifactFormat)
val mappings = mutableMapOf<ImmutableAttributes, MappingSpec>()
value.artifactTypeRegistry.visitArtifactTypes { sourceAttributes ->
val recordingSet = RecordingVariantSet(value.dependencyMetadata.files, sourceAttributes)
val selected = value.selector.select(recordingSet, recordingSet)
if (selected == ResolvedArtifactSet.EMPTY) {
// Don't need to record the mapping
} else if (recordingSet.targetAttributes != null) {
mappings[sourceAttributes] = TransformMapping(recordingSet.targetAttributes!!, recordingSet.transformation!!)
} else {
mappings[sourceAttributes] = IdentityMapping
}
}
write(mappings)
}
}
override suspend fun ReadContext.decode(): LocalFileDependencyBackedArtifactSet {
val noRequestedAttributes = readBoolean()
val componentId = read() as ComponentIdentifier?
val files = readNonNull<FileCollectionInternal>()
val filter = readNonNull<Spec<ComponentIdentifier>>()
// TODO - use an immutable registry implementation
val artifactTypeRegistry = decodePreservingSharedIdentity {
val registry = DefaultArtifactTypeRegistry(instantiator, attributesFactory, CollectionCallbackActionDecorator.NOOP, EmptyVariantTransformRegistry)
val mappings = registry.create()!!
readCollection {
val name = readString()
val attributes = readNonNull<AttributeContainer>()
val mapping = mappings.create(name).attributes
@Suppress("UNCHECKED_CAST")
for (attribute in attributes.keySet() as Set<Attribute<Any>>) {
mapping.attribute(attribute, attributes.getAttribute(attribute) as Any)
}
}
registry
}
val selector = if (noRequestedAttributes) {
NoTransformsSelector()
} else {
val matchingOnArtifactFormat = readBoolean()
val transforms = readNonNull<Map<ImmutableAttributes, MappingSpec>>()
FixedVariantSelector(matchingOnArtifactFormat, transforms, fileCollectionFactory, NoOpTransformedVariantFactory)
}
return LocalFileDependencyBackedArtifactSet(FixedFileMetadata(componentId, files), filter, selector, artifactTypeRegistry, calculatedValueContainerFactory)
}
}
private
class RecordingVariantSet(
private val source: FileCollectionInternal,
private val attributes: ImmutableAttributes
) : ResolvedVariantSet, ResolvedVariant, VariantSelector.Factory, ResolvedArtifactSet {
var targetAttributes: ImmutableAttributes? = null
var transformation: Transformation? = null
override fun asDescribable(): DisplayName {
return Describables.of(source)
}
override fun getSchema(): AttributesSchemaInternal {
return EmptySchema.INSTANCE
}
override fun getVariants(): Set<ResolvedVariant> {
return setOf(this)
}
override fun getAllVariants(): Set<ResolvedVariant> {
return setOf(this)
}
override fun getOverriddenAttributes(): ImmutableAttributes {
return ImmutableAttributes.EMPTY
}
override fun getIdentifier(): VariantResolveMetadata.Identifier? {
return null
}
override fun getAttributes(): AttributeContainerInternal {
return attributes
}
override fun getCapabilities(): CapabilitiesMetadata {
return ImmutableCapabilities.EMPTY
}
override fun visitDependencies(context: TaskDependencyResolveContext) {
throw UnsupportedOperationException("Should not be called")
}
override fun visit(visitor: ResolvedArtifactSet.Visitor) {
throw UnsupportedOperationException("Should not be called")
}
override fun visitTransformSources(visitor: ResolvedArtifactSet.TransformSourceVisitor) {
throw UnsupportedOperationException("Should not be called")
}
override fun visitExternalArtifacts(visitor: Action<ResolvableArtifact>) {
throw UnsupportedOperationException("Should not be called")
}
override fun getArtifacts(): ResolvedArtifactSet {
return this
}
override fun asTransformed(
sourceVariant: ResolvedVariant,
variantDefinition: VariantDefinition,
dependenciesResolver: ExtraExecutionGraphDependenciesResolverFactory,
transformedVariantFactory: TransformedVariantFactory
): ResolvedArtifactSet {
this.transformation = variantDefinition.transformation
this.targetAttributes = variantDefinition.targetAttributes
return sourceVariant.artifacts
}
}
private
sealed class MappingSpec
private
class TransformMapping(private val targetAttributes: ImmutableAttributes, private val transformation: Transformation) : MappingSpec(), VariantDefinition {
override fun getTargetAttributes(): ImmutableAttributes {
return targetAttributes
}
override fun getTransformation(): Transformation {
return transformation
}
override fun getTransformationStep(): TransformationStep {
throw UnsupportedOperationException()
}
override fun getSourceVariant(): VariantDefinition? {
throw UnsupportedOperationException()
}
}
private
object IdentityMapping : MappingSpec()
private
class FixedVariantSelector(
private val matchingOnArtifactFormat: Boolean,
private val transforms: Map<ImmutableAttributes, MappingSpec>,
private val fileCollectionFactory: FileCollectionFactory,
private val transformedVariantFactory: TransformedVariantFactory
) : VariantSelector {
override fun getRequestedAttributes() = throw UnsupportedOperationException("Should not be called")
override fun select(candidates: ResolvedVariantSet, factory: VariantSelector.Factory): ResolvedArtifactSet {
require(candidates.variants.size == 1)
val variant = candidates.variants.first()
return when (val spec = transforms[variant.attributes.asImmutable()]) {
null -> {
// no mapping for extension, so it can be discarded
if (matchingOnArtifactFormat) {
ResolvedArtifactSet.EMPTY
} else {
variant.artifacts
}
}
is IdentityMapping -> variant.artifacts
is TransformMapping -> factory.asTransformed(variant, spec, EmptyDependenciesResolverFactory(fileCollectionFactory), transformedVariantFactory)
}
}
}
private
class NoTransformsSelector : VariantSelector {
override fun getRequestedAttributes() = throw UnsupportedOperationException("Should not be called")
override fun select(candidates: ResolvedVariantSet, factory: VariantSelector.Factory): ResolvedArtifactSet {
require(candidates.variants.size == 1)
return candidates.variants.first().artifacts
}
}
private
class FixedFileMetadata(
private val compId: ComponentIdentifier?,
private val source: FileCollectionInternal
) : LocalFileDependencyMetadata {
override fun getComponentId(): ComponentIdentifier? {
return compId
}
override fun getFiles(): FileCollectionInternal {
return source
}
override fun getSource(): FileCollectionDependency {
throw UnsupportedOperationException("Should not be called")
}
}
private
class EmptyDependenciesResolverFactory(private val fileCollectionFactory: FileCollectionFactory) : ExtraExecutionGraphDependenciesResolverFactory, TransformUpstreamDependenciesResolver, TransformUpstreamDependencies {
override fun create(componentIdentifier: ComponentIdentifier, transformation: Transformation): TransformUpstreamDependenciesResolver {
return this
}
override fun dependenciesFor(transformationStep: TransformationStep): TransformUpstreamDependencies {
return this
}
override fun visitDependencies(context: TaskDependencyResolveContext) {
throw UnsupportedOperationException("Should not be called")
}
override fun selectedArtifacts(): FileCollection {
throw UnsupportedOperationException("Should not be called")
}
override fun finalizeIfNotAlready() {
}
override fun computeArtifacts(): Try<ArtifactTransformDependencies> {
return Try.successful(DefaultArtifactTransformDependencies(FileCollectionFactory.empty()))
}
}
private
object NoOpTransformedVariantFactory : TransformedVariantFactory {
override fun transformedExternalArtifacts(
componentIdentifier: ComponentIdentifier,
sourceVariant: ResolvedVariant,
variantDefinition: VariantDefinition,
dependenciesResolverFactory: ExtraExecutionGraphDependenciesResolverFactory
): ResolvedArtifactSet {
throw UnsupportedOperationException("Should not be called")
}
override fun transformedProjectArtifacts(
componentIdentifier: ComponentIdentifier,
sourceVariant: ResolvedVariant,
variantDefinition: VariantDefinition,
dependenciesResolverFactory: ExtraExecutionGraphDependenciesResolverFactory
): ResolvedArtifactSet {
throw UnsupportedOperationException("Should not be called")
}
}
private
object EmptyVariantTransformRegistry : VariantTransformRegistry {
override fun <T : TransformParameters?> registerTransform(actionType: Class<out TransformAction<T>>, registrationAction: Action<in org.gradle.api.artifacts.transform.TransformSpec<T>>) {
throw UnsupportedOperationException("Should not be called")
}
override fun getTransforms(): MutableList<ArtifactTransformRegistration> {
throw UnsupportedOperationException("Should not be called")
}
}
| apache-2.0 | d14415f064f72ee60f0d38dc4350ae9d | 42.161804 | 217 | 0.756023 | 5.465905 | false | false | false | false |
davinkevin/Podcast-Server | backend/src/test/kotlin/com/github/davinkevin/podcastserver/manager/downloader/FfmpegDownloaderTest.kt | 1 | 13932 | package com.github.davinkevin.podcastserver.manager.downloader
import com.github.davinkevin.podcastserver.download.DownloadRepository
import com.github.davinkevin.podcastserver.download.ItemDownloadManager
import com.github.davinkevin.podcastserver.entity.Status
import com.github.davinkevin.podcastserver.entity.Status.*
import com.github.davinkevin.podcastserver.messaging.MessagingTemplate
import com.github.davinkevin.podcastserver.service.ffmpeg.FfmpegService
import com.github.davinkevin.podcastserver.service.ProcessService
import com.github.davinkevin.podcastserver.service.properties.PodcastServerParameters
import com.github.davinkevin.podcastserver.service.storage.FileMetaData
import com.github.davinkevin.podcastserver.service.storage.FileStorageService
import net.bramp.ffmpeg.builder.FFmpegBuilder
import net.bramp.ffmpeg.progress.Progress
import net.bramp.ffmpeg.progress.ProgressListener
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.Awaitility.await
import org.junit.jupiter.api.*
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.mockito.Mock
import org.mockito.Spy
import org.mockito.invocation.InvocationOnMock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.*
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toMono
import software.amazon.awssdk.services.s3.model.PutObjectResponse
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.time.Clock
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.*
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.io.path.Path
private val fixedDate = OffsetDateTime.of(2019, 3, 4, 5, 6, 7, 0, ZoneOffset.UTC)
/**
* Created by kevin on 20/02/2016 for Podcast Server
*/
@ExtendWith(MockitoExtension::class)
class FfmpegDownloaderTest {
private val item: DownloadingItem = DownloadingItem (
id = UUID.randomUUID(),
title = "Title",
status = Status.NOT_DOWNLOADED,
url = URI("http://a.fake.url/with/file.mp4?param=1"),
numberOfFail = 0,
progression = 0,
podcast = DownloadingItem.Podcast(
id = UUID.randomUUID(),
title = "A Fake ffmpeg Podcast"
),
cover = DownloadingItem.Cover(
id = UUID.randomUUID(),
url = URI("https://bar/foo/cover.jpg")
)
)
@Nested
inner class DownloaderTest {
@Mock lateinit var downloadRepository: DownloadRepository
@Mock lateinit var podcastServerParameters: PodcastServerParameters
@Mock lateinit var template: MessagingTemplate
@Mock lateinit var file: FileStorageService
@Mock lateinit var itemDownloadManager: ItemDownloadManager
@Mock lateinit var ffmpegService: FfmpegService
@Mock lateinit var processService: ProcessService
@Spy val clock: Clock = Clock.fixed(fixedDate.toInstant(), ZoneId.of("UTC"))
lateinit var downloader: FfmpegDownloader
@BeforeEach
fun beforeEach() {
downloader = FfmpegDownloader(downloadRepository, template, clock, file, ffmpegService, processService)
downloader
.with(DownloadingInformation(item, listOf(item.url, URI.create("http://foo.bar.com/end.mp4")), Path("file.mp4"), "Fake UserAgent"), itemDownloadManager)
}
@Nested
inner class DownloadOperation {
@BeforeEach
fun beforeEach() {
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
}
@Test
fun should_download_file() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
whenever(ffmpegService.download(any(), any(), any())).then { i ->
writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
doAnswer { writeEmptyFileTo(it.getArgument<Path>(0).toString()); null
}.whenever(ffmpegService).concat(any(), anyVararg())
whenever(file.upload(eq(item.podcast.title), any()))
.thenReturn(PutObjectResponse.builder().build().toMono())
whenever(file.metadata(eq(item.podcast.title), any()))
.thenReturn(FileMetaData("video/mp4", 123L).toMono())
whenever(downloadRepository.finishDownload(
id = item.id,
length = 123L,
mimeType = "video/mp4",
fileName = Path("file-${item.id}.mp4"),
downloadDate = fixedDate
)).thenReturn(Mono.empty())
/* When */
downloader.run()
/* Then */
assertThat(downloader.downloadingInformation.item.status).isEqualTo(FINISH)
assertThat(downloader.downloadingInformation.item.progression).isEqualTo(100)
}
@Test
fun `should ends on FAILED if one of download failed`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}.whenever(ffmpegService).download(eq(item.url.toASCIIString()), any(), any())
doAnswer { throw RuntimeException("Error during download of other url") }
.whenever(ffmpegService).download(eq("http://foo.bar.com/end.mp4"), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
/* When */
downloader.run()
/* Then */
assertThat(downloader.downloadingInformation.item.status).isSameAs(FAILED)
}
@Test
@Disabled("to check that, we need to extract the temp file generation")
fun `should delete all files if error occurred during download`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
.whenever(ffmpegService).download(eq(item.url.toASCIIString()), any(), any())
doAnswer { throw RuntimeException("Error during download of other url") }
.whenever(ffmpegService).download(eq("http://foo.bar.com/end.mp4"), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
/* When */
downloader.run()
/* Then */
}
@Test
@Disabled("to check that, we need to extract the temp file generation")
fun `should delete all files if error occurred during concat`() {
/* Given */
whenever(ffmpegService.getDurationOf(any(), any())).thenReturn(500.0)
doAnswer { i -> writeEmptyFileTo(outputPath(i))
(0..100).map { it * 5L }.forEach { sendProgress(i, it)}
mock<Process>()
}
.whenever(ffmpegService).download(any(), any(), any())
whenever(processService.waitFor(any())).thenReturn(Result.success(1))
whenever(ffmpegService.concat(any(), anyVararg())).then {
throw RuntimeException("Error during concat operation")
}
/* When */
downloader.run()
/* Then */
}
private fun outputPath(i: InvocationOnMock) = i.getArgument<FFmpegBuilder>(1).build().last()!!
private fun sendProgress(i: InvocationOnMock, outTimeMs: Long) =
i.getArgument<ProgressListener>(2).progress(Progress().apply { out_time_ns = outTimeMs })
private fun writeEmptyFileTo(location: String): Path =
Files.write(Paths.get(location), "".toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
private fun numberOfChildrenFiles(location: Path) = Files
.newDirectoryStream(location)
.map { it }
.size
}
@Nested
inner class DuringDownloadOperation {
@Test
fun should_stop_a_download() {
/* Given */
downloader.downloadingInformation = downloader.downloadingInformation.status(STARTED)
downloader.process = mock()
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
/* When */
downloader.stopDownload()
/* Then */
await().atMost(5, SECONDS).untilAsserted {
assertThat(downloader.downloadingInformation.item.status).isEqualTo(STOPPED)
verify(downloader.process).destroy()
}
}
@Test
fun should_failed_to_stop_a_download() {
/* Given */
downloader.downloadingInformation = downloader.downloadingInformation.status(STARTED)
downloader.process = mock()
doAnswer { throw RuntimeException("Error when executing process") }
.whenever(downloader.process).destroy()
whenever(downloadRepository.updateDownloadItem(any())).thenReturn(Mono.empty())
/* When */
downloader.stopDownload()
/* Then */
await().atMost(5, SECONDS).untilAsserted {
assertThat(downloader.downloadingInformation.item.status).isEqualTo(FAILED)
}
}
}
}
@Nested
inner class CompatibilityTest {
@Mock lateinit var downloadRepository: DownloadRepository
@Mock lateinit var podcastServerParameters: PodcastServerParameters
@Mock lateinit var template: MessagingTemplate
@Mock lateinit var file: FileStorageService
@Mock lateinit var itemDownloadManager: ItemDownloadManager
@Mock lateinit var ffmpegService: FfmpegService
@Mock lateinit var processService: ProcessService
@Spy val clock: Clock = Clock.fixed(fixedDate.toInstant(), ZoneId.of("UTC"))
lateinit var downloader: FfmpegDownloader
@BeforeEach
fun beforeEach() {
downloader = FfmpegDownloader(
downloadRepository,
template,
clock,
file,
ffmpegService,
processService
)
}
@Test
fun `should be compatible with multiple urls ending with M3U8 and MP4`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.M3U8", "http://foo.bar.com/end.mp4").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@Test
fun `should be compatible with only urls ending with M3U8`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.m3u8", "http://foo.bar.com/end.M3U8").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@Test
fun `should be compatible with only urls ending with mp4`() {
/* Given */
val di = DownloadingInformation(item, listOf("http://foo.bar.com/end.MP4", "http://foo.bar.com/end.mp4").map(URI::create), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@DisplayName("should be compatible with only one url with extension")
@ParameterizedTest(name = "{arguments}")
@ValueSource(strings = ["m3u8", "mp4"])
fun `should be compatible with only one url with extension`(ext: String) {
/* Given */
val di = DownloadingInformation(item, listOf(URI.create("http://foo.bar.com/end.$ext")), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(10)
}
@DisplayName("should not be compatible with")
@ParameterizedTest(name = "{arguments}")
@ValueSource(strings = ["http://foo.bar.com/end.webm", "http://foo.bar.com/end.manifest"])
fun `should not be compatible with`(url: String) {
/* Given */
val di = DownloadingInformation(item, listOf(URI.create(url)), Path("end.mp4"), null)
/* When */
val compatibility = downloader.compatibility(di)
/* Then */
assertThat(compatibility).isEqualTo(Integer.MAX_VALUE)
}
}
}
| apache-2.0 | 175427f46764b6ab96b35c015081d7f6 | 40.58806 | 172 | 0.594531 | 4.859435 | false | false | false | false |
davinkevin/Podcast-Server | backend/src/main/kotlin/com/github/davinkevin/podcastserver/update/updaters/rss/RSSUpdater.kt | 1 | 5332 | package com.github.davinkevin.podcastserver.update.updaters.rss
import com.github.davinkevin.podcastserver.extension.java.util.orNull
import com.github.davinkevin.podcastserver.service.image.ImageService
import com.github.davinkevin.podcastserver.update.updaters.*
import org.jdom2.Element
import org.jdom2.Namespace
import org.jdom2.input.SAXBuilder
import org.slf4j.LoggerFactory
import org.springframework.core.io.ByteArrayResource
import org.springframework.util.DigestUtils
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.switchIfEmpty
import reactor.kotlin.core.publisher.toFlux
import reactor.kotlin.core.publisher.toMono
import java.net.URI
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
private val MEDIA = Namespace.getNamespace("media", "http://search.yahoo.com/mrss/")
private val FEED_BURNER = Namespace.getNamespace("feedburner", "http://rssnamespace.org/feedburner/ext/1.0")
private val ITUNES_NS = Namespace.getNamespace("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd")!!
class RSSUpdater(
private val imageService: ImageService,
private val wcb: WebClient.Builder
) : Updater {
private val log = LoggerFactory.getLogger(RSSUpdater::class.java)
override fun findItems(podcast: PodcastToUpdate): Flux<ItemFromUpdate> {
return fetchRss(podcast.url)
.map { SAXBuilder().build(it.inputStream) }
.flatMap { it.rootElement.getChild("channel").toMono() }
.flatMapMany { channel -> channel
.getChildren("item")
.toFlux()
.filter { hasEnclosure(it) }
.map { channel to it }
}
.flatMap { (channel, elem) -> findCoverForItem(channel, elem).toMono()
.flatMap { imageService.fetchCover(it) }
.switchIfEmpty { Optional.empty<ItemFromUpdate.Cover>().toMono() }
.map { elem to it }
}
.map { (elem, cover) ->
ItemFromUpdate(
title = elem.getChildText("title"),
pubDate = getPubDate(elem),
description = elem.getChildText("description"),
cover = cover.orNull(),
url = urlOf(elem),
length = elem.enclosure().getAttributeValue("length")?.toLong(),
mimeType = mimeTypeOf(elem)
)
}
}
private fun findCoverForItem(channelElement: Element, elem: Element): URI? {
val thumbnail = elem.getChild("thumbnail", MEDIA)
if (thumbnail != null) {
return URI.create(thumbnail.getAttributeValue("url") ?: thumbnail.text)
}
val rss = channelElement.getChild("image")?.getChildText("url")
val itunes = channelElement.getChild("image", ITUNES_NS)?.getAttributeValue("href")
val url = rss ?: itunes ?: return null
return URI.create(url)
}
private fun hasEnclosure(item: Element) = item.enclosure() != null
private fun urlOf(element: Element): URI {
val url = if (element.getChild("origEnclosureLink", FEED_BURNER) != null)
element.getChildText("origEnclosureLink", FEED_BURNER)
else
element.enclosure().getAttributeValue("url")
return URI(url.replace(" ", "+"))
}
private fun mimeTypeOf(elem: Element): String {
val type = elem.enclosure().getAttributeValue("type")
return if (!type.isNullOrEmpty()) type else "unknown/unknown"
}
private fun getPubDate(item: Element): ZonedDateTime {
val pubDate = item.getChildText("pubDate") ?: ""
val date = when {
"EDT" in pubDate -> pubDate.replace("EDT", "+0600")
"PST" in pubDate -> pubDate.replace("PST", "+0800")
"PDT" in pubDate -> pubDate.replace("PDT", "+0900")
else -> pubDate
}
return Result.runCatching {
ZonedDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME)
} .onFailure {
log.error("Problem during date parsing of \"{}\" caused by {}", item.getChildText("title"), it.message)
}
.getOrDefault(ZonedDateTime.now())
}
override fun signatureOf(url: URI): Mono<String> = fetchRss(url)
.map { DigestUtils.md5DigestAsHex(it.inputStream) }
.onErrorResume {
log.error("error during update", it)
"error_during_update".toMono()
}
private fun fetchRss(url: URI): Mono<ByteArrayResource> {
return wcb
.clone()
.baseUrl(url.toASCIIString())
.build()
.get()
.retrieve()
.bodyToMono()
}
override fun type() = Type("RSS", "RSS")
override fun compatibility(url: String): Int = when {
url.startsWith("http", true) -> Integer.MAX_VALUE - 1
else -> Integer.MAX_VALUE
}
}
private fun Element.enclosure() = this.getChild("enclosure")
private fun ImageService.fetchCover(url: URI) = this.fetchCoverInformation(url)
.map { cover -> Optional.of(cover.toCoverFromUpdate()) }
| apache-2.0 | 9beb3c35dd1b0e344d998b661ab08072 | 37.359712 | 115 | 0.632783 | 4.3 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf14Statistic.kt | 1 | 956 | package ca.josephroque.bowlingcompanion.statistics.impl.series
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Highest series of 14 games.
*/
class HighSeriesOf14Statistic(value: Int = 0) : HighSeriesStatistic(value) {
// MARK: Overrides
override val seriesSize = 14
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::HighSeriesOf14Statistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_high_series_of_14
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(value = p.readInt())
}
| mit | 242bb4f9e958a35f124d4b71c2d34b1b | 25.555556 | 76 | 0.687238 | 4.267857 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/SecondBallStatistic.kt | 1 | 3514 | package ca.josephroque.bowlingcompanion.statistics.impl.firstball
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.lane.Deck
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.statistics.PercentageStatistic
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame
/**
* Copyright (C) 2018 Joseph Roque
*
* Parent class for statistics which are calculated based on the user throwing a second ball
* at a deck of pins.
*/
abstract class SecondBallStatistic(override var numerator: Int = 0, override var denominator: Int = 0, private var incompatible: Int = 0) : PercentageStatistic {
// MARK: Modifiers
/** @Override */
override fun modify(frame: StatFrame) {
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
// In the 10th frame, for each time the first or second ball cleared the lane,
// add another second ball opportunity and check if the statistic is modified
if (!frame.pinState[0].arePinsCleared && isModifiedByFirstBall(frame.pinState[0], frame.pinState[1])) {
denominator++
numerator += if (isModifiedBySecondBall(frame.pinState[1])) 1 else 0
} else if (frame.pinState[0].arePinsCleared && !frame.pinState[1].arePinsCleared && isModifiedByFirstBall(frame.pinState[1], frame.pinState[2])) {
denominator++
numerator += if (isModifiedBySecondBall(frame.pinState[2])) 1 else 0
} else if (frame.pinState[1].arePinsCleared && !frame.pinState[2].arePinsCleared && isModifiedByFirstBall(frame.pinState[2])) {
incompatible++
}
} else {
// Every frame which is not a strike adds 1 possible hit
if (!frame.pinState[0].arePinsCleared && isModifiedByFirstBall(frame.pinState[0], frame.pinState[1])) {
denominator++
numerator += if (isModifiedBySecondBall(frame.pinState[1])) 1 else 0
}
}
}
// MARK: SecondBallStatistic
/**
* Indicates if this statistic will be modified by a given [Deck] which is the first ball of a frame.
* Also provides the second ball for special cases. By default calls `isModifiedByFirstBall(deck)`.
*
* @param firstBall the first ball of the two shots
* @param secondBall the second ball of the two shots
* @return true if the first ball provides the right conditions for the statistic to be valid, false otherwise
*/
open fun isModifiedByFirstBall(firstBall: Deck, secondBall: Deck): Boolean {
return isModifiedByFirstBall(firstBall)
}
/** Indicates if this statistic will be modified by a given [Deck] which is the first ball of a frame. */
open fun isModifiedByFirstBall(deck: Deck): Boolean {
return false
}
/** Indicates if this statistic will be modified by a given [Deck] which is the second ball of a frame. */
abstract fun isModifiedBySecondBall(deck: Deck): Boolean
// MARK: Overrides
override val category = StatisticsCategory.FirstBall
override fun isModifiedBy(frame: StatFrame) = true
/** @Override */
override fun getSubtitle(): String? {
return if (incompatible > 0) {
"$incompatible thrown in 10th frame on the last ball could not be spared"
} else {
null
}
}
}
| mit | 8691146d1de8b6b03905efacbbbebd42 | 44.051282 | 161 | 0.680421 | 4.654305 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/overall/GameAverageStatistic.kt | 1 | 1432 | package ca.josephroque.bowlingcompanion.statistics.impl.overall
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.statistics.AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.immutable.StatGame
/**
* Copyright (C) 2018 Joseph Roque
*
* Average score across all games.
*/
class GameAverageStatistic(override var total: Int = 0, override var divisor: Int = 0) : AverageStatistic {
// MARK: Modifiers
/** @Override */
override fun modify(game: StatGame) {
divisor++
total += game.score
}
// MARK: Overrides
override val titleId = Id
override val id = Id.toLong()
override val category = StatisticsCategory.Overall
override fun isModifiedBy(game: StatGame) = game.score > 0
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::GameAverageStatistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_average
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(total = p.readInt(), divisor = p.readInt())
}
| mit | 47fd5666ebda2e2056c4247b9fe1a664 | 28.833333 | 107 | 0.706704 | 4.57508 | false | false | false | false |
googlecodelabs/android-compose-codelabs | BasicStateCodelab/app/src/main/java/com/codelabs/state/WellnessScreen.kt | 1 | 1329 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelabs.state
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun WellnessScreen(
modifier: Modifier = Modifier,
wellnessViewModel: WellnessViewModel = viewModel()
) {
Column(modifier = modifier) {
StatefulCounter()
WellnessTasksList(
list = wellnessViewModel.tasks,
onCheckedTask = { task, checked ->
wellnessViewModel.changeTaskChecked(task, checked)
},
onCloseTask = { task ->
wellnessViewModel.remove(task)
}
)
}
}
| apache-2.0 | 752afde0587d006445eb6ba9eadaf199 | 31.414634 | 75 | 0.696012 | 4.459732 | false | false | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/CreateGameForm.kt | 1 | 2297 | package org.luxons.sevenwonders.ui.components.gameBrowser
import com.palantir.blueprintjs.Intent
import com.palantir.blueprintjs.bpButton
import com.palantir.blueprintjs.bpInputGroup
import kotlinx.css.*
import kotlinx.html.js.onSubmitFunction
import org.luxons.sevenwonders.ui.redux.RequestCreateGame
import org.luxons.sevenwonders.ui.redux.connectDispatch
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import react.RBuilder
import react.RClass
import react.RComponent
import react.RProps
import react.RState
import react.buildElement
import react.dom.*
import styled.css
import styled.styledDiv
private interface CreateGameFormProps : RProps {
var createGame: (String) -> Unit
}
private data class CreateGameFormState(var gameName: String = "") : RState
private class CreateGameForm(props: CreateGameFormProps) : RComponent<CreateGameFormProps, CreateGameFormState>(props) {
override fun CreateGameFormState.init(props: CreateGameFormProps) {
gameName = ""
}
override fun RBuilder.render() {
styledDiv {
css {
display = Display.flex
flexDirection = FlexDirection.row
justifyContent = JustifyContent.spaceBetween
}
form {
attrs {
onSubmitFunction = { e -> createGame(e) }
}
bpInputGroup(
placeholder = "Game name",
onChange = { e ->
val input = e.currentTarget as HTMLInputElement
setState(transformState = { CreateGameFormState(input.value) })
},
rightElement = createGameButton(),
)
}
currentPlayerInfo()
}
}
private fun createGameButton() = buildElement {
bpButton(minimal = true, intent = Intent.PRIMARY, icon = "add", onClick = { e -> createGame(e) })
}
private fun createGame(e: Event) {
e.preventDefault() // prevents refreshing the page when pressing Enter
props.createGame(state.gameName)
}
}
val createGameForm: RClass<RProps> = connectDispatch(CreateGameForm::class) { dispatch, _ ->
createGame = { name -> dispatch(RequestCreateGame(name)) }
}
| mit | 05625919a4aff72d8204894992ca010c | 31.352113 | 120 | 0.647801 | 4.486328 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/VersionControlledFilesList.kt | 1 | 4647 | package de.maibornwolff.codecharta.importer.gitlogparser.parser
import de.maibornwolff.codecharta.importer.gitlogparser.input.VersionControlledFile
import de.maibornwolff.codecharta.importer.gitlogparser.input.metrics.MetricsFactory
class VersionControlledFilesList(private val metricsFactory: MetricsFactory) {
private var versionControlledFiles: MutableMap<String, VersionControlledFile> = mutableMapOf()
/**
* The key of the map is the current name
* The value of the map is the oldest name
*/
private var renamesMap: MutableMap<String, String> = mutableMapOf()
/**
* The key of the map is the current name
* The value of the map is the number of name conflicts as a counter
*/
private var nameConflictsMap: MutableMap<String, Int> = mutableMapOf()
fun get(key: String): VersionControlledFile? {
return versionControlledFiles[resolveFileKey(key)]
}
fun addFileBy(key: String): VersionControlledFile {
var newVCFFileName = key
if (hasNameConflict(key)) {
newVCFFileName = handleNameConflict(key)
}
val vcf = VersionControlledFile(newVCFFileName, metricsFactory)
versionControlledFiles[resolveFileKey(key)] = vcf
return vcf
}
private fun hasNameConflict(key: String): Boolean {
val vcf = versionControlledFiles[key]
if (vcf != null) {
return !vcf.isDeleted()
}
return false
}
private fun handleNameConflict(key: String): String {
val marker = nameConflictsMap[key]
val newMarker = if (marker != null) marker + 1 else 0
nameConflictsMap[key] = newMarker
return key + "_\\0_" + newMarker
}
fun getList(): MutableMap<String, VersionControlledFile> {
return versionControlledFiles
}
fun rename(oldFileName: String, newFileName: String) {
var newVCFFileName = newFileName
val possibleConflictName = buildPossibleConflictName(oldFileName)
val oldestName = retrieveOldestName(possibleConflictName)
if (fileExistsAsDeleted(newFileName)) {
handleDeletedFileReplacedByRenamedFile(newFileName)
}
if (versionControlledFiles.containsKey(newFileName) && !isCyclicRename(oldFileName, newFileName)) {
newVCFFileName = handleNameConflict(newFileName)
}
if (oldestName != null) {
renamesMap.remove(possibleConflictName)
}
val updatedOldestName = if (oldestName != null) oldestName else oldFileName
renamesMap[newVCFFileName] = updatedOldestName
// When parsing node.js repository, NullPointerExceptions occurs.
// To not crash the Parser, do a safe call for now.
val notYetRenamedFile = versionControlledFiles[updatedOldestName]
notYetRenamedFile?.addRename(newVCFFileName)
notYetRenamedFile?.filename = newFileName
}
// File A is called B then A again, this will mess up the currentFilename and oldFilename structure, therefore a special handling is needed
private fun isCyclicRename(oldFileName: String, newFileName: String): Boolean {
return get(oldFileName)!!.containsRename(newFileName)
}
private fun fileExistsAsDeleted(key: String): Boolean {
val vcf = versionControlledFiles[key]
if (vcf != null) {
return vcf.isDeleted()
}
return false
}
private fun handleDeletedFileReplacedByRenamedFile(newFileName: String) {
// Clear the corresponding maps for file which will be replaced
renamesMap.remove(versionControlledFiles[newFileName]!!.filename)
nameConflictsMap.remove(buildPossibleConflictName(newFileName))
// Remove deleted file with new file which has been added now
versionControlledFiles.remove(newFileName)
}
private fun resolveFileKey(trackName: String): String {
val possibleConflictName = buildPossibleConflictName(trackName)
val oldestName = retrieveOldestName(possibleConflictName)
return if (oldestName == null) possibleConflictName else oldestName
}
/**
* If file name has already existed before, created new "salted" name to keep track of both files separately.
*/
private fun buildPossibleConflictName(trackName: String): String {
if (nameConflictsMap.containsKey(trackName)) {
return trackName + "_\\0_" + nameConflictsMap[trackName]
}
return trackName
}
private fun retrieveOldestName(possibleConflictName: String): String? {
return renamesMap[possibleConflictName]
}
}
| bsd-3-clause | ce221fa9a8996549bd299b1f3e69dff4 | 34.746154 | 143 | 0.692059 | 4.756397 | false | false | false | false |
LorittaBot/Loritta | common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/Color.kt | 1 | 3157 | package net.perfectdreams.loritta.common.utils
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
// From Kord because it already works pretty well
@Serializable(with = Color.Serializer::class)
class Color(rgb: Int) {
constructor(red: Int, green: Int, blue: Int) : this(rgb(red, green, blue))
val rgb = rgb and 0xFFFFFF
val red: Int get() = (rgb shr 16) and 0xFF
val green: Int get() = (rgb shr 8) and 0xFF
val blue: Int get() = (rgb shr 0) and 0xFF
init {
require(this.rgb in MIN_COLOR..MAX_COLOR) { "RGB should be in range of $MIN_COLOR..$MAX_COLOR but was ${this.rgb}" }
}
override fun toString(): String = "Color(red=$red,green=$green,blue=$blue)"
override fun hashCode(): Int = rgb.hashCode()
override fun equals(other: Any?): Boolean {
val color = other as? Color ?: return false
return color.rgb == rgb
}
companion object {
private const val MIN_COLOR = 0
private const val MAX_COLOR = 0xFFFFFF
fun fromString(input: String): Color {
if (input.indexOf(',') == 3) {
// r,g,b color
val split = input.split(',')
val r = requireNotNull(split[0].toIntOrNull()) { "Red part of the RGB code is not a valid integer!" }
val g = requireNotNull(split[1].toIntOrNull()) { "Green part of the RGB code is not a valid integer!" }
val b = requireNotNull(split[2].toIntOrNull()) { "Blue part of the RGB code is not a valid integer!" }
return Color(r, g, b)
} else if (input.startsWith("#")) {
// Parse it as a hex color
return fromHex(input)
} else {
val inputAsAnInteger = requireNotNull(input.toIntOrNull()) { "The string is not a valid color code!" }
return Color(inputAsAnInteger)
}
}
// https://stackoverflow.com/a/41654372/7271796
fun fromHex(input: String) = Color(input.removePrefix("#").toInt(16))
}
internal object Serializer : KSerializer<Color> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("Kord.color", PrimitiveKind.INT)
override fun deserialize(decoder: Decoder): Color = Color(decoder.decodeInt())
override fun serialize(encoder: Encoder, value: Color) {
encoder.encodeInt(value.rgb)
}
}
}
private fun rgb(red: Int, green: Int, blue: Int): Int {
require(red in 0..255) { "Red should be in range of 0..255 but was $red" }
require(green in 0..255) { "Green should be in range of 0..255 but was $green" }
require(blue in 0..255) { "Blue should be in range of 0..255 but was $blue" }
return red and 0xFF shl 16 or
(green and 0xFF shl 8) or
(blue and 0xFF) shl 0
} | agpl-3.0 | 513e75bc8a2c4cf37c2e50024a0c1c66 | 37.048193 | 124 | 0.631612 | 4.181457 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/tune/EntropyActivity.kt | 1 | 12612 | package com.androidvip.hebf.ui.main.tune
import android.os.Bundle
import android.os.Handler
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import android.widget.SeekBar
import androidx.lifecycle.lifecycleScope
import com.androidvip.hebf.R
import com.androidvip.hebf.animProgress
import com.androidvip.hebf.ui.base.BaseActivity
import com.androidvip.hebf.helpers.HebfApp
import com.androidvip.hebf.roundDecimals
import com.androidvip.hebf.show
import com.androidvip.hebf.utils.K
import com.androidvip.hebf.utils.Logger
import com.androidvip.hebf.utils.RootUtils
import kotlinx.android.synthetic.main.activity_entropy.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
class EntropyActivity : BaseActivity(), SeekBar.OnSeekBarChangeListener {
private var check = 0
private var readThresholdInt: Int = 0
private var writeThresholdInt: Int = 0
private var readThreshold = "64"
private var writeThreshold = "128"
private var availableEntropy = "0"
private var poolsize = "4096"
private val handler = Handler()
private lateinit var getEntropyRunnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_entropy)
setUpToolbar(toolbar)
lifecycleScope.launch(workerContext) {
RootUtils.executeSync("chmod +r $READ_WAKEUP_THRESHOLD && chmod +r $WRITE_WAKEUP_THRESHOLD")
val addRandomStatus = RootUtils.executeSync("cat $ADD_RANDOM")
val minReseedValue = RootUtils.executeSync("cat $URANDOM_MIN_RESEED_SECS")
val supportsAddRandom = addRandomStatus == "0" || addRandomStatus == "1"
val supportsMinReseed = runCatching {
minReseedValue.toInt()
minReseedValue.isNotEmpty()
}.getOrDefault(false)
runSafeOnUiThread {
if (supportsAddRandom) {
entropyAddRandom.setChecked(addRandomStatus == "1")
entropyAddRandom.show()
entropyAddRandom.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { _, isChecked ->
launch {
if (isChecked) {
RootUtils.execute("echo '1' > /sys/block/mmcblk0/queue/add_random")
prefs.putString(K.PREF.ENTROPY_ADD_RANDOM, "1")
} else {
RootUtils.execute("echo '0' > /sys/block/mmcblk0/queue/add_random")
prefs.putString(K.PREF.ENTROPY_ADD_RANDOM, "0")
}
}
})
}
if (supportsMinReseed) {
entropyReseedCard?.show()
entropyReseedText.text = minReseedValue
entropyReseedSeekBar.apply {
progress = minReseedValue.toInt()
setOnSeekBarChangeListener(this@EntropyActivity)
}
}
}
}
setUpRunnable()
// Set up spinner with entropy profiles
val adapter = ArrayAdapter.createFromResource(this, R.array.entropy_profiles, android.R.layout.simple_spinner_item)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
entropySpinner.adapter = adapter
// Avoid triggering the selected option when the activity starts
entropySpinner.onItemSelectedListener = null
entropySpinner.setSelection(prefs.getInt(K.PREF.ENTROPY_SPINNER_SELECTION, 0))
entropySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, position: Int, l: Long) {
check += 1
if (check > 1) {
when (position) {
// Static values
1 -> setProfiles(64, 128, position)
2 -> setProfiles(256, 320, position)
3 -> setProfiles(320, 512, position)
4 -> setProfiles(512, 768, position)
5 -> setProfiles(768, 1024, position)
}
}
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
entropyApplyOnBoot.setOnCheckedChangeListener(null)
entropyApplyOnBoot.isChecked = prefs.getBoolean(K.PREF.ENTROPY_ON_BOOT, false)
entropyApplyOnBoot.setOnCheckedChangeListener { _, isChecked -> prefs.putBoolean(K.PREF.ENTROPY_ON_BOOT, isChecked) }
entropyReadSeekBar.setOnSeekBarChangeListener(this)
entropyWriteSeekBar.setOnSeekBarChangeListener(this)
Logger.logDebug("Reading entropy", this)
lifecycleScope.launch(workerContext) {
poolsize = RootUtils.readSingleLineFile("/proc/sys/kernel/random/poolsize", "4096")
readThreshold = RootUtils.readSingleLineFile(READ_WAKEUP_THRESHOLD, "64")
writeThreshold = RootUtils.readSingleLineFile(WRITE_WAKEUP_THRESHOLD, "128")
runSafeOnUiThread {
// Update the UI with the values we just got
try {
entropyReadSeekBar.progress = Integer.parseInt(readThreshold)
entropyWriteSeekBar.progress = Integer.parseInt(writeThreshold)
entropyReadText.text = readThreshold
entropyWriteText.text = writeThreshold
} catch (e: Exception) {
entropyReadSeekBar.progress = 64
entropyWriteSeekBar.progress = 64
entropyReadText.text = 64.toString()
entropyWriteText.text = 64.toString()
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// "Back button" of the ActionBar
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
handler.removeCallbacks(getEntropyRunnable)
handler.postDelayed(getEntropyRunnable, 1000)
}
override fun onStop() {
super.onStop()
handler.removeCallbacks(getEntropyRunnable)
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.fragment_close_enter, R.anim.slide_out_right)
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, b: Boolean) {
when (seekBar.id) {
entropyReadSeekBar.id -> {
updateUiFromWakeUpThresholdSeekBar(seekBar, progress, true)
}
entropyWriteSeekBar.id -> {
updateUiFromWakeUpThresholdSeekBar(seekBar, progress, false)
}
entropyReseedSeekBar.id -> {
entropyReseedText.text = progress.toString()
}
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
lifecycleScope.launch(workerContext) {
when (seekBar.id) {
entropyReadSeekBar.id -> {
prefs.putInt(K.PREF.ENTROPY_READ_THRESHOLD, readThresholdInt)
RootUtils.execute("sysctl -e -w kernel.random.read_wakeup_threshold=$readThresholdInt")
}
entropyWriteSeekBar.id -> {
prefs.putInt(K.PREF.ENTROPY_WRITE_THRESHOLD, writeThresholdInt)
RootUtils.execute("sysctl -e -w kernel.random.write_wakeup_threshold=$writeThresholdInt")
}
entropyReseedSeekBar.id -> {
prefs.putInt(K.PREF.ENTROPY_MIN_RESEED_SECS, seekBar.progress)
RootUtils.execute("echo '${seekBar.progress}' > /proc/sys/kernel/random/urandom_min_reseed_secs")
}
}
Logger.logInfo(
"Set entropy manually to ($readThresholdInt, $writeThresholdInt)",
applicationContext
)
}
}
/**
* Updates the UI given a SeekBar and its progress and stores the value for
* later saving in the preferences via [setProfiles]
* or onStopTrackingTouch() at [SeekBar.OnSeekBarChangeListener]
* Also, makes the SeekBar only store a multiple of 64 as its progress.
*
* @param seekBar the SeekBar to "correct" the progress
* @param progress the SeekBar's progress
* @param read whether we are dealing with "read" or "write" wakeup threshold
*/
private fun updateUiFromWakeUpThresholdSeekBar(seekBar: SeekBar, progress: Int, read: Boolean) {
var newProgress = progress
// Acceptable step
val step = 64
// Allow only multiples of 64
newProgress = (newProgress / step).toFloat().roundToInt() * step
seekBar.progress = newProgress
if (read) {
readThresholdInt = newProgress
entropyReadText.text = newProgress.toString()
} else {
writeThresholdInt = newProgress
entropyWriteText.text = newProgress.toString()
}
}
/**
* Commits the entropy threshold values and updates the UI accordingly
*
* @param r read_wakeup_threshold
* @param w write_wakeup_threshold
* @param position the spinner position to save in the preferences
*/
private fun setProfiles(r: Int, w: Int, position: Int) {
entropyReadSeekBar.progress = r
entropyReadText.text = r.toString()
entropyWriteSeekBar.progress = w
entropyWriteText.text = w.toString()
prefs.putInt(K.PREF.ENTROPY_READ_THRESHOLD, r)
prefs.putInt(K.PREF.ENTROPY_WRITE_THRESHOLD, w)
prefs.putInt(K.PREF.ENTROPY_SPINNER_SELECTION, position)
lifecycleScope.launch(workerContext) {
RootUtils.execute(arrayOf(
"sysctl -w kernel.random.read_wakeup_threshold=$r",
"sysctl -w kernel.random.write_wakeup_threshold=$w")
)
Logger.logInfo("Set entropy via profile to ($r, $w)", applicationContext)
}
}
/**
* Sets up the handler that will execute [getAvailableEntropy]
* in a 1 second interval
*/
private fun setUpRunnable() {
getEntropyRunnable = object : Runnable {
override fun run() {
lifecycleScope.launch(workerContext){
getAvailableEntropy()
}
handler.postDelayed(this, 1000)
}
}
}
/**
* Fetches the entropy available and updates the UI accordingly,
* this method will run every 1 second, as long as the activity
* is visible
*
* @see .setUpRunnable
*/
private suspend fun getAvailableEntropy() = withContext(Dispatchers.IO) {
availableEntropy = RootUtils.readSingleLineFile(ENTROPY_AVAIL, "0")
runSafeOnUiThread {
try {
val progress = Integer.parseInt(availableEntropy)
val pool = Integer.parseInt(poolsize)
val entropyAvail = "${(progress * 100.0 / pool).roundDecimals(2)}% ($availableEntropy)"
entropyCurrentText.text = entropyAvail
entropyProgress.animProgress(progress)
} catch (e: Exception) {
val ent = "${(1024 * 100.0 / 4096).roundDecimals(2)}% ($availableEntropy)"
entropyCurrentText.text = ent
entropyProgress.animProgress(1042)
}
}
}
companion object {
private const val ENTROPY_AVAIL = "/proc/sys/kernel/random/entropy_avail"
private const val READ_WAKEUP_THRESHOLD = "/proc/sys/kernel/random/read_wakeup_threshold"
private const val WRITE_WAKEUP_THRESHOLD = "/proc/sys/kernel/random/write_wakeup_threshold"
private const val ADD_RANDOM = "/sys/block/mmcblk0/queue/add_random"
private const val URANDOM_MIN_RESEED_SECS = "urandom_min_reseed_secs"
}
}
| apache-2.0 | 8f34d27725b59a70b659cfcf30e21ef4 | 38.785489 | 125 | 0.606407 | 4.743137 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/traits/DisableKeyboardInputTrait.kt | 1 | 2451 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and 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.vanniktech.emoji.traits
import android.view.View
import android.view.View.OnFocusChangeListener
import android.widget.EditText
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.vanniktech.emoji.EmojiPopup
/**
* Disables the keyboard so that letters, digits etc can't be input.
* Instead only the EmojiPopup will be displayed.
*
* Note: This is using a OnFocusChangeListener. Don't overwrite it.
*/
class DisableKeyboardInputTrait(
private val emojiPopup: EmojiPopup,
) : EmojiTraitable {
override fun install(editText: EditText): EmojiTrait {
val forceEmojisOnlyFocusChangeListener = ForceEmojisOnlyFocusChangeListener(
delegate = editText.onFocusChangeListener,
emojiPopup = emojiPopup,
)
editText.onFocusChangeListener = forceEmojisOnlyFocusChangeListener
val isKeyboardOpen = ViewCompat.getRootWindowInsets(editText.rootView)?.isVisible(WindowInsetsCompat.Type.ime()) == true
if (editText.hasFocus() || isKeyboardOpen) {
forceEmojisOnlyFocusChangeListener.focus()
}
return object : EmojiTrait {
override fun uninstall() {
editText.onFocusChangeListener = forceEmojisOnlyFocusChangeListener.delegate
}
}
}
internal class ForceEmojisOnlyFocusChangeListener(
internal val delegate: OnFocusChangeListener?,
private val emojiPopup: EmojiPopup,
) : OnFocusChangeListener {
override fun onFocusChange(view: View, hasFocus: Boolean) {
if (hasFocus) {
emojiPopup.start()
emojiPopup.show()
} else {
emojiPopup.dismiss()
}
delegate?.onFocusChange(view, hasFocus)
}
internal fun focus() {
if (!emojiPopup.isShowing) {
emojiPopup.start()
emojiPopup.show()
}
}
}
}
| apache-2.0 | 49bf92b402a4ccb0f6d26449e6f10fe5 | 30.805195 | 124 | 0.727644 | 4.655894 | false | false | false | false |
simonorono/SRSM | src/main/kotlin/srsm/controller/Asistencia.kt | 1 | 2971 | /*
* Copyright 2016 Sociedad Religiosa Servidores de María
*
* 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 srsm.controller
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.Label
import javafx.scene.control.TableView
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import srsm.G
import srsm.Message
import srsm.controller.util.integerFormat
import srsm.controller.util.required
import srsm.model.Actividad
import srsm.model.Asistencia
import srsm.model.Servidor
@Suppress("unused", "UNUSED_PARAMETER")
class Asistencia {
@FXML lateinit private var descripcion: Label
@FXML lateinit private var cedula: TextField
@FXML lateinit private var tablaAsis: TableView<Servidor>
var actividad: Actividad? = null
fun init() {
descripcion.text = actividad?.descripcion ?: "Actividad"
update()
}
private fun update() {
tablaAsis.items.clear()
tablaAsis.items.addAll(G.db.getAsistenciaByActividad(actividad!!))
}
private fun marcar() {
try {
required(Pair("Cédula", cedula))
integerFormat(Pair("Cédula", cedula))
} catch (e: Exception) {
return
}
val servidor = G.db.getServidorByCedula(cedula.text)
if (servidor == null) {
Message.error("No existe servidor con esa cédula")
} else {
if (!G.db.existeAsistencia(actividad!!, servidor)) {
val a = Asistencia()
a.servidorID = servidor.id
a.actividadID = actividad!!.id
G.db.createAsistencia(a)
} else {
Message.error("Asistencia ya marcada")
}
}
cedula.clear()
cedula.requestFocus()
update()
}
@FXML
private fun initialize() {
}
@FXML
private fun agregarOnAction(event: ActionEvent) {
marcar()
}
@FXML
private fun eliminarOnAction(event: ActionEvent) {
tablaAsis.selectionModel.selectedItem?.let { s ->
val asistencia = G.db.getAsistencia(actividad!!, s)
if (asistencia != null) {
G.db.deleteAsistencia(asistencia)
update()
}
}
}
@FXML fun onKeyPressed(event: KeyEvent) {
if (event.code == KeyCode.ENTER) {
marcar()
}
}
}
| apache-2.0 | c05da8d62b3ac102031faf43c1bfa4e9 | 26.990566 | 75 | 0.635659 | 3.833333 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/AndThePlayerIdles/AndTheFilePositionIsAtTheEnd/WhenThePlayerWillPlayWhenReady.kt | 1 | 2086 | package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.AndThePlayerIdles.AndTheFilePositionIsAtTheEnd
import com.google.android.exoplayer2.Player
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import org.assertj.core.api.AssertionsForClassTypes
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.mockito.invocation.InvocationOnMock
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class WhenThePlayerWillPlayWhenReady {
companion object {
private var eventListener: Player.EventListener? = null
private var isComplete = false
@BeforeClass
@Throws(InterruptedException::class, ExecutionException::class)
fun before() {
val mockExoPlayer = Mockito.mock(PromisingExoPlayer::class.java)
Mockito.`when`(mockExoPlayer.getPlayWhenReady()).thenReturn(true.toPromise())
Mockito.`when`(mockExoPlayer.getCurrentPosition()).thenReturn(100L.toPromise())
Mockito.`when`(mockExoPlayer.getDuration()).thenReturn(100L.toPromise())
Mockito.doAnswer { invocation: InvocationOnMock ->
eventListener = invocation.getArgument(0)
null
}.`when`(mockExoPlayer).addListener(ArgumentMatchers.any())
val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer)
val playbackPromise = exoPlayerPlaybackHandler.promisePlayback().eventually { obj -> obj.promisePlayedFile() }
.then { isComplete = true }
eventListener?.onPlayerStateChanged(true, Player.STATE_IDLE)
try {
FuturePromise(playbackPromise)[1, TimeUnit.SECONDS]
} catch (ignored: TimeoutException) {
}
}
}
@Test
fun thenPlaybackContinues() {
AssertionsForClassTypes.assertThat(isComplete).isFalse
}
}
| lgpl-3.0 | e1e3b7b4885de0e0e1dea05d2ab9bb18 | 41.571429 | 134 | 0.814477 | 4.466809 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/CompShelvingUnit.kt | 2 | 3623 | package com.cout970.magneticraft.systems.gui.components
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.features.multiblocks.ContainerShelvingUnit
import com.cout970.magneticraft.misc.guiTexture
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.gui.AutoGui
import com.cout970.magneticraft.systems.gui.DATA_ID_SHELVING_UNIT_SCROLL
import com.cout970.magneticraft.systems.gui.GuiBase
import com.cout970.magneticraft.systems.gui.components.buttons.SelectButton
import com.cout970.magneticraft.systems.gui.render.IComponent
import com.cout970.magneticraft.systems.gui.render.IGui
import net.minecraft.client.renderer.GlStateManager.color
import net.minecraft.client.renderer.GlStateManager.enableBlend
import net.minecraft.client.resources.I18n
/**
* Created by cout970 on 2017/07/29.
*/
class ComponentShelvingUnit : IComponent {
override val pos: IVector2 = Vec2d.ZERO
override val size: IVector2 = Vec2d.ZERO
override lateinit var gui: IGui
lateinit var scrollBar: ScrollBar
lateinit var searchBar: SearchBar
lateinit var container: ContainerShelvingUnit
var lastScroll = 0
override fun init() {
container = (gui as GuiBase).container as ContainerShelvingUnit
scrollBar = gui.components.filterIsInstance<ScrollBar>().first()
searchBar = gui.components.filterIsInstance<SearchBar>().first()
searchBar.onChange = container::setFilter
val select = gui.components.filterIsInstance<SelectButton>().first()
val oldCallback = select.onClick
select.onClick = {
searchBar.textField.text = ""
oldCallback(it)
}
}
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
val scroll = scrollBar.section
val auto = gui as AutoGui
auto.slots = auto.createSlots(container.inventorySlots)
if (lastScroll != scroll) {
lastScroll = scroll
val scrollPercent = scroll / scrollBar.sections.toFloat()
container.withScroll(scrollPercent)
container.sendUpdate(IBD().setFloat(DATA_ID_SHELVING_UNIT_SCROLL, scrollPercent))
}
}
override fun drawSecondLayer(mouse: Vec2d) {
val scrollPercent = scrollBar.section / scrollBar.sections.toFloat()
val columnIndex = scrollPercent * ((container.currentSlots.size / 9f) - 5)
val column = Math.max(0, Math.round(columnIndex))
gui.bindTexture(guiTexture("misc"))
(0 until 5 * 9).forEach {
val pos = it + column * 9
if (pos >= container.currentSlots.size) {
val x = it % 9 * 18 + 7
val y = it / 9 * 18 + 20
gui.drawTexture(
vec2Of(x, y),
vec2Of(18, 18),
vec2Of(180, 69)
)
}
}
val filterText = searchBar.textField.text
if (container.currentSlots.isEmpty() && (filterText.isEmpty() || filterText.isBlank())) {
val start = vec2Of(6, 56)
val end = start + vec2Of(164, 17)
color(1f, 1f, 1f, 1f)
gui.drawColor(start, end, 0xF0000000.toInt())
gui.drawCenteredString(
text = I18n.format("text.magneticraft.shelving_unit_add_chests"),
pos = vec2Of(88, 61),
color = 0xFFFFFFFF.toInt()
)
enableBlend()
color(1f, 1f, 1f, 1f)
}
}
} | gpl-2.0 | 070708fbd0020689dca1a5a98b2f57fa | 35.979592 | 97 | 0.652498 | 4.154817 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/fragment/BaseFragment.kt | 1 | 1973 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment
import android.content.res.Resources
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.AnimationUtils
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import org.mozilla.focus.ext.hideToolbar
abstract class BaseFragment : Fragment() {
private var animationSet: AnimationSet? = null
override fun onResume() {
super.onResume()
hideToolbar()
}
fun cancelAnimation() {
if (animationSet != null) {
animationSet!!.duration = 0
animationSet!!.cancel()
}
}
@Suppress("SwallowedException")
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
var animation = super.onCreateAnimation(transit, enter, nextAnim)
if (animation == null && nextAnim != 0) {
animation = try {
AnimationUtils.loadAnimation(activity, nextAnim)
} catch (e: Resources.NotFoundException) {
return null
}
}
return if (animation != null) {
val animSet = AnimationSet(true)
animSet.addAnimation(animation)
animationSet = animSet
animSet
} else {
null
}
}
}
fun Fragment.requestInPlacePermissions(
permissionsToRequest: Array<String>,
onResult: (Map<String, Boolean>) -> Unit,
) {
requireActivity().activityResultRegistry.register(
"permissionsRequest",
ActivityResultContracts.RequestMultiplePermissions(),
) { permissions ->
onResult(permissions)
}.also {
it.launch(permissionsToRequest)
}
}
| mpl-2.0 | cf8372be0a810ce4b472ee38f53adb6e | 30.31746 | 93 | 0.651292 | 4.686461 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/ToastEventListener.kt | 2 | 2565 | package leakcanary
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import com.squareup.leakcanary.core.R
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.SECONDS
import leakcanary.EventListener.Event
import leakcanary.EventListener.Event.DumpingHeap
import leakcanary.EventListener.Event.HeapDumpFailed
import leakcanary.EventListener.Event.HeapDump
import leakcanary.internal.InternalLeakCanary
import leakcanary.internal.friendly.mainHandler
object ToastEventListener : EventListener {
// Only accessed from the main thread
private var toastCurrentlyShown: Toast? = null
override fun onEvent(event: Event) {
when (event) {
is DumpingHeap -> {
showToastBlocking()
}
is HeapDump, is HeapDumpFailed -> {
mainHandler.post {
toastCurrentlyShown?.cancel()
toastCurrentlyShown = null
}
}
}
}
@Suppress("DEPRECATION")
private fun showToastBlocking() {
val appContext = InternalLeakCanary.application
val waitingForToast = CountDownLatch(1)
mainHandler.post(Runnable {
val resumedActivity = InternalLeakCanary.resumedActivity
if (resumedActivity == null || toastCurrentlyShown != null) {
waitingForToast.countDown()
return@Runnable
}
val toast = Toast(resumedActivity)
// Resources from application context: https://github.com/square/leakcanary/issues/2023
val iconSize = appContext.resources.getDimensionPixelSize(
R.dimen.leak_canary_toast_icon_size
)
toast.setGravity(Gravity.CENTER_VERTICAL, 0, -iconSize)
toast.duration = Toast.LENGTH_LONG
// Need an activity context because StrictMode added new stupid checks:
// https://github.com/square/leakcanary/issues/2153
val inflater = LayoutInflater.from(resumedActivity)
toast.view = inflater.inflate(R.layout.leak_canary_heap_dump_toast, null)
toast.show()
val toastIcon = toast.view!!.findViewById<View>(R.id.leak_canary_toast_icon)
toastIcon.translationY = -iconSize.toFloat()
toastIcon
.animate()
.translationY(0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
toastCurrentlyShown = toast
waitingForToast.countDown()
}
})
})
waitingForToast.await(5, SECONDS)
}
}
| apache-2.0 | ae0556c641858548d5852f93830b514a | 33.2 | 93 | 0.715789 | 4.680657 | false | false | false | false |
android/camera-samples | CameraXExtensions/app/src/main/java/com/example/android/cameraxextensions/viewmodel/CameraExtensionsViewModel.kt | 1 | 11745 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.cameraxextensions.viewmodel
import android.app.Application
import androidx.camera.core.*
import androidx.camera.core.CameraSelector.LensFacing
import androidx.camera.extensions.ExtensionMode
import androidx.camera.extensions.ExtensionsManager
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.ui.layout.ScaleFactor
import androidx.core.net.toUri
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.cameraxextensions.model.CameraState
import com.example.android.cameraxextensions.model.CameraUiState
import com.example.android.cameraxextensions.model.CaptureState
import com.example.android.cameraxextensions.repository.ImageCaptureRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.launch
/**
* View model for camera extensions. This manages all the operations on the camera.
* This includes opening and closing the camera, showing the camera preview, capturing a photo,
* checking which extensions are available, and selecting an extension.
*
* Camera UI state is communicated via the cameraUiState flow.
* Capture UI state is communicated via the captureUiState flow.
*
* Rebinding to the UI state flows will always emit the last UI state.
*/
class CameraExtensionsViewModel(
private val application: Application,
private val imageCaptureRepository: ImageCaptureRepository
) : ViewModel() {
private lateinit var cameraProvider: ProcessCameraProvider
private lateinit var extensionsManager: ExtensionsManager
private var camera: Camera? = null
private val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
private val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
private val _cameraUiState: MutableStateFlow<CameraUiState> = MutableStateFlow(CameraUiState())
private val _captureUiState: MutableStateFlow<CaptureState> =
MutableStateFlow(CaptureState.CaptureNotReady)
val cameraUiState: Flow<CameraUiState> = _cameraUiState
val captureUiState: Flow<CaptureState> = _captureUiState
/**
* Initializes the camera and checks which extensions are available for the selected camera lens
* face. If no extensions are available then the selected extension will be set to None and the
* available extensions list will also contain None.
* Because this operation is async, clients should wait for cameraUiState to emit
* CameraState.READY. Once the camera is ready the client can start the preview.
*/
fun initializeCamera() {
viewModelScope.launch {
val currentCameraUiState = _cameraUiState.value
// get the camera selector for the select lens face
val cameraSelector = cameraLensToSelector(currentCameraUiState.cameraLens)
// wait for the camera provider instance and extensions manager instance
cameraProvider = ProcessCameraProvider.getInstance(application).await()
extensionsManager =
ExtensionsManager.getInstanceAsync(application, cameraProvider).await()
val availableCameraLens =
listOf(
CameraSelector.LENS_FACING_BACK,
CameraSelector.LENS_FACING_FRONT
).filter { lensFacing ->
cameraProvider.hasCamera(cameraLensToSelector(lensFacing))
}
// get the supported extensions for the selected camera lens by filtering the full list
// of extensions and checking each one if it's available
val availableExtensions = listOf(
ExtensionMode.AUTO,
ExtensionMode.BOKEH,
ExtensionMode.HDR,
ExtensionMode.NIGHT,
ExtensionMode.FACE_RETOUCH
).filter { extensionMode ->
extensionsManager.isExtensionAvailable(cameraSelector, extensionMode)
}
// prepare the new camera UI state which is now in the READY state and contains the list
// of available extensions, available lens faces.
val newCameraUiState = currentCameraUiState.copy(
cameraState = CameraState.READY,
availableExtensions = listOf(ExtensionMode.NONE) + availableExtensions,
availableCameraLens = availableCameraLens,
extensionMode = if (availableExtensions.isEmpty()) ExtensionMode.NONE else currentCameraUiState.extensionMode,
)
_cameraUiState.emit(newCameraUiState)
}
}
/**
* Starts the preview stream. The camera state should be in the READY or PREVIEW_STOPPED state
* when calling this operation.
* This process will bind the preview and image capture uses cases to the camera provider.
*/
fun startPreview(
lifecycleOwner: LifecycleOwner,
previewView: PreviewView
) {
val currentCameraUiState = _cameraUiState.value
val cameraSelector = if (currentCameraUiState.extensionMode == ExtensionMode.NONE) {
cameraLensToSelector(currentCameraUiState.cameraLens)
} else {
extensionsManager.getExtensionEnabledCameraSelector(
cameraLensToSelector(currentCameraUiState.cameraLens),
currentCameraUiState.extensionMode
)
}
val useCaseGroup = UseCaseGroup.Builder()
.setViewPort(previewView.viewPort!!)
.addUseCase(imageCapture)
.addUseCase(preview)
.build()
cameraProvider.unbindAll()
camera = cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
useCaseGroup
)
preview.setSurfaceProvider(previewView.surfaceProvider)
viewModelScope.launch {
_cameraUiState.emit(_cameraUiState.value.copy(cameraState = CameraState.READY))
_captureUiState.emit(CaptureState.CaptureReady)
}
}
/**
* Stops the preview stream. This should be invoked when the captured image is displayed.
*/
fun stopPreview() {
preview.setSurfaceProvider(null)
viewModelScope.launch {
_cameraUiState.emit(_cameraUiState.value.copy(cameraState = CameraState.PREVIEW_STOPPED))
}
}
/**
* Toggle the camera lens face. This has no effect if there is only one available camera lens.
*/
fun switchCamera() {
val currentCameraUiState = _cameraUiState.value
if (currentCameraUiState.cameraState == CameraState.READY) {
// To switch the camera lens, there has to be at least 2 camera lenses
if (currentCameraUiState.availableCameraLens.size == 1) return
val camLensFacing = currentCameraUiState.cameraLens
// Toggle the lens facing
val newCameraUiState = if (camLensFacing == CameraSelector.LENS_FACING_BACK) {
currentCameraUiState.copy(cameraLens = CameraSelector.LENS_FACING_FRONT)
} else {
currentCameraUiState.copy(cameraLens = CameraSelector.LENS_FACING_BACK)
}
viewModelScope.launch {
_cameraUiState.emit(
newCameraUiState.copy(
cameraState = CameraState.NOT_READY,
)
)
_captureUiState.emit(CaptureState.CaptureNotReady)
}
}
}
/**
* Captures the photo and saves it to the pictures directory that's inside the app-specific
* directory on external storage.
* Upon successful capture, the captureUiState flow will emit CaptureFinished with the URI to
* the captured photo.
* If the capture operation failed then captureUiState flow will emit CaptureFailed with the
* exception containing more details on the reason for failure.
*/
fun capturePhoto() {
viewModelScope.launch {
_captureUiState.emit(CaptureState.CaptureStarted)
}
val photoFile = imageCaptureRepository.createImageOutputFile()
val metadata = ImageCapture.Metadata().apply {
// Mirror image when using the front camera
isReversedHorizontal =
_cameraUiState.value.cameraLens == CameraSelector.LENS_FACING_FRONT
}
val outputFileOptions =
ImageCapture.OutputFileOptions.Builder(photoFile)
.setMetadata(metadata)
.build()
imageCapture.takePicture(
outputFileOptions,
Dispatchers.Default.asExecutor(),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
imageCaptureRepository.notifyImageCreated(
application,
outputFileResults.savedUri ?: photoFile.toUri()
)
viewModelScope.launch {
_captureUiState.emit(CaptureState.CaptureFinished(outputFileResults))
}
}
override fun onError(exception: ImageCaptureException) {
viewModelScope.launch {
_captureUiState.emit(CaptureState.CaptureFailed(exception))
}
}
})
}
/**
* Sets the current extension mode. This will force the camera to rebind the use cases.
*/
fun setExtensionMode(@ExtensionMode.Mode extensionMode: Int) {
viewModelScope.launch {
_cameraUiState.emit(
_cameraUiState.value.copy(
cameraState = CameraState.NOT_READY,
extensionMode = extensionMode,
)
)
_captureUiState.emit(CaptureState.CaptureNotReady)
}
}
fun focus(meteringPoint: MeteringPoint) {
val camera = camera ?: return
val meteringAction = FocusMeteringAction.Builder(meteringPoint).build()
camera.cameraControl.startFocusAndMetering(meteringAction)
}
fun scale(scaleFactor: Float) {
val camera = camera ?: return
val currentZoomRatio: Float = camera.cameraInfo.zoomState.value?.zoomRatio ?: 1f
camera.cameraControl.setZoomRatio(scaleFactor * currentZoomRatio)
}
private fun cameraLensToSelector(@LensFacing lensFacing: Int): CameraSelector =
when (lensFacing) {
CameraSelector.LENS_FACING_FRONT -> CameraSelector.DEFAULT_FRONT_CAMERA
CameraSelector.LENS_FACING_BACK -> CameraSelector.DEFAULT_BACK_CAMERA
else -> throw IllegalArgumentException("Invalid lens facing type: $lensFacing")
}
}
| apache-2.0 | 6be2ee5ea0a9d2621e04ad8e07238f9c | 40.648936 | 126 | 0.670158 | 5.395039 | false | false | false | false |
Kotlin/dokka | plugins/all-modules-page/src/main/kotlin/AllModulesPageGeneration.kt | 1 | 2748 | package org.jetbrains.dokka.allModulesPage
import org.jetbrains.dokka.CoreExtensions
import org.jetbrains.dokka.Timer
import org.jetbrains.dokka.generation.Generation
import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.plugin
import org.jetbrains.dokka.plugability.query
import org.jetbrains.dokka.plugability.querySingle
import org.jetbrains.dokka.templates.TemplatingPlugin
import org.jetbrains.dokka.templates.TemplatingResult
import org.jetbrains.dokka.transformers.pages.CreationContext
class AllModulesPageGeneration(private val context: DokkaContext) : Generation {
private val allModulesPagePlugin by lazy { context.plugin<AllModulesPagePlugin>() }
private val templatingPlugin by lazy { context.plugin<TemplatingPlugin>() }
override fun Timer.generate() {
report("Processing submodules")
val generationContext = processSubmodules()
report("Creating all modules page")
val pages = createAllModulesPage(generationContext)
report("Transforming pages")
val transformedPages = transformAllModulesPage(pages)
report("Rendering")
render(transformedPages)
report("Processing multimodule")
processMultiModule(transformedPages)
report("Finish submodule processing")
finishProcessingSubmodules()
report("Running post-actions")
runPostActions()
}
override val generationName = "index page for project"
fun createAllModulesPage(allModulesContext: DefaultAllModulesContext) =
allModulesPagePlugin.querySingle { allModulesPageCreator }.invoke(allModulesContext)
fun transformAllModulesPage(pages: RootPageNode) =
allModulesPagePlugin.query { allModulesPageTransformer }.fold(pages) { acc, t -> t(acc) }
fun render(transformedPages: RootPageNode) {
context.single(CoreExtensions.renderer).render(transformedPages)
}
fun runPostActions() {
context[CoreExtensions.postActions].forEach { it() }
}
fun processSubmodules() =
templatingPlugin.querySingle { submoduleTemplateProcessor }
.process(context.configuration.modules)
.let { DefaultAllModulesContext(it) }
fun processMultiModule(root: RootPageNode) =
templatingPlugin.querySingle { multimoduleTemplateProcessor }.process(root)
fun finishProcessingSubmodules() =
templatingPlugin.query { templateProcessingStrategy }.forEach { it.finish(context.configuration.outputDir) }
data class DefaultAllModulesContext(val nonEmptyModules: List<String>) : CreationContext {
constructor(templating: TemplatingResult) : this(templating.modules)
}
}
| apache-2.0 | 72a662785a6e12f2e3fa5ec01c5ccd71 | 36.643836 | 116 | 0.75182 | 5.042202 | false | false | false | false |
asommer70/todopila | src/main/kotlin/Item.kt | 1 | 790 | package todopila
import ninja.sakib.pultusorm.annotations.AutoIncrement
import ninja.sakib.pultusorm.annotations.Ignore
import ninja.sakib.pultusorm.annotations.PrimaryKey
class Item {
@PrimaryKey
@AutoIncrement
var itemId: Int = 0
var content = ""
var listId = ""
var userId = ""
var status = false
var archive = false
var createdAt = ""
var updatedAt = ""
fun create(content: String, listId: String) {
val newItem: Item = Item()
newItem.content = content
newItem.listId = listId
newItem.userId = "0"
newItem.status = false
newItem.archive = false
newItem.createdAt = (System.currentTimeMillis() / 1000).toString()
newItem.updatedAt = (System.currentTimeMillis() / 1000).toString()
pultusORM.save(newItem)
println("Item saved.")
}
} | mit | a2aee4bf8ae704994c108a0c69c3ca41 | 24.516129 | 68 | 0.707595 | 3.542601 | false | false | false | false |
ishwarsawale/RSSReaderKotlinAndroid | SampleRss/app/src/main/java/rss/sample/com/samplerss/MainActivity.kt | 1 | 2835 | package rss.sample.com.samplerss
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import rss.sample.com.samplerss.Adapter.FeedAdapter
import rss.sample.com.samplerss.Common.HTTPDataHandler
import rss.sample.com.samplerss.Model.RootObject
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private val RSS_link = "http://www.datatau.com/rss"
private val RSS_to_JSON_API = "https://api.rss2json.com/v1/api.json?rss_url="
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar.title="DATATAU"
setSupportActionBar(toolbar)
var linearLayoutManager = LinearLayoutManager(baseContext,LinearLayoutManager.VERTICAL,false)
recyclerView.layoutManager = linearLayoutManager
loadRSS()
}
private fun loadRSS() {
val loadRSSAsync = @SuppressLint("StaticFieldLeak")
object:AsyncTask<String,String,String>(){
internal var mDialog = ProgressDialog(this@MainActivity)
override fun doInBackground(vararg p0: String?): String {
val result:String
val http = HTTPDataHandler()
result = http.GetHTTPDataHandler(p0[0])
return result
}
override fun onPostExecute(result: String?) {
mDialog.dismiss()
var rootObject:RootObject
rootObject = Gson().fromJson<RootObject>(result,RootObject::class.java!!)
val adapter = FeedAdapter(rootObject,baseContext)
recyclerView.adapter = adapter
adapter.notifyDataSetChanged()
}
override fun onPreExecute() {
mDialog.setMessage("Please wait..")
mDialog.show()
}
}
val url_get_data = StringBuilder(RSS_to_JSON_API)
url_get_data.append(RSS_link)
loadRSSAsync.execute(url_get_data.toString())
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu,menu)
return true
}
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.menu_refresh)
loadRSS()
return true
}
}
| apache-2.0 | 57d9c3bade409538ed064cf3689c9e66 | 31.215909 | 101 | 0.668783 | 4.701493 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/model/classscodestruct/UnModifiableGenericClass.kt | 1 | 886 | package wu.seal.jsontokotlin.model.classscodestruct
import wu.seal.jsontokotlin.model.builder.ICodeBuilder
import java.lang.UnsupportedOperationException
/**
* Created by Seal.Wu on 2019-11-24
* Kotlin class which could not be modified the code content also with generic type
*/
abstract class UnModifiableGenericClass : GenericKotlinClass {
override val modifiable: Boolean = false
override fun getCode(): String = throw UnsupportedOperationException("Dont support this function called on unModifiable Class")
override fun getOnlyCurrentCode(): String = throw UnsupportedOperationException("Dont support this function called on unModifiable Class")
override fun rename(newName: String): KotlinClass = throw UnsupportedOperationException("Dont support this function called on unModifiable Class")
override val codeBuilder: ICodeBuilder<*> = ICodeBuilder.EMPTY
} | gpl-3.0 | 70f6e6b93ada53cef59ef7694ec69070 | 54.4375 | 150 | 0.805869 | 5.27381 | false | false | false | false |
yawkat/javap | server/src/test/kotlin/at/yawk/javap/model/CompilerConfigurationSerializerTest.kt | 1 | 1454 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package at.yawk.javap.model
import at.yawk.javap.SdkLanguage
import at.yawk.javap.jsonConfiguration
import kotlinx.serialization.json.Json
import org.testng.Assert
import org.testng.annotations.Test
import java.util.concurrent.ThreadLocalRandom
class CompilerConfigurationSerializerTest {
private val properties = ConfigProperties.properties.getValue(SdkLanguage.JAVA)
private fun withoutDefaults(configuration: CompilerConfiguration): Map<String, Any?> {
return configuration.filter { (k, v) ->
properties.single { it.id == k }.default != v
}
}
@Test
fun test() {
val config = mutableMapOf<String, Any?>()
for (property in properties) {
if (property is ConfigProperty.Flag) {
config[property.id] = ThreadLocalRandom.current().nextBoolean()
}
}
config[ConfigProperties.lint.id] = setOf("a", "b")
val serializer = ConfigProperties.serializers.getValue(SdkLanguage.JAVA)
val json = Json{ jsonConfiguration }
Assert.assertEquals(
withoutDefaults(json.decodeFromString(serializer, json.encodeToString(serializer, config))),
withoutDefaults(config)
)
}
} | mpl-2.0 | 4f57a8d29a7d7bff41cfe60bbe839077 | 34.487805 | 108 | 0.675378 | 4.432927 | false | true | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/uploader/viewmodel/UploaderViewModel.kt | 1 | 2740 | package me.sweetll.tucao.business.uploader.viewmodel
import android.view.View
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import me.sweetll.tucao.Const
import me.sweetll.tucao.base.BaseViewModel
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.business.uploader.UploaderActivity
import me.sweetll.tucao.extension.sanitizeHtml
import me.sweetll.tucao.extension.toast
import org.jsoup.nodes.Document
class UploaderViewModel(val activity: UploaderActivity, val userId: String): BaseViewModel() {
var pageIndex = 1
var pageSize = 20
init {
loadData()
}
fun loadData() {
pageIndex = 1
rawApiService.space(userId, pageIndex)
.bindToLifecycle(activity)
.sanitizeHtml {
parseVideos(this)
}
.subscribe({
data ->
pageIndex ++
activity.loadData(data)
}, {
error ->
error.printStackTrace()
})
}
fun loadMoreData() {
rawApiService.space(userId, pageIndex)
.bindToLifecycle(activity)
.sanitizeHtml {
parseVideos(this)
}
.subscribe({
data ->
if (data.size < pageSize) {
activity.loadMoreData(data, Const.LOAD_MORE_END)
} else {
pageIndex ++
activity.loadMoreData(data, Const.LOAD_MORE_COMPLETE)
}
}, {
error ->
error.printStackTrace()
activity.loadMoreData(null, Const.LOAD_MORE_FAIL)
})
}
fun parseVideos(doc: Document): MutableList<Video> {
val v_divs = doc.select("div.v")
return v_divs.fold(mutableListOf()) {
total, v_div ->
val tt_a = v_div.select("a.tt")[0]
val title = tt_a.text()
val hid = tt_a.attr("href").replace("[\\D]".toRegex(), "")
val thumb = v_div.select("img")[0].attr("src")
val i_div = v_div.select("div.i")[0]
val info = i_div.text().replace(",", "").replace("[\\D]+".toRegex(), " ")
val nums = info.trim().split(" ").takeLast(4)
val play = nums[0].toInt()
val mukio = nums[1].toInt()
val video = Video(title = title, hid = hid, thumb = thumb, play = play, mukio = mukio)
total.add(video)
total
}
}
fun onClickSendMessage(view: View) {
"不发不发就不发σ`∀´)".toast()
}
}
| mit | 359f088f7d92034812800d37468287d0 | 29.931818 | 98 | 0.506613 | 4.469622 | false | false | false | false |
b95505017/android-architecture-components | PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/ui/SubRedditViewModel.kt | 1 | 1913 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.paging.pagingwithnetwork.reddit.ui
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations.map
import android.arch.lifecycle.Transformations.switchMap
import android.arch.lifecycle.ViewModel
import com.android.example.paging.pagingwithnetwork.reddit.repository.RedditPostRepository
/**
* A RecyclerView ViewHolder that displays a single reddit post.
*/
class SubRedditViewModel(private val repository: RedditPostRepository) : ViewModel() {
private val subredditName = MutableLiveData<String>()
private val repoResult = map(subredditName, {
repository.postsOfSubreddit(it, 30)
})
val posts = switchMap(repoResult, { it.pagedList })!!
val networkState = switchMap(repoResult, { it.networkState })!!
val refreshState = switchMap(repoResult, { it.refreshState })!!
fun refresh() {
repoResult.value?.refresh?.invoke()
}
fun showSubreddit(subreddit: String): Boolean {
if (subredditName.value == subreddit) {
return false
}
subredditName.value = subreddit
return true
}
fun retry() {
val listing = repoResult?.value
listing?.retry?.invoke()
}
fun currentSubreddit(): String? = subredditName.value
} | apache-2.0 | dd87d4542a20970666cfbc07e10d3560 | 33.8 | 90 | 0.720857 | 4.49061 | false | false | false | false |
square/duktape-android | zipline/src/jniMain/kotlin/app/cash/zipline/QuickJsException.kt | 1 | 3229 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.cash.zipline
import androidx.annotation.Keep
import java.util.regex.Pattern
@Keep // Instruct ProGuard not to strip this type.
actual class QuickJsException @JvmOverloads constructor(
detailMessage: String,
jsStackTrace: String? = null
) : RuntimeException(detailMessage) {
init {
if (jsStackTrace != null) {
addJavaScriptStack(jsStackTrace)
}
}
private companion object {
/**
* QuickJs stack trace strings have multiple lines of the format "at func (file.ext:line)".
* "func" is optional, but we'll omit frames without a function, since it means the frame is in
* native code.
*/
private val STACK_TRACE_PATTERN =
Pattern.compile("\\s*at ([^\\s]+) \\(([^\\s]+(?<!cpp))[:(\\d+)]?\\).*$")
/** Java StackTraceElements require a class name. We don't have one in JS, so use this. */
private const val STACK_TRACE_CLASS_NAME = "JavaScript"
/**
* Parses `StackTraceElement`s from `detailMessage` and adds them to the proper place
* in `throwable`'s stack trace.
*
* NOTE: This method is also called from native code.
*/
@JvmStatic // Expose for easy invocation from native.
@JvmSynthetic // Hide from public API to Java consumers.
fun Throwable.addJavaScriptStack(detailMessage: String) {
val lines = detailMessage.split('\n').dropLastWhile(String::isEmpty)
if (lines.isEmpty()) {
return
}
// We have a stacktrace following the message. Add it to the exception.
val elements = mutableListOf<StackTraceElement>()
// Splice the JavaScript stack in right above the call to QuickJs.
var spliced = false
for (stackTraceElement in stackTrace) {
if (!spliced
&& stackTraceElement.isNativeMethod
&& stackTraceElement.isZipline) {
spliced = true
for (line in lines) {
val jsElement = toStackTraceElement(line) ?: continue
elements += jsElement
}
}
elements += stackTraceElement
}
stackTrace = elements.toTypedArray()
}
private val StackTraceElement.isZipline: Boolean
get() = className == QuickJs::class.java.name || className == JniCallChannel::class.java.name
private fun toStackTraceElement(s: String): StackTraceElement? {
val m = STACK_TRACE_PATTERN.matcher(s)
return if (!m.matches()) {
null // Nothing interesting on this line.
} else {
StackTraceElement(STACK_TRACE_CLASS_NAME, m.group(1), m.group(2),
if (m.groupCount() > 3) m.group(3)!!.toInt() else -1)
}
}
}
}
| apache-2.0 | 12fb20ecfa0cf350e3fb75421a8f1173 | 34.877778 | 99 | 0.65655 | 4.311081 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/base/lifecycle/LifecycleConnection.kt | 1 | 392 | package com.infinum.dbinspector.ui.shared.base.lifecycle
internal data class LifecycleConnection(
val databaseName: String? = null,
val databasePath: String? = null,
val schemaName: String? = null
) {
val hasDatabaseData = databaseName.isNullOrBlank().not() && databasePath.isNullOrBlank().not()
val hasSchemaData = hasDatabaseData && schemaName.isNullOrBlank().not()
}
| apache-2.0 | 8af8d06400d552e943c78edbb2ad6a51 | 34.636364 | 98 | 0.737245 | 4.454545 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/manager/transaction/OutgoingTransactionManager.kt | 1 | 11529 | /*
* 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.manager.transaction
import com.toshi.manager.model.ERC20TokenPaymentTask
import com.toshi.manager.model.ExternalPaymentTask
import com.toshi.manager.model.PaymentTask
import com.toshi.manager.model.ResendToshiPaymentTask
import com.toshi.manager.model.SentToshiPaymentTask
import com.toshi.manager.model.ToshiPaymentTask
import com.toshi.manager.store.PendingTransactionStore
import com.toshi.model.local.OutgoingPaymentResult
import com.toshi.model.local.PendingTransaction
import com.toshi.model.local.Recipient
import com.toshi.model.local.SendState
import com.toshi.model.local.User
import com.toshi.model.sofa.SofaAdapters
import com.toshi.model.sofa.SofaMessage
import com.toshi.model.sofa.payment.Payment
import com.toshi.util.logging.LogUtil
import com.toshi.view.BaseApplication
import rx.Single
import rx.Subscription
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import rx.subscriptions.CompositeSubscription
class OutgoingTransactionManager(
private val pendingTransactionStore: PendingTransactionStore,
private val transactionSigner: TransactionSigner
) {
private val userManager by lazy { BaseApplication.get().userManager }
private val chatManager by lazy { BaseApplication.get().chatManager }
private val newOutgoingPaymentQueue by lazy { PublishSubject.create<PaymentTask>() }
private val subscriptions by lazy { CompositeSubscription() }
private var outgoingPaymentSub: Subscription? = null
private val paymentErrorTask by lazy { PaymentErrorTask() }
private val balanceManager by lazy { BaseApplication.get().balanceManager }
val outgoingPaymentResultSubject by lazy { PublishSubject.create<OutgoingPaymentResult>() }
fun attachNewOutgoingPaymentSubscriber() {
// Explicitly clear first to avoid double subscription
clearSubscription()
outgoingPaymentSub = newOutgoingPaymentQueue
.subscribeOn(Schedulers.io())
.subscribe(
{ processNewOutgoingPayment(it) },
{ LogUtil.exception("Error while handling outgoing payment $it") }
)
subscriptions.add(outgoingPaymentSub)
}
private fun processNewOutgoingPayment(paymentTask: PaymentTask) {
when (paymentTask) {
is ResendToshiPaymentTask -> resendPayment(paymentTask)
is ToshiPaymentTask -> sendToshiPayment(paymentTask)
is ExternalPaymentTask -> sendExternalPayment(paymentTask)
is ERC20TokenPaymentTask -> sendERC20Payment(paymentTask)
}
}
private fun sendToshiPayment(paymentTask: ToshiPaymentTask) {
getUpdatedToshiPayment(paymentTask)
.subscribe(
{ handleOutgoingToshiPayment(it.first, it.second) },
{ LogUtil.exception("Error while sending payment $it") }
)
}
private fun getUpdatedToshiPayment(paymentTask: ToshiPaymentTask): Single<Pair<ToshiPaymentTask, SofaMessage>> {
val receiver = getReceiverFromTask(paymentTask)
val sender = getSenderFromTask(paymentTask)
return balanceManager
.generateLocalPrice(paymentTask.payment)
.map { storePayment(receiver, it, sender) }
.map { Pair(paymentTask, it) }
.subscribeOn(Schedulers.io())
}
private fun handleOutgoingToshiPayment(paymentTask: ToshiPaymentTask, storedSofaMessage: SofaMessage) {
transactionSigner.signAndSendTransaction(paymentTask.unsignedTransaction)
.map { SentToshiPaymentTask(paymentTask, it) }
.doOnSuccess { broadcastSuccessfulPayment(paymentTask) }
.doOnError { broadcastUnsuccessfulPayment(paymentTask, it) }
.observeOn(Schedulers.io())
.subscribe(
{ handleOutgoingToshiPaymentSuccess(it, storedSofaMessage) },
{ handleOutgoingPaymentError(it, paymentTask.user, storedSofaMessage) }
)
}
private fun handleOutgoingToshiPaymentSuccess(paymentTask: SentToshiPaymentTask, storedSofaMessage: SofaMessage) {
val sentTransaction = paymentTask.sentTransaction
val payment = paymentTask.payment
val receiver = paymentTask.user
val txHash = sentTransaction.txHash
payment.txHash = txHash
// Update the stored message with the transactions details
val updatedMessage = generateMessageFromPayment(payment, getLocalUser())
storedSofaMessage.payload = updatedMessage.payloadWithHeaders
updateMessageState(receiver, storedSofaMessage, SendState.STATE_SENT)
storeUnconfirmedTransaction(txHash, storedSofaMessage)
chatManager.sendMessage(Recipient(receiver), storedSofaMessage)
}
private fun handleOutgoingPaymentError(error: Throwable, receiver: User, storedSofaMessage: SofaMessage) {
updateMessageState(receiver, storedSofaMessage, SendState.STATE_FAILED)
paymentErrorTask.handleOutgoingPaymentError(error, receiver, storedSofaMessage)
}
private fun resendPayment(paymentTask: ResendToshiPaymentTask) {
val sofaMessageId = paymentTask.sofaMessage.privateKey
chatManager.getSofaMessageById(sofaMessageId)
.map { paymentTask.copy(sofaMessage = it) }
.subscribe(
{ handleOutgoingResendPayment(it) },
{ LogUtil.exception("Error while resending payment $it") }
)
}
private fun handleOutgoingResendPayment(paymentTask: ResendToshiPaymentTask) {
val sofaMessage = paymentTask.sofaMessage
updateMessageState(paymentTask.user, sofaMessage, SendState.STATE_SENDING)
handleOutgoingToshiPayment(paymentTask, sofaMessage)
}
private fun updateMessageState(user: User, sofaMessage: SofaMessage, @SendState.State sendState: Int) {
sofaMessage.sendState = sendState
updateMessage(user, sofaMessage)
}
private fun updateMessage(user: User, message: SofaMessage) {
val recipient = Recipient(user)
chatManager.updateMessage(recipient, message)
}
private fun sendExternalPayment(paymentTask: ExternalPaymentTask) {
getUpdatedPayment(paymentTask)
.flatMap { transactionSigner.signAndSendTransaction(paymentTask.unsignedTransaction) }
.doOnError { broadcastUnsuccessfulPayment(paymentTask, it) }
.subscribe(
{ broadcastSuccessfulPayment(paymentTask) },
{ handleOutgoingExternalPaymentError(it, paymentTask) }
)
}
private fun sendERC20Payment(paymentTask: ERC20TokenPaymentTask) {
getUpdatedPayment(paymentTask)
.flatMap { transactionSigner.signAndSendTransaction(paymentTask.unsignedTransaction) }
.doOnError { broadcastUnsuccessfulPayment(paymentTask, it) }
.subscribe(
{ broadcastSuccessfulPayment(paymentTask) },
{ handleOutgoingExternalPaymentError(it, paymentTask) }
)
}
private fun getUpdatedPayment(paymentTask: PaymentTask): Single<PaymentTask> {
val receiver = getReceiverFromTask(paymentTask)
val sender = getSenderFromTask(paymentTask)
return balanceManager
.generateLocalPrice(paymentTask.payment)
.doOnSuccess { storePayment(receiver, it, sender) }
.map { paymentTask }
.subscribeOn(Schedulers.io())
}
private fun handleOutgoingExternalPaymentError(error: Throwable, paymentTask: PaymentTask) {
paymentErrorTask.handleOutgoingExternalPaymentError(error, paymentTask)
}
private fun storeUnconfirmedTransaction(txHash: String, message: SofaMessage) {
val pendingTransaction = PendingTransaction()
.setSofaMessage(message)
.setTxHash(txHash)
pendingTransactionStore.save(pendingTransaction)
}
private fun storePayment(receiver: User?, payment: Payment, sender: User?): SofaMessage {
val sofaMessage = generateMessageFromPayment(payment, sender)
storeMessage(receiver, sofaMessage)
return sofaMessage
}
private fun generateMessageFromPayment(payment: Payment, sender: User?): SofaMessage {
val messageBody = SofaAdapters.get().toJson(payment)
return SofaMessage().makeNewFromTransaction(payment.txHash, sender, messageBody)
}
private fun storeMessage(receiver: User?, message: SofaMessage) {
// receiver will be null if this is an external payment
receiver?.let {
message.sendState = SendState.STATE_SENDING
chatManager.saveTransaction(receiver, message)
}
}
private fun getSenderFromTask(task: PaymentTask): User? {
if (task is ToshiPaymentTask) return getLocalUser()
if (task is ExternalPaymentTask) return getLocalUser()
if (task is ERC20TokenPaymentTask) return getLocalUser()
throw IllegalStateException("Unknown payment task action.")
}
private fun getReceiverFromTask(task: PaymentTask): User? {
if (task is ToshiPaymentTask) return task.user
if (task is ExternalPaymentTask) return null
if (task is ERC20TokenPaymentTask) return null
throw IllegalStateException("Unknown payment task action.")
}
fun addOutgoingToshiPaymentTask(paymentTask: ToshiPaymentTask) {
addOutgoingPaymentTask(paymentTask)
}
fun addOutgoingResendPaymentTask(paymentTask: ResendToshiPaymentTask) {
addOutgoingPaymentTask(paymentTask)
}
fun addOutgoingExternalPaymentTask(paymentTask: ExternalPaymentTask) {
addOutgoingPaymentTask(paymentTask)
}
fun addOutgoingERC20PaymentTask(paymentTask: ERC20TokenPaymentTask) {
addOutgoingPaymentTask(paymentTask)
}
private fun broadcastSuccessfulPayment(paymentTask: PaymentTask) {
val successfulPayment = OutgoingPaymentResult(paymentTask)
outgoingPaymentResultSubject.onNext(successfulPayment)
}
private fun broadcastUnsuccessfulPayment(paymentTask: PaymentTask, throwable: Throwable) {
val unsuccessfulPayment = OutgoingPaymentResult(paymentTask, throwable)
outgoingPaymentResultSubject.onNext(unsuccessfulPayment)
}
private fun getLocalUser(): User? = userManager.getCurrentUser().toBlocking().value()
private fun clearSubscription() = outgoingPaymentSub?.unsubscribe()
private fun addOutgoingPaymentTask(paymentTask: PaymentTask) = newOutgoingPaymentQueue.onNext(paymentTask)
fun clearSubscriptions() = subscriptions.clear()
} | gpl-3.0 | 5e81a4e84ee022d1acea9c6df29f40f3 | 43.517375 | 118 | 0.705178 | 4.852273 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/fs/AbstractUsbFile.kt | 2 | 2420 | package me.jahnen.libaums.core.fs
import android.util.Log
import java.io.IOException
/**
* Created by magnusja on 3/1/17.
*/
abstract class AbstractUsbFile : UsbFile {
override val absolutePath: String
get() {
if (isRoot) {
return "/"
}
return parent?.let { parent ->
if (parent.isRoot) {
"/$name"
} else parent.absolutePath + UsbFile.separator + name
}.orEmpty() // should never happen
}
@Throws(IOException::class)
override fun search(path: String): UsbFile? {
var path = path
if (!isDirectory) {
throw UnsupportedOperationException("This is a file!")
}
Log.d(TAG, "search file: $path")
if (isRoot && path == UsbFile.separator) {
return this
}
if (isRoot && path.startsWith(UsbFile.separator)) {
path = path.substring(1)
}
if (path.endsWith(UsbFile.separator)) {
path = path.substring(0, path.length - 1)
}
val index = path.indexOf(UsbFile.separator)
if (index < 0) {
Log.d(TAG, "search entry: $path")
return searchThis(path)
} else {
val subPath = path.substring(index + 1)
val dirName = path.substring(0, index)
Log.d(TAG, "search recursively $subPath in $dirName")
val file = searchThis(dirName)
if (file != null && file.isDirectory) {
Log.d(TAG, "found directory $dirName")
return file.search(subPath)
}
}
Log.d(TAG, "not found $path")
return null
}
@Throws(IOException::class)
private fun searchThis(name: String): UsbFile? {
for (file in listFiles()) {
if (file.name == name)
return file
}
return null
}
override fun hashCode(): Int {
return absolutePath.hashCode()
}
override fun toString(): String {
return name
}
override fun equals(other: Any?): Boolean {
// TODO add getFileSystem and check if file system is the same
// TODO check reference
return other is UsbFile && absolutePath == other.absolutePath
}
companion object {
private val TAG = AbstractUsbFile::class.java.simpleName
}
}
| apache-2.0 | c2c0296ccbfd04163adc102f06c53c9c | 23.948454 | 70 | 0.536777 | 4.456722 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/db/GameDao.kt | 1 | 40299 | package com.boardgamegeek.db
import android.content.ContentProviderOperation
import android.content.ContentProviderOperation.Builder
import android.content.ContentResolver
import android.content.ContentValues
import android.graphics.Color
import android.net.Uri
import android.provider.BaseColumns
import android.text.format.DateUtils
import androidx.core.content.contentValuesOf
import androidx.core.database.getDoubleOrNull
import androidx.core.database.getIntOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.boardgamegeek.BggApplication
import com.boardgamegeek.entities.*
import com.boardgamegeek.extensions.*
import com.boardgamegeek.io.BggService
import com.boardgamegeek.provider.BggContract.*
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.provider.BggContract.Companion.PATH_ARTISTS
import com.boardgamegeek.provider.BggContract.Companion.PATH_CATEGORIES
import com.boardgamegeek.provider.BggContract.Companion.PATH_DESIGNERS
import com.boardgamegeek.provider.BggContract.Companion.PATH_EXPANSIONS
import com.boardgamegeek.provider.BggContract.Companion.PATH_MECHANICS
import com.boardgamegeek.provider.BggContract.Companion.PATH_PUBLISHERS
import com.boardgamegeek.provider.BggContract.Companion.POLL_TYPE_LANGUAGE_DEPENDENCE
import com.boardgamegeek.provider.BggContract.Companion.POLL_TYPE_SUGGESTED_PLAYER_AGE
import com.boardgamegeek.provider.BggDatabase.*
import com.boardgamegeek.util.DataUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class GameDao(private val context: BggApplication) {
private val resolver: ContentResolver = context.contentResolver
suspend fun load(gameId: Int): GameEntity? = withContext(Dispatchers.IO) {
if (gameId != INVALID_ID) {
val projection = arrayOf(
Games.Columns.GAME_ID,
Games.Columns.GAME_NAME,
Games.Columns.DESCRIPTION,
Games.Columns.SUBTYPE,
Games.Columns.THUMBNAIL_URL,
Games.Columns.IMAGE_URL, // 5
Games.Columns.YEAR_PUBLISHED,
Games.Columns.MIN_PLAYERS,
Games.Columns.MAX_PLAYERS,
Games.Columns.PLAYING_TIME,
Games.Columns.MIN_PLAYING_TIME, // 10
Games.Columns.MAX_PLAYING_TIME,
Games.Columns.MINIMUM_AGE,
Games.Columns.HERO_IMAGE_URL,
Games.Columns.STATS_AVERAGE,
Games.Columns.STATS_USERS_RATED, // 15
Games.Columns.STATS_NUMBER_COMMENTS,
Games.Columns.UPDATED,
Games.Columns.UPDATED_PLAYS,
Games.Columns.GAME_RANK,
Games.Columns.STATS_STANDARD_DEVIATION, // 20
Games.Columns.STATS_BAYES_AVERAGE,
Games.Columns.STATS_AVERAGE_WEIGHT,
Games.Columns.STATS_NUMBER_WEIGHTS,
Games.Columns.STATS_NUMBER_OWNED,
Games.Columns.STATS_NUMBER_TRADING, // 25
Games.Columns.STATS_NUMBER_WANTING,
Games.Columns.STATS_NUMBER_WISHING,
Games.Columns.CUSTOM_PLAYER_SORT,
Games.Columns.STARRED,
Games.Columns.POLLS_COUNT, // 30
Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL,
Games.Columns.ICON_COLOR,
Games.Columns.DARK_COLOR,
Games.Columns.WINS_COLOR,
Games.Columns.WINNABLE_PLAYS_COLOR, // 35
Games.Columns.ALL_PLAYS_COLOR,
Games.Columns.GAME_SORT_NAME,
)
context.contentResolver.load(Games.buildGameUri(gameId), projection)?.use {
if (it.moveToFirst()) {
GameEntity(
id = it.getInt(0),
name = it.getStringOrNull(1).orEmpty(),
description = it.getStringOrNull(2).orEmpty(),
subtype = it.getStringOrNull(3).orEmpty(),
thumbnailUrl = it.getStringOrNull(4).orEmpty(),
imageUrl = it.getStringOrNull(5).orEmpty(),
yearPublished = it.getIntOrNull(6) ?: GameEntity.YEAR_UNKNOWN,
minPlayers = it.getIntOrNull(7) ?: 0,
maxPlayers = it.getIntOrNull(8) ?: 0,
playingTime = it.getIntOrNull(9) ?: 0,
minPlayingTime = it.getIntOrNull(10) ?: 0,
maxPlayingTime = it.getIntOrNull(11) ?: 0,
minimumAge = it.getIntOrNull(12) ?: 0,
heroImageUrl = it.getStringOrNull(13).orEmpty(),
rating = it.getDoubleOrNull(14) ?: 0.0,
numberOfRatings = it.getIntOrNull(15) ?: 0,
numberOfComments = it.getIntOrNull(16) ?: 0,
overallRank = it.getIntOrNull(19) ?: GameRankEntity.RANK_UNKNOWN,
standardDeviation = it.getDoubleOrNull(20) ?: 0.0,
bayesAverage = it.getDoubleOrNull(21) ?: 0.0,
averageWeight = it.getDoubleOrNull(22) ?: 0.0,
numberOfUsersWeighting = it.getIntOrNull(23) ?: 0,
numberOfUsersOwned = it.getIntOrNull(24) ?: 0,
numberOfUsersTrading = it.getIntOrNull(25) ?: 0,
numberOfUsersWanting = it.getIntOrNull(26) ?: 0,
numberOfUsersWishListing = it.getIntOrNull(27) ?: 0,
updated = it.getLongOrNull(17) ?: 0L,
updatedPlays = it.getLongOrNull(18) ?: 0L,
customPlayerSort = it.getBoolean(28),
isFavorite = it.getBoolean(29),
pollVoteTotal = it.getIntOrNull(30) ?: 0,
suggestedPlayerCountPollVoteTotal = it.getIntOrNull(31) ?: 0,
iconColor = it.getIntOrNull(32) ?: Color.TRANSPARENT,
darkColor = it.getIntOrNull(33) ?: Color.TRANSPARENT,
winsColor = it.getIntOrNull(34) ?: Color.TRANSPARENT,
winnablePlaysColor = it.getIntOrNull(35) ?: Color.TRANSPARENT,
allPlaysColor = it.getIntOrNull(36) ?: Color.TRANSPARENT,
sortName = it.getStringOrNull(37).orEmpty(),
)
} else null
}
} else null
}
suspend fun loadRanks(gameId: Int): List<GameRankEntity> = withContext(Dispatchers.IO) {
val ranks = arrayListOf<GameRankEntity>()
if (gameId != INVALID_ID) {
val uri = Games.buildRanksUri(gameId)
context.contentResolver.load(
uri,
arrayOf(
GameRanks.Columns.GAME_RANK_ID,
GameRanks.Columns.GAME_RANK_TYPE,
GameRanks.Columns.GAME_RANK_NAME,
GameRanks.Columns.GAME_RANK_FRIENDLY_NAME,
GameRanks.Columns.GAME_RANK_VALUE,
GameRanks.Columns.GAME_RANK_BAYES_AVERAGE,
)
)?.use {
if (it.moveToFirst()) {
do {
ranks += GameRankEntity(
id = it.getIntOrNull(0) ?: INVALID_ID,
type = it.getStringOrNull(1).orEmpty(),
name = it.getStringOrNull(2).orEmpty(),
friendlyName = it.getStringOrNull(3).orEmpty(),
value = it.getIntOrNull(4) ?: GameRankEntity.RANK_UNKNOWN,
bayesAverage = it.getDoubleOrNull(5) ?: 0.0,
)
} while (it.moveToNext())
}
}
}
ranks
}
suspend fun loadPoll(gameId: Int, pollType: String): GamePollEntity? = withContext(Dispatchers.IO) {
if (gameId != INVALID_ID && pollType in arrayOf(
POLL_TYPE_SUGGESTED_PLAYER_AGE,
POLL_TYPE_LANGUAGE_DEPENDENCE,
)
) {
val uri = Games.buildPollResultsResultUri(gameId, pollType)
val results = arrayListOf<GamePollResultEntity>()
val projection = arrayOf(
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_LEVEL,
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VALUE,
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VOTES,
)
context.contentResolver.load(uri, projection)?.use {
if (it.moveToFirst()) {
do {
results += GamePollResultEntity(
level = it.getIntOrNull(0) ?: 0,
value = it.getStringOrNull(1).orEmpty(),
numberOfVotes = it.getIntOrNull(2) ?: 0,
)
} while (it.moveToNext())
}
}
GamePollEntity(results)
} else null
}
suspend fun loadPlayerPoll(gameId: Int): GamePlayerPollEntity? = withContext(Dispatchers.IO) {
if (gameId != INVALID_ID) {
val uri = Games.buildSuggestedPlayerCountPollResultsUri(gameId)
val results = arrayListOf<GamePlayerPollResultsEntity>()
val projection = arrayOf(
Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL,
GameSuggestedPlayerCountPollPollResults.Columns.PLAYER_COUNT,
GameSuggestedPlayerCountPollPollResults.Columns.BEST_VOTE_COUNT,
GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDED_VOTE_COUNT,
GameSuggestedPlayerCountPollPollResults.Columns.NOT_RECOMMENDED_VOTE_COUNT,
GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION, // TODO why is this not loading into the entity
)
context.contentResolver.load(uri, projection)?.use {
if (it.moveToFirst()) {
do {
results += GamePlayerPollResultsEntity(
totalVotes = it.getIntOrNull(0) ?: 0,
playerCount = it.getStringOrNull(1).orEmpty(),
bestVoteCount = it.getIntOrNull(2) ?: 0,
recommendedVoteCount = it.getIntOrNull(3) ?: 0,
notRecommendedVoteCount = it.getIntOrNull(4) ?: 0,
)
} while (it.moveToNext())
}
}
GamePlayerPollEntity(results)
} else null
}
suspend fun loadDesigners(gameId: Int): List<GameDetailEntity> = withContext(Dispatchers.IO) {
val results = arrayListOf<GameDetailEntity>()
if (gameId != INVALID_ID) {
context.contentResolver.load(
Games.buildDesignersUri(gameId),
arrayOf(
Designers.Columns.DESIGNER_ID,
Designers.Columns.DESIGNER_NAME,
)
)?.use {
if (it.moveToFirst()) {
do {
results += GameDetailEntity(
it.getInt(0),
it.getString(1),
)
} while (it.moveToNext())
}
}
}
results
}
suspend fun loadArtists(gameId: Int): List<GameDetailEntity> = withContext(Dispatchers.IO) {
val results = arrayListOf<GameDetailEntity>()
if (gameId != INVALID_ID) {
context.contentResolver.load(
Games.buildArtistsUri(gameId),
arrayOf(
Artists.Columns.ARTIST_ID,
Artists.Columns.ARTIST_NAME,
)
)?.use {
if (it.moveToFirst()) {
do {
results += GameDetailEntity(
it.getInt(0),
it.getString(1),
)
} while (it.moveToNext())
}
}
}
results
}
suspend fun loadPublishers(gameId: Int): List<GameDetailEntity> = withContext(Dispatchers.IO) {
val results = arrayListOf<GameDetailEntity>()
if (gameId != INVALID_ID) {
context.contentResolver.load(
Games.buildPublishersUri(gameId),
arrayOf(
Publishers.Columns.PUBLISHER_ID,
Publishers.Columns.PUBLISHER_NAME,
)
)?.use {
if (it.moveToFirst()) {
do {
results += GameDetailEntity(
it.getInt(0),
it.getString(1),
)
} while (it.moveToNext())
}
}
}
results
}
suspend fun loadCategories(gameId: Int): List<GameDetailEntity> = withContext(Dispatchers.IO) {
val results = arrayListOf<GameDetailEntity>()
if (gameId != INVALID_ID) {
context.contentResolver.load(
Games.buildCategoriesUri(gameId),
arrayOf(
Categories.Columns.CATEGORY_ID,
Categories.Columns.CATEGORY_NAME,
),
)?.use {
if (it.moveToFirst()) {
do {
results += GameDetailEntity(
it.getInt(0),
it.getString(1),
)
} while (it.moveToNext())
}
}
}
results
}
suspend fun loadMechanics(gameId: Int): List<GameDetailEntity> = withContext(Dispatchers.IO) {
val results = arrayListOf<GameDetailEntity>()
if (gameId != INVALID_ID) {
context.contentResolver.load(
Games.buildMechanicsUri(gameId),
arrayOf(
Mechanics.Columns.MECHANIC_ID,
Mechanics.Columns.MECHANIC_NAME,
),
)?.use {
if (it.moveToFirst()) {
do {
results += GameDetailEntity(
it.getInt(0),
it.getString(1)
)
} while (it.moveToNext())
}
}
}
results
}
suspend fun loadExpansions(gameId: Int, inbound: Boolean = false): List<GameExpansionsEntity> =
withContext(Dispatchers.IO) {
val results = arrayListOf<GameExpansionsEntity>()
if (gameId != INVALID_ID) {
val briefResults = arrayListOf<GameExpansionsEntity>()
context.contentResolver.load(
Games.buildExpansionsUri(gameId),
arrayOf(
GamesExpansions.Columns.EXPANSION_ID,
GamesExpansions.Columns.EXPANSION_NAME,
),
selection = "${GamesExpansions.Columns.INBOUND}=?",
selectionArgs = arrayOf(if (inbound) "1" else "0")
)?.use {
if (it.moveToFirst()) {
do {
briefResults += GameExpansionsEntity(
it.getInt(0),
it.getString(1),
)
} while (it.moveToNext())
}
}
for (result in briefResults) {
context.contentResolver.load(
Collection.CONTENT_URI,
projection = arrayOf(
Collection.Columns.STATUS_OWN,
Collection.Columns.STATUS_PREVIOUSLY_OWNED,
Collection.Columns.STATUS_PREORDERED,
Collection.Columns.STATUS_FOR_TRADE,
Collection.Columns.STATUS_WANT,
Collection.Columns.STATUS_WANT_TO_PLAY,
Collection.Columns.STATUS_WANT_TO_BUY,
Collection.Columns.STATUS_WISHLIST,
Collection.Columns.STATUS_WISHLIST_PRIORITY,
Games.Columns.NUM_PLAYS,
Collection.Columns.RATING,
Collection.Columns.COMMENT
),
selection = "collection.${Collection.Columns.GAME_ID}=?",
selectionArgs = arrayOf(result.id.toString())
)?.use {
if (it.moveToFirst()) {
do {
results += result.copy(
own = it.getBoolean(0),
previouslyOwned = it.getBoolean(1),
preOrdered = it.getBoolean(2),
forTrade = it.getBoolean(3),
wantInTrade = it.getBoolean(4),
wantToPlay = it.getBoolean(5),
wantToBuy = it.getBoolean(6),
wishList = it.getBoolean(7),
wishListPriority = it.getIntOrNull(8) ?: GameExpansionsEntity.WISHLIST_PRIORITY_UNKNOWN,
numberOfPlays = it.getIntOrNull(9) ?: 0,
rating = it.getDoubleOrNull(10) ?: 0.0,
comment = it.getStringOrNull(11).orEmpty(),
)
} while (it.moveToNext())
} else {
results += result
}
}
}
}
results
}
suspend fun loadPlayColors(gameId: Int): List<String> = withContext(Dispatchers.IO) {
context.contentResolver.queryStrings(Games.buildColorsUri(gameId), GameColors.Columns.COLOR).filterNot { it.isBlank() }
}
suspend fun loadPlayColors(): List<Pair<Int, String>> = withContext(Dispatchers.IO) {
val colors = mutableListOf<Pair<Int, String>>()
context.contentResolver.load(
GameColors.CONTENT_URI,
arrayOf(GameColors.Columns.GAME_ID, GameColors.Columns.COLOR),
)?.use {
if (it.moveToFirst()) {
do {
colors += (it.getIntOrNull(0) ?: INVALID_ID) to it.getStringOrNull(1).orEmpty()
} while (it.moveToNext())
}
}
colors
}
suspend fun loadPlayInfo(
includeIncompletePlays: Boolean,
includeExpansions: Boolean,
includeAccessories: Boolean
): List<GameForPlayStatEntity> = withContext(Dispatchers.IO) {
val results = mutableListOf<GameForPlayStatEntity>()
context.contentResolver.load(
Games.CONTENT_PLAYS_URI,
arrayOf(
Plays.Columns.SUM_QUANTITY,
Plays.Columns.ITEM_NAME,
Games.Columns.GAME_RANK,
Games.Columns.GAME_ID
),
selection = arrayListOf<String>().apply {
add(Plays.Columns.DELETE_TIMESTAMP.whereZeroOrNull())
if (!includeIncompletePlays) {
add(Plays.Columns.INCOMPLETE.whereZeroOrNull())
}
if (!includeExpansions && !includeAccessories) {
add(Games.Columns.SUBTYPE.whereEqualsOrNull())
} else if (!includeExpansions || !includeAccessories) {
add(Games.Columns.SUBTYPE.whereNotEqualsOrNull())
}
}.joinTo(" AND ").toString(),
selectionArgs = arrayListOf<String>().apply {
if (!includeExpansions && !includeAccessories) {
add(BggService.THING_SUBTYPE_BOARDGAME)
} else if (!includeExpansions) {
add(BggService.THING_SUBTYPE_BOARDGAME_EXPANSION)
} else if (!includeAccessories) {
add(BggService.THING_SUBTYPE_BOARDGAME_ACCESSORY)
}
}.toTypedArray(),
sortOrder = "${Plays.Columns.SUM_QUANTITY} DESC, ${Games.Columns.GAME_SORT_NAME} ASC"
)?.use {
if (it.moveToFirst()) {
do {
results += GameForPlayStatEntity(
it.getIntOrNull(3) ?: INVALID_ID,
it.getStringOrNull(1).orEmpty(),
it.getIntOrNull(0) ?: 0,
it.getIntOrNull(2) ?: 0,
)
} while (it.moveToNext())
}
}
results
}
suspend fun delete(gameId: Int): Int = withContext(Dispatchers.IO) {
if (gameId == INVALID_ID) 0
else resolver.delete(Games.buildGameUri(gameId), null, null)
}
suspend fun delete(): Int = withContext(Dispatchers.IO) {
resolver.delete(Games.CONTENT_URI, null, null)
}
suspend fun insertColor(gameId: Int, color: String) = withContext(Dispatchers.IO) {
resolver.insert(Games.buildColorsUri(gameId), contentValuesOf(GameColors.Columns.COLOR to color))
}
suspend fun deleteColor(gameId: Int, color: String): Int = withContext(Dispatchers.IO) {
resolver.delete(Games.buildColorsUri(gameId, color), null, null)
}
suspend fun insertColors(gameId: Int, colors: List<String>): Int = withContext(Dispatchers.IO) {
if (colors.isEmpty()) 0
else {
val values = colors.map { contentValuesOf(GameColors.Columns.COLOR to it) }
resolver.bulkInsert(Games.buildColorsUri(gameId), values.toTypedArray())
}
}
suspend fun update(gameId: Int, values: ContentValues) = withContext(Dispatchers.IO) {
resolver.update(Games.buildGameUri(gameId), values, null, null)
}
suspend fun save(game: GameEntity, updateTime: Long) = withContext(Dispatchers.IO) {
if (game.name.isBlank()) {
Timber.w("Missing name from game ID=%s", game.id)
} else {
Timber.i("Saving game %s (%s)", game.name, game.id)
val batch = arrayListOf<ContentProviderOperation>()
val cpoBuilder: Builder
val values = toValues(game, updateTime)
val internalId = resolver.queryLong(Games.buildGameUri(game.id), BaseColumns._ID, INVALID_ID.toLong())
cpoBuilder = if (internalId != INVALID_ID.toLong()) {
values.remove(Games.Columns.GAME_ID)
if (shouldClearHeroImageUrl(game)) {
values.put(Games.Columns.HERO_IMAGE_URL, "")
}
ContentProviderOperation.newUpdate(Games.buildGameUri(game.id))
} else {
ContentProviderOperation.newInsert(Games.CONTENT_URI)
}
batch += cpoBuilder.withValues(values).withYieldAllowed(true).build()
batch += createRanksBatch(game)
batch += createPollsBatch(game)
batch += createPlayerPollBatch(game.id, game.playerPoll)
batch += createExpansionsBatch(game.id, game.expansions)
saveReference(game.designers, Designers.CONTENT_URI, Designers.Columns.DESIGNER_ID, Designers.Columns.DESIGNER_NAME)
saveReference(game.artists, Artists.CONTENT_URI, Artists.Columns.ARTIST_ID, Artists.Columns.ARTIST_NAME)
saveReference(game.publishers, Publishers.CONTENT_URI, Publishers.Columns.PUBLISHER_ID, Publishers.Columns.PUBLISHER_NAME)
saveReference(game.categories, Categories.CONTENT_URI, Categories.Columns.CATEGORY_ID, Categories.Columns.CATEGORY_NAME)
saveReference(game.mechanics, Mechanics.CONTENT_URI, Mechanics.Columns.MECHANIC_ID, Mechanics.Columns.MECHANIC_NAME)
batch += createAssociationBatch(game.id, game.designers, PATH_DESIGNERS, GamesDesigners.DESIGNER_ID)
batch += createAssociationBatch(game.id, game.artists, PATH_ARTISTS, GamesArtists.ARTIST_ID)
batch += createAssociationBatch(game.id, game.publishers, PATH_PUBLISHERS, GamesPublishers.PUBLISHER_ID)
batch += createAssociationBatch(game.id, game.categories, PATH_CATEGORIES, GamesCategories.CATEGORY_ID)
batch += createAssociationBatch(game.id, game.mechanics, PATH_MECHANICS, GamesMechanics.MECHANIC_ID)
resolver.applyBatch(batch, "Game ${game.id}")
if (internalId == INVALID_ID.toLong()) {
Timber.i(
"Inserted game ID '%s' at %s",
game.id,
DateUtils.formatDateTime(context, updateTime, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME)
)
} else {
Timber.i(
"Updated game ID '%s' (%s) at %s",
game.id,
internalId,
DateUtils.formatDateTime(context, updateTime, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME)
)
}
}
}
suspend fun upsert(gameId: Int, values: ContentValues): Int = withContext(Dispatchers.IO) {
val resolver = context.contentResolver
val uri = Games.buildGameUri(gameId)
if (resolver.rowExists(uri)) {
val count = resolver.update(uri, values, null, null)
Timber.d("Updated %,d game rows at %s", count, uri)
count
} else {
values.put(Games.Columns.GAME_ID, gameId)
val insertedUri = resolver.insert(Artists.CONTENT_URI, values)
Timber.d("Inserted game at %s", insertedUri)
1
}
}
suspend fun resetPlaySync(): Int = withContext(Dispatchers.IO) {
context.contentResolver.update(Games.CONTENT_URI, contentValuesOf(Games.Columns.UPDATED_PLAYS to 0), null, null)
}
private fun toValues(game: GameEntity, updateTime: Long): ContentValues {
val values = contentValuesOf(
Games.Columns.UPDATED to updateTime,
Games.Columns.UPDATED_LIST to updateTime,
Games.Columns.GAME_ID to game.id,
Games.Columns.GAME_NAME to game.name,
Games.Columns.GAME_SORT_NAME to game.sortName,
Games.Columns.THUMBNAIL_URL to game.thumbnailUrl,
Games.Columns.IMAGE_URL to game.imageUrl,
Games.Columns.DESCRIPTION to game.description,
Games.Columns.SUBTYPE to game.subtype,
Games.Columns.YEAR_PUBLISHED to game.yearPublished,
Games.Columns.MIN_PLAYERS to game.minPlayers,
Games.Columns.MAX_PLAYERS to game.maxPlayers,
Games.Columns.PLAYING_TIME to game.playingTime,
Games.Columns.MIN_PLAYING_TIME to game.minPlayingTime,
Games.Columns.MAX_PLAYING_TIME to game.maxPlayingTime,
Games.Columns.MINIMUM_AGE to game.minimumAge,
Games.Columns.GAME_RANK to game.overallRank,
)
val statsValues = if (game.hasStatistics) {
contentValuesOf(
Games.Columns.STATS_AVERAGE to game.rating,
Games.Columns.STATS_BAYES_AVERAGE to game.bayesAverage,
Games.Columns.STATS_STANDARD_DEVIATION to game.standardDeviation,
Games.Columns.STATS_MEDIAN to game.median,
Games.Columns.STATS_USERS_RATED to game.numberOfRatings,
Games.Columns.STATS_NUMBER_OWNED to game.numberOfUsersOwned,
Games.Columns.STATS_NUMBER_TRADING to game.numberOfUsersTrading,
Games.Columns.STATS_NUMBER_WANTING to game.numberOfUsersWanting,
Games.Columns.STATS_NUMBER_WISHING to game.numberOfUsersWishListing,
Games.Columns.STATS_NUMBER_COMMENTS to game.numberOfComments,
Games.Columns.STATS_NUMBER_WEIGHTS to game.numberOfUsersWeighting,
Games.Columns.STATS_AVERAGE_WEIGHT to game.averageWeight,
)
} else contentValuesOf()
val pollValues = game.playerPoll?.let {
contentValuesOf(
Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL to it.totalVotes,
Games.Columns.PLAYER_COUNTS_BEST to it.bestCounts.forDatabase(GamePlayerPollEntity.separator),
Games.Columns.PLAYER_COUNTS_RECOMMENDED to it.recommendedAndBestCounts.forDatabase(GamePlayerPollEntity.separator),
Games.Columns.PLAYER_COUNTS_NOT_RECOMMENDED to it.notRecommendedCounts.forDatabase(GamePlayerPollEntity.separator),
)
} ?: contentValuesOf()
values.putAll(statsValues)
values.putAll(pollValues)
return values
}
private suspend fun shouldClearHeroImageUrl(game: GameEntity): Boolean = withContext(Dispatchers.IO) {
val cursor = resolver.query(Games.buildGameUri(game.id), arrayOf(Games.Columns.IMAGE_URL, Games.Columns.THUMBNAIL_URL), null, null, null)
cursor?.use { c ->
if (c.moveToFirst()) {
val imageUrl = c.getStringOrNull(0).orEmpty()
val thumbnailUrl = c.getStringOrNull(1).orEmpty()
imageUrl != game.imageUrl || thumbnailUrl != game.thumbnailUrl
} else false
} ?: false
}
private suspend fun createPollsBatch(game: GameEntity): ArrayList<ContentProviderOperation> = withContext(Dispatchers.IO) {
val batch = arrayListOf<ContentProviderOperation>()
val existingPollNames = resolver.queryStrings(Games.buildPollsUri(game.id), GamePolls.Columns.POLL_NAME).filterNot { it.isBlank() }.toMutableList()
for (poll in game.polls) {
val values = contentValuesOf(
GamePolls.Columns.POLL_TITLE to poll.title,
GamePolls.Columns.POLL_TOTAL_VOTES to poll.totalVotes,
)
val existingResultKeys = mutableListOf<String>()
batch += if (existingPollNames.remove(poll.name)) {
existingResultKeys += resolver.queryStrings(
Games.buildPollResultsUri(game.id, poll.name),
GamePollResults.Columns.POLL_RESULTS_PLAYERS
).filterNot { it.isBlank() }
ContentProviderOperation.newUpdate(Games.buildPollsUri(game.id, poll.name))
} else {
values.put(GamePolls.Columns.POLL_NAME, poll.name)
ContentProviderOperation.newInsert(Games.buildPollsUri(game.id))
}.withValues(values).build()
for ((resultsIndex, results) in poll.results.withIndex()) {
val resultsValues = contentValuesOf(GamePollResults.Columns.POLL_RESULTS_SORT_INDEX to resultsIndex + 1)
val existingResultsResultKeys = mutableListOf<String>()
batch += if (existingResultKeys.remove(results.key)) {
existingResultsResultKeys += resolver.queryStrings(
Games.buildPollResultsResultUri(game.id, poll.name, results.key),
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_KEY
).filterNot { it.isBlank() }
ContentProviderOperation.newUpdate(Games.buildPollResultsUri(game.id, poll.name, results.key))
} else {
resultsValues.put(GamePollResults.Columns.POLL_RESULTS_PLAYERS, results.key)
ContentProviderOperation.newInsert(Games.buildPollResultsUri(game.id, poll.name))
}.withValues(resultsValues).build()
for ((resultSortIndex, result) in results.result.withIndex()) {
val resultsResultValues = contentValuesOf(
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VALUE to result.value,
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VOTES to result.numberOfVotes,
GamePollResultsResult.Columns.POLL_RESULTS_RESULT_SORT_INDEX to resultSortIndex + 1,
)
if (result.level > 0) resultsResultValues.put(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_LEVEL, result.level)
val key = DataUtils.generatePollResultsKey(result.level, result.value)
batch += if (existingResultsResultKeys.remove(key)) {
ContentProviderOperation.newUpdate(Games.buildPollResultsResultUri(game.id, poll.name, results.key, key))
} else {
ContentProviderOperation.newInsert(Games.buildPollResultsResultUri(game.id, poll.name, results.key))
}.withValues(resultsResultValues).build()
}
existingResultsResultKeys.mapTo(batch) {
ContentProviderOperation.newDelete(Games.buildPollResultsResultUri(game.id, poll.name, results.key, it)).build()
}
}
existingResultKeys.mapTo(batch) { ContentProviderOperation.newDelete(Games.buildPollResultsUri(game.id, poll.name, it)).build() }
}
existingPollNames.mapTo(batch) { ContentProviderOperation.newDelete(Games.buildPollsUri(game.id, it)).build() }
}
private suspend fun createPlayerPollBatch(gameId: Int, poll: GamePlayerPollEntity?): ArrayList<ContentProviderOperation> =
withContext(Dispatchers.IO) {
val batch = arrayListOf<ContentProviderOperation>()
if (poll == null)
batch
else {
val existingResults = resolver.queryStrings(
Games.buildSuggestedPlayerCountPollResultsUri(gameId),
GameSuggestedPlayerCountPollPollResults.Columns.PLAYER_COUNT
).filterNot { it.isBlank() }.toMutableList()
for ((sortIndex, results) in poll.results.withIndex()) {
val values = contentValuesOf(
GameSuggestedPlayerCountPollPollResults.Columns.SORT_INDEX to sortIndex + 1,
GameSuggestedPlayerCountPollPollResults.Columns.BEST_VOTE_COUNT to results.bestVoteCount,
GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDED_VOTE_COUNT to results.recommendedVoteCount,
GameSuggestedPlayerCountPollPollResults.Columns.NOT_RECOMMENDED_VOTE_COUNT to results.notRecommendedVoteCount,
GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION to results.calculatedRecommendation,
)
batch += if (existingResults.remove(results.playerCount)) {
val uri = Games.buildSuggestedPlayerCountPollResultsUri(gameId, results.playerCount)
ContentProviderOperation.newUpdate(uri).withValues(values).build()
} else {
values.put(GameSuggestedPlayerCountPollPollResults.Columns.PLAYER_COUNT, results.playerCount)
val uri = Games.buildSuggestedPlayerCountPollResultsUri(gameId)
ContentProviderOperation.newInsert(uri).withValues(values).build()
}
}
existingResults.mapTo(batch) { ContentProviderOperation.newDelete(Games.buildSuggestedPlayerCountPollResultsUri(gameId, it)).build() }
}
}
private suspend fun createRanksBatch(game: GameEntity): ArrayList<ContentProviderOperation> = withContext(Dispatchers.IO) {
val batch = arrayListOf<ContentProviderOperation>()
val existingRankIds = resolver.queryInts(
GameRanks.CONTENT_URI,
GameRanks.Columns.GAME_RANK_ID,
"${GameRanks.Columns.GAME_RANK_ID}=?",
arrayOf(game.id.toString())
).toMutableList()
for ((id, type, name, friendlyName, value, bayesAverage) in game.ranks) {
val values = contentValuesOf(
GameRanks.Columns.GAME_RANK_TYPE to type,
GameRanks.Columns.GAME_RANK_NAME to name,
GameRanks.Columns.GAME_RANK_FRIENDLY_NAME to friendlyName,
GameRanks.Columns.GAME_RANK_VALUE to value,
GameRanks.Columns.GAME_RANK_BAYES_AVERAGE to bayesAverage,
)
batch += if (existingRankIds.remove(id)) {
ContentProviderOperation.newUpdate(Games.buildRanksUri(game.id, id)).withValues(values).build()
} else {
values.put(GameRanks.Columns.GAME_RANK_ID, id)
ContentProviderOperation.newInsert(Games.buildRanksUri(game.id)).withValues(values).build()
}
}
existingRankIds.mapTo(batch) { ContentProviderOperation.newDelete(GameRanks.buildGameRankUri(it)).build() }
}
private suspend fun createExpansionsBatch(
gameId: Int,
newLinks: List<Triple<Int, String, Boolean>>
): ArrayList<ContentProviderOperation> = withContext(Dispatchers.IO) {
val batch = arrayListOf<ContentProviderOperation>()
val pathUri = Games.buildPathUri(gameId, PATH_EXPANSIONS)
val existingIds = resolver.queryInts(pathUri, GamesExpansions.Columns.EXPANSION_ID).toMutableList()
for ((id, name, inbound) in newLinks) {
if (!existingIds.remove(id)) {
// insert association row
batch.add(
ContentProviderOperation.newInsert(pathUri).withValues(
contentValuesOf(
GamesExpansions.Columns.EXPANSION_ID to id,
GamesExpansions.Columns.EXPANSION_NAME to name,
GamesExpansions.Columns.INBOUND to inbound,
)
).build()
)
}
}
// remove unused associations
existingIds.mapTo(batch) { ContentProviderOperation.newDelete(Games.buildPathUri(gameId, PATH_EXPANSIONS, it)).build() }
}
/**
* Upsert each ID/name pair.
*/
private fun saveReference(newLinks: List<Pair<Int, String>>, baseUri: Uri, idColumn: String, nameColumn: String) {
val batch = arrayListOf<ContentProviderOperation>()
for ((id, name) in newLinks) {
val uri = baseUri.buildUpon().appendPath(id.toString()).build()
batch += if (resolver.rowExists(uri)) {
ContentProviderOperation.newUpdate(uri).withValue(nameColumn, name).build()
} else {
ContentProviderOperation.newInsert(baseUri).withValues(
contentValuesOf(
idColumn to id,
nameColumn to name,
)
).build()
}
}
resolver.applyBatch(batch, "Saving ${baseUri.lastPathSegment}")
}
private fun createAssociationBatch(
gameId: Int,
newLinks: List<Pair<Int, String>>,
uriPath: String,
idColumn: String
): ArrayList<ContentProviderOperation> {
val batch = arrayListOf<ContentProviderOperation>()
val associationUri = Games.buildPathUri(gameId, uriPath)
val existingIds = resolver.queryInts(associationUri, idColumn).toMutableList()
for ((id, _) in newLinks) {
if (!existingIds.remove(id)) {
// insert association row
batch += ContentProviderOperation.newInsert(associationUri).withValue(idColumn, id).build()
}
}
// remove unused associations
return existingIds.mapTo(batch) { ContentProviderOperation.newDelete(Games.buildPathUri(gameId, uriPath, it)).build() }
}
}
| gpl-3.0 | 7a814a316107813341df3dccc59c1717 | 48.145122 | 155 | 0.565696 | 5.103723 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/ScrollHideToolbarListener.kt | 1 | 3883 | package com.pr0gramm.app.ui
import android.view.View
import android.view.ViewPropertyAnimator
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
/**
*/
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ScrollHideToolbarListener(private val toolbar: View) {
private var toolbarMarginOffset: Int = 0
private var animation: ViewPropertyAnimator? = null
private var hidden: Boolean = false
init {
toolbar.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
val newHeight = bottom - top
val oldHeight = oldBottom - oldTop
if (oldHeight > 0 && newHeight != oldHeight && toolbarMarginOffset == oldHeight) {
toolbarMarginOffset = newHeight
applyToolbarPosition(false)
}
}
}
private fun applyToolbarPosition(animated: Boolean) {
// do not do anything if hidden
if (hidden) return
// stop any previous animation
animation?.cancel()
animation = null
val y = -toolbarMarginOffset
val targetVisible = toolbar.height > toolbarMarginOffset
if (animated) {
if (targetVisible) {
toolbar.isVisible = true
}
animation = toolbar.animate()
.translationY(y.toFloat())
.setDuration(250)
.withEndAction {
if (!targetVisible) {
toolbar.isVisible = false
}
}
.apply { start() }
} else {
toolbar.translationY = y.toFloat()
toolbar.isVisible = targetVisible
}
}
fun onScrolled(dy: Int) {
// do not do anything if hidden
if (hidden) return
val abHeight = toolbar.height
if (abHeight == 0)
return
toolbarMarginOffset += dy
if (toolbarMarginOffset >= abHeight) {
toolbarMarginOffset = abHeight
}
if (toolbarMarginOffset < 0)
toolbarMarginOffset = 0
applyToolbarPosition(false)
}
fun onScrollFinished(y: Int) {
// do not do anything if hidden
if (hidden) return
val abHeight = toolbar.height
if (abHeight == 0)
return
if (y < abHeight) {
reset()
} else {
toolbarMarginOffset = if (toolbarMarginOffset > abHeight / 2) abHeight else 0
applyToolbarPosition(true)
}
}
fun reset() {
hidden = false
if (toolbarMarginOffset != 0) {
toolbarMarginOffset = 0
applyToolbarPosition(true)
}
}
val toolbarHeight: Int
get() = toolbar.height
val visibleHeight: Int
get() = (toolbar.height + toolbar.translationY).toInt()
fun hide() {
if (toolbarMarginOffset != toolbar.height) {
toolbarMarginOffset = toolbar.height
applyToolbarPosition(true)
hidden = true
}
}
interface ToolbarActivity {
val scrollHideToolbarListener: ScrollHideToolbarListener
}
companion object {
/**
* This method estimates scrolling based on y value of the first element
* in this recycler view. If scrolling could not be estimated, an empty optional
* will be returned.
* @param recyclerView The recycler view to estimate scrolling of
*/
fun estimateRecyclerViewScrollY(recyclerView: RecyclerView): Int? {
var scrollY: Int? = null
val view = recyclerView.layoutManager?.findViewByPosition(0)
if (view != null) {
scrollY = -view.y.toInt()
}
return scrollY
}
}
}
| mit | 793d60ab3393107253f8093594553db8 | 26.539007 | 112 | 0.564254 | 5.115942 | false | false | false | false |
brayvqz/ejercicios_kotlin | triangulo_rectangulo/main.kt | 1 | 655 | package triangulo_rectangulo
import java.util.*
/**
* Created by brayan on 15/04/2017.
*/
fun main(args: Array<String>) {
var scan = Scanner(System.`in`)
println("Digite el valor de la base del triangulo : ")
var base = scan.nextDouble()
println("Digite el valor de la altura del triangulo : ")
var altura = scan.nextDouble()
println("El area del triangulo es : \n${area(base,altura)}")
println("El perimetro del triangulo es : \n${perimetro(base,altura)}")
}
fun area(b:Double=0.0,h:Double=0.0):Double = b + h + (Math.sqrt(Math.pow(b,2.0)+Math.pow(h,2.0)))
fun perimetro(b:Double=0.0,h:Double=0.0):Double = (b * h) / 2 | mit | 6a7ee6b83a20012965e5b1c1f0fd9647 | 28.818182 | 97 | 0.654962 | 2.763713 | false | false | false | false |
colriot/anko | dsl/static/src/common/RelativeLayoutLayoutParamsHelpers.kt | 1 | 3014 | /*
* Copyright 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
@file:JvmMultifileClass
@file:JvmName("RelativeLayoutLayoutParamsHelpersKt")
package org.jetbrains.anko
import android.view.View
import android.widget.RelativeLayout.*
inline fun LayoutParams.topOf(v: View): Unit = addRule(ABOVE, v.id)
inline fun LayoutParams.above(v: View): Unit = addRule(ABOVE, v.id)
inline fun LayoutParams.below(v: View): Unit = addRule(BELOW, v.id)
inline fun LayoutParams.bottomOf(v: View): Unit = addRule(BELOW, v.id)
inline fun LayoutParams.leftOf(v: View): Unit = addRule(LEFT_OF, v.id)
inline fun LayoutParams.rightOf(v: View): Unit = addRule(RIGHT_OF, v.id)
inline fun LayoutParams.sameLeft(v: View): Unit = addRule(ALIGN_LEFT, v.id)
inline fun LayoutParams.sameTop(v: View): Unit = addRule(ALIGN_TOP, v.id)
inline fun LayoutParams.sameRight(v: View): Unit = addRule(ALIGN_RIGHT, v.id)
inline fun LayoutParams.sameBottom(v: View): Unit = addRule(ALIGN_BOTTOM, v.id)
inline fun LayoutParams.topOf(id: Int): Unit = addRule(ABOVE, id)
inline fun LayoutParams.above(id: Int): Unit = addRule(ABOVE, id)
inline fun LayoutParams.below(id: Int): Unit = addRule(BELOW, id)
inline fun LayoutParams.bottomOf(id: Int): Unit = addRule(BELOW, id)
inline fun LayoutParams.leftOf(id: Int): Unit = addRule(LEFT_OF, id)
inline fun LayoutParams.rightOf(id: Int): Unit = addRule(RIGHT_OF, id)
inline fun LayoutParams.sameLeft(id: Int): Unit = addRule(ALIGN_LEFT, id)
inline fun LayoutParams.sameTop(id: Int): Unit = addRule(ALIGN_TOP, id)
inline fun LayoutParams.sameRight(id: Int): Unit = addRule(ALIGN_RIGHT, id)
inline fun LayoutParams.sameBottom(id: Int): Unit = addRule(ALIGN_BOTTOM, id)
inline fun LayoutParams.alignParentTop(): Unit = addRule(ALIGN_PARENT_TOP)
inline fun LayoutParams.alignParentLeft(): Unit = addRule(ALIGN_PARENT_LEFT)
inline fun LayoutParams.alignParentBottom(): Unit = addRule(ALIGN_PARENT_BOTTOM)
inline fun LayoutParams.alignParentRight(): Unit = addRule(ALIGN_PARENT_RIGHT)
inline fun LayoutParams.centerHorizontally(): Unit = addRule(CENTER_HORIZONTAL)
inline fun LayoutParams.centerVertically(): Unit = addRule(CENTER_VERTICAL)
inline fun LayoutParams.centerInParent(): Unit = addRule(CENTER_IN_PARENT)
// Unavailable in older versions of SDK
inline fun LayoutParams.alignParentStart(): Unit = addRule(20) // ALIGN_PARENT_START
inline fun LayoutParams.alignParentEnd(): Unit = addRule(21) // ALIGN_PARENT_END
| apache-2.0 | 0638cc2bde6316086d4c2c7115b66f2f | 35.756098 | 84 | 0.757465 | 3.579572 | false | false | false | false |
pjq/rpi | android/app/src/main/java/me/pjq/rpicar/CarControllerApiService.kt | 1 | 2637 | package me.pjq.rpicar
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by i329817([email protected]) on 30/07/2017.
*/
class CarControllerApiService private constructor() {
lateinit var api: CarControllerApi
internal set
internal lateinit var mOkHttpClient: OkHttpClient
object Config {
var HOST = "http://192.168.31.154"
private val isSshRediret: Boolean
get() = HOST.contains("pjq")
fun HOST(): String {
return HOST
}
fun API_URL(): String {
var port = ":8092"
if (isSshRediret) {
port = ":18080"
}
return HOST() + port
}
fun STREAM_URL(): String {
var port = ":8081"
if (isSshRediret) {
port = ":18092"
}
return HOST() + port
}
fun CAPTURE_VIDEO_URL(): String {
var port = ""
if (isSshRediret) {
port = ":18081"
}
return HOST() + port + "/motion/"
}
}
init {
init()
}
fun init() {
val builder = OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间
// int cacheSize = 10 * 1024 * 1024; // 10 MiB
// Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);
// builder.cache(cache);
// builder.addInterceptor(interceptor);
mOkHttpClient = builder.build()
val builder2 = Retrofit.Builder()
builder2.client(mOkHttpClient)
builder2.addConverterFactory(GsonConverterFactory.create())
builder2.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
val retrofit = builder2.baseUrl(Config.API_URL()).build()
api = retrofit.create(CarControllerApi::class.java)
}
fun getmOkHttpClient(): OkHttpClient {
return mOkHttpClient
}
companion object {
private var INSTANCE: CarControllerApiService? = null
val instance: CarControllerApiService
get() {
if (null == INSTANCE) {
INSTANCE = CarControllerApiService()
}
return INSTANCE!!
}
}
}
| apache-2.0 | 4b01beb8fd00fe404ab4ea7455dd38d4 | 25.731959 | 85 | 0.558427 | 4.597518 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/astrid/dao/Database.kt | 1 | 2108 | package com.todoroo.astrid.dao
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import com.todoroo.astrid.data.Task
import org.tasks.data.*
import org.tasks.data.TaskDao
import org.tasks.db.Migrations
import org.tasks.notifications.Notification
import org.tasks.notifications.NotificationDao
@Database(
entities = [
Notification::class,
TagData::class,
UserActivity::class,
TaskAttachment::class,
TaskListMetadata::class,
Task::class,
Alarm::class,
Place::class,
Geofence::class,
Tag::class,
GoogleTask::class,
Filter::class,
GoogleTaskList::class,
CaldavCalendar::class,
CaldavTask::class,
CaldavAccount::class,
GoogleTaskAccount::class,
Principal::class,
PrincipalAccess::class,
Attachment::class,
],
autoMigrations = [
AutoMigration(from = 83, to = 84, spec = Migrations.AutoMigrate83to84::class),
],
version = 86
)
abstract class Database : RoomDatabase() {
abstract fun notificationDao(): NotificationDao
abstract val tagDataDao: TagDataDao
abstract val userActivityDao: UserActivityDao
abstract val taskAttachmentDao: TaskAttachmentDao
abstract val taskListMetadataDao: TaskListMetadataDao
abstract val alarmDao: AlarmDao
abstract val locationDao: LocationDao
abstract val tagDao: TagDao
abstract val googleTaskDao: GoogleTaskDao
abstract val filterDao: FilterDao
abstract val googleTaskListDao: GoogleTaskListDao
abstract val taskDao: TaskDao
abstract val caldavDao: CaldavDao
abstract val deletionDao: DeletionDao
abstract val contentProviderDao: ContentProviderDao
abstract val upgraderDao: UpgraderDao
abstract val principalDao: PrincipalDao
/** @return human-readable database name for debugging
*/
override fun toString(): String {
return "DB:$name"
}
val name: String
get() = NAME
companion object {
const val NAME = "database"
}
} | gpl-3.0 | 7b98a27e1248a4ff2ded01751f34e42b | 28.291667 | 86 | 0.695446 | 4.715884 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/GithubAuthenticationManager.kt | 1 | 5007 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import git4idea.DialogManager
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder
import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog
import java.awt.Component
/**
* Entry point for interactions with Github authentication subsystem
*/
class GithubAuthenticationManager internal constructor(private val accountManager: GithubAccountManager,
private val executorFactory: GithubApiRequestExecutor.Factory) {
@CalledInAny
fun hasAccounts(): Boolean = accountManager.accounts.isNotEmpty()
@CalledInAny
fun getAccounts(): Set<GithubAccount> = accountManager.accounts
@CalledInAny
internal fun getTokenForAccount(account: GithubAccount): String? = accountManager.getTokenForAccount(account)
@CalledInAwt
@JvmOverloads
internal fun getOrRequestTokenForAccount(account: GithubAccount,
project: Project?,
parentComponent: Component? = null): String? {
return getTokenForAccount(account) ?: requestNewToken(account, project, parentComponent)
}
@CalledInAwt
private fun requestNewToken(account: GithubAccount, project: Project?, parentComponent: Component? = null): String? {
val dialog = GithubLoginDialog(executorFactory, project, parentComponent, message = "Missing access token for $account")
.withServer(account.server.toString(), false)
.withCredentials(account.name)
.withToken()
DialogManager.show(dialog)
if (!dialog.isOK) return null
val token = dialog.getToken()
account.name = dialog.getLogin()
accountManager.updateAccountToken(account, token)
return token
}
@CalledInAwt
@JvmOverloads
fun requestNewAccount(project: Project?, parentComponent: Component? = null): GithubAccount? {
val dialog = GithubLoginDialog(executorFactory, project, parentComponent, ::isAccountUnique)
DialogManager.show(dialog)
if (!dialog.isOK) return null
return registerAccount(dialog.getLogin(), dialog.getServer(), dialog.getToken())
}
@CalledInAwt
@JvmOverloads
fun requestNewAccountForServer(server: GithubServerPath, project: Project?, parentComponent: Component? = null): GithubAccount? {
val dialog = GithubLoginDialog(executorFactory, project, parentComponent, ::isAccountUnique).withServer(server.toUrl(), false)
DialogManager.show(dialog)
if (!dialog.isOK) return null
return registerAccount(dialog.getLogin(), dialog.getServer(), dialog.getToken())
}
private fun isAccountUnique(name: String, server: GithubServerPath) = accountManager.accounts.none { it.name == name && it.server == server }
private fun registerAccount(name: String, server: GithubServerPath, token: String): GithubAccount {
val account = GithubAccountManager.createAccount(name, server)
accountManager.accounts += account
accountManager.updateAccountToken(account, token)
return account
}
@TestOnly
fun registerAccount(name: String, host: String, token: String): GithubAccount {
return registerAccount(name, GithubServerPath.from(host), token)
}
@TestOnly
fun clearAccounts() {
for (account in accountManager.accounts) accountManager.updateAccountToken(account, null)
accountManager.accounts = emptySet()
}
fun getDefaultAccount(project: Project): GithubAccount? {
return project.service<GithubProjectDefaultAccountHolder>().account
}
@TestOnly
fun setDefaultAccount(project: Project, account: GithubAccount?) {
project.service<GithubProjectDefaultAccountHolder>().account = account
}
@CalledInAwt
@JvmOverloads
fun ensureHasAccounts(project: Project?, parentComponent: Component? = null): Boolean {
if (!hasAccounts()) {
if (requestNewAccount(project, parentComponent) == null) {
return false
}
}
return true
}
fun getSingleOrDefaultAccount(project: Project): GithubAccount? {
project.service<GithubProjectDefaultAccountHolder>().account?.let { return it }
val accounts = accountManager.accounts
if (accounts.size == 1) return accounts.first()
return null
}
companion object {
@JvmStatic
fun getInstance(): GithubAuthenticationManager {
return service()
}
}
}
| apache-2.0 | 88600f40f3c71e675f80cde66b8137c1 | 37.813953 | 143 | 0.748153 | 5.072948 | false | false | false | false |
olonho/carkot | proto/compiler/google/src/google/protobuf/compiler/kotlin/protoc-tests/kt_java_tests/src/kt_java_tests/BaseExtendedTest.kt | 1 | 7453 | package kt_java_tests
import java_msg.BaseMessage
import java_msg.ExtendedMessage
import Base
import CodedInputStream
import Extended
import java.io.ByteArrayOutputStream
object BaseExtendedTest {
fun generateKtBaseMessage(): Base {
val arrSize = RandomGen.rnd.nextInt(1000)
val arr = LongArray(arrSize)
for (i in 0..(arrSize - 1)) {
arr[i] = RandomGen.rnd.nextLong()
}
val flag = if (RandomGen.rnd.nextInt() % 2 == 0) false else true
val int = RandomGen.rnd.nextInt()
return Base.BuilderBase(arr, flag, int).build()
}
fun generateKtExtendedMessage(): Extended {
val arrSize = RandomGen.rnd.nextInt(1000)
val arr = LongArray(arrSize)
for (i in 0..(arrSize - 1)) {
arr[i] = RandomGen.rnd.nextLong()
}
val flag = if (RandomGen.rnd.nextInt() % 2 == 0) false else true
val int = RandomGen.rnd.nextInt()
val long = RandomGen.rnd.nextLong()
val longsSize = RandomGen.rnd.nextInt(1000)
val longs = LongArray(longsSize)
for (i in 0..(longsSize - 1)) {
longs[i] = RandomGen.rnd.nextLong()
}
return Extended.BuilderExtended(arr, longs, flag, long, int).build()
}
fun generateJvBaseMessage(): BaseMessage.Base {
val arrSize = RandomGen.rnd.nextInt(1000)
val arr = LongArray(arrSize)
for (i in 0..(arrSize - 1)) {
arr[i] = RandomGen.rnd.nextLong()
}
val flag = if (RandomGen.rnd.nextInt() % 2 == 0) false else true
val int = RandomGen.rnd.nextInt()
return BaseMessage.Base.newBuilder()
.addAllArr(arr.asIterable())
.setFlag(flag)
.setInt(int)
.build()
}
fun generateJvExtendedMessage(): ExtendedMessage.Extended {
val arrSize = RandomGen.rnd.nextInt(1000)
val arr = LongArray(arrSize)
for (i in 0..(arrSize - 1)) {
arr[i] = RandomGen.rnd.nextLong()
}
val flag = if (RandomGen.rnd.nextInt() % 2 == 0) false else true
val int = RandomGen.rnd.nextInt()
val long = RandomGen.rnd.nextLong()
val longsSize = RandomGen.rnd.nextInt(1000)
val longs = LongArray(longsSize)
for (i in 0..(longsSize - 1)) {
longs[i] = RandomGen.rnd.nextLong()
}
return ExtendedMessage.Extended.newBuilder()
.addAllArr(arr.asIterable())
.addAllArrLongs(longs.asIterable())
.setFlag(flag)
.setInt(int)
.setLong(long)
.build()
}
fun compareBases(kt: Base, jv: BaseMessage.Base): Boolean {
return kt.flag == jv.flag &&
kt.int == jv.int &&
Util.compareArrays(kt.arr.asIterable(), jv.arrList)
}
fun compareExtended(kt: Extended, jv: ExtendedMessage.Extended): Boolean {
return kt.flag == jv.flag &&
kt.int == jv.int &&
Util.compareArrays(kt.arr.asIterable(), jv.arrList) &&
Util.compareArrays(kt.arr_longs.asIterable(), jv.arrLongsList) &&
kt.long == jv.long
}
fun compareBaseKtToJavaExtended(kt: Base, jv: ExtendedMessage.Extended): Boolean {
return kt.flag == jv.flag &&
kt.int == jv.int &&
Util.compareArrays(kt.arr.asIterable(), jv.arrList)
}
fun compareExtendedKtToJavaBase(kt: Extended, jv: BaseMessage.Base): Boolean {
return kt.flag == jv.flag &&
kt.int == jv.int &&
Util.compareArrays(kt.arr.asIterable(), jv.arrList)
}
fun baseKtToBaseJavaOnce() {
val kt = generateKtBaseMessage()
val outs = Util.getKtOutputStream(kt.getSizeNoTag())
kt.writeTo(outs)
val ins = Util.KtOutputStreamToInputStream(outs)
val jv = BaseMessage.Base.parseFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareBases(kt, jv))
}
fun baseJavaToBaseKtOnce() {
val outs = ByteArrayOutputStream(100000)
val jv = generateJvBaseMessage()
jv.writeTo(outs)
val ins = CodedInputStream(outs.toByteArray())
val kt = Base.BuilderBase(LongArray(0), false, 0).build()
kt.mergeFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareBases(kt, jv))
}
fun baseKtToExtendedJavaOnce() {
val kt = generateKtBaseMessage()
val outs = Util.getKtOutputStream(kt.getSizeNoTag())
kt.writeTo(outs)
val ins = Util.KtOutputStreamToInputStream(outs)
val jv = ExtendedMessage.Extended.parseFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareBaseKtToJavaExtended(kt, jv))
}
fun extendedJavaToBaseKtOnce() {
val outs = ByteArrayOutputStream(100000)
val jv = generateJvExtendedMessage()
jv.writeTo(outs)
val ins = CodedInputStream(outs.toByteArray())
val kt = Base.BuilderBase(LongArray(0), false, 0).build()
kt.mergeFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareBaseKtToJavaExtended(kt, jv))
}
fun extendedKtToBaseJavaOnce() {
val kt = generateKtExtendedMessage()
val outs = Util.getKtOutputStream(kt.getSizeNoTag())
kt.writeTo(outs)
val ins = Util.KtOutputStreamToInputStream(outs)
val jv = BaseMessage.Base.parseFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareExtendedKtToJavaBase(kt, jv))
}
fun baseJavaToExtendedKtOnce() {
val outs = ByteArrayOutputStream(100000)
val jv = generateJvBaseMessage()
jv.writeTo(outs)
val ins = CodedInputStream(outs.toByteArray())
val kt = Extended.BuilderExtended(LongArray(0), LongArray(0), false, 0L, 0).build()
kt.mergeFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareExtendedKtToJavaBase(kt, jv))
}
fun extendedKtToExtendedJavaOnce() {
val kt = generateKtExtendedMessage()
val outs = Util.getKtOutputStream(kt.getSizeNoTag())
kt.writeTo(outs)
val ins = Util.KtOutputStreamToInputStream(outs)
val jv = ExtendedMessage.Extended.parseFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareExtended(kt, jv))
}
fun extendedJavaToExtendedKtOnce() {
val outs = ByteArrayOutputStream(100000)
val jv = generateJvExtendedMessage()
jv.writeTo(outs)
val ins = CodedInputStream(outs.toByteArray())
val kt = Extended.BuilderExtended(LongArray(0), LongArray(0), false, 0L, 0).build()
kt.mergeFrom(ins)
Util.assert(kt.errorCode == 0)
Util.assert(compareExtended(kt, jv))
}
val testRuns = 1000
fun runTests() {
for (i in 0..testRuns) {
// base - base
baseJavaToBaseKtOnce()
baseKtToBaseJavaOnce()
// base - extended
baseKtToExtendedJavaOnce()
// extendedJavaToBaseKtOnce() - currently failing, proper parsing of unknown fields is needed.
// extended - base
baseJavaToExtendedKtOnce()
extendedKtToBaseJavaOnce()
// extended - extended
extendedJavaToExtendedKtOnce()
extendedKtToExtendedJavaOnce()
}
}
} | mit | 5210bc003e29955eb963177976a30650 | 29.54918 | 106 | 0.597209 | 4.09956 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/player/songlist/InfoFragment.kt | 1 | 8467 | package be.florien.anyflow.feature.player.songlist
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.size
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import be.florien.anyflow.R
import be.florien.anyflow.data.view.Song
import be.florien.anyflow.databinding.FragmentInfoBinding
import be.florien.anyflow.databinding.ItemInfoBinding
import be.florien.anyflow.feature.quickActions.InfoActionsSelectionViewModel
import be.florien.anyflow.injection.ViewModelFactoryHolder
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class InfoFragment(
private var song: Song = Song(
SongInfoActions.DUMMY_SONG_ID, "", "", "", "", 0, "", "", ""
)
) : BottomSheetDialogFragment() {
companion object {
private const val SONG = "SONG"
}
private lateinit var viewModel: InfoViewModel
private var songListViewModel: SongListViewModel? = null
private lateinit var binding: FragmentInfoBinding
init {
arguments?.let {
song = it.getParcelable(SONG) ?: song
}
if (arguments == null) {
arguments = Bundle().apply {
putParcelable(SONG, song)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewModel = if (song.id == SongInfoActions.DUMMY_SONG_ID) {
ViewModelProvider(requireActivity(), (requireActivity() as ViewModelFactoryHolder).getFactory())
.get(InfoActionsSelectionViewModel::class.java)
.apply {
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
val itemWidth = resources.getDimensionPixelSize(R.dimen.minClickableSize)
val margin = resources.getDimensionPixelSize(R.dimen.smallDimen)
val itemFullWidth = itemWidth + margin + margin
maxItems = (width / itemFullWidth) - 1
}
} else {
ViewModelProvider(this, (requireActivity() as ViewModelFactoryHolder).getFactory())
.get(InfoDisplayViewModel::class.java)
}
if (parentFragment != null) {
songListViewModel = ViewModelProvider(
requireParentFragment(),
(requireActivity() as ViewModelFactoryHolder).getFactory()
).get(SongListViewModel::class.java)
}
viewModel.song = song
binding = FragmentInfoBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.songInfo.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
binding.songInfo.adapter = InfoAdapter()
viewModel.songRows.observe(viewLifecycleOwner) {
val infoAdapter = binding.songInfo.adapter as InfoAdapter
infoAdapter.submitList(it)
}
if (songListViewModel != null) {
viewModel.searchTerm.observe(viewLifecycleOwner) {
if (it != null) {
songListViewModel?.isSearching?.value = true
songListViewModel?.searchedText?.value = it
dismiss()
}
}
}
viewModel.isPlaylistListDisplayed.observe(viewLifecycleOwner) {
if (it) {
SelectPlaylistFragment(song.id).show(childFragmentManager, null)
}
}
}
inner class InfoAdapter : ListAdapter<SongInfoActions.SongRow, InfoViewHolder>(object :
DiffUtil.ItemCallback<SongInfoActions.SongRow>() {
override fun areItemsTheSame(
oldItem: SongInfoActions.SongRow,
newItem: SongInfoActions.SongRow
): Boolean {
val isSameAction = (oldItem.actionType == newItem.actionType)
|| (oldItem.actionType == SongInfoActions.ActionType.EXPANDED_TITLE && newItem.actionType == SongInfoActions.ActionType.EXPANDABLE_TITLE)
|| (oldItem.actionType == SongInfoActions.ActionType.EXPANDABLE_TITLE && newItem.actionType == SongInfoActions.ActionType.EXPANDED_TITLE)
return oldItem.fieldType == newItem.fieldType && isSameAction
}
override fun areContentsTheSame(
oldItem: SongInfoActions.SongRow,
newItem: SongInfoActions.SongRow
) = areItemsTheSame(
oldItem,
newItem
) && oldItem.actionType == newItem.actionType && oldItem.order == newItem.order
}) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InfoViewHolder =
InfoViewHolder(parent)
override fun onBindViewHolder(holder: InfoViewHolder, position: Int) {
holder.bindNewData(getItem(position))
}
override fun onBindViewHolder(
holder: InfoViewHolder,
position: Int,
payloads: MutableList<Any>
) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, position, payloads)
} else {
holder.bindChangedData(getItem(position))
}
}
}
inner class InfoViewHolder(
val parent: ViewGroup,
val binding: ItemInfoBinding = ItemInfoBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
) :
RecyclerView.ViewHolder(binding.root) {
fun bindNewData(row: SongInfoActions.SongRow) {
bindChangedData(row)
binding.display = row
binding.descriptionText = when {
row.text == null && row.textRes != null -> parent.context.resources.getString(row.textRes)
row.text != null && row.textRes == null -> row.text
row.text != null && row.textRes != null -> parent.context.resources.getString(
row.textRes,
row.text
)
else -> ""
}
binding.root.setOnClickListener {
viewModel.executeAction(row.fieldType, row.actionType)
}
if (row.actionType == SongInfoActions.ActionType.NONE) {
binding.root.setBackgroundColor(
ResourcesCompat.getColor(
parent.context.resources,
R.color.primaryBackground,
parent.context.theme
)
)
} else if (row.actionType != SongInfoActions.ActionType.INFO_TITLE && row.actionType != SongInfoActions.ActionType.EXPANDABLE_TITLE && row.actionType != SongInfoActions.ActionType.EXPANDED_TITLE) {
binding.root.setBackgroundColor(
ResourcesCompat.getColor(
parent.context.resources,
R.color.accentBackground,
parent.context.theme
)
)
} else {
binding.root.setBackgroundColor(0)
}
}
fun bindChangedData(row: SongInfoActions.SongRow) {
if (row.order != null) {
binding.order.removeViews(2, binding.order.size - 2)
val inflater = LayoutInflater.from(binding.root.context)
for (i in 0 until row.order) {
val unselectedView = inflater
.inflate(R.layout.item_action_order, binding.order, false) as ImageView
unselectedView.setImageResource(R.drawable.ic_action_order_item_unselected)
binding.order.addView(unselectedView)
}
}
}
}
}
| gpl-3.0 | daab9888aca4f94be52d23df44ee891b | 40.101942 | 209 | 0.611433 | 5.379288 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/server/EventReceiver.kt | 1 | 5763 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import net.mm2d.upnp.Http
import net.mm2d.upnp.HttpRequest
import net.mm2d.upnp.HttpResponse
import net.mm2d.upnp.Property
import net.mm2d.upnp.internal.parser.parseEventXml
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.internal.thread.ThreadCondition
import net.mm2d.upnp.internal.util.closeQuietly
import net.mm2d.upnp.log.Logger
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.ServerSocket
import java.net.Socket
import java.util.*
/**
* Class to receive Event notified by event subscription.
*
* It only accepts requests as an HTTP server.
* The listener parses HTTP messages.
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
internal class EventReceiver(
private val taskExecutors: TaskExecutors,
private val listener: (sid: String, seq: Long, properties: List<Pair<String, String>>) -> Boolean
) : Runnable {
private var serverSocket: ServerSocket? = null
private val clientList: MutableList<ClientTask> = Collections.synchronizedList(LinkedList())
private val threadCondition = ThreadCondition(taskExecutors.server)
fun start(): Unit = threadCondition.start(this)
fun stop() {
threadCondition.stop()
serverSocket.closeQuietly()
synchronized(clientList) {
clientList.forEach { it.stop() }
clientList.clear()
}
}
// VisibleForTesting
@Throws(IOException::class)
internal fun createServerSocket(): ServerSocket = ServerSocket(0)
fun getLocalPort(): Int {
if (!threadCondition.waitReady()) return 0
return serverSocket?.localPort ?: 0
}
override fun run() {
Thread.currentThread().let {
it.name = it.name + "-event-receiver"
}
try {
val socket = createServerSocket()
serverSocket = socket
threadCondition.notifyReady()
while (!threadCondition.isCanceled()) {
val clientSocket = socket.accept().also {
it.soTimeout = Property.DEFAULT_TIMEOUT
}
ClientTask(taskExecutors, this, clientSocket).let {
clientList.add(it)
it.start()
}
}
} catch (ignored: IOException) {
} finally {
serverSocket.closeQuietly()
serverSocket = null
}
}
fun notifyClientFinished(client: ClientTask) {
clientList.remove(client)
}
// VisibleForTesting
internal fun notifyEvent(sid: String, request: HttpRequest): Boolean {
val seq = request.getHeader(Http.SEQ)?.toLongOrNull() ?: return false
val properties = request.getBody().parseEventXml()
if (properties.isEmpty()) return false
return listener(sid, seq, properties)
}
// VisibleForTesting
internal class ClientTask(
taskExecutors: TaskExecutors,
private val eventReceiver: EventReceiver,
private val socket: Socket
) : Runnable {
private val condition = ThreadCondition(taskExecutors.io)
fun start(): Unit = condition.start(this)
fun stop() {
condition.stop()
socket.closeQuietly()
}
override fun run() {
try {
receiveAndReply(socket.getInputStream(), socket.getOutputStream())
} catch (e: IOException) {
Logger.w(e)
} finally {
socket.closeQuietly()
eventReceiver.notifyClientFinished(this)
}
}
// VisibleForTesting
@Throws(IOException::class)
fun receiveAndReply(inputStream: InputStream, outputStream: OutputStream) {
val request = HttpRequest.create().apply {
readData(inputStream)
}
Logger.v { "receive event:\n$request" }
val nt = request.getHeader(Http.NT)
val nts = request.getHeader(Http.NTS)
val sid = request.getHeader(Http.SID)
if (nt.isNullOrEmpty() || nts.isNullOrEmpty()) {
RESPONSE_BAD.writeData(outputStream)
} else if (sid.isNullOrEmpty() || nt != Http.UPNP_EVENT || nts != Http.UPNP_PROPCHANGE) {
RESPONSE_FAIL.writeData(outputStream)
} else {
if (eventReceiver.notifyEvent(sid, request)) {
RESPONSE_OK.writeData(outputStream)
} else {
RESPONSE_FAIL.writeData(outputStream)
}
}
}
companion object {
private val RESPONSE_OK = HttpResponse.create().apply {
setStatus(Http.Status.HTTP_OK)
setHeader(Http.SERVER, Property.SERVER_VALUE)
setHeader(Http.CONNECTION, Http.CLOSE)
setHeader(Http.CONTENT_LENGTH, "0")
}
private val RESPONSE_BAD = HttpResponse.create().apply {
setStatus(Http.Status.HTTP_BAD_REQUEST)
setHeader(Http.SERVER, Property.SERVER_VALUE)
setHeader(Http.CONNECTION, Http.CLOSE)
setHeader(Http.CONTENT_LENGTH, "0")
}
private val RESPONSE_FAIL = HttpResponse.create().apply {
setStatus(Http.Status.HTTP_PRECON_FAILED)
setHeader(Http.SERVER, Property.SERVER_VALUE)
setHeader(Http.CONNECTION, Http.CLOSE)
setHeader(Http.CONTENT_LENGTH, "0")
}
}
}
}
| mit | 07f53ae6d24a378f7fa5aafef57fe9dc | 33.208333 | 101 | 0.602575 | 4.664773 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/forge/util/ForgePackDescriptor.kt | 1 | 2168 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.util
import com.demonwav.mcdev.util.MinecraftVersions
import com.demonwav.mcdev.util.SemanticVersion
data class ForgePackDescriptor(val format: Int, val comment: String) {
companion object {
// Current data from https://github.com/MinecraftForge/MinecraftForge/blob/0ff8a596fc1ef33d4070be89dd5cb4851f93f731/mdk/src/main/resources/pack.mcmeta
val FORMAT_3 = ForgePackDescriptor(
3,
"A pack_format of 3 should be used starting with Minecraft 1.11." +
" All resources, including language files, should be lowercase (eg: en_us.lang)." +
" A pack_format of 2 will load your mod resources with LegacyV2Adapter," +
" which requires language files to have uppercase letters (eg: en_US.lang)."
)
val FORMAT_4 = ForgePackDescriptor(
4,
"A pack_format of 4 requires json lang files. Note: we require v4 pack meta for all mods."
)
val FORMAT_5 = ForgePackDescriptor(
5,
"A pack_format of 5 requires json lang files and some texture changes from 1.15." +
" Note: we require v5 pack meta for all mods."
)
val FORMAT_6 = ForgePackDescriptor(
6,
"A pack_format of 6 requires json lang files and some texture changes from 1.16.2." +
" Note: we require v6 pack meta for all mods."
)
val FORMAT_7 = ForgePackDescriptor(7, "")
// See https://minecraft.gamepedia.com/Tutorials/Creating_a_resource_pack#.22pack_format.22
fun forMcVersion(version: SemanticVersion): ForgePackDescriptor? = when {
version <= MinecraftVersions.MC1_12_2 -> FORMAT_3
version <= MinecraftVersions.MC1_14_4 -> FORMAT_4
version <= MinecraftVersions.MC1_16_1 -> FORMAT_5
version < MinecraftVersions.MC1_17 -> FORMAT_6
version >= MinecraftVersions.MC1_17 -> FORMAT_7
else -> null
}
}
}
| mit | 507fcee984edbfd0559725392464e13a | 40.692308 | 158 | 0.629613 | 4.022263 | false | false | false | false |
ohmae/WheelColorChooser | src/main/java/net/mm2d/wcc/HueCircle.kt | 1 | 6520 | /*
* Copyright (c) 2014 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.wcc
import net.mm2d.color.ColorUtils
import net.mm2d.color.setAlpha
import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.image.BufferedImage
import javax.swing.JPanel
import kotlin.math.*
/**
* 色相環を表示操作するクラス
*
* @param sampleCount 色数
*/
class HueCircle(private var sampleCount: Int) : JPanel() {
private val image: BufferedImage = BufferedImage(DIAMETER, DIAMETER, BufferedImage.TYPE_4BYTE_ABGR)
private val marginTop: Int = (WIDTH - DIAMETER) / 2
private val marginLeft: Int = (WIDTH - DIAMETER) / 2
private val centerX: Int = WIDTH / 2
private val centerY: Int = HEIGHT / 2
private var hue: Float = 0f
private var saturation: Float = 1f
private var value: Float = 1f
private var reverse = false
var onHsChangeListener: ((h: Float, s: Float, v: Float) -> Unit)? = null
/**
* 選択した色のリストを返す
*
* @return 色のリスト
*/
val colors: IntArray
get() {
val colors = IntArray(sampleCount)
for (i in 0 until sampleCount) {
val h = decimal(hue + i.toFloat() / sampleCount)
val color = ColorUtils.hsvToColor(h, saturation, value)
if (reverse) {
colors[(sampleCount - i) % sampleCount] = color
} else {
colors[i] = color
}
}
return colors
}
init {
makeHSCircle(value)
preferredSize = Dimension(WIDTH, HEIGHT)
object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
selectPoint(e.x, e.y)
}
override fun mouseDragged(e: MouseEvent) {
selectPoint(e.x, e.y)
}
}.let {
addMouseListener(it)
addMouseMotionListener(it)
}
}
/**
* クリックもしくはドラッグによって色を選択する
*
* @param x X座標
* @param y Y座標
*/
private fun selectPoint(x: Int, y: Int) {
val cx = (x - centerX).toFloat()
val cy = (centerY - y).toFloat()
val distance = hypot(cx, cy)
val h = calculateRadian(cx, cy) / (PI * 2)
val s: Float = if (distance < RADIUS) {
distance / RADIUS
} else {
1f
}
setHsv(h, s, value, true)
}
/**
* HSVの値を設定する
*
* リスナー通知は行わない
*
* @param h Hue
* @param s Saturation
* @param v Value
*/
fun setHsv(h: Float, s: Float, v: Float) {
setHsv(h, s, v, false)
}
/**
* HSVの値を設定する
*
* @param h Hue
* @param s Saturation
* @param v Value
* @param notify リスナー通知の有無
*/
private fun setHsv(h: Float, s: Float, v: Float, notify: Boolean) {
hue = h
saturation = s
if (value != v) {
value = v
makeHSCircle(value)
}
if (notify) {
onHsChangeListener?.invoke(h, s, v)
}
repaint()
}
/**
* 分割数を設定する
*
* @param div 分割数
*/
fun setDivision(div: Int) {
sampleCount = div
repaint()
}
/**
* 向き反転
*
* @param reverse 反転するときtrue
*/
fun setReverse(reverse: Boolean) {
this.reverse = reverse
}
/**
* 色相環の画像を作成する
*
* @param v 明度
*/
private fun makeHSCircle(v: Float) {
for (y in 0 until image.height) {
val cy = (RADIUS - y).toFloat()
for (x in 0 until image.width) {
val cx = (x - RADIUS).toFloat()
val distance = hypot(cx, cy)
var color = 0
if (distance < RADIUS + 1) {
val radian = calculateRadian(cx, cy)
val h = radian / (PI * 2f)
val s = (distance / RADIUS).coerceIn(0.0f, 1.0f)
color = ColorUtils.hsvToColor(h, s, v)
val alpha = RADIUS + 1 - distance
if (alpha < 1) { // アンチエイリアス
color = color.setAlpha(alpha)
}
}
image.setRGB(x, y, color)
}
}
}
/**
* 小数部を取り出す
*
* @param value 実数
* @return 小数部
*/
private fun decimal(value: Float): Float {
return value - value.toInt()
}
/**
* 指定された座標とX軸がなす角度を計算して返す
*
* @param x X座標
* @param y Y座標
* @return 座標とX軸の角度 radian
*/
private fun calculateRadian(x: Float, y: Float): Float {
if (x == 0f) {
// ゼロ除算回避
return if (y > 0f) {
PI / 2f
} else {
PI * 3f / 2f
}
}
return atan(y / x) + when {
x < 0f -> PI
y < 0f -> PI * 2f
else -> 0f
}
}
override fun paint(g: Graphics?) {
val g2 = g as? Graphics2D ?: return
g2.background = background
g2.clearRect(0, 0, width, height)
g2.drawImage(image, marginLeft, marginTop, this)
val r = saturation * RADIUS
// 選択している点を表示
g2.setXORMode(Color.WHITE)
for (i in 0 until sampleCount) {
val a = decimal(hue + i.toFloat() / sampleCount) * 2f * PI
val x = centerX + (cos(a) * r).roundToInt()
val y = centerY - (sin(a) * r).roundToInt()
if (i == 0) {
// 操作点を大きく
g2.drawRect(x - 3, y - 3, 4, 4)
} else {
g2.drawRect(x - 2, y - 2, 2, 2)
}
}
}
companion object {
private const val RADIUS = 255
private const val DIAMETER = RADIUS * 2 + 1
private const val WIDTH = 520
private const val HEIGHT = 520
private const val PI = Math.PI.toFloat()
}
}
| mit | daa62cfb5dd27b2b58d8838a900f8913 | 24.881356 | 103 | 0.492796 | 3.588719 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/dialog/RepliesDialogContentFragment.kt | 1 | 8427 | package com.emogoth.android.phone.mimi.dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.activity.GalleryActivity2
import com.emogoth.android.phone.mimi.activity.PostItemDetailActivity
import com.emogoth.android.phone.mimi.activity.PostItemListActivity
import com.emogoth.android.phone.mimi.adapter.RepliesListAdapter
import com.emogoth.android.phone.mimi.db.DatabaseUtils
import com.emogoth.android.phone.mimi.db.HistoryTableConnection
import com.emogoth.android.phone.mimi.db.PostTableConnection
import com.emogoth.android.phone.mimi.db.models.History
import com.emogoth.android.phone.mimi.interfaces.GoToPostListener
import com.emogoth.android.phone.mimi.model.OutsideLink
import com.emogoth.android.phone.mimi.util.Extras
import com.emogoth.android.phone.mimi.util.RxUtil
import com.emogoth.android.phone.mimi.view.gallery.GalleryPagerAdapter
import com.emogoth.android.phone.mimi.viewmodel.ChanDataSource
import com.mimireader.chanlib.models.ChanPost
import com.mimireader.chanlib.models.ChanThread
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
class RepliesDialogContentFragment : Fragment(), LifecycleObserver {
private var listView: RecyclerView? = null
private var boardName: String = ""
private var threadId: Long = 0
private var replies: ArrayList<String> = ArrayList()
private var outsideLinks: List<OutsideLink> = ArrayList()
private var thread: ChanThread = ChanThread()
private var id: Long = 0
private var repliesSubscription: Disposable? = null
private var loadRepliesSubscription: Disposable? = null
var updateReplies: ((ChanPost) -> Unit)? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.dialog_replies_content, container, false)
listView = v.findViewById(R.id.replies_list)
arguments?.let { extractExtras(it) }
if (threadId > 0) {
val loadRepliesSubscription = PostTableConnection.fetchThread(threadId)
.map(PostTableConnection.mapDbPostsToChanThread(boardName, threadId))
.compose(DatabaseUtils.applySingleSchedulers())
.subscribe({
thread = it
loadReplies()
}, {
Toast.makeText(activity, R.string.error_occurred, Toast.LENGTH_SHORT).show()
Log.e("RepliesContent", "Caught exception", it)
})
}
return v
}
private fun loadReplies() {
RxUtil.safeUnsubscribe(repliesSubscription)
val dataSource = ChanDataSource()
repliesSubscription = dataSource.watchThread(boardName, threadId)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.zipWith(HistoryTableConnection.fetchPost(boardName, threadId).toFlowable(), BiFunction { chanThread: ChanThread, history: History -> Pair(history, chanThread) })
.flatMap { (_, second) ->
val posts: ArrayList<ChanPost> = ArrayList()
for (reply in replies) {
for (post in second.posts) {
if (post.no == reply.toInt().toLong()) {
posts.add(post)
}
}
}
Flowable.just(posts)
}
.first(ArrayList())
.subscribe { posts: List<ChanPost> ->
val adapter = RepliesListAdapter(posts, outsideLinks, thread)
adapter.linkClickListener = { outsideLink: OutsideLink ->
val intent: Intent
val id = outsideLink.threadId
if (id != null && TextUtils.isDigitsOnly(id)) {
intent = Intent(activity, PostItemDetailActivity::class.java)
intent.putExtra(Extras.EXTRAS_THREAD_ID, java.lang.Long.valueOf(id))
intent.putExtra(Extras.EXTRAS_SINGLE_THREAD, true)
} else {
intent = Intent(activity, PostItemListActivity::class.java)
}
intent.putExtra(Extras.EXTRAS_BOARD_NAME, outsideLink.boardName)
activity?.startActivity(intent)
}
adapter.repliesTextClickListener = { (post) ->
if (post != null) {
updateReplies?.invoke(post)
}
}
adapter.thumbClickListener = { chanPost: ChanPost ->
if (activity != null) {
val postsWithImages = GalleryPagerAdapter.getPostsWithImages(posts)
val ids = LongArray(postsWithImages.size)
for (i in postsWithImages.indices) {
ids[i] = postsWithImages[i].no
}
val act = activity
if (act != null) {
GalleryActivity2.start(act, GalleryActivity2.GALLERY_TYPE_PAGER, chanPost.no, boardName, thread.threadId, ids)
}
}
}
adapter.goToPostListener = {
if (parentFragment is GoToPostListener) {
val l: GoToPostListener = parentFragment as GoToPostListener
l.goToPost(it.no)
}
}
listView?.layoutManager = LinearLayoutManager(activity)
listView?.adapter = adapter
}
}
private fun extractExtras(bundle: Bundle?) {
if (bundle == null) {
return
}
if (bundle.containsKey(Extras.EXTRAS_BOARD_NAME)) {
boardName = bundle.getString(Extras.EXTRAS_BOARD_NAME) ?: ""
}
if (bundle.containsKey(Extras.EXTRAS_POST_ID)) {
id = bundle.getLong(Extras.EXTRAS_POST_ID)
}
replies = if (bundle.containsKey(Extras.EXTRAS_POST_LIST)) {
bundle.getStringArrayList(Extras.EXTRAS_POST_LIST) ?: ArrayList()
} else {
ArrayList()
}
outsideLinks = if (bundle.containsKey(Extras.EXTRAS_OUTSIDE_LINK_LIST)) {
bundle.getParcelableArrayList(Extras.EXTRAS_OUTSIDE_LINK_LIST) ?: ArrayList()
} else {
emptyList()
}
// if (bundle.containsKey(Extras.EXTRAS_SINGLE_THREAD)) {
// thread = bundle.getParcelable(Extras.EXTRAS_SINGLE_THREAD) ?: ChanThread()
// }
if (bundle.containsKey(Extras.EXTRAS_THREAD_ID)) {
val id = bundle.getLong(Extras.EXTRAS_THREAD_ID)
if (thread.threadId == -1L) {
thread = ChanThread(boardName, id, ArrayList())
}
threadId = id
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
open fun onAny(source: LifecycleOwner?, event: Lifecycle.Event?): Unit {
Log.d("RepliesDialogContent", "Owner: ${source?.lifecycle.toString()}, Event: ${event}")
if (event == Lifecycle.Event.ON_DESTROY) {
if (loadRepliesSubscription?.isDisposed == false) loadRepliesSubscription?.dispose()
}
}
} | apache-2.0 | 54404ddcec07dccc6c2831cbd204a0b9 | 44.069519 | 178 | 0.601875 | 4.998221 | false | false | false | false |
Egorand/kotlin-playground | src/me/egorand/kotlin/playground/classes/BackingFields.kt | 1 | 1753 | /*
* Copyright 2016 Egor Andreevici
*
* 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 me.egorand.kotlin.playground.classes
import java.util.*
// classes in Kotlin don't have fields, but for some cases (e.g. custom accessors) backing fields can be created and
// accessed via 'field'
class BackingFields {
// backing field will be generated since setter has default implementation
var counter = 0
set(value) {
if (value > 0) {
field = value
}
}
var size = 0
// no backing fields will be generated
val isEmpty: Boolean
get() = this.size == 0
// another option is using backing properties, which are just like Java fields
private var _table: Map<String, Int>? = null
val table: Map<String, Int>
get() {
if (_table == null) {
_table = HashMap()
}
return _table ?: throw RuntimeException("can't smart cast, value has probably been changed")
}
}
fun main(args: Array<String>) {
val bf = BackingFields()
bf.counter = -1
println(bf.counter)
bf.counter = 4
println(bf.counter)
bf.size = 0
println(bf.isEmpty)
bf.size = 5
println(bf.isEmpty)
val table = bf.table
println(table)
} | apache-2.0 | 26b63de4b4ca8f069c7f8ec8d5a565a3 | 25.575758 | 116 | 0.662864 | 3.895556 | false | false | false | false |
mix-it/mixit | src/main/kotlin/mixit/web/handler/UserHandler.kt | 1 | 15188 | package mixit.web.handler
import mixit.MixitProperties
import mixit.model.Language
import mixit.model.Link
import mixit.model.Role
import mixit.model.User
import mixit.model.anonymize
import mixit.repository.TalkRepository
import mixit.repository.TicketRepository
import mixit.repository.UserRepository
import mixit.util.Cryptographer
import mixit.util.MarkdownConverter
import mixit.util.camelCase
import mixit.util.encodeToMd5
import mixit.util.json
import mixit.util.language
import mixit.util.markFoundOccurrences
import mixit.util.seeOther
import mixit.util.toUrlPath
import mixit.util.validator.EmailValidator
import mixit.util.validator.MarkdownValidator
import mixit.util.validator.MaxLengthValidator
import mixit.util.validator.UrlValidator
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyExtractors
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.created
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.reactive.function.server.body
import org.springframework.web.reactive.function.server.bodyToMono
import org.springframework.web.util.UriUtils
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toMono
import java.net.URI.create
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.util.stream.IntStream
@Component
class UserHandler(
private val repository: UserRepository,
private val talkRepository: TalkRepository,
private val ticketRepository: TicketRepository,
private val markdownConverter: MarkdownConverter,
private val cryptographer: Cryptographer,
private val properties: MixitProperties,
private val emailValidator: EmailValidator,
private val urlValidator: UrlValidator,
private val maxLengthValidator: MaxLengthValidator,
private val markdownValidator: MarkdownValidator
) {
companion object {
val speakerStarInHistory = listOf(
"tastapod",
"joel.spolsky",
"pamelafox",
"MattiSG",
"bodil",
"mojavelinux",
"andrey.breslav",
// "kowen",
"ppezziardi",
"rising.linda",
"jhoeller",
"sharonsteed",
"allan.rennebo",
"agilex",
"laura.carvajal",
"augerment",
"dgageot",
"romainguy",
"graphicsgeek1",
"andre",
"mary",
"Woody.Zuill",
"james.carlson",
"egorcenski",
"ojuncu",
"hsablonniere",
"nitot"
)
val speakerStarInCurrentEvent = listOf<String>()
}
enum class ViewMode { ViewMyProfile, ViewUser, EditProfile }
fun findOneView(req: ServerRequest) =
try {
val idLegacy = req.pathVariable("login").toLong()
repository.findByLegacyId(idLegacy).flatMap { findOneViewDetail(req, it) }
} catch (e: NumberFormatException) {
repository.findOne(URLDecoder.decode(req.pathVariable("login"), "UTF-8"))
.flatMap { findOneViewDetail(req, it) }
}
fun findProfileView(req: ServerRequest) =
req.session().flatMap {
val currentUserEmail = it.getAttribute<String>("email")
repository.findByNonEncryptedEmail(currentUserEmail!!).flatMap { findOneViewDetail(req, it, ViewMode.ViewMyProfile) }
}
fun editProfileView(req: ServerRequest) =
req.session().flatMap {
val currentUserEmail = it.getAttribute<String>("email")
repository.findByNonEncryptedEmail(currentUserEmail!!).flatMap { findOneViewDetail(req, it, ViewMode.EditProfile) }
}
private fun findOneViewDetail(
req: ServerRequest,
user: User,
viewMode: ViewMode = ViewMode.ViewUser,
errors: Map<String, String> = emptyMap()
): Mono<ServerResponse> =
if (viewMode == ViewMode.EditProfile) {
ok().render(
"user-edit",
mapOf(
Pair("user", user.toDto(req.language(), markdownConverter)),
Pair("usermail", cryptographer.decrypt(user.email)),
Pair("description-fr", user.description[Language.FRENCH]),
Pair("description-en", user.description[Language.ENGLISH]),
Pair("userlinks", user.toLinkDtos()),
Pair("baseUri", UriUtils.encode(properties.baseUri, StandardCharsets.UTF_8)),
Pair("errors", errors),
Pair("hasErrors", errors.isNotEmpty())
)
)
} else if (viewMode == ViewMode.ViewMyProfile) {
ticketRepository
.findByEmail(cryptographer.decrypt(user.email)!!)
.flatMap {
ok().render(
"user",
mapOf(
Pair("user", user.toDto(req.language(), markdownConverter)),
Pair("hasLotteryTicket", true),
Pair("canUpdateProfile", true),
Pair("baseUri", UriUtils.encode(properties.baseUri, StandardCharsets.UTF_8))
)
)
}
.switchIfEmpty(
ok().render(
"user",
mapOf(
Pair("user", user.toDto(req.language(), markdownConverter)),
Pair("canUpdateProfile", true),
Pair("baseUri", UriUtils.encode(properties.baseUri, StandardCharsets.UTF_8))
)
)
)
} else {
talkRepository
.findBySpeakerId(listOf(user.login))
.collectList()
.flatMap { talks ->
val talkDtos = talks.map { talk -> talk.toDto(req.language(), listOf(user)) }
ok().render(
"user",
mapOf(
Pair("user", user.toDto(req.language(), markdownConverter)),
Pair("talks", talkDtos),
Pair("hasTalks", talkDtos.isNotEmpty()),
Pair("baseUri", UriUtils.encode(properties.baseUri, StandardCharsets.UTF_8))
)
)
}
}
fun saveProfile(req: ServerRequest): Mono<ServerResponse> = req.session().flatMap {
val currentUserEmail = it.getAttribute<String>("email")
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// In his profile screen a user can't change all the data. In the first step we load the user
repository.findByNonEncryptedEmail(currentUserEmail!!).flatMap {
val errors = mutableMapOf<String, String>()
// Null check
if (formData["firstname"].isNullOrBlank()) {
errors.put("firstname", "user.form.error.firstname.required")
}
if (formData["lastname"].isNullOrBlank()) {
errors.put("lastname", "user.form.error.lastname.required")
}
if (formData["email"].isNullOrBlank()) {
errors.put("email", "user.form.error.email.required")
}
if (formData["description-fr"].isNullOrBlank()) {
errors.put("description-fr", "user.form.error.description.fr.required")
}
if (formData["description-en"].isNullOrBlank()) {
errors.put("description-en", "user.form.error.description.en.required")
}
if (errors.isNotEmpty()) {
findOneViewDetail(req, it, ViewMode.EditProfile, errors = errors)
}
val user = User(
it.login,
formData["firstname"]!!,
formData["lastname"]!!,
cryptographer.encrypt(formData["email"]!!),
if (formData["company"] == "") null else formData["company"],
mapOf(
Pair(Language.FRENCH, markdownValidator.sanitize(formData["description-fr"]!!)),
Pair(Language.ENGLISH, markdownValidator.sanitize(formData["description-en"]!!))
),
if (formData["photoUrl"].isNullOrBlank()) formData["email"]!!.encodeToMd5() else null,
if (formData["photoUrl"] == "") null else formData["photoUrl"],
it.role,
extractLinks(formData),
it.legacyId,
it.tokenExpiration,
it.token
)
// We want to control data to not save invalid things in our database
if (!maxLengthValidator.isValid(user.firstname, 30)) {
errors.put("firstname", "user.form.error.firstname.size")
}
if (!maxLengthValidator.isValid(user.lastname, 30)) {
errors.put("lastname", "user.form.error.lastname.size")
}
if (user.company != null && !maxLengthValidator.isValid(user.company, 60)) {
errors.put("company", "user.form.error.company.size")
}
if (!emailValidator.isValid(formData["email"]!!)) {
errors.put("email", "user.form.error.email")
}
if (!markdownValidator.isValid(user.description.get(Language.FRENCH))) {
errors.put("description-fr", "user.form.error.description.fr")
}
if (!markdownValidator.isValid(user.description.get(Language.ENGLISH))) {
errors.put("description-en", "user.form.error.description.en")
}
if (!urlValidator.isValid(user.photoUrl)) {
errors.put("photoUrl", "user.form.error.photourl")
}
user.links.forEachIndexed { index, link ->
if (!maxLengthValidator.isValid(link.name, 30)) {
errors.put("link${index + 1}Name", "user.form.error.link${index + 1}.name")
}
if (!urlValidator.isValid(link.url)) {
errors.put("link${index + 1}Url", "user.form.error.link${index + 1}.url")
}
}
if (errors.isEmpty()) {
// If everything is Ok we save the user
repository.save(user).then(seeOther("${properties.baseUri}/me"))
} else {
findOneViewDetail(req, user, ViewMode.EditProfile, errors = errors)
}
}
}
}
private fun extractLinks(formData: Map<String, String>): List<Link> =
IntStream.range(0, 5)
.toArray()
.asList()
.mapIndexed { index, _ -> Pair(formData["link${index}Name"], formData["link${index}Url"]) }
.filter { !it.first.isNullOrBlank() && !it.second.isNullOrBlank() }
.map { Link(it.first!!, it.second!!) }
fun findOne(req: ServerRequest) = ok().json().body(repository.findOne(req.pathVariable("login")).map { it.anonymize() })
fun findAll(req: ServerRequest) = ok().json().body(repository.findAll().map { it.anonymize() })
fun findStaff(req: ServerRequest) = ok().json().body(repository.findByRoles(listOf(Role.STAFF)).map { it.anonymize() })
fun findOneStaff(req: ServerRequest) = ok().json().body(repository.findOneByRoles(req.pathVariable("login"), listOf(Role.STAFF, Role.STAFF_IN_PAUSE)).map { it.anonymize() })
fun findSpeakerByEventId(req: ServerRequest) =
ok().json().body(talkRepository.findByEvent(req.pathVariable("year")).flatMap { repository.findMany(it.speakerIds).map { it.anonymize() } }.distinct())
fun create(req: ServerRequest) = repository.save(req.bodyToMono<User>()).flatMap {
created(create("/api/user/${it.login}")).json().body(it.toMono())
}
fun check(req: ServerRequest) = ok().json().body(
repository.findByNonEncryptedEmail(req.pathVariable("email"))
.filter { it.token == req.headers().header("token").get(0) }
.map { it.toDto(req.language(), markdownConverter) }
)
}
class LinkDto(
val name: String,
val url: String,
val index: String
)
fun Link.toLinkDto(index: Int) = LinkDto(name, url, "link${index + 1}")
fun User.toLinkDtos(): Map<String, List<LinkDto>> =
if (links.size > 4) {
links.mapIndexed { index, link -> link.toLinkDto(index) }.groupBy { it.index }
} else {
val existingLinks = links.size
val userLinks = links.mapIndexed { index, link -> link.toLinkDto(index) }.toMutableList()
IntStream.range(0, 5 - existingLinks).forEach { userLinks.add(LinkDto("", "", "link${existingLinks + it + 1}")) }
userLinks.groupBy { it.index }
}
class SpeakerStarDto(
val login: String,
val key: String,
val name: String
)
fun User.toSpeakerStarDto() = SpeakerStarDto(login, lastname.lowercase().replace("è", "e"), "${firstname.camelCase()} ${lastname.camelCase()}")
class UserDto(
val login: String,
val firstname: String,
val lastname: String,
var email: String? = null,
var company: String? = null,
var description: String,
var emailHash: String? = null,
var photoUrl: String? = null,
val role: Role,
var links: List<Link>,
val logoType: String?,
val logoWebpUrl: String? = null,
val isAbsoluteLogo: Boolean = if (photoUrl == null) false else photoUrl.startsWith("http"),
val path: String = login.toUrlPath()
)
fun User.toDto(language: Language, markdownConverter: MarkdownConverter, searchTerms: List<String> = emptyList()) =
UserDto(
login,
firstname.markFoundOccurrences(searchTerms),
lastname.markFoundOccurrences(searchTerms),
email,
company,
markdownConverter.toHTML(description[language] ?: "").markFoundOccurrences(searchTerms),
emailHash,
photoUrl,
role,
links,
logoType(photoUrl),
logoWebpUrl(photoUrl)
)
fun logoWebpUrl(url: String?) =
when {
url == null -> null
url.endsWith("png") -> url.replace("png", "webp")
url.endsWith("jpg") -> url.replace("jpg", "webp")
else -> null
}
fun logoType(url: String?) =
when {
url == null -> null
url.endsWith("svg") -> "image/svg+xml"
url.endsWith("png") -> "image/png"
url.endsWith("jpg") -> "image/jpeg"
url.endsWith("gif") -> "image/gif"
else -> null
}
| apache-2.0 | 06cec07f89a044d79093180506f7f9d3 | 40.045946 | 177 | 0.573451 | 4.553823 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/preferences/IncrementerNumberRangePreferenceCompat.kt | 1 | 5958 | /****************************************************************************************
* Copyright (c) 2021 Tushar Bhatt <[email protected]> *
* Copyright (c) 2021 David Allison <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.preferences
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import com.ichi2.anki.R
/** Marker class to be used in preferences */
class IncrementerNumberRangePreferenceCompat : NumberRangePreferenceCompat {
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?) : super(context)
class IncrementerNumberRangeDialogFragmentCompat : NumberRangePreferenceCompat.NumberRangeDialogFragmentCompat() {
private var mLastValidEntry = 0
/**
* Sets [.mEditText] width and gravity.
*/
override fun onBindDialogView(view: View?) {
super.onBindDialogView(view)
// Layout parameters for mEditText
val editTextParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
3.0f
)
mLastValidEntry = try {
editText.text.toString().toInt()
} catch (nfe: NumberFormatException) {
// This should not be possible but just in case, recover with a valid minimum from superclass
numberRangePreference.min
}
editText.layoutParams = editTextParams
// Centre text inside mEditText
editText.gravity = Gravity.CENTER_HORIZONTAL
}
/**
* Sets appropriate Text and OnClickListener for buttons
*
* Sets orientation for layout
*/
override fun onCreateDialogView(context: Context?): View {
val linearLayout = LinearLayout(context)
val incrementButton = Button(context)
val decrementButton = Button(context)
val editText: EditText = super.onCreateDialogView(context).findViewById(android.R.id.edit)
(editText.parent as ViewGroup).removeView(editText)
// Layout parameters for incrementButton and decrementButton
val buttonParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1.0f
)
incrementButton.setText(R.string.plus_sign)
decrementButton.setText(R.string.minus_sign)
incrementButton.layoutParams = buttonParams
decrementButton.layoutParams = buttonParams
incrementButton.setOnClickListener { updateEditText(true) }
decrementButton.setOnClickListener { updateEditText(false) }
linearLayout.orientation = LinearLayout.HORIZONTAL
linearLayout.addView(decrementButton)
linearLayout.addView(editText)
linearLayout.addView(incrementButton)
return linearLayout
}
/**
* Increments/Decrements the value of [.mEditText] by 1 based on the parameter value.
*
* @param isIncrement Indicator for whether to increase or decrease the value.
*/
private fun updateEditText(isIncrement: Boolean) {
var value: Int = try {
editText.text.toString().toInt()
} catch (e: NumberFormatException) {
// If the user entered a non-number then incremented, restore to a good value
mLastValidEntry
}
value = if (isIncrement) value + 1 else value - 1
// Make sure value is within range
mLastValidEntry = numberRangePreference.getValidatedRangeFromInt(value)
editText.setText(mLastValidEntry.toString())
}
companion object {
@JvmStatic
fun newInstance(key: String?): IncrementerNumberRangeDialogFragmentCompat {
val fragment = IncrementerNumberRangeDialogFragmentCompat()
val b = Bundle(1)
b.putString(ARG_KEY, key)
fragment.arguments = b
return fragment
}
}
}
}
| gpl-3.0 | a42924b3168e346b5b7a3f529e49b71d | 45.186047 | 144 | 0.582075 | 5.65812 | false | false | false | false |
android/health-samples | health-services/MeasureData/app/src/main/java/com/example/measuredata/HealthServicesManager.kt | 1 | 3236 | /*
* 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.measuredata
import android.util.Log
import androidx.concurrent.futures.await
import androidx.health.services.client.HealthServicesClient
import androidx.health.services.client.MeasureCallback
import androidx.health.services.client.data.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
/**
* Entry point for [HealthServicesClient] APIs, wrapping them in coroutine-friendly APIs.
*/
class HealthServicesManager @Inject constructor(
healthServicesClient: HealthServicesClient
) {
private val measureClient = healthServicesClient.measureClient
suspend fun hasHeartRateCapability(): Boolean {
val capabilities = measureClient.getCapabilitiesAsync().await()
return (DataType.HEART_RATE_BPM in capabilities.supportedDataTypesMeasure)
}
/**
* Returns a cold flow. When activated, the flow will register a callback for heart rate data
* and start to emit messages. When the consuming coroutine is cancelled, the measure callback
* is unregistered.
*
* [callbackFlow] is used to bridge between a callback-based API and Kotlin flows.
*/
@ExperimentalCoroutinesApi
fun heartRateMeasureFlow() = callbackFlow {
val callback = object : MeasureCallback {
override fun onAvailabilityChanged(dataType: DeltaDataType<*, *>, availability: Availability) {
// Only send back DataTypeAvailability (not LocationAvailability)
if (availability is DataTypeAvailability) {
trySendBlocking(MeasureMessage.MeasureAvailability(availability))
}
}
override fun onDataReceived(data: DataPointContainer) {
val heartRateBpm = data.getData(DataType.HEART_RATE_BPM)
trySendBlocking(MeasureMessage.MeasureData(heartRateBpm))
}
}
Log.d(TAG, "Registering for data")
measureClient.registerMeasureCallback(DataType.HEART_RATE_BPM, callback)
awaitClose {
Log.d(TAG, "Unregistering for data")
runBlocking {
measureClient.unregisterMeasureCallbackAsync(DataType.HEART_RATE_BPM, callback)
}
}
}
}
sealed class MeasureMessage {
class MeasureAvailability(val availability: DataTypeAvailability) : MeasureMessage()
class MeasureData(val data: List<SampleDataPoint<Double>>): MeasureMessage()
}
| apache-2.0 | 08a29c48af38bbbd121f27575b6e1b9a | 38.463415 | 107 | 0.723424 | 4.91047 | false | false | false | false |
hannesa2/owncloud-android | owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalShareDataSourceTest.kt | 2 | 10083 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program 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.
*
* 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.owncloud.android.data.shares.datasources
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import com.owncloud.android.data.OwncloudDatabase
import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLocalShareDataSource
import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLocalShareDataSource.Companion.toEntity
import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLocalShareDataSource.Companion.toModel
import com.owncloud.android.data.sharing.shares.db.OCShareDao
import com.owncloud.android.data.sharing.shares.db.OCShareEntity
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.testutil.OC_ACCOUNT_NAME
import com.owncloud.android.testutil.OC_PRIVATE_SHARE
import com.owncloud.android.testutil.OC_PUBLIC_SHARE
import com.owncloud.android.testutil.OC_SHARE
import com.owncloud.android.testutil.livedata.getLastEmittedValue
import io.mockk.every
import io.mockk.mockkClass
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class OCLocalShareDataSourceTest {
private lateinit var ocLocalSharesDataSource: OCLocalShareDataSource
private val ocSharesDao = mockkClass(OCShareDao::class)
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@Before
fun init() {
val db = mockkClass(OwncloudDatabase::class)
every {
db.shareDao()
} returns ocSharesDao
ocLocalSharesDataSource =
OCLocalShareDataSource(
ocSharesDao,
)
}
/******************************************************************************************************
******************************************* PRIVATE SHARES *******************************************
******************************************************************************************************/
private val privateShares = listOf(
OC_PRIVATE_SHARE.copy(
path = "/Docs/doc1.doc",
shareWith = "username",
sharedWithDisplayName = "Sophie"
).toEntity(),
OC_PRIVATE_SHARE.copy(
path = "/Docs/doc1.doc",
shareWith = "user.name",
sharedWithDisplayName = "Nicole"
).toEntity()
)
private val privateShareTypes = listOf(ShareType.USER, ShareType.GROUP, ShareType.FEDERATED)
@Test
fun readLocalPrivateShares() {
val privateSharesAsLiveData: MutableLiveData<List<OCShareEntity>> = MutableLiveData()
privateSharesAsLiveData.value = privateShares
every {
ocSharesDao.getSharesAsLiveData(
"/Docs/doc1.doc",
"admin@server",
privateShareTypes.map { it.value })
} returns privateSharesAsLiveData
val shares =
ocLocalSharesDataSource.getSharesAsLiveData(
"/Docs/doc1.doc", "admin@server", privateShareTypes
).getLastEmittedValue()!!
assertEquals(2, shares.size)
assertEquals("/Docs/doc1.doc", shares.first().path)
assertEquals(false, shares.first().isFolder)
assertEquals("username", shares.first().shareWith)
assertEquals("Sophie", shares.first().sharedWithDisplayName)
assertEquals("/Docs/doc1.doc", shares[1].path)
assertEquals(false, shares[1].isFolder)
assertEquals("user.name", shares[1].shareWith)
assertEquals("Nicole", shares[1].sharedWithDisplayName)
}
@Test
fun readLocalPrivateShare() {
val privateShareAsLiveData: MutableLiveData<OCShareEntity> = MutableLiveData()
privateShareAsLiveData.value = privateShares.first()
every { ocSharesDao.getShareAsLiveData(OC_SHARE.remoteId) } returns privateShareAsLiveData
val share = ocLocalSharesDataSource.getShareAsLiveData(OC_SHARE.remoteId).getLastEmittedValue()!!
assertEquals("/Docs/doc1.doc", share.path)
assertEquals(false, share.isFolder)
assertEquals("username", share.shareWith)
assertEquals("Sophie", share.sharedWithDisplayName)
}
@Test
fun insertPrivateShares() {
every { ocSharesDao.insert(privateShares[0]) } returns 10
val insertedShareId = ocLocalSharesDataSource.insert(
OC_PRIVATE_SHARE.copy(
path = "/Docs/doc1.doc",
shareWith = "username",
sharedWithDisplayName = "Sophie"
)
)
assertEquals(10, insertedShareId)
}
@Test
fun updatePrivateShare() {
every { ocSharesDao.update(privateShares[1]) } returns 3
val updatedShareId = ocLocalSharesDataSource.update(
OC_PRIVATE_SHARE.copy(
path = "/Docs/doc1.doc",
shareWith = "user.name",
sharedWithDisplayName = "Nicole"
)
)
assertEquals(3, updatedShareId)
}
/******************************************************************************************************
******************************************* PUBLIC SHARES ********************************************
******************************************************************************************************/
private val publicShares = listOf(
OC_PUBLIC_SHARE.copy(
path = "/Photos/",
isFolder = true,
name = "Photos link",
shareLink = "http://server:port/s/1"
).toEntity(),
OC_PUBLIC_SHARE.copy(
path = "/Photos/",
isFolder = true,
name = "Photos link 2",
shareLink = "http://server:port/s/2"
).toEntity()
)
@Test
fun readLocalPublicShares() {
val publicSharesAsLiveData: MutableLiveData<List<OCShareEntity>> = MutableLiveData()
publicSharesAsLiveData.value = publicShares
every {
ocSharesDao.getSharesAsLiveData(
"/Photos/",
"admin@server",
listOf(ShareType.PUBLIC_LINK.value)
)
} returns publicSharesAsLiveData
val shares = ocLocalSharesDataSource.getSharesAsLiveData(
"/Photos/",
"admin@server",
listOf(ShareType.PUBLIC_LINK)
).getLastEmittedValue()!!
assertEquals(2, shares.size)
assertEquals("/Photos/", shares.first().path)
assertEquals(true, shares.first().isFolder)
assertEquals("Photos link", shares.first().name)
assertEquals("http://server:port/s/1", shares.first().shareLink)
assertEquals("/Photos/", shares[1].path)
assertEquals(true, shares[1].isFolder)
assertEquals("Photos link 2", shares[1].name)
assertEquals("http://server:port/s/2", shares[1].shareLink)
}
@Test
fun insertPublicShare() {
every { ocSharesDao.insert(publicShares[0]) } returns 7
val insertedShareId = ocLocalSharesDataSource.insert(
OC_PUBLIC_SHARE.copy(
path = "/Photos/",
isFolder = true,
name = "Photos link",
shareLink = "http://server:port/s/1"
)
)
assertEquals(7, insertedShareId)
}
@Test
fun insertPublicShares() {
val expectedValues = listOf<Long>(1, 2)
every { ocSharesDao.insert(publicShares) } returns expectedValues
val retrievedValues = ocLocalSharesDataSource.insert(
publicShares.map { it.toModel() }
)
assertEquals(expectedValues, retrievedValues)
}
@Test
fun updatePublicShares() {
every { ocSharesDao.update(publicShares[1]) } returns 8
val updatedShareId = ocLocalSharesDataSource.update(
OC_PUBLIC_SHARE.copy(
path = "/Photos/",
isFolder = true,
name = "Photos link 2",
shareLink = "http://server:port/s/2"
)
)
assertEquals(8, updatedShareId)
}
/**************************************************************************************************************
*************************************************** COMMON ***************************************************
**************************************************************************************************************/
@Test
fun replaceShares() {
val expectedValues = listOf<Long>(1, 2)
every { ocSharesDao.replaceShares(publicShares) } returns expectedValues
val retrievedValues = ocLocalSharesDataSource.replaceShares(
publicShares.map { it.toModel() }
)
assertEquals(expectedValues, retrievedValues)
}
@Test
fun deleteSharesForFile() {
every { ocSharesDao.deleteSharesForFile("file", OC_ACCOUNT_NAME) } returns Unit
ocLocalSharesDataSource.deleteSharesForFile("file", OC_ACCOUNT_NAME)
verify { ocSharesDao.deleteSharesForFile("file", OC_ACCOUNT_NAME) }
}
@Test
fun deleteShare() {
every { ocSharesDao.deleteShare(OC_SHARE.remoteId) } returns 1
val deletedRows = ocLocalSharesDataSource.deleteShare(OC_SHARE.remoteId)
assertEquals(1, deletedRows)
}
}
| gpl-2.0 | af350d219f73e03f77ff0bca693e2c89 | 34.625442 | 116 | 0.586094 | 4.959174 | false | true | false | false |
codeka/wwmmo | common/src/main/kotlin/au/com/codeka/warworlds/common/net/GzipHelper.kt | 1 | 1132 | package au.com.codeka.warworlds.common.net
import au.com.codeka.warworlds.common.Log
import com.google.common.io.ByteStreams
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
/**
* Helper for working with Gzip compression.
*/
object GzipHelper {
private val log = Log("GzipHelper")
/** Compress the given byte array. */
fun compress(uncompressed: ByteArray?): ByteArray? {
return try {
val outs = ByteArrayOutputStream()
val zip = GZIPOutputStream(outs)
zip.write(uncompressed)
zip.close()
outs.toByteArray()
} catch (e: IOException) {
log.warning("Error compressing byte array.", e)
null
}
}
/** Decompress the given byte array. */
fun decompress(compressed: ByteArray?): ByteArray? {
return try {
val ins = ByteArrayInputStream(compressed)
val zip = GZIPInputStream(ins)
ByteStreams.toByteArray(zip)
} catch (e: IOException) {
log.warning("Error decompressing byte array.", e)
null
}
}
} | mit | 89a166a38cb9665923156866eb20beb0 | 25.97619 | 55 | 0.693463 | 4.161765 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/fixes/AddStructFieldsPatFixTest.kt | 2 | 8391 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import org.rust.MockAdditionalCfgOptions
import org.rust.ide.annotator.RsAnnotatorTestBase
import org.rust.ide.annotator.RsErrorAnnotator
class AddStructFieldsPatFixTest : RsAnnotatorTestBase(RsErrorAnnotator::class) {
fun `test one field missing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
}
fn main() {
let <error>Foo { a, b }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
}
fn main() {
let Foo { a, b, c }/*caret*/ = foo;
}
"""
)
fun `test one field missing with trailing comma`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
}
fn main() {
let <error>Foo { a, b, }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
}
fn main() {
let Foo { a, b, c, }/*caret*/ = foo;
}
"""
)
fun `test missing fields with extra fields existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { a, <error>bar</error>, d }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, bar, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test filling order between 2 last fields existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { b, d }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test filling order between first and last fields existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { a, d }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test filling order with the first field existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { a }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test filling order with the second field existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { b }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test filling order with the third field existing`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let <error>Foo { c }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
b: i32,
c: i32,
d: i32,
}
fn main() {
let Foo { a, b, c, d }/*caret*/ = foo;
}
"""
)
fun `test one field missing in tuple`() = checkFixByText("Add missing fields", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
<error>Foo::Bar(a, b)/*caret*/</error> => {}
}
}
""", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
Foo::Bar(a, b, _0/*caret*/) => {}
}
}
"""
)
fun `test tuple with no fields`() = checkFixByText("Add missing fields", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
<error>Foo::Bar()/*caret*/</error> => {}
}
}
""", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
Foo::Bar(_0/*caret*/, _1, _2) => {}
}
}
"""
)
fun `test tuple with one field with comma`() = checkFixByText("Add missing fields", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
<error>Foo::Bar(a,)/*caret*/</error> => {}
}
}
""", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
Foo::Bar(a, _0/*caret*/, _1, ) => {}
}
}
"""
)
fun `test tuple with one field without comma`() = checkFixByText("Add missing fields", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
<error>Foo::Bar(a)/*caret*/</error> => {}
}
}
""", """
enum Foo {
Bar(i32, i32, i32)
}
fn main() {
let x = Foo::Bar(1, 2, 3);
match x {
Foo::Bar(a, _0/*caret*/, _1) => {}
}
}
"""
)
@MockAdditionalCfgOptions("intellij_rust")
fun `test field with cfg attribute`() = checkFixByText("Add missing fields", """
struct Foo {
a: i32,
#[cfg(intellij_rust)]
b: i32,
}
fn main() {
let <error>Foo { a }/*caret*/</error> = foo;
}
""", """
struct Foo {
a: i32,
#[cfg(intellij_rust)]
b: i32,
}
fn main() {
let Foo { a, b }/*caret*/ = foo;
}
"""
)
fun `test raw field name 1`() = checkFixByText("Add missing fields", """
struct S {
r#enum: i32,
r#type: u8
}
fn match_something(s: S) {
match s {
<error>S { }/*caret*/</error> => {}
}
}
""", """
struct S {
r#enum: i32,
r#type: u8
}
fn match_something(s: S) {
match s {
S { r#enum, r#type }/*caret*/ => {}
}
}
""")
fun `test raw field name 2`() = checkFixByText("Add missing fields", """
struct S {
r#enum: i32,
r#type: u8
}
fn match_something(s: S) {
match s {
<error>S { r#enum }/*caret*/</error> => {}
}
}
""", """
struct S {
r#enum: i32,
r#type: u8
}
fn match_something(s: S) {
match s {
S { r#enum, r#type }/*caret*/ => {}
}
}
""")
}
| mit | def6ed07046a562e7c1a07ca9056ea45 | 22.70339 | 112 | 0.359433 | 3.924696 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.