repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
charbgr/CliffHanger
cliffhanger/arch/src/test/kotlin/com/github/charbgr/arch/MviPresenterTest.kt
1
887
package com.github.charbgr.arch import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import org.junit.Test import kotlin.test.assertTrue class MviPresenterTest { @Test fun test_creating_null_intent() { val presenter = TestPresenter() presenter.init(TestView) assertTrue(presenter.addIntent(null) == Observable.empty<Any>()) } @Test fun test_creating_intent() { val presenter = TestPresenter() presenter.init(TestView) val observable = PublishSubject.create<Unit>().hide() assertTrue(presenter.addIntent(observable) == observable) } private object TestView : View private class TestPresenter : MviPresenter<TestView, Unit>() { fun addIntent(observable: Observable<*>?): Observable<*> = intent(observable) override fun bindIntents() {} override fun renders(): Observable<Unit> = Observable.empty() } }
mit
f03f23a8c56f78456f7a43f7b0096489
25.878788
81
0.726043
4.22381
false
true
false
false
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/teams/TeamsEntity.kt
1
435
package com.waz.zclient.storage.db.teams import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "Teams") data class TeamsEntity( @PrimaryKey @ColumnInfo(name = "_id") val teamId: String, @ColumnInfo(name = "name") val teamName: String, @ColumnInfo(name = "creator") val creatorId: String, @ColumnInfo(name = "icon") val iconId: String )
gpl-3.0
2d90d9015ea51f8b1168e4f964b47991
19.714286
40
0.694253
3.75
false
false
false
false
toastkidjp/Jitte
music/src/main/java/jp/toastkid/media/music/notification/NotificationFactory.kt
1
4345
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.media.music.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.media.session.MediaButtonReceiver import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.media.R import jp.toastkid.media.music.AlbumArtFinder /** * @author toastkidjp */ class NotificationFactory( private val context: Context, private val mediaSessionSupplier: () -> MediaSessionCompat ) { private val preferenceApplier = PreferenceApplier(context) private val albumArtFinder = AlbumArtFinder(context.contentResolver) private val pauseAction = NotificationCompat.Action( R.drawable.ic_pause, context.getString(R.string.action_pause), MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PAUSE) ) private val playAction = NotificationCompat.Action( R.drawable.ic_play_media, context.getString(R.string.action_play), MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY) ) operator fun invoke(): Notification? { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel() } val currentDescription = mediaSessionSupplier().controller?.metadata?.description ?: return null val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) .setStyle(androidx.media.app.NotificationCompat.MediaStyle() .setMediaSession(mediaSessionSupplier().sessionToken) .setShowActionsInCompactView(0, 1) ) .setColor(preferenceApplier.color) .setSmallIcon(R.drawable.ic_music) .setLargeIcon(currentDescription.iconUri?.let { albumArtFinder(it) }) .setContentTitle(currentDescription.title) .setContentText(currentDescription.subtitle) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setDeleteIntent( MediaButtonReceiver.buildMediaButtonPendingIntent( context, PlaybackStateCompat.ACTION_STOP ) ) notificationBuilder.addAction(if (isPlaying()) pauseAction else playAction) notificationBuilder.addAction( R.drawable.ic_music, context.getString(R.string.display), PendingIntent.getBroadcast( context, 23, Intent("jp.toastkid.music.action.open"), PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE ) ) return notificationBuilder.build() } private fun isPlaying() = mediaSessionSupplier().controller.playbackState.state == PlaybackStateCompat.STATE_PLAYING @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel() { val manager: NotificationManager? = context.getSystemService(NotificationManager::class.java) if (manager?.getNotificationChannel(CHANNEL_ID) == null) { val channel = NotificationChannel( CHANNEL_ID, context.getString(R.string.title_audio_player), NotificationManager.IMPORTANCE_LOW ).also { it.description = context.getString(R.string.title_audio_player) } manager?.createNotificationChannel(channel) } } companion object { private const val CHANNEL_ID = "music" } }
epl-1.0
4bc54b6fc5643e9cc28ad6697e3833c6
38.509091
104
0.669505
5.279465
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/database/converter/LocalDateTimeBpConverter.kt
1
2646
/* * Copyright 2016 requery.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.xpece.android.database.converter import io.requery.Converter import net.xpece.android.time.toLocalDateTime import net.xpece.android.time.toSqlTimestamp import org.threeten.bp.LocalDateTime import java.sql.Timestamp /** * Converts from a [LocalDateTime] to a [T]. */ abstract class LocalDateTimeBpConverter<T> : Converter<LocalDateTime, T> { override fun getMappedType(): Class<LocalDateTime> { return LocalDateTime::class.java } override fun getPersistedSize(): Int? { return null } /** * Converts from a [LocalDateTime] to a [String]. * Can be compared as long as year is in range of 0 to 9999. */ object WithString : LocalDateTimeBpConverter<String>() { override fun getPersistedType(): Class<String> { return String::class.java } override fun convertToPersisted(value: LocalDateTime?): String? { if (value == null) { return null } return value.toString() } override fun convertToMapped(type: Class<out LocalDateTime>?, value: String?): LocalDateTime? { if (value == null) { return null } return LocalDateTime.parse(value) } } /** * Converts from a [LocalDateTime] to a [Timestamp]. * Safe to use since requery-1.0.0. */ object WithTimestamp : LocalDateTimeBpConverter<Timestamp>() { override fun getPersistedType(): Class<Timestamp> { return Timestamp::class.java } override fun convertToPersisted(value: LocalDateTime?): Timestamp? { if (value == null) { return null } return value.toSqlTimestamp() } override fun convertToMapped(type: Class<out LocalDateTime>, value: Timestamp?): LocalDateTime? { if (value == null) { return null } return value.toLocalDateTime() } } }
apache-2.0
33fb83f270985f6c76eb891e84d91734
29.413793
103
0.620559
4.666667
false
false
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2021/Day9.kt
1
3140
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.mul import java.awt.Color import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO /** * --- Day 9: Smoke Basin --- * https://adventofcode.com/2021/day/9 */ class Day9 : Solver { override fun solve(lines: List<String>): Result { val input = PuzzleInput(lines) var partA = 0 for (x in 0 until input.width) { for (y in 0 until input.height) { val pos = XY(x, y) val elevation = input.height(pos) val adjacent = pos.adjacent().map { input.height(it) }.toSet() if (elevation < adjacent.min()!!) { partA += elevation + 1 } } } // Calculate which positions flow directly into which other. val flownInto = mutableMapOf<XY, MutableSet<XY>>() for (x in 0 until input.width) { for (y in 0 until input.height) { val pos = XY(x, y) flownInto[pos] = mutableSetOf() val elevation = input.height(pos) val checkCandidate = { p: XY -> val neighbor = input.height(p) if (neighbor in (elevation + 1)..8) flownInto[pos]!!.add(p) } pos.adjacent().forEach { checkCandidate(it) } } } // Group basins together by recursively combining flows. val flownIntoResult = flownInto.keys.associateWith { allThatFlowInto(it, flownInto) } // Take top 3 sizes and multiply them together. val partB = flownIntoResult.map { it.value.size }.sortedDescending().take(3).mul() writeImage(input, flownIntoResult) return Result("$partA", "$partB") } /** Recursively get a complete list of all that flows into 'pos'. */ private fun allThatFlowInto(pos: XY, flownInto: Map<XY, MutableSet<XY>>): MutableSet<XY> { // First add itself, then recursively everything else that flows into it. val result = mutableSetOf(pos) for (flowsInto in flownInto[pos]!!) { result.addAll(allThatFlowInto(flowsInto, flownInto)) } return result } // Just for fun... private fun writeImage(puzzle: PuzzleInput, basins: Map<XY, Set<XY>>) { val winningPositions = basins.map { it.value }.sortedByDescending { it.size }.take(3).flatten().toSet() val img = BufferedImage(puzzle.width, puzzle.height, BufferedImage.TYPE_INT_RGB) for (x in 0 until puzzle.width) { for (y in 0 until puzzle.height) { val hue = if (winningPositions.contains(XY(x, y))) 1f else 0.5f img.setRGB(x, y, Color.HSBtoRGB(hue, 1f, 1f - puzzle.height(XY(x, y)) / 9f)) } } val file = File("Day9.png") println(file.absolutePath) ImageIO.write(img, "png", file) } } private data class XY(val x: Int, val y: Int) private fun XY.adjacent() = setOf(XY(x - 1, y), XY(x + 1, y), XY(x, y + 1), XY(x, y - 1)) private class PuzzleInput(lines_: List<String>) { val lines = lines_ val width = lines[0].length val height = lines.size fun height(pos: XY): Int { if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) return Int.MAX_VALUE return lines[pos.y][pos.x].toString().toInt() } }
apache-2.0
2af4732801ba2099909e2aded8e8077c
32.414894
107
0.633758
3.358289
false
false
false
false
kory33/SignVote
src/main/kotlin/com/github/kory33/signvote/session/VoteSession.kt
1
11463
package com.github.kory33.signvote.session import com.github.kory33.chatgui.util.collection.BijectiveHashMap import com.github.kory33.signvote.constants.* import com.github.kory33.signvote.exception.* import com.github.kory33.signvote.manager.VoteLimitManager import com.github.kory33.signvote.manager.vote.VoteManager import com.github.kory33.signvote.utils.FileUtils import com.github.kory33.signvote.vote.Limit import com.github.kory33.signvote.vote.VotePoint import com.github.kory33.signvote.vote.VoteScore import com.google.gson.JsonObject import org.bukkit.Bukkit import org.bukkit.block.Sign import org.bukkit.entity.Player import java.io.File import java.io.IOException import java.util.concurrent.CompletableFuture import java.util.logging.Level class VoteSession { private val signMap: BijectiveHashMap<Sign, VotePoint> private val votePointNameMap: BijectiveHashMap<String, VotePoint> val voteLimitManager: VoteLimitManager val name: String val voteManager: VoteManager var isOpen: Boolean = false /** * Constructs the vote session from the given session folder * @param sessionSaveLocation directory from which session data is read * * * @throws IllegalArgumentException when the session folder is invalid */ @Throws(IllegalArgumentException::class, IOException::class) constructor(sessionSaveLocation: File) { this.signMap = BijectiveHashMap<Sign, VotePoint>() this.votePointNameMap = BijectiveHashMap<String, VotePoint>() // read information of this vote session val sessionDataFile = File(sessionSaveLocation, FilePaths.SESSION_DATA_FILENAME) val sessionConfigJson = FileUtils.readJSON(sessionDataFile) val voteLimitsJsonArray = sessionConfigJson .get(VoteSessionDataFileKeys.VOTE_SCORE_LIMITS) .asJsonArray this.voteLimitManager = VoteLimitManager.fromJsonArray(voteLimitsJsonArray) this.name = sessionConfigJson.get(VoteSessionDataFileKeys.NAME).asString this.isOpen = sessionConfigJson.get(VoteSessionDataFileKeys.IS_OPEN).asBoolean // load all the saved votepoints val votePointDirectory = File(sessionSaveLocation, FilePaths.VOTE_POINTS_DIR) FileUtils.getFileListStream(votePointDirectory).forEach( { this.addVotePoint(it) }) // initialize vote manager this.voteManager = VoteManager(File(sessionSaveLocation, FilePaths.VOTE_DATA_DIR), this) } /** * Constructs the vote session from its parameters. * @param sessionName name of the session */ constructor(sessionName: String) { this.name = sessionName this.voteLimitManager = VoteLimitManager() this.voteManager = VoteManager(this) this.signMap = BijectiveHashMap<Sign, VotePoint>() this.votePointNameMap = BijectiveHashMap<String, VotePoint>() this.isOpen = true } /** * Load a votepoint from the existing votepoint data file. * @param votePointFIle file which contains information about vote point */ private fun addVotePoint(votePointFIle: File) { try { val votePoint = VotePoint(votePointFIle) this.addVotePoint(votePoint) } catch (e: Exception) { Bukkit.getLogger().log(Level.SEVERE, "", e) } } /** * add a vote point to the session * @param votePoint vote point */ fun addVotePoint(votePoint: VotePoint) { this.signMap.put(votePoint.voteSign, votePoint) this.votePointNameMap.put(votePoint.name, votePoint) } /** * Get Json object containing information directly related to this object * @return json object containing information about session */ private fun toJson(): JsonObject { val jsonObject = JsonObject() jsonObject.addProperty(VoteSessionDataFileKeys.NAME, this.name) jsonObject.add(VoteSessionDataFileKeys.VOTE_SCORE_LIMITS, this.voteLimitManager.toJsonArray()) jsonObject.addProperty(VoteSessionDataFileKeys.IS_OPEN, this.isOpen) return jsonObject } /** * purge non-registered votepoint files under a given directory. * @param votePointDirectory directory which contains vote point directory */ private fun purgeInvalidVpFiles(votePointDirectory: File) { val nonExistentVpFiles = FileUtils.getFileListStream(votePointDirectory).filter { file -> val matcher = Patterns.JSON_FILE_NAME.matcher(file.name) !matcher.find() || !this.votePointNameMap.containsKey(matcher.group(1)) } CompletableFuture.runAsync { nonExistentVpFiles.forEach { file -> println("Deleting " + file.name) file.delete() } } } /** * Save the session data to the given directory. * @param sessionSaveLocation location to which session data is saved * * * @throws IOException when any error occurs whilst saving files */ @Throws(IOException::class) fun saveTo(sessionSaveLocation: File) { if (!sessionSaveLocation.exists() && !sessionSaveLocation.mkdirs()) { throw IOException("Failed to create vote session save directory!") } else if (!sessionSaveLocation.isDirectory) { throw IOException("Vote session was about to be saved into a file! (" + sessionSaveLocation.absolutePath + ")") } // initialize vote point dir val votePointDirectory = File(sessionSaveLocation, FilePaths.VOTE_POINTS_DIR) if (!votePointDirectory.exists() && !votePointDirectory.mkdirs()) { throw IOException("Failed to create vote point save directory!") } this.purgeInvalidVpFiles(votePointDirectory) // save vote points signMap.getInverse().keys.stream().parallel() .forEach { votePoint -> val saveTarget = File(votePointDirectory, votePoint.name + Formats.JSON_EXT) FileUtils.writeJSON(saveTarget, votePoint.toJson()) } // save vote data val voteDataDirectory = File(sessionSaveLocation, FilePaths.VOTE_DATA_DIR) if (!voteDataDirectory.exists() && !voteDataDirectory.mkdirs()) { throw IOException("Failed to create vote data directory!") } this.voteManager.playersVoteData.forEach { playerUUID, voteData -> val playerVoteDataFile = File(voteDataDirectory, playerUUID.toString() + Formats.JSON_EXT) FileUtils.writeJSON(playerVoteDataFile, voteData) } // write session data val sessionDataFile = File(sessionSaveLocation, FilePaths.SESSION_DATA_FILENAME) val jsonData = this.toJson() FileUtils.writeJSON(sessionDataFile, jsonData) } /** * Get a VotePoint associated with a given Sign. * @param sign vote point sign * * * @return vote point instance associated with sign, null if sign is not a vote point */ fun getVotePoint(sign: Sign): VotePoint? { return this.signMap[sign] } fun getVotePoint(pointName: String): VotePoint? { return this.votePointNameMap[pointName] } /** * Get a score -> count map of available votes for a given player * @param player player instance * * * @return map of score -> reserved limit * * limit is an optional with limit value, empty if infinite number of votes can be casted */ fun getAvailableVoteCounts(player: Player): Map<VoteScore, Limit> { val availableCounts = this.getReservedVoteCounts(player).toMutableMap() val votedScoreCounts = this.voteManager.getVotedPointsCount(player.uniqueId) votedScoreCounts.forEach { score, votedNum -> if (!availableCounts.containsKey(score)) { return@forEach } val reservedVotes = availableCounts.remove(score)!! val remainingVotes = reservedVotes - votedNum // iff remaining != 0 if (!remainingVotes.isZero) { availableCounts.put(score, remainingVotes) } } return availableCounts } /** * Get a score -> count map of reserved votes for a given player * @param player player instance * * * @return map of score -> available limit * * limit is an optional with limit value, empty if infinite number of votes can be casted */ fun getReservedVoteCounts(player: Player): Map<VoteScore, Limit> { return this.voteLimitManager.getLimitSet(player) } /** * Make a vote to the specified votepoint with a given score. * Score has to be checked for it's validity, * but may not be checked for player vote limits as an exception is thrown * @param player player who is attempting to vote * * * @param votePoint vote point to which the player is attempting to vote * * * @param voteScore score of vote which the player is attempting to cast * * * * * @throws ScoreCountLimitReachedException when the player can no longer vote with the given score due to the limit * * * @throws VotePointAlreadyVotedException when the player has already voted to the votepoint * * * @throws VoteSessionClosedException when this vote session is closed */ @Throws(ScoreCountLimitReachedException::class, VotePointAlreadyVotedException::class, InvalidScoreVotedException::class, VoteSessionClosedException::class) fun vote(player: Player, votePoint: VotePoint, voteScore: VoteScore) { if (this.voteLimitManager.getLimit(voteScore, player).isZero) { throw InvalidScoreVotedException(votePoint, player, voteScore) } if (!this.getReservedVoteCounts(player).containsKey(voteScore)) { throw ScoreCountLimitReachedException(player, votePoint, voteScore) } if (!this.getAvailableVoteCounts(player).containsKey(voteScore)) { throw ScoreCountLimitReachedException(player, votePoint, voteScore) } if (!this.isOpen) { throw VoteSessionClosedException(this) } this.voteManager.addVotePointData(player.uniqueId, voteScore, votePoint) } /** * Cancel a vote to the specified votepoint made by a given player. * @param player player who is trying to cancel a vote * * * @param votePoint vote point from which the vote should be removed * * * @throws VotePointNotVotedException When the player hasn't voted the votepoint. */ @Throws(VotePointNotVotedException::class) fun unvote(player: Player, votePoint: VotePoint) { this.voteManager.removeVote(player.uniqueId, votePoint) } /** * Delete the specified votepoint * @param votePoint target vote point */ fun deleteVotepoint(votePoint: VotePoint) { this.voteManager.removeAllVotes(votePoint) this.votePointNameMap.removeValue(votePoint) val sign = this.signMap.removeValue(votePoint) ?: return sign.setLine(0, SignTexts.REGISTERED_SIGN_TEXT) sign.setLine(1, SignTexts.DELETED) sign.setLine(2, "") sign.update() } /** * Get all the votepoints registered to this vote session */ val allVotePoints: Set<VotePoint> get() = this.votePointNameMap.getInverse().keys }
gpl-3.0
0010098f64ad494096031af1658d3c03
36.583607
160
0.677484
4.455111
false
false
false
false
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/io/fileWatchUtils.kt
1
1505
package cz.softdeluxe.jlib.io import com.sun.nio.file.SensitivityWatchEventModifier import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.nio.file.* import kotlin.coroutines.experimental.buildSequence data class FileWatchEventDto(val file: File, val event: WatchEvent.Kind<*>) /** * * @author balat */ fun fileWatch(directory: File, events: Array<WatchEvent.Kind<*>> = arrayOf(StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE), sensitive: SensitivityWatchEventModifier = SensitivityWatchEventModifier.LOW, logger: Logger = LoggerFactory.getLogger("fileWatchUtils")): Sequence<FileWatchEventDto> { val directoryPath: Path = directory.directory.toPath() logger.info("Spuštím file watcher pro adresář $directoryPath") val wather: WatchService = directoryPath.fileSystem.newWatchService() directoryPath.register(wather, events, sensitive) // wather.close() return buildSequence { while (true) { val key: WatchKey = wather.take() for (event: WatchEvent<*> in key.pollEvents()) { val path = event.context() as Path val file: File = path.toFile().absoluteFile val eventDto = FileWatchEventDto(file, event.kind()) yield(eventDto) } if (!key.reset()) break } } }
apache-2.0
3b7803802b3660facb1fee72107209e0
34.738095
104
0.660227
4.480597
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/PollFrequencyPreferenceView.kt
1
1870
package com.garpr.android.features.settings import android.content.Context import android.content.DialogInterface import android.util.AttributeSet import android.view.View import androidx.appcompat.app.AlertDialog import com.garpr.android.R import com.garpr.android.data.models.PollFrequency import com.garpr.android.features.common.views.SimplePreferenceView class PollFrequencyPreferenceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : SimplePreferenceView(context, attrs), DialogInterface.OnClickListener, View.OnClickListener { var listener: Listener? = null private var pollFrequency: PollFrequency? = null interface Listener { fun onPollFrequencyChange(v: PollFrequencyPreferenceView, pollFrequency: PollFrequency) } init { titleText = context.getText(R.string.poll_frequency) setOnClickListener(this) if (isInEditMode) { descriptionText = context.getText(R.string.every_3_days) } } override fun onClick(dialog: DialogInterface, which: Int) { dialog.dismiss() val selected = PollFrequency.values()[which] if (pollFrequency != selected) { listener?.onPollFrequencyChange(this, selected) } } override fun onClick(v: View) { val items = PollFrequency.values() .map { resources.getText(it.textResId) } .toTypedArray() val checkedItem = checkNotNull(pollFrequency).ordinal AlertDialog.Builder(context) .setSingleChoiceItems(items, checkedItem, this) .setTitle(R.string.poll_frequency) .show() } fun setContent(pollFrequency: PollFrequency) { this.pollFrequency = pollFrequency descriptionText = resources.getText(pollFrequency.textResId) } }
unlicense
e0bf70cbeff11d1dc912e151b3dddc3f
29.655738
97
0.688235
4.734177
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/ability/MoveAbility.kt
1
6637
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity.ability import com.badlogic.ashley.core.Entity import com.badlogic.gdx.ai.pfa.Connection import com.badlogic.gdx.ai.pfa.DefaultGraphPath import com.badlogic.gdx.ai.pfa.indexed.IndexedAStarPathFinder import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.graphics.g2d.TextureRegion import com.jupiter.europa.EuropaGame import com.jupiter.europa.entity.Families import com.jupiter.europa.entity.Mappers import com.jupiter.europa.entity.MovementSystem import com.jupiter.europa.entity.behavior.Heuristics import com.jupiter.europa.entity.messaging.InputRequestMessage import com.jupiter.europa.entity.messaging.Message import com.jupiter.europa.entity.messaging.WalkCompleteMessage import com.jupiter.europa.entity.messaging.WalkRequestMessage import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.io.FileLocations import com.jupiter.europa.world.Level import com.jupiter.ganymede.event.Listener import java.awt.Point import java.awt.Rectangle import kotlin.properties.Delegates /** * Created by nathan on 5/21/15. */ public class MoveAbility(private val entity: Entity) : Ability { override val action: MoveAction init { this.action = MoveAction(this.entity) } // Public Methods override val name: String = NAME override val description: String = DESCRIPTION override val cost: Cost = COST override val category: AbilityCategory = BasicAbilityCategories.ALL_ABILITIES override val icon: TextureRegion = ICON // Inner Classes public class MoveAction internal constructor(entity: Entity) : Action(entity) { override val targets: List<(Level, Point) -> Boolean> = listOf( { level, point -> if (!level.contains(Rectangle(point.x, point.y, 1, 1))) { false } else { val pointUnder = Mappers.position[this.entity].tilePosition val pathFinder = IndexedAStarPathFinder<Level.LevelSquare>(level) val path = DefaultGraphPath<Connection<Level.LevelSquare>>() val found = pathFinder.searchConnectionPath(level.getSquare(pointUnder), level.getSquare(point), Heuristics.CITY_BLOCK, path ) found && path.getCount() <= if (Families.attributed.matches(entity)) { Mappers.attributes[entity].currentAttributes[AttributeSet.Attributes.MOVEMENT_SPEED] } else { 1 } } } ) override fun apply(targets: List<Point>) { val walkTo = targets[0] val comp = Mappers.position[this.entity] val level = comp.level ?: return val currentPoint = comp.tilePosition val pathFinder = IndexedAStarPathFinder<Level.LevelSquare>(level) val path = DefaultGraphPath<Connection<Level.LevelSquare>>() val found = pathFinder.searchConnectionPath(level.getSquare(currentPoint), level.getSquare(walkTo), Heuristics.CITY_BLOCK, path) if (found && path.nodes.size > 0) { EuropaGame.game.messageSystem.publish(InputRequestMessage(InputRequestMessage.InputRequests.NONE)) MoveManager(path, this.entity, { this.complete() }).start() } else { this.complete() } } protected class MoveManager(private val path: DefaultGraphPath<Connection<Level.LevelSquare>>, private val entity: Entity, private val onComplete: () -> Unit) : Listener<Message> { private var position: Int = 0 public fun start() { EuropaGame.game.messageSystem.subscribe(this, javaClass<WalkCompleteMessage>()) this.move(this.path.nodes[this.position]) } public override fun handle(message: Message) { if (message is WalkCompleteMessage && message.entity === this.entity) { this.position++ if (this.position < this.path.nodes.size) { this.move(this.path.nodes[this.position]) } else { this.complete() } } } private fun move(connection: Connection<Level.LevelSquare>) { val first = connection.getFromNode() val second = connection.getToNode() val direction = MovementSystem.MovementDirections.getSingleStepDirectionFor(second.x - first.x, second.y - first.y) ?: return this.complete() // If we can't move, exit EuropaGame.game.messageSystem.publish(WalkRequestMessage(this.entity, direction)) } private fun complete() { EuropaGame.game.messageSystem.unsubscribe(this, javaClass<WalkCompleteMessage>()) this.onComplete.invoke() } } } companion object { private val NAME = "Move" private val DESCRIPTION = "Move to a location within range." private val ICON_NAME = "move" private val COST = Cost.NONE private val ICON by Delegates.lazy { EuropaGame.game.assetManager!!.get(FileLocations.ICON_ATLAS, javaClass<TextureAtlas>()).findRegion(ICON_NAME) } } }
mit
c87f97a247c01b874901aefe18eae1d1
42.664474
188
0.64939
4.657544
false
false
false
false
JimSeker/ui
RecyclerViews/CallBacksItemViewDemo_kt/app/src/main/java/edu/cs4730/callbacksitemviewdemo_kt/myAdapter.kt
1
3345
package edu.cs4730.callbacksitemviewdemo_kt import android.content.Context import android.util.Log import androidx.recyclerview.widget.RecyclerView import android.widget.TextView import android.view.ViewGroup import android.view.LayoutInflater import android.view.View /** * * This code has a listeners defined in the class and ViewHolder class, so that a piece of data * can be passed all the way back to the mainActivity (via the fragment) * * Instead of needing a button, we can use the itemview and set a listener for it. Note, * we didn't make the layout clickable or focusable either. see * itemView.setOnClickListener(new View.OnClickListener() { in the viewvholder. */ class myAdapter //constructor ( var myList: List<String>?, private val rowLayout: Int, //for things like a toast or other things that need context. private val mContext: Context ) : RecyclerView.Adapter<myAdapter.ViewHolder>() { private val TAG = "myAdapter" // Define listener member variable private var listener: OnItemClickListener? = null // Define the listener interface interface OnItemClickListener { fun onItemClick(itemView: View, id: String) } // Define the method that allows the parent activity or fragment to define the listener fun setOnItemClickListener(listener: OnItemClickListener?) { this.listener = listener } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder class ViewHolder(view: View, mlistener: OnItemClickListener?) : RecyclerView.ViewHolder(view) { var mName: TextView private val TAG = "ViewHolder" init { mName = view.findViewById<View>(R.id.name) as TextView /** * this setups a clicklistener on the whole layout. Be careful with buttons, because * this is taking the "click". */ itemView.setOnClickListener { // Triggers click upwards to the adapter on click if (mlistener != null) { Log.v(TAG, "Listener at $TAG") mlistener.onItemClick(itemView, mName.tag.toString()) } } } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(rowLayout, viewGroup, false) return ViewHolder(v, listener) } // Replace the contents of a view (invoked by the layout manager) override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) { val entry = myList!![i] viewHolder.mName.text = entry //below sets some data into the "tag" field. The row id in this case, maybe the _id for the database or //id of the rest service etc. tag is pretty generic, so you can put a lot in here. viewHolder.mName.tag = i //sample data to show, this is the row id of the list, which is well the same as position in this case. } // Return the size of your dataset (invoked by the layout manager) override fun getItemCount(): Int { return if (myList == null) 0 else myList!!.size } }
apache-2.0
4cedd1d8172993c66ee3253a577b3880
39.313253
117
0.673543
4.607438
false
false
false
false
kvnxiao/kommandant
kommandant-core/src/main/kotlin/com/github/kvnxiao/kommandant/command/CommandProperties.kt
2
2056
/* * Copyright 2017 Ze Hao Xiao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.kvnxiao.kommandant.command /** * A data class containing the properties of the command. * * @property[prefix] The command's prefix. Defaults to [CommandDefaults.PREFIX]. * @property[uniqueName] The command's unique name / identifier. * @property[description] The command's description. Defaults to [CommandDefaults.NO_DESCRIPTION]. * @property[usage] The command's usage information. Defaults to [CommandDefaults.NO_USAGE]. * @property[execWithSubcommands] Specifies whether to execute the command alongside its subcommands. Defaults to [CommandDefaults.EXEC_WITH_SUBCOMMANDS]. * @property[disabled] Specifies whether the command is disabled or not. Defaults to [CommandDefaults.IS_DISABLED]. * @property[aliases] The command's aliases. Defaults to a singleton list containing the [uniqueName]. */ data class CommandProperties( val prefix: String = CommandDefaults.PREFIX, val uniqueName: String, val description: String = CommandDefaults.NO_DESCRIPTION, val usage: String = CommandDefaults.NO_USAGE, val execWithSubcommands: Boolean = CommandDefaults.EXEC_WITH_SUBCOMMANDS, val disabled: Boolean = CommandDefaults.IS_DISABLED, val aliases: Set<String> = setOf(uniqueName)) { /** * Overrided toString method returns the [uniqueName]. * * @return[uniqueName] The command's unique name / identifier. */ override fun toString(): String { return this.uniqueName } }
apache-2.0
5ff62660903a5aabb80ce0a62420d662
42.765957
154
0.742218
4.440605
false
false
false
false
outadoc/Twistoast-android
twistoast/src/main/kotlin/fr/outadev/twistoast/ActivityMain.kt
1
8840
/* * Twistoast - ActivityMain.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.twistoast import android.app.Fragment import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.util.Log import android.util.SparseArray import android.view.MenuItem import android.view.View import fr.outadev.android.transport.timeo.TimeoRequestHandler import fr.outadev.android.transport.timeo.TimeoTrafficAlert import fr.outadev.twistoast.background.BackgroundTasksManager import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.view_toolbar.* import kotlinx.android.synthetic.main.view_traffic_alert.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * The main activity of the app. * * @author outadoc */ class ActivityMain : ThemedActivity(), IStopsListContainer, NavigationView.OnNavigationItemSelectedListener { private lateinit var drawerToggle: ActionBarDrawerToggle private var currentDrawerItem = 0 private val loadedFragments: SparseArray<Fragment> private var trafficAlert: TimeoTrafficAlert? = null private val requestHandler: TimeoRequestHandler init { requestHandler = TimeoRequestHandler() loadedFragments = SparseArray<Fragment>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Toolbar setSupportActionBar(toolbar) // Drawer config drawerToggle = object : ActionBarDrawerToggle(this, navigationDrawer, toolbar, R.string.drawer_action_open, R.string.drawer_action_close) { override fun onDrawerOpened(drawerView: View) { super.onDrawerOpened(drawerView) } override fun onDrawerClosed(view: View) { super.onDrawerClosed(view) } } navigationDrawer.addDrawerListener(drawerToggle) if (navigationView != null) { navigationView.setNavigationItemSelectedListener(this) } if (intent != null && intent.extras != null && intent.extras.containsKey("show_fragment")) { // Handle app shortcut calls // If we launched the app from a shortcut, show the requested fragment currentDrawerItem = when (intent.extras.getString("show_fragment")) { "realtime" -> R.id.drawer_realtime "timetables" -> R.id.drawer_timetables "routes" -> R.id.drawer_routes "map" -> R.id.drawer_map else -> R.id.drawer_realtime } loadFragmentForDrawerItem(currentDrawerItem) checkForGlobalTrafficInfo() } else if (savedInstanceState != null) { // If we're restoring the instance state // Handle saved variables and check traffic info if needed currentDrawerItem = savedInstanceState.getInt("key_current_drawer_item") trafficAlert = savedInstanceState.get("key_traffic_alert") as TimeoTrafficAlert? displayGlobalTrafficInfo() refreshActionBarTitle() } else { // Default behavior, launch the default fragment currentDrawerItem = DEFAULT_DRAWER_ITEM loadFragmentForDrawerItem(currentDrawerItem) checkForGlobalTrafficInfo() } // Turn the notifications back off if necessary val db = Database(DatabaseOpenHelper()) val config = ConfigurationManager() if (db.watchedStopsCount > 0) { BackgroundTasksManager.enableStopAlarmJob(applicationContext) } if (config.trafficNotificationsEnabled) { BackgroundTasksManager.enableTrafficAlertJob(applicationContext) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) drawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) drawerToggle.onConfigurationChanged(newConfig) } override fun onBackPressed() { val frag = loadedFragments[currentDrawerItem] if (frag is FragmentWebView && frag.canGoBack) { // If we can move back of a page in the browser, do it frag.goBack() } else if (currentDrawerItem == DEFAULT_DRAWER_ITEM) { // If we're on the main screen, just exit super.onBackPressed() } else if (!navigationDrawer.isDrawerOpen(GravityCompat.START)) { // If the drawer isn't opened, open it navigationDrawer.openDrawer(GravityCompat.START) } else { // Otherwise, go back to the main screen loadFragmentForDrawerItem(DEFAULT_DRAWER_ITEM) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("key_current_drawer_item", currentDrawerItem) outState.putSerializable("key_traffic_alert", trafficAlert) } override fun onStart() { super.onStart() displayGlobalTrafficInfo() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item) } override fun endRefresh(success: Boolean) { } override fun onUpdatedStopReferences() { } override val isRefreshing: Boolean get() = false override fun setNoContentViewVisible(visible: Boolean) { } override fun loadFragmentForDrawerItem(itemId: Int) { currentDrawerItem = itemId val fragmentToOpen = loadedFragments[itemId] ?: FragmentFactory.getFragmentFromMenuItem(this, itemId)!! loadedFragments.put(itemId, fragmentToOpen) // Insert the fragment by replacing any existing fragment fragmentManager.beginTransaction().replace(R.id.content_frame, fragmentToOpen).commit() // Highlight the selected item, update the title, and close the drawer refreshActionBarTitle() navigationView.setCheckedItem(currentDrawerItem) navigationDrawer.closeDrawer(GravityCompat.START) } fun refreshActionBarTitle() { val item = navigationView.menu.findItem(currentDrawerItem) ?: return supportActionBar?.title = item.title } /** * Fetches and stores a global traffic info if there is one available. */ private fun checkForGlobalTrafficInfo() { doAsync { val alert = requestHandler.globalTrafficAlert uiThread { trafficAlert = alert displayGlobalTrafficInfo() } } } /** * Displays a global traffic info if one was downloaded by checkForGlobalTrafficInfo. */ private fun displayGlobalTrafficInfo() { if (trafficAlert != null && trafficAlertContainer != null && trafficAlertMessage != null) { Log.i(TAG, trafficAlert.toString()) val url = trafficAlert?.url trafficAlertContainer.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) startActivity(intent) } trafficAlertMessage.text = trafficAlert?.label?.replace("Info Trafic", "")?.trim({ it <= ' ' }) trafficAlertMessage.isSelected = true trafficAlertContainer.visibility = View.VISIBLE } else if (trafficAlertContainer != null) { trafficAlertContainer.visibility = View.GONE } } override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { loadFragmentForDrawerItem(menuItem.itemId) return true } companion object { private val TAG = ActivityMain::class.java.simpleName private val DEFAULT_DRAWER_ITEM = R.id.drawer_realtime } }
gpl-3.0
d762841b6b28d6ef9ea4e51bce6b3df8
34.36
147
0.674774
4.99435
false
false
false
false
Vakosta/Chapper
app/src/main/java/org/chapper/chapper/domain/usecase/NotificationUseCase.kt
1
1744
package org.chapper.chapper.domain.usecase import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.media.RingtoneManager import android.support.v4.app.NotificationCompat import org.chapper.chapper.R import org.chapper.chapper.data.Constants import org.chapper.chapper.presentation.screen.chat.ChatActivity object NotificationUseCase { fun sendNotification(context: Context, chatId: String, title: String, text: String) { val notificationIntent = Intent(context, ChatActivity::class.java) notificationIntent.putExtra(Constants.CHAT_ID_EXTRA, chatId) val contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT) val mBuilder = NotificationCompat.Builder(context) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.message) .setContentTitle(title) .setContentText(text) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(longArrayOf(1000, 250, 250, 250, 250)) .setLights(Color.GREEN, 3000, 3000) .setPriority(Notification.PRIORITY_HIGH) val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(12, mBuilder.build()) } fun cleatAll(context: Context) { val nMgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nMgr.cancelAll() } }
gpl-2.0
e2711c615c582800662314cd1968a050
39.581395
96
0.71445
5.011494
false
false
false
false
strazzere/simplify
sdbg/src/main/java/org/cf/sdbg/command/InfoCommand.kt
2
2214
package org.cf.sdbg.command import picocli.CommandLine import picocli.CommandLine.ParentCommand sealed class InfoTarget data class InfoTargetClass(val classDescriptor: String) : InfoTarget() data class InfoTargetMethod(val methodSignature: String) : InfoTarget() data class InfoTargetRange(val start: Int = -1, val stop: Int? = null) : InfoTarget() object InfoTargetInvalid : InfoTarget() @CommandLine.Command(name = "info", aliases = ["i"], mixinStandardHelpOptions = true, description = ["List information about target"]) class InfoCommand : DebuggerCommand() { @ParentCommand lateinit var parent: CliCommands @CommandLine.Parameters(index = "0", arity = "0..1", paramLabel = "TARGET", description = ["break | breakpoints | registers"]) var target: String? = null private enum class InfoTargetType { REGISTERS, BREAK, INVALID } private fun parseTarget(target: String?): InfoTargetType { return when { target == null -> InfoTargetType.REGISTERS target.toLowerCase() == "registers" -> InfoTargetType.REGISTERS target.toLowerCase() == "break" -> InfoTargetType.BREAK target.toLowerCase() == "breakpoints" -> InfoTargetType.BREAK else -> InfoTargetType.INVALID } } private fun printRegisterInfo() { val currentNode = debugger.currentNode val context = currentNode.context val methodState = context.methodState.toString(false) parent.out.println(methodState) } private fun printBreakInfo() { val breakpoints = debugger.breakpoints.sorted() parent.out.println("breakpoint count=${breakpoints.size}") if (breakpoints.isNotEmpty()) { val lines = breakpoints.joinToString("\n") parent.out.println(lines); } } override fun run() { val parsedTarget = parseTarget(target) when (parsedTarget) { InfoTargetType.REGISTERS -> printRegisterInfo() InfoTargetType.BREAK -> printBreakInfo() InfoTargetType.INVALID -> { parent.out.println("invalid target") return } } } }
mit
43fe0a307b1bb176664a4a1ab60f10e6
34.142857
85
0.64589
4.751073
false
false
false
false
CarrotCodes/Pellet
server/src/main/kotlin/dev/pellet/server/codec/mime/MediaTypeParser.kt
1
4728
package dev.pellet.server.codec.mime import dev.pellet.server.codec.ParseException import dev.pellet.server.codec.http.HTTPCharacters import dev.pellet.server.extension.isEmptyOrLWS import dev.pellet.server.extension.removeSurrounding import dev.pellet.server.extension.trimEndLWS import dev.pellet.server.extension.trimLWS object MediaTypeParser { /** * Parses "media type" strings as per https://www.rfc-editor.org/rfc/inline-errata/rfc7231.html * * Spec: * media-type = type "/" subtype *( OWS ";" OWS parameter ) * type = token * subtype = token * The type/subtype MAY be followed by parameters in the form of * name=value pairs. * parameter = token "=" ( token / quoted-string ) */ fun parse(string: String): Result<MediaType> { if (string.isEmptyOrLWS() || string.length < 3) { return Result.failure( ParseException("empty / malformed media type string") ) } val firstSemicolonIndex = string.indexOf(HTTPCharacters.SEMICOLON) if (firstSemicolonIndex < 0) { // the entire string is the type/subtype part val (type, subtype) = parseTypeSubtype(string).getOrElse { return Result.failure(it) } return Result.success( MediaType( type = type, subtype = subtype, parameters = listOf() ) ) } var currentIndex = 0 val typeSubtypePart = string.substring(currentIndex, firstSemicolonIndex) val (type, subtype) = parseTypeSubtype(typeSubtypePart).getOrElse { return Result.failure(it) } currentIndex += firstSemicolonIndex + 1 val parameters = mutableListOf<Pair<String, String>>() while (currentIndex < string.length) { val nextSemicolonIndex = string.indexOf(HTTPCharacters.SEMICOLON, currentIndex) if (nextSemicolonIndex <= 0) { // no more semicolons/parameters - parse the rest of the string val restOfString = string .substring(currentIndex) .trimLWS() val parameter = parseParameter(restOfString).getOrElse { return Result.failure(it) } parameters += parameter break } val nextParameter = string .substring(currentIndex, nextSemicolonIndex) .trimLWS() val parameter = parseParameter(nextParameter).getOrElse { return Result.failure(it) } parameters += parameter currentIndex = nextSemicolonIndex + 1 } return Result.success( MediaType( type = type, subtype = subtype, parameters = parameters ) ) } private fun parseTypeSubtype(string: String): Result<Pair<String, String>> { val firstSlashPosition = string.indexOf(HTTPCharacters.FORWARD_SLASH) if (firstSlashPosition <= 0 || firstSlashPosition > string.length - 1) { return Result.failure( ParseException("malformed type/subtype") ) } val type = string.substring(0, firstSlashPosition) val subtype = string .substring(firstSlashPosition + 1) .trimEndLWS() if (type.isEmptyOrLWS() || subtype.isEmptyOrLWS()) { return Result.failure( ParseException("malformed type/subtype, empty parts") ) } if (subtype.contains(HTTPCharacters.FORWARD_SLASH)) { return Result.failure( ParseException("malformed subtype, contains /") ) } return Result.success(type to subtype) } private fun parseParameter(string: String): Result<Pair<String, String>> { val firstEqualsPosition = string.indexOf(HTTPCharacters.EQUALS) if (firstEqualsPosition <= 0 || firstEqualsPosition > string.length - 1) { return Result.failure( ParseException("malformed parameter") ) } val key = string.substring(0, firstEqualsPosition) val value = string .substring(firstEqualsPosition + 1) .removeSurrounding(HTTPCharacters.QUOTE) if (key.isEmptyOrLWS() || value.isEmptyOrLWS()) { return Result.failure( ParseException("malformed parameter key or value - lws") ) } return Result.success(key to value) } }
apache-2.0
c5c4ca97748dcaf4473d3ad0f4f57a06
34.818182
99
0.575085
4.961175
false
false
false
false
airien/workbits
android-sunflower-master/app/src/main/java/no/politiet/soip/PlantDetailFragment.kt
1
4077
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.politiet.soip import android.content.Intent import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.app.ShareCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import no.politiet.soip.databinding.FragmentPlantDetailBinding import no.politiet.soip.utilities.InjectorUtils import no.politiet.soip.viewmodels.PlantDetailViewModel /** * A fragment representing a single Plant detail screen. */ class PlantDetailFragment : Fragment() { private lateinit var shareText: String override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val plantId = PlantDetailFragmentArgs.fromBundle(arguments!!).plantId val factory = InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), plantId) val plantDetailViewModel = ViewModelProviders.of(this, factory) .get(PlantDetailViewModel::class.java) val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>( inflater, R.layout.fragment_plant_detail, container, false).apply { viewModel = plantDetailViewModel setLifecycleOwner(this@PlantDetailFragment) fab.setOnClickListener { view -> plantDetailViewModel.addPlantToGarden() Snackbar.make(view, R.string.added_plant_to_garden, Snackbar.LENGTH_LONG).show() } } plantDetailViewModel.plant.observe(this, Observer { plant -> shareText = if (plant == null) { "" } else { getString(R.string.share_text_plant, plant.name) } }) setHasOptionsMenu(true) return binding.root } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_plant_detail, menu) super.onCreateOptionsMenu(menu, inflater) } @Suppress("DEPRECATION") override fun onOptionsItemSelected(item: MenuItem?): Boolean { return when (item?.itemId) { R.id.action_share -> { val shareIntent = ShareCompat.IntentBuilder.from(activity) .setText(shareText) .setType("text/plain") .createChooserIntent() .apply { // https://android-developers.googleblog.com/2012/02/share-with-intents.html if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // If we're on Lollipop, we can open the intent as a document addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) } else { // Else, we will use the old CLEAR_WHEN_TASK_RESET flag addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) } } startActivity(shareIntent) return true } else -> super.onOptionsItemSelected(item) } } }
lgpl-3.0
d08556aa9f60f4635b276f8505c9be7e
36.75
109
0.650233
4.894358
false
false
false
false
benjamingarcia/mifuchi
src/main/kotlin/org/benji/mifuchi/query/FindAllPlayerQueryHandler.kt
1
1162
package org.benji.mifuchi.query import io.reactiverse.reactivex.pgclient.PgPool import io.reactiverse.reactivex.pgclient.PgRowSet import org.benji.mifuchi.common.Query import org.benji.mifuchi.common.QueryHandler import org.benji.mifuchi.domain.CardName import org.benji.mifuchi.domain.Player import org.benji.mifuchi.domain.PlayerColor import org.benji.mifuchi.domain.TreasureName class FindAllPlayerQueryHandler(private val client : PgPool) : QueryHandler<FindAllPlayerQueryResponse> { override fun handle(query: Query): FindAllPlayerQueryResponse { val players = client.rxQuery("SELECT * FROM player").map { t: PgRowSet -> var playerTemp = emptyList<Player>() for (row in t){ val uuid = row.getUUID(0) val name = row.getString(1) val color = PlayerColor.valueOf(row.getString(2)) playerTemp+=playerTemp.plus(Player(uuid, name, color)) } playerTemp }.blockingGet() return FindAllPlayerQueryResponse(players) } override fun listenTo(): String { return FindAllPlayerQuery::class.qualifiedName!! } }
mit
9eb076c54ad03e4aa13cba38e2a31f94
36.516129
105
0.694492
4.15
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/commands/LatexColorDefinitionCommand.kt
1
2360
package nl.hannahsten.texifyidea.lang.commands import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.COLOR import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.XCOLOR /** * @author Hannah Schellekens */ enum class LatexColorDefinitionCommand( override val command: String, override vararg val arguments: Argument = emptyArray(), override val dependency: LatexPackage = LatexPackage.DEFAULT, override val display: String? = null, override val isMathMode: Boolean = false, val collapse: Boolean = false ) : LatexCommand { DEFINECOLOR("definecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = COLOR), PROVIDECOLOR("providecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = XCOLOR), COLORLET("colorlet", "type".asOptional(), "name".asRequired(), "num model".asOptional(), "color".asRequired(), dependency = XCOLOR), DEFINECOLORSET("definecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR), PROVIDECOLORSET("providecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR), PREPARECOLOR("preparecolor", "type".asOptional(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = XCOLOR), PREPARECOLORSET("preparecolorset", "type".asOptional(), "model-list".asRequired(), "head".asRequired(), "tail".asRequired(), "set spec".asRequired(), dependency = XCOLOR), DEFINE_NAMED_COLOR("DefineNamedColor", "type".asRequired(), "name".asRequired(), "model-list".asRequired(), "spec-list".asRequired(), dependency = COLOR), DEFINECOLORS("definecolors", "id-list".asRequired(), dependency = XCOLOR), PROVIDECOLORS("providecolors", "id-list".asRequired(), dependency = XCOLOR), DEFINECOLORSERIES("definecolorseries", "name".asRequired(), "core model".asRequired(), "method".asRequired(), "b-model".asOptional(), "b-spec".asRequired(), "s-model".asRequired(), "s-spec".asRequired(), dependency = XCOLOR), ; override val identifier: String get() = name }
mit
2cb86f4753c25493c7786b5b9c02f912
68.441176
229
0.708898
4.147627
false
false
false
false
googlecodelabs/watchnext-for-movie-tv-episodes
step_4_completed/src/main/java/com/android/tv/reference/shared/image/ImageBlurManager.kt
9
2450
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.shared.image import android.content.Context import android.graphics.Bitmap import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicBlur import androidx.annotation.FloatRange import androidx.annotation.WorkerThread /** * Helper class to simplify blurring images * * Only the application context is retained, so it's safe to use this across Activity lifecycles. * The backing RenderScript is lazily created when a blur is requested, so it's also lightweight * to construct this class in cases where a blur is only sometimes needed. */ class ImageBlurManager(context: Context) { private val applicationContext = context.applicationContext private val renderScript by lazy { RenderScript.create(applicationContext) } private val blurScript by lazy { ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript)) } /** * Returns a new blurred Bitmap based on the one passed in * * The passed Bitmap is NOT recycled by this method. */ @WorkerThread fun blur( inputBitmap: Bitmap, @FloatRange(from = 1.0, to = 25.0) radius: Float = 25f ): Bitmap { val inputAllocation = Allocation.createFromBitmap(renderScript, inputBitmap) val outputAllocation = Allocation.createTyped(renderScript, inputAllocation.type) blurScript.setInput(inputAllocation) blurScript.setRadius(radius) blurScript.forEach(outputAllocation) val outputBitmap = Bitmap.createBitmap(inputBitmap.width, inputBitmap.height, inputBitmap.config) outputAllocation.copyTo(outputBitmap) inputAllocation.destroy() outputAllocation.destroy() return outputBitmap } }
apache-2.0
a0e53962eae76248b5354312875218d0
35.029412
97
0.736735
4.657795
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ExperiencesAssembler.kt
1
4024
package io.rover.sdk.experiences import android.app.Application import android.content.Context import io.rover.sdk.core.UrlSchemes import io.rover.sdk.core.container.Assembler import io.rover.sdk.core.container.Container import io.rover.sdk.core.container.Resolver import io.rover.sdk.core.container.Scope import io.rover.sdk.core.data.graphql.GraphQlApiServiceInterface import io.rover.sdk.core.events.ContextProvider import io.rover.sdk.core.events.EventQueueServiceInterface import io.rover.sdk.core.logging.log import io.rover.sdk.core.platform.LocalStorage import io.rover.sdk.core.routing.Router import io.rover.sdk.experiences.events.contextproviders.ConversionsContextProvider import io.rover.sdk.experiences.services.EventEmitter /** * Location Assembler contains the Rover SDK subsystems for Geofence, Beacon, and location tracking. * * It can automatically use the Google Location services, which you can opt out of by passing false * to the following boolean parameters. You may wish to do this if you want to use a Location SDK * from a vendor other than Google, integrate with your own location implementation, or do not * require the functionality. * * Note: if you use any of the below, then you must complete the Google Play Services setup as per * the SDK documentation (also needed for the Notifications module). */ class ExperiencesAssembler : Assembler { override fun assemble(container: Container) { container.register( Scope.Singleton, PresentExperienceIntents::class.java ) { resolver -> PresentExperienceIntents( resolver.resolveSingletonOrFail(Context::class.java) ) } container.register( Scope.Singleton, ContextProvider::class.java, "conversions" ) { resolver -> ConversionsContextProvider( resolver.resolveSingletonOrFail(LocalStorage::class.java) ) } } override fun afterAssembly(resolver: Resolver) { super.afterAssembly(resolver) resolver.resolveSingletonOrFail(Router::class.java).apply { val urlSchemes = resolver.resolveSingletonOrFail(UrlSchemes::class.java) registerRoute( PresentExperienceRoute( urlSchemes = urlSchemes.schemes, associatedDomains = urlSchemes.associatedDomains, presentExperienceIntents = resolver.resolveSingletonOrFail( PresentExperienceIntents::class.java ) ) ) } RoverExperiences.initialize( resolver.resolveSingletonOrFail(Application::class.java), resolver.resolveSingletonOrFail(String::class.java, "accountToken"), resolver.resolveSingletonOrFail(Int::class.java, "chromeTabBackgroundColor"), resolver.resolveSingletonOrFail(GraphQlApiServiceInterface::class.java) ) /** * Attempt to retrieve the [EventEmitter] instance from the rover sdk in order to receive * events for analytics and automation purposes. */ val eventEmitter = RoverExperiences.shared?.eventEmitter eventEmitter?.let { EventReceiver( resolver.resolveSingletonOrFail(EventQueueServiceInterface::class.java) ).startListening(it) (resolver.resolveSingletonOrFail( ContextProvider::class.java, "conversions" ) as ConversionsContextProvider).startListening(it) } ?: log.w("A Rover SDK event emitter wasn't available; Rover events will not be tracked. Make sure you call Rover.initialize() before initializing the Rover SDK.") resolver.resolveSingletonOrFail(EventQueueServiceInterface::class.java).addContextProvider( resolver.resolveSingletonOrFail(ContextProvider::class.java, "conversions") ) } }
apache-2.0
fda47872c2e9c04f49558072494187da
40.484536
175
0.682406
5.192258
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/services/FollowService.kt
1
1922
package com.pr0gramm.app.services import com.pr0gramm.app.api.pr0gramm.Api import com.pr0gramm.app.db.AppDB import com.squareup.sqldelight.runtime.coroutines.asFlow import com.squareup.sqldelight.runtime.coroutines.mapToOneOrNull import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext /** * Service to handle follow & subscription. */ class FollowService(private val api: Api, private val db: AppDB) { suspend fun update(state: FollowState, userId: Long, name: String) { withContext(NonCancellable + Dispatchers.Default) { when (state) { FollowState.NONE -> { api.profileUnsubscribe(null, name) } FollowState.FOLLOW -> { api.profileFollow(null, name) api.profileUnsubscribe(null, name, keepFollow = true) } FollowState.SUBSCRIBED -> { api.profileSubscribe(null, name) } } db.userFollowEntryQueries.updateUser(userId, state.ordinal) } } fun getState(userId: Long): Flow<FollowState> { return db.userFollowEntryQueries.forUser(userId) .asFlow() .mapToOneOrNull() .map { value -> mapToState(value?.state) } } private fun mapToState(value: Int?): FollowState { val idx = value ?: return FollowState.NONE return FollowState.values().getOrNull(idx) ?: FollowState.NONE } } /** * Follow state, do not reorder, ordinal is used in database.. */ enum class FollowState(val following: Boolean, val subscribed: Boolean) { NONE(following = false, subscribed = false), FOLLOW(following = true, subscribed = false), SUBSCRIBED(following = true, subscribed = true) }
mit
75c4bd06f31ab4b87c155d3d3097386a
31.033333
73
0.6436
4.358277
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/Address.kt
3
7444
/* * Copyright (C) 2012 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 okhttp3 import java.net.Proxy import java.net.ProxySelector import java.util.Objects import javax.net.SocketFactory import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSocketFactory import okhttp3.internal.toImmutableList /** * A specification for a connection to an origin server. For simple connections, this is the * server's hostname and port. If an explicit proxy is requested (or [no proxy][Proxy.NO_PROXY] is explicitly requested), * this also includes that proxy information. For secure connections the address also includes the SSL socket factory, * hostname verifier, and certificate pinner. * * HTTP requests that share the same [Address] may also share the same [Connection]. */ class Address( uriHost: String, uriPort: Int, /** Returns the service that will be used to resolve IP addresses for hostnames. */ @get:JvmName("dns") val dns: Dns, /** Returns the socket factory for new connections. */ @get:JvmName("socketFactory") val socketFactory: SocketFactory, /** Returns the SSL socket factory, or null if this is not an HTTPS address. */ @get:JvmName("sslSocketFactory") val sslSocketFactory: SSLSocketFactory?, /** Returns the hostname verifier, or null if this is not an HTTPS address. */ @get:JvmName("hostnameVerifier") val hostnameVerifier: HostnameVerifier?, /** Returns this address's certificate pinner, or null if this is not an HTTPS address. */ @get:JvmName("certificatePinner") val certificatePinner: CertificatePinner?, /** Returns the client's proxy authenticator. */ @get:JvmName("proxyAuthenticator") val proxyAuthenticator: Authenticator, /** * Returns this address's explicitly-specified HTTP proxy, or null to delegate to the {@linkplain * #proxySelector proxy selector}. */ @get:JvmName("proxy") val proxy: Proxy?, protocols: List<Protocol>, connectionSpecs: List<ConnectionSpec>, /** * Returns this address's proxy selector. Only used if the proxy is null. If none of this * selector's proxies are reachable, a direct connection will be attempted. */ @get:JvmName("proxySelector") val proxySelector: ProxySelector ) { /** * Returns a URL with the hostname and port of the origin server. The path, query, and fragment of * this URL are always empty, since they are not significant for planning a route. */ @get:JvmName("url") val url: HttpUrl = HttpUrl.Builder() .scheme(if (sslSocketFactory != null) "https" else "http") .host(uriHost) .port(uriPort) .build() /** * The protocols the client supports. This method always returns a non-null list that * contains minimally [Protocol.HTTP_1_1]. */ @get:JvmName("protocols") val protocols: List<Protocol> = protocols.toImmutableList() @get:JvmName("connectionSpecs") val connectionSpecs: List<ConnectionSpec> = connectionSpecs.toImmutableList() @JvmName("-deprecated_url") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "url"), level = DeprecationLevel.ERROR) fun url() = url @JvmName("-deprecated_dns") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "dns"), level = DeprecationLevel.ERROR) fun dns() = dns @JvmName("-deprecated_socketFactory") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "socketFactory"), level = DeprecationLevel.ERROR) fun socketFactory() = socketFactory @JvmName("-deprecated_proxyAuthenticator") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "proxyAuthenticator"), level = DeprecationLevel.ERROR) fun proxyAuthenticator() = proxyAuthenticator @JvmName("-deprecated_protocols") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "protocols"), level = DeprecationLevel.ERROR) fun protocols() = protocols @JvmName("-deprecated_connectionSpecs") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "connectionSpecs"), level = DeprecationLevel.ERROR) fun connectionSpecs() = connectionSpecs @JvmName("-deprecated_proxySelector") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "proxySelector"), level = DeprecationLevel.ERROR) fun proxySelector() = proxySelector @JvmName("-deprecated_proxy") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "proxy"), level = DeprecationLevel.ERROR) fun proxy() = proxy @JvmName("-deprecated_sslSocketFactory") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "sslSocketFactory"), level = DeprecationLevel.ERROR) fun sslSocketFactory() = sslSocketFactory @JvmName("-deprecated_hostnameVerifier") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "hostnameVerifier"), level = DeprecationLevel.ERROR) fun hostnameVerifier() = hostnameVerifier @JvmName("-deprecated_certificatePinner") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "certificatePinner"), level = DeprecationLevel.ERROR) fun certificatePinner() = certificatePinner override fun equals(other: Any?): Boolean { return other is Address && url == other.url && equalsNonHost(other) } override fun hashCode(): Int { var result = 17 result = 31 * result + url.hashCode() result = 31 * result + dns.hashCode() result = 31 * result + proxyAuthenticator.hashCode() result = 31 * result + protocols.hashCode() result = 31 * result + connectionSpecs.hashCode() result = 31 * result + proxySelector.hashCode() result = 31 * result + Objects.hashCode(proxy) result = 31 * result + Objects.hashCode(sslSocketFactory) result = 31 * result + Objects.hashCode(hostnameVerifier) result = 31 * result + Objects.hashCode(certificatePinner) return result } internal fun equalsNonHost(that: Address): Boolean { return this.dns == that.dns && this.proxyAuthenticator == that.proxyAuthenticator && this.protocols == that.protocols && this.connectionSpecs == that.connectionSpecs && this.proxySelector == that.proxySelector && this.proxy == that.proxy && this.sslSocketFactory == that.sslSocketFactory && this.hostnameVerifier == that.hostnameVerifier && this.certificatePinner == that.certificatePinner && this.url.port == that.url.port } override fun toString(): String { return "Address{" + "${url.host}:${url.port}, " + (if (proxy != null) "proxy=$proxy" else "proxySelector=$proxySelector") + "}" } }
apache-2.0
01175be5e0d1b02b3c5196a594644477
35.135922
121
0.698146
4.550122
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/location/GeocoderMapbox.kt
1
3111
package org.tasks.location import android.content.Context import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request import org.tasks.DebugNetworkInterceptor import org.tasks.R import org.tasks.data.Place import org.tasks.data.Place.Companion.newPlace import org.tasks.extensions.JsonObject.getStringOrNull import org.tasks.preferences.Preferences import java.io.IOException import javax.inject.Inject class GeocoderMapbox @Inject constructor( @ApplicationContext context: Context, private val preferences: Preferences, private val interceptor: DebugNetworkInterceptor, ) : Geocoder { private val token = context.getString(R.string.mapbox_key) override suspend fun reverseGeocode(mapPosition: MapPosition): Place? = withContext(Dispatchers.IO) { val builder = OkHttpClient().newBuilder() if (preferences.isFlipperEnabled) { interceptor.apply(builder) } val client = builder.build() val url = "https://api.mapbox.com/geocoding/v5/mapbox.places/${mapPosition.longitude},${mapPosition.latitude}.json?access_token=$token" val response = client.newCall(Request.Builder().get().url(url).build()).execute() if (response.isSuccessful) { response.body?.string()?.let { jsonToPlace(it) } } else { throw IOException("${response.code} ${response.message}") } } companion object { internal fun jsonToPlace(json: String): Place? = JsonParser .parseString(json).asJsonObject.getAsJsonArray("features") .takeIf { it.size() > 0 }?.get(0)?.asJsonObject ?.let { toPlace(it) } internal fun toPlace(feature: JsonObject): Place = newPlace().apply { val types = feature.get("place_type").asStringList val text = feature.get("text").asString name = if (types.contains("address")) { feature .getStringOrNull("address") ?.let { "$it $text" } ?: text } else { text } address = feature.get("place_name").asString feature.get("center").asCoordinates.let { longitude = it.first latitude = it.second } } private val JsonElement.asStringList: List<String> get() = asJsonArray.map { it.asString } private val JsonElement.asCoordinates: Pair<Double, Double> get() = asJsonArray.let { Pair(it[0].asDouble, it[1].asDouble) } } }
gpl-3.0
7c4430ed1be97e20f1bacbd8505098f7
39.947368
151
0.582449
5.075041
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/GlobalShortcuts.kt
1
3378
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.scene.Node import javafx.scene.Scene import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.tools.HomeTool class GlobalShortcuts(val scene: Scene, val projectWindow: ProjectWindow) { init { put(ParataskActions.TOOL_STOP) { halfTab()?.onStop() } put(ParataskActions.TOOL_RUN) { halfTab()?.onRun() } put(ParataskActions.TOOL_SELECT) { projectWindow.addTool(HomeTool()) } put(ParataskActions.TOOL_CLOSE) { halfTab()?.close() } put(ParataskActions.HISTORY_BACK) { halfTab()?.history?.undo() } put(ParataskActions.HISTORY_FORWARD) { halfTab()?.history?.redo() } put(ParataskActions.NEXT_MAJOR_TAB) { projectWindow.tabs.nextTab() } put(ParataskActions.PREV_MAJOR_TAB) { projectWindow.tabs.prevTab() } put(ParataskActions.NEXT_MINOR_TAB) { toolPane()?.nextTab() } put(ParataskActions.PREV_MINOR_TAB) { toolPane()?.prevTab() } put(ParataskActions.FOCUS_HEADER) { ParaTaskApp.logFocus("GlobalShortcuts FOCUS_HEADER. toolPane().focusHeader()") toolPane()?.focusHeader() } put(ParataskActions.FOCUS_RESULTS) { ParaTaskApp.logFocus("GlobalShortcuts FOCUS_RESULTS. toolPane().focusResults()") toolPane()?.focusResults() } put(ParataskActions.FOCUS_OPTION) { ParaTaskApp.logFocus("GlobalShortcuts FOCUS_OPTION. halfTab().focusOption()") halfTab()?.focusOption() } put(ParataskActions.FOCUS_OTHER_SPLIT) { ParaTaskApp.logFocus("GlobalShortcuts FOCUS_OTHER_SPLIT. halfTab().focusOtherHalf()") halfTab()?.focusOtherHalf() } put(ParataskActions.TAB_NEW) { projectWindow.tabs.addTool(HomeTool()) } put(ParataskActions.TAB_RESTORE) { projectWindow.tabs.restoreTab() } for ((index, action) in ParataskActions.MAJOR_TABS.withIndex()) { put(action) { projectWindow.tabs.selectTab(index) } } for ((index, action) in ParataskActions.MINOR_TABS.withIndex()) { put(action) { toolPane()?.selectTab(index) } } } fun put(action: ParataskAction, call: () -> Unit) { scene.accelerators.put(action.keyCodeCombination, Runnable { call() }) } fun tab(): ProjectTab? = projectWindow.tabs.currentTab() fun halfTab(): HalfTab? { var node: Node? = scene.focusOwner while (node != null) { if (node is HalfTab) { return node } node = node.parent } return tab()?.left } fun toolPane(): ToolPane? = halfTab()?.toolPane }
gpl-3.0
d7f25237009333f6099f9f2a4dac3bf9
35.728261
97
0.661338
4.249057
false
false
false
false
ledao/chatbot
src/main/kotlin/com/davezhao/restfull/controllers/PatternController.kt
1
799
package com.davezhao.restfull.controllers import com.davezhao.services.PatternService import io.javalin.Context import org.slf4j.LoggerFactory class PatternController { val log = LoggerFactory.getLogger(this::class.java) val patternService = PatternService() fun getPatternCheckResult(cxt: Context) { log.info("in pattern check") val sent = cxt.param("sent") val category = cxt.param("category") if (sent == null || category == null || category.toIntOrNull() == null) { cxt.status(201) cxt.result("bad request") return } val checkResult = patternService.checkPattern(sent = sent, category = category.toInt()) cxt.json(PatternCheckResult(sent = sent, is_hit = checkResult != null)) } }
gpl-3.0
82f651efb4a5d951cb00d951b02eef63
28.62963
95
0.65582
4.055838
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/Parameter.kt
1
1976
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.parameters import uk.co.nickthecoder.paratask.ParameterResolver import uk.co.nickthecoder.paratask.PlainDirectoryResolver import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.parameters.fields.ParameterField import uk.co.nickthecoder.paratask.util.Labelled interface Parameter : Labelled { val name: String val aliases: List<String> val description: String val hint: String var parent: Parameter? val parameterListeners: ParameterListeners val isBoxed: Boolean /** * Only used when isBoxed is true */ var isExpanded: Boolean var hidden: Boolean var enabled: Boolean fun listen(listener: (event: ParameterEvent) -> Unit) fun isStretchy(): Boolean fun errorMessage(): String? fun createField(): ParameterField fun findRoot(): RootParameter? { return parent?.findRoot() } fun resolver(): ParameterResolver = findRoot()?.taskD?.resolver ?: PlainDirectoryResolver.instance fun findTaskD(): TaskDescription? = parent?.findTaskD() fun isProgrammingMode(): Boolean = findTaskD()?.programmingMode ?: false fun copy(): Parameter fun createInfo() = InformationParameter("info_${name}", label = "", information = description) }
gpl-3.0
4a5d1e5372ad3cdab09a156f22045b7c
26.444444
102
0.741397
4.56351
false
false
false
false
rcgroot/open-gpstracker-ng
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/model/Preferences.kt
1
2615
package nl.sogeti.android.gpstracker.ng.features.model import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import androidx.annotation.WorkerThread import androidx.core.content.edit import nl.sogeti.android.gpstracker.ng.base.dagger.DiskIO import nl.sogeti.android.gpstracker.ng.features.dagger.FeatureScope import java.util.concurrent.Executor import javax.inject.Inject @FeatureScope class Preferences @Inject constructor(context: Context, @DiskIO private val executor: Executor) { val wakelockScreen = MutableLiveData<Boolean>() val satellite = MutableLiveData<Boolean>() private lateinit var preferences: SharedPreferences private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> when (key) { WAKE_LOCK_SCREEN -> executor.execute { readWakeLockScreen() } SATELLITE -> executor.execute { readSatellite() } } } private val wakelockScreenObserver = Observer<Boolean> { _ -> wakelockScreen.storeAsPreference(WAKE_LOCK_SCREEN) } private val satelliteObserver = Observer<Boolean> { _ -> satellite.storeAsPreference(SATELLITE) } init { executor.execute { preferences = context.getSharedPreferences("settings", MODE_PRIVATE) preferences.registerOnSharedPreferenceChangeListener(preferenceListener) readWakeLockScreen() readSatellite() } wakelockScreen.observeForever(wakelockScreenObserver) satellite.observeForever(satelliteObserver) } @WorkerThread private fun readSatellite() { satellite.postValue(preferences.getBoolean(SATELLITE, false)) } @WorkerThread private fun readWakeLockScreen() { wakelockScreen.postValue(preferences.getBoolean(WAKE_LOCK_SCREEN, false)) } private fun MutableLiveData<Boolean>.storeAsPreference(key: String) { val storedValue = preferences.getBoolean(key, false) val value = valueOrFalse() if (storedValue != value) { preferences.edit { putBoolean(key, value) } } } companion object { private const val WAKE_LOCK_SCREEN = "WAKE_LOCK_SCREEN" private const val SATELLITE = "SATELLITE" } } fun MutableLiveData<Boolean>.valueOrFalse(): Boolean = this.value ?: false fun MutableLiveData<Boolean>.not() = this.valueOrFalse().not() .also { this.value = it }
gpl-3.0
66c52d7e6e1df385a09e0eeaa4bedb4e
33.407895
99
0.702103
4.789377
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/KotlinPropertyDSL.kt
1
1083
package com.github.pgutkowski.kgraphql.schema.dsl import com.github.pgutkowski.kgraphql.Context import com.github.pgutkowski.kgraphql.schema.model.PropertyDef import java.lang.IllegalArgumentException import kotlin.reflect.KProperty1 class KotlinPropertyDSL<T : Any, R> ( private val kProperty: KProperty1<T, R>, block : KotlinPropertyDSL<T, R>.() -> Unit ) : LimitedAccessItemDSL<T>(){ var ignore = false init { block() } fun accessRule(rule: (T, Context) -> Exception?){ val accessRuleAdapter: (T?, Context) -> Exception? = { parent, ctx -> if (parent != null) rule(parent, ctx) else IllegalArgumentException("Unexpected null parent of kotlin property") } this.accessRuleBlock = accessRuleAdapter } fun toKQLProperty() = PropertyDef.Kotlin ( kProperty = kProperty, description = description, isDeprecated = isDeprecated, deprecationReason = deprecationReason, isIgnored = ignore, accessRule = accessRuleBlock ) }
mit
831da550a72f51128bc52a9accce697f
28.297297
124
0.65651
4.688312
false
false
false
false
yinpeng/kotlin-matrix
src/test/kotlin/com/ichipsea/kotlin/matrix/MatrixTest.kt
1
7206
package com.ichipsea.kotlin.matrix import org.jetbrains.spek.api.Spek import kotlin.test.assertEquals import kotlin.test.assertFails import kotlin.test.assertFalse import kotlin.test.assertNotEquals class MatrixTest: Spek({ describe("a character matrix") { val m = createMatrix(2, 3) { x, y -> if (x===0) 'A' else 'B' } it("should return a matrix with 2 cols and 3 rows") { assertEquals(2, m.cols) assertEquals(3, m.rows) } it("size should be 6") { assertEquals(6, m.size) } it("should have 'A' in first column and 'B' in second column") { m.forEachIndexed { x, y, value -> assertEquals(if (x===0) 'A' else 'B', value) } } it("should be correct") { assertEquals( "ABABAB".toList().toMatrix(2, 3), m ) assertNotEquals( "ABABAB".toList().toMatrix(3, 2), m ) } it("should convert to correct string") { assertEquals( "[[A, B], [A, B], [A, B]]", m.toString() ) } describe("as transposed") { val t = m.asTransposed() it ("transpose view should have 3 cols and 2 rows") { assertEquals(3, t.cols) assertEquals(2, t.rows) } it("transpose view should have 'A' in first row and 'B' in second row") { t.forEachIndexed { x, y, value -> assertEquals(if (y === 0) 'A' else 'B', value) } } } } describe("a mutable Pair<Int, Double> matrix") { val m = mutableMatrixOf(4, 2, 3 to 3.1, 5 to 8.0, 6 to 2.2, 1 to 3.5, 0 to 7.0, 0 to 1.8, 9 to 1000.35, 972345 to 11.3 ) it("should return a matrix with 4 cols and 3 rows") { assertEquals(4, m.cols) assertEquals(2, m.rows) } it ("size should be 8") { assertEquals(8, m.size) } it ("should be mutable") { val old = m[2, 1] val new = 100 to 0.0 m[2, 1] = new assert(m[2, 1] === new) m[2, 1] = old assert(m[2, 1] === old) } it ("should be mutable by asTransposed()") { val old = m[3, 0] val new = 888 to 111.0 m.asTransposed()[0, 3] = new assert(m[3, 0] === new) m[3, 0] = old assert(m.asTransposed()[0, 3] === old) } } describe("equation and hash code") { val m1 = (1..6).toMatrix(3, 2) val m2 = (1..6).toMutableMatrix(3, 2) val m3 = matrixOf(3, 2, 1, 2, 3, 4, 5, null) val m4 = matrixOf(3, 2, 1, 2, 3, 4, 5, null) it("equation test") { assertEquals(m1, m2) assertEquals(m3, m4) assertNotEquals(m1, m3) assertNotEquals(m1, m1.toList().toMatrix(2, 3)) val m = m1.toList().toMutableMatrix(3, 2) assertEquals(m1, m) m[0, 0] += 5 assertNotEquals(m1, m) m[0, 0] -= 5 assertEquals(m1, m) } it("have same hash codes for equal matrices") { assertEquals(m1.hashCode(), m2.hashCode()) assertEquals(m3.hashCode(), m4.hashCode()) } } describe("conversions") { val mm = createMutableMatrix(2, 2, { x, y -> x + y*10 }) val itr: Iterable<Int> = 0..9 it("should convertible from Matrix to List") { val l = mm.toList() assertEquals(listOf(0, 1, 10, 11), l) } it("should convertible from Matrix to MutableList") { val l = mm.toMutableList() assertEquals(mutableListOf(0, 1, 10, 11), l) val old = mm[0, 0] l[0] = mm[0, 0] + 123 assertEquals(old, mm[0, 0], "it should not change the original matrix through the mutable list") } it("should be convertible from Iterable to Matrix") { val m = itr.toMatrix(5, 2) assertEquals(m, matrixOf(5, 2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) assertFails { itr.toMatrix(6, 2) } } it("should be convertible from Iterable to MutableMatrix") { val m = itr.toMutableMatrix(5, 2) assertEquals(m, mutableMatrixOf(5, 2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) m[0, 0] = 10000 assertFalse(itr.contains(10000), "it should not change the original Iterable through the mutable matrix)") } } describe("map and forEach") { val m = matrixOf(2, 3, 1, 2, 3, 4, 5, 6) it("test map()") { assertEquals(matrixOf(2, 3, "1", "2", "3", "4", "5", "6"), m.map { it.toString() } ) assertEquals(createMatrix(2, 3, { x, y -> m[x, y] + x + y }), m.mapIndexed { x, y, value -> value + x + y } ) } it("test forEach()") { var s = 0 m.forEach { s += it } assertEquals(21, s) m.forEachIndexed { x, y, value -> if (x == y) s -= value } assertEquals(16, s) } } describe("matrix numeric operations") { val a = (1..6).toMatrix(3, 2) val b = createMatrix(3, 2, { x, y -> 0.5 }) val c = matrixOf(2, 4, 3, 7, 2, 2, 1, 0, 9, 5 ) it("addition") { assertEquals( matrixOf(3, 2, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5 ), a + b ) assertFails { a + c } } it("subtraction") { assertEquals( matrixOf(3, 2, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5 ), a - b ) assertFails { a - c } } it("multiplication by number") { assertEquals( matrixOf(3, 2, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0 ), a * 2.0 ) assertEquals(c * 0.8, 0.8 * c ) } it("dot product") { assertEquals( matrixOf(3, 2, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 ), a * b ) assertFails { a * c } } it("cross product") { assertEquals( matrixOf(3, 4, 31.0, 41.0, 51.0, 10.0, 14.0, 18.0, 1.0, 2.0, 3.0, 29.0, 43.0, 57.0 ), a x c ) assertFails { a x b } } } })
apache-2.0
fb1cdb1b63a981c5c07da8192c889099
28.292683
118
0.407438
3.826872
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsModItem.kt
1
1684
package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiDirectory import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsInnerAttr import org.rust.lang.core.psi.RsModItem import org.rust.lang.core.psi.RsOuterAttr import org.rust.lang.core.psi.RustPsiImplUtil import org.rust.lang.core.stubs.RsModItemStub import javax.swing.Icon abstract class RsModItemImplMixin : RsStubbedNamedElementImpl<RsModItemStub>, RsModItem { constructor(node: ASTNode) : super(node) constructor(stub: RsModItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int): Icon = iconWithVisibility(flags, RsIcons.MODULE) override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) override val `super`: RsMod get() = containingMod override val modName: String? get() = name override val crateRelativePath: String? get() = RustPsiImplUtil.modCrateRelativePath(this) override val ownsDirectory: Boolean = true // Any inline nested mod owns a directory override val ownedDirectory: PsiDirectory? get() { val name = name ?: return null return `super`.ownedDirectory?.findSubdirectory(name) } override val isCrateRoot: Boolean = false override val innerAttrList: List<RsInnerAttr> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, RsInnerAttr::class.java) override val outerAttrList: List<RsOuterAttr> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, RsOuterAttr::class.java) }
mit
4e8906d2c307d12e7fca950adbc741a4
34.083333
94
0.741093
4.329049
false
false
false
false
genobis/tornadofx
src/main/java/tornadofx/AutoCompleteComboBoxSkin.kt
1
15805
package tornadofx import com.sun.javafx.scene.control.behavior.ComboBoxListViewBehavior import com.sun.javafx.scene.control.skin.ComboBoxPopupControl import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.css.PseudoClass import javafx.event.EventHandler import javafx.scene.AccessibleRole import javafx.scene.Node import javafx.scene.control.* import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.util.Callback /** * Extension function to combobox to add autocomplete capabilities * Accept in parameter a callback to create the autocomplete list based on input text * Default filter use the string produced by the converter of combobox and search with contains ignore case the occurrence of typed text * @param automaticPopupWidth Use the width required to display all content. Default: false */ fun <T> ComboBox<T>.makeAutocompletable(automaticPopupWidth: Boolean = false, autoCompleteFilter: ((String) -> List<T>)? = null) { skin = AutoCompleteComboBoxSkin(this, autoCompleteFilter, automaticPopupWidth) } interface Resettable { fun reset() } interface FilterHandler { fun handleFilterChange(text : String) fun validateSelection() fun showSuggestion() : Boolean fun hideSuggestion() : Boolean } class FilterTooltipHandler(val control : Control, val filterHandler : FilterHandler) : EventHandler<KeyEvent> , Resettable { private val filter = SimpleStringProperty("") private val tooltip = Tooltip() init { tooltip.textProperty().bind(filter) filter.addListener { _, _, newValue -> handleFilterChanged_(newValue) } } override fun handle(event: KeyEvent) { val code = event.code val isControlDown = event.isControlDown val isShiftDown = event.isShiftDown var filterValue: String = filter.get() if (isControlDown) { when (code) { KeyCode.V -> Unit else -> return } } if (isShiftDown) { when (code) { KeyCode.LEFT, KeyCode.RIGHT, KeyCode.HOME, KeyCode.END -> return else -> Unit } } when (code) { KeyCode.DOWN, KeyCode.UP -> { filterHandler.showSuggestion() } KeyCode.BACK_SPACE -> { if(filterValue.isNotBlank()) { filterValue = filterValue.substring(0, filterValue.length - 1) } } KeyCode.ESCAPE -> { reset() filterHandler.hideSuggestion() return } KeyCode.ENTER -> { filterHandler.validateSelection() return } KeyCode.RIGHT, KeyCode.LEFT, KeyCode.HOME, KeyCode.END, KeyCode.TAB, KeyCode.SHIFT, KeyCode.CONTROL -> return else -> filterValue += event.text } filter.value = filterValue } private fun handleFilterChanged_(newValue: String) { filterHandler.handleFilterChange(newValue) if(newValue.isNotBlank()) { showTooltip() } else { tooltip.hide() } } private fun showTooltip() { if (!tooltip.isShowing) { val stage = control.scene.window val posX = stage.x + control.localToScene(control.boundsInLocal).minX val posY = stage.y + control.localToScene(control.boundsInLocal).minY tooltip.show(stage, posX, posY) } } override fun reset() { filter.value = "" tooltip.hide() } } class FilterInputTextHandler(val editor : TextField, val filterHandler : FilterHandler) : EventHandler<KeyEvent>, Resettable { private var lastText: String = "" override fun handle(event: KeyEvent) { val text = editor.text val inputChanged = lastText != text lastText = text val code = event.code val isControlDown = event.isControlDown val isShiftDown = event.isShiftDown val caretPosition = editor.caretPosition if (isControlDown) { when (code) { KeyCode.V -> Unit else -> return } } if (isShiftDown) { when (code) { KeyCode.LEFT, KeyCode.RIGHT, KeyCode.HOME, KeyCode.END -> return else -> Unit } } when (code) { KeyCode.DOWN, KeyCode.UP -> { if(!filterHandler.showSuggestion()) { editor.positionCaret(text.length) } return } KeyCode.ESCAPE -> { filterHandler.hideSuggestion() return } KeyCode.ENTER -> { filterHandler.validateSelection() return } KeyCode.RIGHT, KeyCode.LEFT, KeyCode.HOME, KeyCode.END, KeyCode.TAB, KeyCode.SHIFT, KeyCode.CONTROL -> return else -> Unit } if (inputChanged) { filterHandler.handleFilterChange(text) editor.text = text editor.positionCaret(caretPosition) } } override fun reset() { lastText = "" } } /** * Auto Complete support for combobox * Accept a call back to make custom filter * Default filter use the string produced by the converter of combobox and search with contains ignore case the occurrence of typed text * Created by anouira on 15/02/2017. */ open class AutoCompleteComboBoxSkin<T>(val comboBox: ComboBox<T>, autoCompleteFilter: ((String) -> List<T>)?, automaticPopupWidth: Boolean) : ComboBoxPopupControl<T>(comboBox, ComboBoxListViewBehavior(comboBox)), FilterHandler { var autoCompleteFilter_: (String) -> List<T> = autoCompleteFilter ?: { comboBox.items.filter { current -> comboBox.converter.toString(current).contains(it, true) } } protected val listView = ListView<T>(comboBox.items) private var skipValueUpdate = false private var comboBoxItems: ObservableList<T> = if (comboBox.items == null) FXCollections.emptyObservableList<T>() else comboBox.items private val filterHandler by lazy<EventHandler<KeyEvent>> { if(comboBox.isEditable) { FilterInputTextHandler(comboBox.editor, this) } else { FilterTooltipHandler(comboBox, this) } } init { with(comboBox) { onKeyReleased = filterHandler focusedProperty().onChange { focus -> if(!focus) { resetFilter() comboBox.hide() }} arrowButton.setOnMouseClicked { if (isShowing) { resetFilter() } } } listView.selectionModel.selectedItemProperty().onChange { if (!skipValueUpdate) comboBox.value = it } listView.onUserSelect(clickCount = 1) { comboBox.value = it if(filterHandler is FilterTooltipHandler) { resetFilter() } comboBox.hide() updateDisplayArea() } if (!automaticPopupWidth) { // Note that we cannot bind prefWidthProperty because JavaFX sets // the preferred width upon reconfiguration. (ComboBoxPopupControl.java:322) comboBox.widthProperty().onChange { listView.prefWidth = it } } updateCellFactory() updateButtonCell() updateValue() comboBox.cellFactoryProperty().onChange { updateCellFactory() } } override fun handleFilterChange(text : String) { val list = autoCompleteFilter_.invoke(text) listView.items = (list as? ObservableList<T>) ?: list.observable() listView.requestLayout() if (list.isEmpty()) { comboBox.hide() } else { comboBox.show() if (listView.selectedItem == null) { skipValueUpdate = true listView.selectionModel.selectFirst() skipValueUpdate = false } listView.requestFocus() } } /** Specific auto complete implementation */ override fun validateSelection() { if (!listView.selectionModel.isEmpty) { comboBox.value = listView.selectedItem } if (comboBox.isShowing) { comboBox.hide() } } override fun showSuggestion() : Boolean { if(!comboBox.isShowing) { comboBox.show() return true } return false } override fun hideSuggestion() : Boolean { if(comboBox.isShowing) { comboBox.hide() return true } return false } private fun updateCellFactory() { if (comboBox.cellFactory != null) { listView.cellFactory = comboBox.cellFactory } else { createDefaultCellFactory() } } private fun createDefaultCellFactory() { val cellFormat: (ListCell<T>.(T) -> Unit) = { if (it is Node) { graphic = it } else if (it != null) { if (converter != null) text = converter.toString(it) else if (it is String) text = it else text = it.toString() } } listView.properties["tornadofx.cellFormat"] = cellFormat listView.cellFactory = Callback { SmartListCell(DefaultScope, listView) } } private fun resetFilter() { listView.items = comboBox.items (filterHandler as? Resettable)?.reset() } /** End of Specific auto complete implementation */ /** Implementation copied from ComboBoxListViewSkin */ private var buttonCell: ListCell<T>? = null // These three pseudo class states are duplicated from Cell private val PSEUDO_CLASS_SELECTED = PseudoClass.getPseudoClass("selected") private val PSEUDO_CLASS_EMPTY = PseudoClass.getPseudoClass("empty") private val PSEUDO_CLASS_FILLED = PseudoClass.getPseudoClass("filled") override fun getDisplayNode(): Node? { val displayNode: Node if (comboBox.isEditable) { displayNode = editableInputNode } else { displayNode = buttonCell as Node } updateDisplayNode() return displayNode } private fun updateButtonCell() { buttonCell = if (comboBox.buttonCell != null) comboBox.buttonCell else getDefaultCellFactory().call(listView) buttonCell?.setMouseTransparent(true) buttonCell?.updateListView(listView) updateDisplayArea() // As long as the screen-reader is concerned this node is not a list item. // This matters because the screen-reader counts the number of list item // within combo and speaks it to the user. buttonCell?.setAccessibleRole(AccessibleRole.NODE) } private fun getDefaultCellFactory(): Callback<ListView<T>, ListCell<T>> { return Callback { object : ListCell<T>() { public override fun updateItem(item: T, empty: Boolean) { super.updateItem(item, empty) updateDisplayText(this, item, empty) } } } } private fun updateDisplayText(cell: ListCell<T>?, item: T?, empty: Boolean): Boolean { if (empty) { if (cell == null) return true cell.graphic = null cell.text = null return true } else if (item is Node) { val currentNode = cell!!.graphic val newNode = item if (currentNode == null || currentNode != newNode) { cell.text = null cell.graphic = newNode } return false } else { // run item through StringConverter if it isn't null val c = comboBox.converter val s = if (item == null) comboBox.promptText else if (c == null) item.toString() else c.toString(item) cell!!.text = s cell.graphic = null return s == null || s.isEmpty() } } private fun updateValue() { val newValue = comboBox.value val listViewSM = listView.selectionModel if (newValue == null) { listViewSM.clearSelection() } else { // RT-22386: We need to test to see if the value is in the comboBox // items list. If it isn't, then we should clear the listview // selection val indexOfNewValue = getIndexOfComboBoxValueInItemsList() if (indexOfNewValue == -1) { //listSelectionLock = true listViewSM.clearSelection() //listSelectionLock = false } else { val index = comboBox.selectionModel.selectedIndex if (index in comboBoxItems.indices) { val itemsObj = comboBoxItems.get(index) if (itemsObj != null && itemsObj == newValue) { listViewSM.select(index) } else { listViewSM.select(newValue) } } else { // just select the first instance of newValue in the list val listViewIndex = comboBoxItems.indexOf(newValue) if (listViewIndex == -1) { // RT-21336 Show the ComboBox value even though it doesn't // exist in the ComboBox items list (part one of fix) updateDisplayNode() } else { listViewSM.select(listViewIndex) } } } } } private fun getIndexOfComboBoxValueInItemsList(): Int { val value = comboBox.value val index = comboBoxItems.indexOf(value) return index } override fun updateDisplayNode() { if (editor != null) { super.updateDisplayNode() } else { val value = comboBox.value val index = getIndexOfComboBoxValueInItemsList() if (index > -1) { buttonCell?.setItem(null) buttonCell?.updateIndex(index) } else { // RT-21336 Show the ComboBox value even though it doesn't // exist in the ComboBox items list (part two of fix) buttonCell?.updateIndex(-1) val empty = updateDisplayText(buttonCell, value, false) // Note that empty boolean collected above. This is used to resolve // RT-27834, where we were getting different styling based on whether // the cell was updated via the updateIndex method above, or just // by directly updating the text. We fake the pseudoclass state // for empty, filled, and selected here. buttonCell?.pseudoClassStateChanged(PSEUDO_CLASS_EMPTY, empty) buttonCell?.pseudoClassStateChanged(PSEUDO_CLASS_FILLED, !empty) buttonCell?.pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, true) } } } override fun getPopupContent() = listView override fun getEditor() = if (skinnable.isEditable) (skinnable as ComboBox<T>).editor else null override fun getConverter() = (skinnable as ComboBox<T>).converter /* End of Implementation copied from ComboBoxListViewSkin */ }
apache-2.0
8c5ef26276db822d8658af6c40b12a7b
33.0625
228
0.577286
5.200724
false
false
false
false
olonho/carkot
translator/src/main/kotlin/main.kt
1
1088
import com.intellij.openapi.util.Disposer import com.jshmrsn.karg.parseArguments import org.kotlinnative.translator.ProjectTranslator import org.kotlinnative.translator.TranslationState import java.io.* fun main(args: Array<String>) { // TODO make good help message (ex. is rm --help) val arguments = parseArguments(args, ::DefaultArguments) val disposer = Disposer.newDisposable() val analyzedFiles = arguments.sources.toMutableList() if (arguments.includeDir != null) { val libraryFiles = File(arguments.includeDir).walk().filter { !it.isDirectory }.map { it.absolutePath } analyzedFiles.addAll(libraryFiles) } val translationState = TranslationState.createTranslationState(analyzedFiles, disposer, arguments.mainClass, arguments.arm) val code:String = ProjectTranslator( translationState.environment.getSourceFiles(), translationState ).generateCode() if (arguments.output == null) { println(code) } else { val output = File(arguments.output) output.writeText(code) } }
mit
ff995b02a8968155fa61a2faac5cddeb
35.3
127
0.715993
4.369478
false
false
false
false
samtstern/quickstart-android
database/app/src/main/java/com/google/firebase/quickstart/database/kotlin/PostDetailActivity.kt
1
10864
package com.google.firebase.quickstart.database.kotlin import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.database.R import com.google.firebase.quickstart.database.databinding.ActivityPostDetailBinding import com.google.firebase.quickstart.database.kotlin.models.Comment import com.google.firebase.quickstart.database.kotlin.models.Post import com.google.firebase.quickstart.database.kotlin.models.User import java.util.ArrayList class PostDetailActivity : BaseActivity(), View.OnClickListener { private lateinit var postKey: String private lateinit var postReference: DatabaseReference private lateinit var commentsReference: DatabaseReference private var postListener: ValueEventListener? = null private var adapter: CommentAdapter? = null private lateinit var binding: ActivityPostDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPostDetailBinding.inflate(layoutInflater) setContentView(binding.root) // Get post key from intent postKey = intent.getStringExtra(EXTRA_POST_KEY) ?: throw IllegalArgumentException("Must pass EXTRA_POST_KEY") // Initialize Database postReference = Firebase.database.reference .child("posts").child(postKey) commentsReference = Firebase.database.reference .child("post-comments").child(postKey) // Initialize Views with(binding) { buttonPostComment.setOnClickListener(this@PostDetailActivity) recyclerPostComments.layoutManager = LinearLayoutManager(this@PostDetailActivity) } } public override fun onStart() { super.onStart() // Add value event listener to the post // [START post_value_event_listener] val postListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { // Get Post object and use the values to update the UI val post = dataSnapshot.getValue<Post>() // [START_EXCLUDE] post?.let { binding.postAuthorLayout.postAuthor.text = it.author with(binding.postTextLayout) { postTitle.text = it.title postBody.text = it.body } } // [END_EXCLUDE] } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // [START_EXCLUDE] Toast.makeText(baseContext, "Failed to load post.", Toast.LENGTH_SHORT).show() // [END_EXCLUDE] } } postReference.addValueEventListener(postListener) // [END post_value_event_listener] // Keep copy of post listener so we can remove it when app stops this.postListener = postListener // Listen for comments adapter = CommentAdapter(this, commentsReference) binding.recyclerPostComments.adapter = adapter } public override fun onStop() { super.onStop() // Remove post value event listener postListener?.let { postReference.removeEventListener(it) } // Clean up comments listener adapter?.cleanupListener() } override fun onClick(v: View) { val i = v.id if (i == R.id.buttonPostComment) { postComment() } } private fun postComment() { val uid = uid Firebase.database.reference.child("users").child(uid) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { // Get user information val user = dataSnapshot.getValue<User>() if (user == null) { return } val authorName = user.username // Create new comment object val commentText = binding.fieldCommentText.text.toString() val comment = Comment(uid, authorName, commentText) // Push the comment, it will appear in the list commentsReference.push().setValue(comment) // Clear the field binding.fieldCommentText.text = null } override fun onCancelled(databaseError: DatabaseError) { } }) } private class CommentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(comment: Comment) { itemView.findViewById<TextView>(R.id.commentAuthor).text = comment.author itemView.findViewById<TextView>(R.id.commentBody).text = comment.text } } private class CommentAdapter( private val context: Context, private val databaseReference: DatabaseReference ) : RecyclerView.Adapter<CommentViewHolder>() { private val childEventListener: ChildEventListener? private val commentIds = ArrayList<String>() private val comments = ArrayList<Comment>() init { // Create child event listener // [START child_event_listener_recycler] val childEventListener = object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildAdded:" + dataSnapshot.key!!) // A new comment has been added, add it to the displayed list val comment = dataSnapshot.getValue<Comment>() // [START_EXCLUDE] // Update RecyclerView commentIds.add(dataSnapshot.key!!) comments.add(comment!!) notifyItemInserted(comments.size - 1) // [END_EXCLUDE] } override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildChanged: ${dataSnapshot.key}") // A comment has changed, use the key to determine if we are displaying this // comment and if so displayed the changed comment. val newComment = dataSnapshot.getValue<Comment>() val commentKey = dataSnapshot.key // [START_EXCLUDE] val commentIndex = commentIds.indexOf(commentKey) if (commentIndex > -1 && newComment != null) { // Replace with the new data comments[commentIndex] = newComment // Update the RecyclerView notifyItemChanged(commentIndex) } else { Log.w(TAG, "onChildChanged:unknown_child: $commentKey") } // [END_EXCLUDE] } override fun onChildRemoved(dataSnapshot: DataSnapshot) { Log.d(TAG, "onChildRemoved:" + dataSnapshot.key!!) // A comment has changed, use the key to determine if we are displaying this // comment and if so remove it. val commentKey = dataSnapshot.key // [START_EXCLUDE] val commentIndex = commentIds.indexOf(commentKey) if (commentIndex > -1) { // Remove data from the list commentIds.removeAt(commentIndex) comments.removeAt(commentIndex) // Update the RecyclerView notifyItemRemoved(commentIndex) } else { Log.w(TAG, "onChildRemoved:unknown_child:" + commentKey!!) } // [END_EXCLUDE] } override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildMoved:" + dataSnapshot.key!!) // A comment has changed position, use the key to determine if we are // displaying this comment and if so move it. val movedComment = dataSnapshot.getValue<Comment>() val commentKey = dataSnapshot.key // ... } override fun onCancelled(databaseError: DatabaseError) { Log.w(TAG, "postComments:onCancelled", databaseError.toException()) Toast.makeText(context, "Failed to load comments.", Toast.LENGTH_SHORT).show() } } databaseReference.addChildEventListener(childEventListener) // [END child_event_listener_recycler] // Store reference to listener so it can be removed on app stop this.childEventListener = childEventListener } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentViewHolder { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.item_comment, parent, false) return CommentViewHolder(view) } override fun onBindViewHolder(holder: CommentViewHolder, position: Int) { holder.bind(comments[position]) } override fun getItemCount(): Int = comments.size fun cleanupListener() { childEventListener?.let { databaseReference.removeEventListener(it) } } } companion object { private const val TAG = "PostDetailActivity" const val EXTRA_POST_KEY = "post_key" } }
apache-2.0
beea973c195fd01d43f65b89d24f8a2f
38.079137
101
0.587353
5.574141
false
false
false
false
nevi-me/turf-kotlin
src/main/kotlin/za/co/movinggauteng/turfkotlin/measurement/Along.kt
1
1168
package za.co.movinggauteng.turfkotlin.measurement import za.co.movinggauteng.turfkotlin.geojson.LineString import za.co.movinggauteng.turfkotlin.geojson.Point import za.co.movinggauteng.turfkotlin.helpers.Units import za.co.movinggauteng.turfkotlin.helpers.point /** * Created by Neville on 21 Feb 2017. */ fun along(line: LineString, distance: Double, units: Units) : Point { val coords: List<List<Double>> = line.coordinates var travelled = 0.0 coords.forEachIndexed { i, list -> if (distance >= travelled && i == coords.size - 1) { return@forEachIndexed } else if (travelled >= distance) { val overshot = distance - travelled if (overshot == 0.0) { val pt = Point() pt.coordinates = list return pt } else { val direction = bearing(point(list), point(coords[i - 1])) - 180 return destination(point(list), overshot, direction, units) } } else { travelled += distance(point(list), point(coords[i + 1]), units) } } return point(coords[coords.size - 1]) }
apache-2.0
3e02d191f0e2d97ecede9937729081f9
30.567568
80
0.604452
3.779935
false
false
false
false
cashapp/sqldelight
dialects/sqlite-3-25/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_25/grammar/mixins/ResultColumnMixin.kt
1
941
package app.cash.sqldelight.dialects.sqlite_3_25.grammar.mixins import app.cash.sqldelight.dialects.sqlite_3_25.grammar.psi.SqliteResultColumn import com.alecstrong.sql.psi.core.ModifiableFileLazy import com.alecstrong.sql.psi.core.psi.QueryElement import com.alecstrong.sql.psi.core.psi.QueryElement.QueryResult import com.alecstrong.sql.psi.core.psi.impl.SqlResultColumnImpl import com.intellij.lang.ASTNode internal abstract class ResultColumnMixin(node: ASTNode) : SqlResultColumnImpl(node), SqliteResultColumn { private val queryExposed = ModifiableFileLazy lazy@{ if (windowFunctionInvocation != null) { var column = QueryElement.QueryColumn(this) columnAlias?.let { alias -> column = column.copy(element = alias) } return@lazy listOf(QueryResult(columns = listOf(column))) } return@lazy super.queryExposed() } override fun queryExposed() = queryExposed.forFile(containingFile) }
apache-2.0
f1bad78586a3fdda984edeb2207a68ff
36.64
106
0.772582
3.872428
false
false
false
false
matejdro/WearMusicCenter
mobile/src/test/java/com/matejdro/wearmusiccenter/util/StreamIntegerTest.kt
1
1667
package com.matejdro.wearmusiccenter.util import org.junit.Assert.* import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.DataOutputStream class StreamIntegerTest { @Test fun testReadingInteger() { val arrayStream = ByteArrayOutputStream() val dataStream = DataOutputStream(arrayStream) dataStream.writeInt(1234) dataStream.writeInt(-4321) dataStream.writeInt(0) dataStream.writeInt(Int.MAX_VALUE) dataStream.writeInt(Int.MIN_VALUE) val array = arrayStream.toByteArray() val inputStream = ByteArrayInputStream(array) assertEquals(1234, inputStream.readInt()) assertEquals(-4321, inputStream.readInt()) assertEquals(0, inputStream.readInt()) assertEquals(Int.MAX_VALUE, inputStream.readInt()) assertEquals(Int.MIN_VALUE, inputStream.readInt()) } @Test fun testWritingInteger() { val arrayStream = ByteArrayOutputStream() arrayStream.writeInt(1234) arrayStream.writeInt(-4321) arrayStream.writeInt(0) arrayStream.writeInt(Int.MAX_VALUE) arrayStream.writeInt(Int.MIN_VALUE) val array = arrayStream.toByteArray() val inputStream = ByteArrayInputStream(array) val dataStream = DataInputStream(inputStream) assertEquals(1234, dataStream.readInt()) assertEquals(-4321, dataStream.readInt()) assertEquals(0, dataStream.readInt()) assertEquals(Int.MAX_VALUE, dataStream.readInt()) assertEquals(Int.MIN_VALUE, dataStream.readInt()) } }
gpl-3.0
bc34d6be08a7eab0097cfe251052832b
32.36
58
0.694661
4.749288
false
true
false
false
syrop/Victor-Events
events/src/main/kotlin/pl/org/seva/events/message/MessagesFragment.kt
1
2308
/* * Copyright (C) 2019 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.events.message import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fr_messages.* import kotlinx.coroutines.launch import pl.org.seva.events.R import pl.org.seva.events.main.extension.onSwipe import pl.org.seva.events.main.extension.plus import pl.org.seva.events.main.extension.verticalDivider import pl.org.seva.events.main.init.instance class MessagesFragment : Fragment(R.layout.fr_messages) { private val messages by instance<Messages>() override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) messages_view.setHasFixedSize(true) messages_view.layoutManager = LinearLayoutManager(context) messages_view.adapter = MessagesAdapter() messages_view.verticalDivider() messages_view.onSwipe { position -> lifecycleScope.launch { messages[position].delete() } } (messages.updatedLiveData() + this) { if (messages.isEmpty()) { messages_view.visibility = View.GONE prompt.visibility = View.VISIBLE } else { messages_view.visibility = View.VISIBLE checkNotNull(messages_view.adapter).notifyDataSetChanged() prompt.visibility = View.GONE } } } }
gpl-3.0
9c5eb8144b62d760061ba89bd43a5192
36.225806
98
0.713172
4.354717
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/Gcs.kt
1
680
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.annotations.Internal /** * GCS data. * * @param endByte Expected ending byte range for the current [uploadLink]. * @param startByte Expected starting byte size for the current [uploadLink]. * @param uploadLink Link for uploading file chunk to. */ @Internal @JsonClass(generateAdapter = true) data class Gcs( @Internal @Json(name = "end_byte") val endByte: Long? = null, @Internal @Json(name = "start_byte") val startByte: Long? = null, @Internal @Json(name = "upload_link") val uploadLink: String? = null )
mit
0b8fa97ea00a77167ad38303ba5a7bbc
22.448276
77
0.702941
3.655914
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsCStringPointerInspection.kt
3
1204
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentDotExpr class RsCStringPointerInspection : RsLocalInspectionTool() { override fun getDisplayName() = "Unsafe CString pointer" override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() { override fun visitMethodCall(asPtrCall: RsMethodCall) { if (asPtrCall.referenceName != "as_ptr") return val unwrapCall = (asPtrCall.parentDotExpr.expr as? RsDotExpr)?.methodCall ?: return if (unwrapCall.referenceName != "unwrap") return val ctorExpr = unwrapCall.parentDotExpr.expr as? RsCallExpr ?: return val pathExpr = ctorExpr.expr if (pathExpr is RsPathExpr && pathExpr.path.identifier?.text == "new" && pathExpr.path.path?.identifier?.text == "CString") { holder.registerProblem(asPtrCall.parentDotExpr, displayName) } } } }
mit
20c01ca91235687136dc8ea8c511cd4b
37.83871
99
0.627076
4.560606
false
false
false
false
TakWolf/Android-HeaderAndFooterRecyclerView
app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/LinearHorizontalActivity.kt
1
1831
package com.takwolf.android.demo.hfrecyclerview.ui.activity import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.takwolf.android.demo.hfrecyclerview.R import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityRecyclerViewBinding import com.takwolf.android.demo.hfrecyclerview.ui.adapter.LinearHorizontalAdapter import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener import com.takwolf.android.demo.hfrecyclerview.vm.SingleListViewModel import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView class LinearHorizontalActivity : AppCompatActivity() { private val viewModel: SingleListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityRecyclerViewBinding.inflate(layoutInflater) binding.toolbar.setTitle(R.string.linear_horizontal) binding.toolbar.setNavigationOnClickListener { finish() } binding.recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) viewModel.extraHolder.setupHorizontal(layoutInflater, binding.recyclerView, binding.hfDashboard) val adapter = LinearHorizontalAdapter(layoutInflater).apply { onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder) onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder) } binding.recyclerView.adapter = adapter viewModel.photosHolder.setupView(this, adapter) setContentView(binding.root) } }
apache-2.0
d5142804bcf3542992fcf5f78b056841
45.948718
104
0.798471
4.975543
false
false
false
false
taigua/exercism
kotlin/flatten-array/src/test/kotlin/FlattenerTest.kt
1
1671
import org.junit.Test import kotlin.test.assertEquals class FlattenerTest { @Test fun flattensANestedList() { val nestedList = listOf<Any>(emptyList<Any>()) assertEquals(emptyList<Any>(), Flattener.flatten(nestedList)) } @Test fun flattens2LevelNestedList() { val nestedList = listOf(1, listOf(2, 3, 4), 5) assertEquals(listOf(1, 2, 3, 4, 5), Flattener.flatten(nestedList)) } @Test fun flattens3LevelNestedList() { val nestedList = listOf(1, listOf(2, 3, 4), 5, listOf(6, listOf(7, 8))) assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), Flattener.flatten(nestedList)) } @Test fun flattens5LevelNestedList() { val nestedList = listOf(0, 2, listOf(listOf(2, 3), 8, 100, 4, listOf(listOf(listOf(50))), -2)) assertEquals(listOf(0, 2, 2, 3, 8, 100, 4, 50, -2), Flattener.flatten(nestedList)) } @Test fun flattens6LevelNestedList() { val nestedList = listOf(1, listOf(2, listOf(listOf(3)), listOf(4, listOf(listOf(5))), 6, 7), 8) assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), Flattener.flatten(nestedList)) } @Test fun flattens6LevelNestedListWithNulls() { val nestedList = listOf(1, listOf(2, null, listOf(listOf(3), null), listOf(4, listOf(listOf(5))), 6, 7, listOf(listOf(null))), 8, null) assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), Flattener.flatten(nestedList)) } @Test fun allNullNestedListReturnsEmptyList() { val nestedList = listOf(null, listOf(null, listOf(null), listOf(listOf(listOf(null)))), null) assertEquals(emptyList<Any>(), Flattener.flatten(nestedList)) } }
mit
0574279c6ff671c2aa2fbc58f270f658
33.833333
143
0.627169
3.250973
false
true
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/extension/RxBindingExtensions.kt
2
3221
@file:Suppress("NOTHING_TO_INLINE") package me.proxer.app.util.extension import android.view.MotionEvent import android.view.View import android.widget.TextView import androidx.annotation.CheckResult import androidx.preference.Preference import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import com.github.rubensousa.previewseekbar.exoplayer.PreviewTimeBar import com.jakewharton.rxbinding3.recyclerview.scrollEvents import io.reactivex.Observable import me.proxer.app.util.rx.PreferenceChangeObservable import me.proxer.app.util.rx.PreferenceClickObservable import me.proxer.app.util.rx.PreviewTimeBarRequestObservable import me.proxer.app.util.rx.SubsamplingScaleImageViewEventObservable import me.proxer.app.util.rx.TextViewLinkClickObservable import me.proxer.app.util.rx.TextViewLinkLongClickObservable import me.proxer.app.util.rx.ViewTouchMonitorObservable @CheckResult inline fun View.touchesMonitored(noinline handled: (MotionEvent) -> Boolean = { true }): Observable<MotionEvent> { return ViewTouchMonitorObservable(this, handled) } @CheckResult inline fun TextView.linkClicks(noinline handled: (String) -> Boolean = { true }): Observable<String> { return TextViewLinkClickObservable(this, handled) } @CheckResult inline fun TextView.linkLongClicks(noinline handled: (String) -> Boolean = { true }): Observable<String> { return TextViewLinkLongClickObservable(this, handled) } @CheckResult inline fun <T> Preference.changes(noinline handled: (T) -> Boolean = { true }): Observable<T> { return PreferenceChangeObservable(this, handled) } @CheckResult inline fun Preference.clicks(noinline handled: (Unit) -> Boolean = { true }): Observable<Unit> { return PreferenceClickObservable(this, handled) } @CheckResult inline fun SubsamplingScaleImageView.events(): Observable<SubsamplingScaleImageViewEventObservable.Event> { return SubsamplingScaleImageViewEventObservable(this) } @CheckResult inline fun PreviewTimeBar.loadRequests(): Observable<Long> { return PreviewTimeBarRequestObservable(this) } @CheckResult inline fun RecyclerView.endScrolls(threshold: Int = 5): Observable<Unit> = scrollEvents() .filter { safeLayoutManager.let { safeLayoutManager -> val pastVisibleItems = when (safeLayoutManager) { is StaggeredGridLayoutManager -> { val visibleItemPositions = IntArray(safeLayoutManager.spanCount).apply { safeLayoutManager.findFirstVisibleItemPositions(this) } when (visibleItemPositions.isNotEmpty()) { true -> visibleItemPositions[0] false -> 0 } } is LinearLayoutManager -> safeLayoutManager.findFirstVisibleItemPosition() else -> 0 } safeLayoutManager.itemCount > 0 && safeLayoutManager.childCount + pastVisibleItems >= safeLayoutManager.itemCount - threshold } } .map { Unit }
gpl-3.0
09411d566c2897aff7795023908a3d06
37.807229
114
0.741385
4.814649
false
false
false
false
jeremymailen/kotlinter-gradle
src/test/kotlin/org/jmailen/gradle/kotlinter/functional/ExtensionTest.kt
1
3979
package org.jmailen.gradle.kotlinter.functional import org.gradle.testkit.runner.TaskOutcome import org.jmailen.gradle.kotlinter.functional.utils.kotlinClass import org.jmailen.gradle.kotlinter.functional.utils.resolve import org.jmailen.gradle.kotlinter.functional.utils.settingsFile import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.io.File internal class ExtensionTest : WithGradleTest.Kotlin() { lateinit var projectRoot: File @BeforeEach fun setUp() { projectRoot = testProjectDir.apply { resolve("settings.gradle") { writeText(settingsFile) } resolve("build.gradle") { // language=groovy val buildScript = """ plugins { id 'kotlin' id 'org.jmailen.kotlinter' } """.trimIndent() writeText(buildScript) } } } @Test fun `extension configures ignoreFailures`() { projectRoot.resolve("build.gradle") { // language=groovy val script = """ kotlinter { ignoreFailures = true } """.trimIndent() appendText(script) } projectRoot.resolve("src/main/kotlin/FileName.kt") { writeText(kotlinClass("DifferentClassName")) } build("lintKotlin").apply { assertEquals(TaskOutcome.SUCCESS, task(":lintKotlinMain")?.outcome) } } @Test fun `extension configures reporters`() { projectRoot.resolve("build.gradle") { // language=groovy val script = """ kotlinter { reporters = ['html'] } """.trimIndent() appendText(script) } projectRoot.resolve("src/main/kotlin/KotlinClass.kt") { writeText(kotlinClass("KotlinClass")) } build("lintKotlin").apply { assertEquals(TaskOutcome.SUCCESS, task(":lintKotlinMain")?.outcome) } val report = projectRoot.resolve("build/reports/ktlint/main-lint.html") assertTrue(report.readText().isNotEmpty()) } @Test fun `extension configures disabledRules`() { projectRoot.resolve("build.gradle") { // language=groovy val script = """ kotlinter { disabledRules = ["filename"] } """.trimIndent() appendText(script) } projectRoot.resolve("src/main/kotlin/FileName.kt") { writeText(kotlinClass("DifferentClassName")) } build("lintKotlin").apply { assertEquals(TaskOutcome.SUCCESS, task(":lintKotlinMain")?.outcome) } } @Test fun `extension properties are evaluated only during task execution`() { projectRoot.resolve("build.gradle") { // language=groovy val buildScript = """ plugins { id 'kotlin' id 'org.jmailen.kotlinter' } tasks.whenTaskAdded { // configure all tasks eagerly } kotlinter { disabledRules = ["filename"] } """.trimIndent() writeText(buildScript) } projectRoot.resolve("src/main/kotlin/FileName.kt") { writeText(kotlinClass("DifferentClassName")) } build("lintKotlin").apply { assertEquals(TaskOutcome.SUCCESS, task(":lintKotlinMain")?.outcome) } } }
apache-2.0
516415cbd7486bc4bb79a038161fb020
29.374046
79
0.52199
5.557263
false
true
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/tools/CustomStorageFlags.kt
1
4629
// Copyright 2022 The Cross-Media Measurement 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.wfanet.panelmatch.client.tools import com.google.crypto.tink.integration.awskms.AwsKmsClient import com.google.crypto.tink.integration.gcpkms.GcpKmsClient import java.io.File import java.util.Optional import org.wfanet.measurement.aws.s3.S3StorageClient import org.wfanet.measurement.common.crypto.tink.TinkKeyStorageProvider import org.wfanet.measurement.gcloud.gcs.GcsFromFlags import org.wfanet.measurement.gcloud.gcs.GcsStorageClient import org.wfanet.measurement.storage.StorageClient import org.wfanet.measurement.storage.filesystem.FileSystemStorageClient import org.wfanet.panelmatch.client.deploy.DaemonStorageClientDefaults import org.wfanet.panelmatch.client.storage.FileSystemStorageFactory import org.wfanet.panelmatch.client.storage.StorageDetails import org.wfanet.panelmatch.client.storage.aws.s3.S3StorageFactory import org.wfanet.panelmatch.client.storage.gcloud.gcs.GcsStorageFactory import org.wfanet.panelmatch.common.ExchangeDateKey import org.wfanet.panelmatch.common.storage.StorageFactory import picocli.CommandLine import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.s3.S3Client // TODO: Add flags to support other storage clients class CustomStorageFlags { @CommandLine.Option( names = ["--storage-type"], description = ["Type of destination storage: \${COMPLETION-CANDIDATES}"], required = true, ) lateinit var storageType: StorageDetails.PlatformCase private set @CommandLine.Option( names = ["--private-storage-root"], description = ["Private storage root directory"], ) private lateinit var privateStorageRoot: File @CommandLine.Option( names = ["--s3-storage-bucket"], description = ["The name of the s3 bucket used for default private storage."], ) lateinit var s3Bucket: String private set @CommandLine.Option( names = ["--s3-region"], description = ["The region the s3 bucket is located in."], ) lateinit var s3Region: String private set @CommandLine.Option( names = ["--tink-key-uri"], description = ["URI for tink"], required = true, ) private lateinit var tinkKeyUri: String @CommandLine.Mixin private lateinit var gcsFlags: GcsFromFlags.Flags private val rootStorageClient: StorageClient by lazy { when (storageType) { StorageDetails.PlatformCase.GCS -> GcsStorageClient.fromFlags(GcsFromFlags(gcsFlags)) StorageDetails.PlatformCase.AWS -> S3StorageClient(S3Client.builder().region(Region.of(s3Region)).build(), s3Bucket) StorageDetails.PlatformCase.FILE -> { require(privateStorageRoot.exists() && privateStorageRoot.isDirectory) FileSystemStorageClient(privateStorageRoot) } else -> throw IllegalArgumentException("Unsupported storage type") } } private val defaults by lazy { if (storageType == StorageDetails.PlatformCase.GCS) { // Register GcpKmsClient before setting storage folders. GcpKmsClient.register(Optional.of(tinkKeyUri), Optional.empty()) } else if (storageType == StorageDetails.PlatformCase.AWS) { // Register AwsKmsClient before setting storage folders. AwsKmsClient.register(Optional.of(tinkKeyUri), Optional.empty()) } DaemonStorageClientDefaults(rootStorageClient, tinkKeyUri, TinkKeyStorageProvider()) } val addResource by lazy { ConfigureResource(defaults) } /** This should be customized per deployment. */ val privateStorageFactories: Map<StorageDetails.PlatformCase, (StorageDetails, ExchangeDateKey) -> StorageFactory> by lazy { when (storageType) { StorageDetails.PlatformCase.GCS -> mapOf(StorageDetails.PlatformCase.GCS to ::GcsStorageFactory) StorageDetails.PlatformCase.FILE -> mapOf(StorageDetails.PlatformCase.FILE to ::FileSystemStorageFactory) StorageDetails.PlatformCase.AWS -> mapOf(StorageDetails.PlatformCase.AWS to ::S3StorageFactory) else -> throw IllegalArgumentException("Unsupported storage type") } } }
apache-2.0
1fe19840c0ebaeb2aaf85373a8f00b02
38.564103
99
0.759343
4.294063
false
false
false
false
dataloom/datastore
src/main/java/com/openlattice/datastore/services/AnalysisService.kt
1
4530
/* * Copyright (C) 2018. OpenLattice, 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/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.datastore.services import com.google.common.collect.Sets import com.openlattice.analysis.requests.NeighborType import com.openlattice.authorization.* import com.openlattice.data.DataGraphManager import com.openlattice.edm.type.PropertyType import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import java.util.* import java.util.stream.Collectors /** * This class is a bundle of layer violations. * TODO: Make it not so. * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ @SuppressFBWarnings( value = ["RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", "BC_BAD_CAST_TO_ABSTRACT_COLLECTION"], justification = "Allowing redundant kotlin null check on lateinit variables, " + "Allowing kotlin collection mapping cast to List" ) class AnalysisService( val dgm: DataGraphManager, val authorizations: AuthorizationManager, val edmManager: EdmManager, val entitySetManager: EntitySetManager ) : AuthorizingComponent { private val authzHelper = EdmAuthorizationHelper(edmManager, authorizations, entitySetManager) /** * This function is a layer violation and should live in */ fun getAuthorizedNeighbors(entitySetIds: Set<UUID>): Map<UUID, Map<UUID, PropertyType>> { val neighborEntitySets = dgm.getNeighborEntitySets(entitySetIds) val allEntitySetIds = neighborEntitySets.asSequence() .flatMap { sequenceOf(it.srcEntitySetId, it.edgeEntitySetId, it.dstEntitySetId) } .toSet() return authzHelper.getAuthorizedPropertiesOnEntitySets( allEntitySetIds, EnumSet.of(Permission.READ), Principals.getCurrentPrincipals() ) } fun getNeighborTypes(entitySetIds: Set<UUID>): Iterable<NeighborType> { val neighborEntitySets = dgm.getNeighborEntitySets(entitySetIds) val allEntitySetIds = neighborEntitySets.asSequence() .flatMap { sequenceOf(it.srcEntitySetId, it.edgeEntitySetId, it.dstEntitySetId) } .toSet() val accessChecks = allEntitySetIds.map { AccessCheck(AclKey(it), EnumSet.of(Permission.READ)) }.toSet() //TODO: These access checks should be performed in the controller. val authorizedEntitySetIds = authorizations .accessChecksForPrincipals(accessChecks, Principals.getCurrentPrincipals()) .filter { it.permissions[Permission.READ] ?: false } .map { it.aclKey[0] } .collect(Collectors.toSet()) val entitySets = entitySetManager.getEntitySetsAsMap(authorizedEntitySetIds) val entityTypes = edmManager.getEntityTypesAsMap(entitySets.values.map { it.entityTypeId }.toSet()) val neighborTypes = Sets.newHashSet<NeighborType>() neighborEntitySets.forEach { val src = entitySetIds.contains(it.srcEntitySetId) val associationEntitySetId = it.edgeEntitySetId val neighborEntitySetId = if (src) it.dstEntitySetId else it.srcEntitySetId if (authorizedEntitySetIds.contains(associationEntitySetId) && authorizedEntitySetIds .contains(neighborEntitySetId)) { neighborTypes.add( NeighborType( entityTypes[entitySets[associationEntitySetId]?.entityTypeId], entityTypes[entitySets[neighborEntitySetId]?.entityTypeId], src ) ) } } return neighborTypes } override fun getAuthorizationManager(): AuthorizationManager { return authorizations } }
gpl-3.0
4e02bd49f067f52e4248206392727835
40.190909
111
0.679691
4.679752
false
false
false
false
CoderLine/alphaTab
src.kotlin/alphaTab/alphaTab/src/commonMain/kotlin/alphaTab/collections/List.kt
1
3025
package alphaTab.collections public class List<T> : Iterable<T> { private val _data: MutableList<T> val length: Double get() = _data.size.toDouble() public constructor() { _data = ArrayList() } public constructor(vararg items: T) { _data = items.toMutableList() } @Suppress("UNCHECKED_CAST") public constructor(size: Int) { _data = ArrayList() var remaining = size while (remaining-- > 0) { _data.add(null as T) } } public constructor(items: Iterable<T>) { _data = items.toMutableList() } private constructor(items: MutableList<T>) { _data = items } public override fun iterator(): Iterator<T> { return _data.iterator() } public fun push(item: T) { _data.add(item) } public fun fill(item: T) { _data.fill(item) } public fun push(items: List<T>) { _data.addAll(items._data) } public operator fun get(index: Int): T { return _data[index] } public operator fun set(index: Int, value: T) { _data[index] = value } public fun filter(predicate: (T) -> Boolean): List<T> { return List(_data.filter(predicate)) } public fun indexOf(value: T): Double { return _data.indexOf(value).toDouble() } public fun pop(): T { return _data.removeLast() } public fun unshift(item:T) { _data.add(0, item) } public fun sort(comparison: (a: T, b: T) -> Double) : List<T> { _data.sortWith { a, b -> comparison(a, b).toInt() } return this } public fun <TOut> map(transform: (v: T) -> TOut): List<TOut> { return List(_data.map(transform)) } public fun map(transform: (v: T) -> Double): DoubleList { val mapped = DoubleList(_data.size) _data.forEachIndexed { index, item -> mapped[index] = transform(item) } return mapped } @kotlin.jvm.JvmName("mapIntToDouble") public fun map(transform: (v: T) -> Int): DoubleList { val mapped = DoubleList(_data.size) _data.forEachIndexed { index, item -> mapped[index] = transform(item).toDouble() } return mapped } public fun reverse(): List<T> { _data.reverse() return this } public fun slice(): List<T> { return List(ArrayList(_data)) } public fun slice(start: Double): List<T> { return List(_data.subList(start.toInt(), _data.size)) } public fun splice(start: Double, deleteCount: Double, vararg newElements: T) { var actualStart = start.toInt() if (actualStart < 0) { actualStart += _data.size } _data.subList(start.toInt(), (start + deleteCount).toInt()).clear() _data.addAll(start.toInt(), newElements.toList()) } public fun join(separator: String): String { return _data.joinToString(separator) } }
mpl-2.0
5d011c6e5a2477484ad55862a1318c1e
22.818898
82
0.556694
3.84371
false
false
false
false
cliffroot/awareness
app/src/main/java/hive/com/paradiseoctopus/awareness/BackgroundDatabaseListenService.kt
1
4524
package hive.com.paradiseoctopus.awareness import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.IBinder import android.support.v7.app.NotificationCompat import com.bumptech.glide.Glide import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.FirebaseDatabase import hive.com.paradiseoctopus.awareness.singleplace.ShowSinglePlaceView import hive.com.paradiseoctopus.awareness.singleplace.SubscriptionModel import hive.com.paradiseoctopus.awareness.utils.BaseChildEventListener import hive.com.paradiseoctopus.awareness.utils.BaseValueEventListener import rx.Observable import rx.schedulers.Schedulers /** * Created by edanylenko on 10/4/16. */ class BackgroundDatabaseListenService(val name : String = "notificationService") : Service() { val PENDING_INTENT_CODE = 119 val NOTIFICATION_CODE = 2001 override fun onBind(intent: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) subscribeToUpdates() return START_STICKY } private fun subscribeToUpdates() { val database : FirebaseDatabase = (applicationContext as App).firebaseDatabase val auth : FirebaseAuth = (applicationContext as App).firebaseAuth val ref = database.getReference("subscriptions").child(auth.currentUser?.uid) // TODO: referencing by non-constant string ref.addValueEventListener(object : BaseValueEventListener() { override fun onDataChange(p0: DataSnapshot?) { p0?.children?.map { child -> child.ref.addChildEventListener(object : BaseChildEventListener() { override fun onChildAdded(p0: DataSnapshot?, p1: String?) { // a new subscription added val model = (p0?.getValue(SubscriptionModel::class.java) as SubscriptionModel) loadUserImage(model.subscriberPhotoUrl).subscribe { bitmap -> showNotification(model, bitmap) } } }) } } }) } private fun showNotification (model : SubscriptionModel, bitmap : Bitmap) { val mBuilder = NotificationCompat.Builder(this@BackgroundDatabaseListenService) .setLargeIcon(bitmap) .setSmallIcon(R.drawable.ic_add_white) .setContentTitle([email protected](R.string.subscription_request)) .setContentText(String.format( [email protected](R.string.user_subscribed_to_your_places), model.subscriberName )) .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false) .setContentIntent(generatePendingIntent(model.ownerUserId, model.placeId)) val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager mNotificationManager.notify(NOTIFICATION_CODE, mBuilder.build()) } private fun generatePendingIntent(ownerId : String, placeId : String): PendingIntent? { val intent : Intent = Intent(this, ShowSinglePlaceView::class.java) intent.data = Uri.parse("${resources.getString(R.string.API_PATH)}$ownerId/$placeId") val pendingIntent : PendingIntent = PendingIntent.getActivity( this, PENDING_INTENT_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT) return pendingIntent } private fun loadUserImage (imageUrl : String) : Observable<Bitmap> { return Observable.create<Bitmap> { try { val theBitmap = Glide.with(this@BackgroundDatabaseListenService).load(imageUrl).asBitmap().into(128, 128).get() it.onNext(theBitmap) it.onCompleted() } catch (e : Exception) { //it.onNext() TODO :// show something it.onCompleted() } }.subscribeOn(Schedulers.computation()) } }
apache-2.0
d9d7ac6618a6695654a1e2c5519c6e50
42.92233
130
0.655615
5.117647
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/module/text/TextEntity.kt
1
771
package com.intfocus.template.subject.nine.module.text import org.json.JSONObject /** * @author liuruilin * @data 2017/11/1 * @describe */ class TextEntity { /** * element_type : * title : 问题反馈标题 * sub_title : * hint : 问题简单描述 * value : */ var title: String = "" var value: String = "" var element_type: String = "" var sub_title: String = "" var hint: String = "" override fun toString(): String { var textJson = JSONObject() textJson.put("title", title) textJson.put("sub_title", sub_title) textJson.put("hint", hint) textJson.put("element_type", element_type) textJson.put("value", value) return textJson.toString() } }
gpl-3.0
333d5de5effdbb5adc6aaafc2cc49b48
21.636364
54
0.576975
3.540284
false
false
false
false
BoD/CineToday
app/src/main/kotlin/org/jraf/android/cinetoday/glide/CineTodayGlideModule.kt
1
5051
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([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 org.jraf.android.cinetoday.glide import android.content.Context import android.net.Uri import com.bumptech.glide.Glide import com.bumptech.glide.GlideBuilder import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.Options import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory import com.bumptech.glide.load.engine.cache.LruResourceCache import com.bumptech.glide.load.engine.cache.MemorySizeCalculator import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.load.model.ModelLoader import com.bumptech.glide.load.model.ModelLoaderFactory import com.bumptech.glide.load.model.MultiModelLoaderFactory import com.bumptech.glide.module.AppGlideModule import com.bumptech.glide.request.RequestOptions import okhttp3.OkHttpClient import org.jraf.android.cinetoday.BuildConfig import org.jraf.android.cinetoday.dagger.Components import org.jraf.android.util.log.Log import java.io.InputStream @GlideModule class CineTodayGlideModule : AppGlideModule() { companion object { private const val CACHE_SIZE_B = 5 * 1024 * 1024L private const val CACHE_DIRECTORY_NAME = "images" private const val CLOUD_IMG_URL = "https://ce8eb4b9c.cloudimg.io/crop" private const val CLOUD_IMG_FORMAT = "twebp" } override fun applyOptions(context: Context, builder: GlideBuilder) { val memorySizeCalculator = MemorySizeCalculator.Builder(context).build() builder // Disk cache .setDiskCache(InternalCacheDiskCacheFactory(context, CACHE_DIRECTORY_NAME, CACHE_SIZE_B)) // Memory cache / bitmap pool .setMemoryCache(LruResourceCache(memorySizeCalculator.memoryCacheSize.toLong())) .setBitmapPool(LruBitmapPool(memorySizeCalculator.bitmapPoolSize.toLong())) .setDefaultRequestOptions( RequestOptions() // Decode format - RGB565 is enough .format(DecodeFormat.PREFER_RGB_565) // Disable this optimization because we need to access pixels (because we use Palette on them) .disallowHardwareConfig() ) // Logs .setLogLevel(if (BuildConfig.DEBUG_LOGS) android.util.Log.VERBOSE else android.util.Log.WARN) } override fun isManifestParsingEnabled() = false override fun registerComponents(context: Context, glide: Glide, registry: Registry) { val okHttpClient = Components.application.notCachingOkHttpClient registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlResizeModelLoaderFactory(okHttpClient)) } /** * Manipulate image uris to use the 'zimage.io' service that serves resized images. */ private class OkHttpUrlResizeModelLoaderFactory(private val okHttpClient: OkHttpClient) : ModelLoaderFactory<GlideUrl, InputStream> { override fun build(factories: MultiModelLoaderFactory): ModelLoader<GlideUrl, InputStream> { return object : OkHttpUrlLoader(okHttpClient) { override fun buildLoadData( model: GlideUrl, width: Int, height: Int, options: Options ): ModelLoader.LoadData<InputStream>? { var uri = Uri.parse(CLOUD_IMG_URL) uri = uri.buildUpon() .appendPath("${width}x$height") .appendPath(CLOUD_IMG_FORMAT) .appendPath(model.toStringUrl()) .build() val cloudImgUrl = GlideUrl(uri.toString()) Log.d("cloudImgUrl=$cloudImgUrl") return super.buildLoadData(cloudImgUrl, width, height, options) } } } override fun teardown() {} } }
gpl-3.0
069425bd961c6b49b82212f8bbe8ee31
40.743802
120
0.661849
4.575181
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/psi/PluginPsiTest.kt
1
85623
/* * Copyright (C) 2016-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.tests.psi import com.intellij.navigation.ItemPresentation import com.intellij.navigation.NavigationItem import com.intellij.openapi.extensions.PluginId import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.util.elementType import org.hamcrest.CoreMatchers.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.navigation.ItemPresentationEx import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFileSystem import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.module.path.XdmModuleType import uk.co.reecedunn.intellij.plugin.xdm.types.* import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginContextItemFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginLambdaFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginSequenceTypeList import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginTypeAlias import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.* import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType import uk.co.reecedunn.intellij.plugin.xpath.model.getPrincipalNodeKind import uk.co.reecedunn.intellij.plugin.xpath.model.getUsageType import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathIcons import uk.co.reecedunn.intellij.plugin.xpm.context.XpmUsageType import uk.co.reecedunn.intellij.plugin.xpm.context.expand import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmAccessLevel import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmAnnotated import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmCatchClause import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.text import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionDeclaration import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionProvider import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmArrayExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmMapExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.item.keyName import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceProvider import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmAxisType import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmPathStep import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.* import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.* import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType import uk.co.reecedunn.intellij.plugin.xquery.model.getNamespaceType import uk.co.reecedunn.intellij.plugin.xquery.optree.XQueryFunctionProvider import uk.co.reecedunn.intellij.plugin.xquery.optree.XQueryNamespaceProvider import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryElementType import uk.co.reecedunn.intellij.plugin.xquery.resources.XQueryIcons import uk.co.reecedunn.intellij.plugin.xquery.tests.parser.ParserTestCase import xqt.platform.intellij.saxon.SaxonXPathTokenProvider import xqt.platform.intellij.xpath.XPathTokenProvider @Suppress("RedundantVisibilityModifier", "Reformat") @DisplayName("XQuery IntelliJ Plugin - IntelliJ Program Structure Interface (PSI) - XQuery") class PluginPsiTest : ParserTestCase() { override val pluginId: PluginId = PluginId.getId("PluginPsiTest") private val res = ResourceVirtualFileSystem(this::class.java.classLoader) fun parseResource(resource: String): XQueryModule = res.toPsiFile(resource, project) override fun registerServicesAndExtensions() { super.registerServicesAndExtensions() XpmNamespaceProvider.register(this, XQueryNamespaceProvider) XpmFunctionProvider.register(this, XQueryFunctionProvider) } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.1) SequenceType Syntax") internal inner class SequenceTypeSyntax { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (72) DocumentTest") internal inner class DocumentTest { @Test @DisplayName("array node") fun arrayNode() { val test = parse<XPathDocumentTest>("() instance of document-node ( array-node ( (::) ) )")[0] assertThat(test.rootNodeType, `is`(instanceOf(PluginAnyArrayNodeTest::class.java))) val type = test as XdmItemType assertThat(type.typeName, `is`("document-node(array-node())")) assertThat(type.typeClass, `is`(sameInstance(XdmDocumentNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("object node") fun objectNode() { val test = parse<XPathDocumentTest>("() instance of document-node ( object-node ( (::) ) )")[0] assertThat(test.rootNodeType, `is`(instanceOf(PluginAnyMapNodeTest::class.java))) val type = test as XdmItemType assertThat(type.typeName, `is`("document-node(object-node())")) assertThat(type.typeClass, `is`(sameInstance(XdmDocumentNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (68) NamedKindTest") fun namedKindTest() { val test = parse<PluginNamedKindTest>("() instance of node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (71) NamedNumberNodeTest") fun namedTextTest() { val test = parse<PluginNamedTextTest>("() instance of text ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("text(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmTextNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.2) Tuple Test") internal inner class RecordTest { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (23) RecordTest") internal inner class RecordTest { @Test @DisplayName("empty") fun empty() { val test = parse<XPathRecordTest>("() instance of tuple ( (::) )")[0] assertThat(test.fields.count(), `is`(0)) assertThat(test.isExtensible, `is`(true)) val type = test as XdmItemType assertThat(type.typeName, `is`("map(*)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("one field") fun one() { val test = parse<XPathRecordTest>("() instance of tuple ( test )")[0] assertThat(test.fields.count(), `is`(1)) assertThat(test.isExtensible, `is`(false)) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("multiple fields") fun multiple() { val test = parse<XPathRecordTest>("() instance of tuple ( x : xs:float , y : xs:float )")[0] assertThat(test.fields.count(), `is`(2)) assertThat(test.isExtensible, `is`(false)) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(x: xs:float, y: xs:float)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("empty; extensible") fun emptyExtensible() { val test = parse<XPathRecordTest>("() instance of tuple ( * )")[0] assertThat(test.fields.count(), `is`(0)) assertThat(test.isExtensible, `is`(true)) val type = test as XdmItemType assertThat(type.typeName, `is`("map(*)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("multiple fields; extensible") fun multipleExtensible() { val test = parse<XPathRecordTest>("() instance of tuple ( x : xs:float , y : xs:float , * )")[0] assertThat(test.fields.count(), `is`(2)) assertThat(test.isExtensible, `is`(true)) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(x: xs:float, y: xs:float, *)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (24) FieldDeclaration") internal inner class FieldDeclaration { @Test @DisplayName("required; unspecified type") fun nameOnlyRequired() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType, `is`(nullValue())) assertThat(field.fieldSeparator, `is`(nullValue())) assertThat(field.isOptional, `is`(false)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("optional; unspecified type") fun nameOnlyOptional() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test ? )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType, `is`(nullValue())) assertThat(field.fieldSeparator, `is`(nullValue())) assertThat(field.isOptional, `is`(true)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test?)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("required; specified type (Saxon 9.8 syntax)") fun nameAndTypeRequired_saxon9() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test : xs:string )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType?.typeName, `is`("xs:string")) assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon)) assertThat(field.isOptional, `is`(false)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test: xs:string)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("optional; specified type (Saxon 9.8 syntax)") fun nameAndTypeOptional_saxon9() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test ? : xs:string )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType?.typeName, `is`("xs:string")) assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon)) assertThat(field.isOptional, `is`(true)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test?: xs:string)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("optional; specified type; compact whitespace (Saxon 9.8 syntax)") fun nameAndTypeOptional_compactWhitespace_saxon9() { val field = parse<XPathFieldDeclaration>("() instance of tuple(test?:xs:string)")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType?.typeName, `is`("xs:string")) assertThat(field.fieldSeparator, `is`(XPathTokenType.ELVIS)) assertThat(field.isOptional, `is`(true)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test?: xs:string)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("required; specified type (Saxon 10 syntax)") fun nameAndTypeRequired_saxon10() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test as xs:string )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType?.typeName, `is`("xs:string")) assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs)) assertThat(field.isOptional, `is`(false)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test as xs:string)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("optional; specified type (Saxon 10 syntax)") fun nameAndTypeOptional_saxon10() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( test ? as xs:string )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType?.typeName, `is`("xs:string")) assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs)) assertThat(field.isOptional, `is`(true)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test? as xs:string)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("StringLiteral name; no space in name") fun stringLiteralName_noSpace() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( 'test' )")[0] assertThat(field.fieldName.data, `is`("test")) assertThat(field.fieldType, `is`(nullValue())) assertThat(field.fieldSeparator, `is`(nullValue())) assertThat(field.isOptional, `is`(false)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("StringLiteral name; space in name") fun stringLiteralName_withSpace() { val field = parse<XPathFieldDeclaration>("() instance of tuple ( 'test key name' )")[0] assertThat(field.fieldName.data, `is`("test key name")) assertThat(field.fieldType, `is`(nullValue())) assertThat(field.fieldSeparator, `is`(nullValue())) assertThat(field.isOptional, `is`(false)) val test = field.parent as XPathRecordTest assertThat(test.fields.first(), `is`(sameInstance(field))) val type = test as XdmItemType assertThat(type.typeName, `is`("tuple(\"test key name\")")) assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.3) Binary Test") internal inner class BinaryTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (29) BinaryTest") fun binaryTest() { val type = parse<PluginBinaryTest>("() instance of binary ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("binary()")) assertThat(type.typeClass, `is`(sameInstance(XdmBinary::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.4) Schema Kind Tests") internal inner class SchemaKindTests { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (37) AttributeDeclTest") internal inner class AttributeTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginAttributeDeclTest>("() instance of attribute-decl ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("attribute-decl()")) assertThat(type.typeClass, `is`(sameInstance(XdmAttributeDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginAttributeDeclTest>("() instance of attribute-decl ( * )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("attribute-decl()")) assertThat(type.typeClass, `is`(sameInstance(XdmAttributeDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginAttributeDeclTest>("() instance of attribute-decl ( test )")[0] assertThat(test.nodeName?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("attribute-decl(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmAttributeDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (38) ComplexTypeTest") internal inner class ComplexTypeTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginComplexTypeTest>("() instance of complex-type ( (::) )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("complex-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmComplexType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginComplexTypeTest>("() instance of complex-type ( * )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("complex-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmComplexType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginComplexTypeTest>("() instance of complex-type ( test )")[0] assertThat(test.schemaType?.type?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("complex-type(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmComplexType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (39) ElementDeclTest") internal inner class ElementDeclTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginElementDeclTest>("() instance of element-decl ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("element-decl()")) assertThat(type.typeClass, `is`(sameInstance(XdmElementDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginElementDeclTest>("() instance of element-decl ( * )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("element-decl()")) assertThat(type.typeClass, `is`(sameInstance(XdmElementDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginElementDeclTest>("() instance of element-decl ( test )")[0] assertThat(test.nodeName?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("element-decl(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmElementDecl::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (40) SchemaComponentTest") fun schemaComponentTest() { val type = parse<PluginSchemaComponentTest>("() instance of schema-component ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("schema-component()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaComponent::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (41) SchemaParticleTest") internal inner class SchemaParticleTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginSchemaParticleTest>("() instance of schema-particle ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-particle()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaParticle::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginSchemaParticleTest>("() instance of schema-particle ( * )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-particle()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaParticle::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginSchemaParticleTest>("() instance of schema-particle ( test )")[0] assertThat(test.nodeName?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-particle(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaParticle::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (42) SchemaRootTest") fun schemaRootTest() { val type = parse<PluginSchemaRootTest>("() instance of schema-root ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("schema-root()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaRoot::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (43) SchemaTypeTest") internal inner class SchemaTypeTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginSchemaTypeTest>("() instance of schema-type ( (::) )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginSchemaTypeTest>("() instance of schema-type ( * )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginSchemaTypeTest>("() instance of schema-type ( test )")[0] assertThat(test.schemaType?.type?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-type(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (44) SimpleTypeTest") internal inner class SimpleTypeTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginSimpleTypeTest>("() instance of simple-type ( (::) )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("simple-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmSimpleType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginSimpleTypeTest>("() instance of simple-type ( * )")[0] assertThat(test.schemaType, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("simple-type()")) assertThat(type.typeClass, `is`(sameInstance(XdmSimpleType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginSimpleTypeTest>("() instance of simple-type ( test )")[0] assertThat(test.schemaType?.type?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("simple-type(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmSimpleType::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (45) SchemaFacetTest") internal inner class SchemaFacetTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginSchemaFacetTest>("() instance of schema-facet ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-facet()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaFacet::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginSchemaFacetTest>("() instance of schema-facet ( * )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-facet()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaFacet::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginSchemaFacetTest>("() instance of schema-facet ( test )")[0] assertThat(test.nodeName?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("schema-facet(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaFacet::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (103) SchemaWildcardTest") fun schemaWildcardTest() { val type = parse<PluginSchemaWildcardTest>("() instance of schema-wildcard ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("schema-wildcard()")) assertThat(type.typeClass, `is`(sameInstance(XdmSchemaWildcard::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (104) ModelGroupTest") internal inner class ModelGroupTest { @Test @DisplayName("any; empty") fun anyEmpty() { val test = parse<PluginModelGroupTest>("() instance of model-group ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("model-group()")) assertThat(type.typeClass, `is`(sameInstance(XdmModelGroup::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("any; wildcard") fun anyWildcard() { val test = parse<PluginModelGroupTest>("() instance of model-group ( (::) )")[0] assertThat(test.nodeName, `is`(nullValue())) val type = test as XdmItemType assertThat(type.typeName, `is`("model-group()")) assertThat(type.typeClass, `is`(sameInstance(XdmModelGroup::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("name") fun name() { val test = parse<PluginModelGroupTest>("() instance of model-group ( test )")[0] assertThat(test.nodeName?.localName!!.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("model-group(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmModelGroup::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.5.1) Boolean Node Test") internal inner class BooleanNodeTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (48) AnyBooleanNodeTest") fun anyBooleanTest() { val type = parse<PluginAnyBooleanNodeTest>("() instance of boolean-node ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("boolean-node()")) assertThat(type.typeClass, `is`(sameInstance(XdmBooleanNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (61) NamedBooleanNodeTest") fun namedBooleanTest() { val test = parse<PluginNamedBooleanNodeTest>("() instance of boolean-node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("boolean-node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmBooleanNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.5.2) Number Node Test") internal inner class NumberNodeTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (52) AnyNumberNodeTest") fun anyNumberTest() { val type = parse<PluginAnyNumberNodeTest>("() instance of number-node ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("number-node()")) assertThat(type.typeClass, `is`(sameInstance(XdmNumberNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (53) NamedNumberNodeTest") fun namedNumberTest() { val test = parse<PluginNamedNumberNodeTest>("() instance of number-node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("number-node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmNumberNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.5.3) Null Node Test") internal inner class NullNodeTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (56) AnyNullNodeTest") fun anyNullTest() { val type = parse<PluginAnyNullNodeTest>("() instance of null-node ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("null-node()")) assertThat(type.typeClass, `is`(sameInstance(XdmNullNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (57) NamedNullNodeTest") fun namedNullTest() { val test = parse<PluginNamedNullNodeTest>("() instance of null-node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("null-node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmNullNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.5.4) Array Node Test") internal inner class ArrayNodeTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (60) AnyArrayNodeTest") fun anyArrayTest() { val type = parse<PluginAnyArrayNodeTest>("() instance of array-node ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("array-node()")) assertThat(type.typeClass, `is`(sameInstance(XdmArrayNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (61) NamedArrayNodeTest") fun namedArrayTest() { val test = parse<PluginNamedArrayNodeTest>("() instance of array-node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("array-node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmArrayNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.5.5) Map Node Test") internal inner class MapNodeTest { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (64) AnyMapNodeTest") fun anyMapTest() { val type = parse<PluginAnyMapNodeTest>("() instance of object-node ( (::) )")[0] as XdmItemType assertThat(type.typeName, `is`("object-node()")) assertThat(type.typeClass, `is`(sameInstance(XdmObjectNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (65) NamedMapNodeTest") fun namedMapTest() { val test = parse<PluginNamedMapNodeTest>("() instance of object-node ( \"test\" )")[0] assertThat(test.keyName.data, `is`("test")) val type = test as XdmItemType assertThat(type.typeName, `is`("object-node(\"test\")")) assertThat(type.typeClass, `is`(sameInstance(XdmObjectNode::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.6) Sequence Types") internal inner class SequenceTypes { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (87) SequenceTypeList") internal inner class SequenceTypeList { @Test @DisplayName("parenthesized") fun parenthesized() { val test = parse<PluginSequenceTypeList>( "() instance of ( node ( (::) ) , xs:string , array ( * ) )" )[0] assertThat(test.isParenthesized, `is`(true)) val type = test as XdmSequenceTypeList assertThat(type.typeName, `is`("(node(), xs:string, array(*))")) val types = type.types.toList() assertThat(types.size, `is`(3)) assertThat(types[0].typeName, `is`("node()")) assertThat(types[1].typeName, `is`("xs:string")) assertThat(types[2].typeName, `is`("array(*)")) assertThat(type.itemType?.typeName, `is`("item()")) assertThat(type.lowerBound, `is`(0)) assertThat(type.upperBound, `is`(Int.MAX_VALUE)) } @Test @DisplayName("not parenthesized") fun notParenthesized() { val test = parse<PluginSequenceTypeList>( "() instance of ( xs:int | node ( (::) ) , xs:string , array ( * ) )" )[0] assertThat(test.isParenthesized, `is`(false)) val type = test as XdmSequenceTypeList assertThat(type.typeName, `is`("node(), xs:string, array(*)")) val types = type.types.toList() assertThat(types.size, `is`(3)) assertThat(types[0].typeName, `is`("node()")) assertThat(types[1].typeName, `is`("xs:string")) assertThat(types[2].typeName, `is`("array(*)")) assertThat(type.itemType?.typeName, `is`("item()")) assertThat(type.lowerBound, `is`(0)) assertThat(type.upperBound, `is`(Int.MAX_VALUE)) } } @Test @DisplayName("XQuery 3.1 EBNF (76) SequenceTypeUnion") fun sequenceTypeUnion() { val test = parse<XQuerySequenceTypeUnion>("() instance of ( node ( (::) ) | xs:string | array ( * ) )")[0] assertThat(test.isParenthesized, `is`(true)) val type = test as XdmSequenceTypeUnion assertThat(type.typeName, `is`("(node() | xs:string | array(*))")) val types = type.types.toList() assertThat(types.size, `is`(3)) assertThat(types[0].typeName, `is`("node()")) assertThat(types[1].typeName, `is`("xs:string")) assertThat(types[2].typeName, `is`("array(*)")) assertThat(type.itemType?.typeName, `is`("item()")) assertThat(type.lowerBound, `is`(0)) assertThat(type.upperBound, `is`(Int.MAX_VALUE)) } @Test @DisplayName("XQuery IntelliJ Plugin EBNF (98) EmptySequenceType") fun emptySequence() { val type = parse<XPathSequenceType>("() instance of empty ( (::) )")[0] as XdmSequenceType assertThat(type.typeName, `is`("empty-sequence()")) assertThat(type.itemType, `is`(nullValue())) assertThat(type.lowerBound, `is`(0)) assertThat(type.upperBound, `is`(0)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (2.1.2.9) Type Alias") internal inner class TypeAlias { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (116) TypeAlias") internal inner class TypeAlias { @Test @DisplayName("NCName namespace resolution") fun ncname() { val qname = parse<XPathEQName>( """ declare default function namespace "http://www.example.co.uk/function"; declare default element namespace "http://www.example.co.uk/element"; () instance of ~ test """ )[0] as XsQNameValue assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType)) assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type)) assertThat(qname.isLexicalQName, `is`(true)) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("test")) assertThat(qname.element, sameInstance(qname as PsiElement)) val expanded = qname.expand().toList() assertThat(expanded.size, `is`(1)) assertThat(expanded[0].isLexicalQName, `is`(false)) assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element")) assertThat(expanded[0].prefix, `is`(nullValue())) assertThat(expanded[0].localName!!.data, `is`("test")) assertThat(expanded[0].element, sameInstance(qname as PsiElement)) } @Test @DisplayName("item type; Saxon 9.8") fun itemType_saxon9() { val test = parse<PluginTypeAlias>("() instance of ~ test")[0] assertThat(test.type, `is`(sameInstance(test.children().filterIsInstance<XsQNameValue>().first()))) val type = test as XdmItemType assertThat(type.typeName, `is`("type(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmItem::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } @Test @DisplayName("item type; Saxon 10.0") fun itemType_saxon10() { val test = parse<PluginTypeAlias>("() instance of type ( test )")[0] assertThat(test.type, `is`(sameInstance(test.children().filterIsInstance<XsQNameValue>().first()))) val type = test as XdmItemType assertThat(type.typeName, `is`("type(test)")) assertThat(type.typeClass, `is`(sameInstance(XdmItem::class.java))) assertThat(type.itemType, `is`(sameInstance(type))) assertThat(type.lowerBound, `is`(1)) assertThat(type.upperBound, `is`(1)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.5) Update Expressions") internal inner class UpdateExpressions { @Nested @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (12) UpdateExpr") internal inner class UpdateExpr { @Test @DisplayName("enclosed expression") fun enclosedExpr() { val expr = parse<PluginUpdateExpr>("() update { () }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryTokenType.K_UPDATE)) assertThat(expr.expressionElement?.textOffset, `is`(3)) } @Test @DisplayName("expression") fun expr() { val expr = parse<PluginUpdateExpr>("() update ()")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryTokenType.K_UPDATE)) assertThat(expr.expressionElement?.textOffset, `is`(3)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.7) Primary Expressions") internal inner class PrimaryExpressions { @Nested @DisplayName("XQuery IntelliJ Plugin (3.7.1) Non-Deterministic Function Calls") internal inner class NonDeterministicFunctionCalls { @Test @DisplayName("XQuery IntelliJ Plugin EBNF (16) NonDeterministicFunctionCall") fun nonDeterministicFunctionCall() { val expr = parse<PluginNonDeterministicFunctionCall>("non-deterministic \$x()")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST)) assertThat(expr.expressionElement?.textOffset, `is`(20)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.7.2) Inline Function Expressions") internal inner class InlineFunctionExpressions { @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (81) ContextItemFunctionExpr") fun contextItemFunctionExpr() { val expr = parse<PluginContextItemFunctionExpr>(".{ () }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CONTEXT_ITEM_FUNCTION_EXPR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (117) LambdaFunctionExpr") fun lambdaFunctionExpr() { val expr = parse<PluginLambdaFunctionExpr>("_{ $1 }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.LAMBDA_FUNCTION_EXPR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.8) JSON Constructors") internal inner class JSONConstructors { @Nested @DisplayName("XQuery IntelliJ Plugin (3.8.1) Maps") internal inner class Maps { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (66) MapConstructor") internal inner class MapConstructor { @Test @DisplayName("empty") fun empty() { val expr = parse<XPathMapConstructor>("object-node {}")[0] as XpmMapExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.MAP_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) assertThat(expr.itemTypeClass, sameInstance(XdmObjectNode::class.java)) assertThat(expr.itemExpression, sameInstance(expr)) val entries = expr.entries.toList() assertThat(entries.size, `is`(0)) } @Test @DisplayName("with entries") fun withEntries() { val expr = parse<XPathMapConstructor>("object-node { \"1\" : \"one\", \"2\" : \"two\" }")[0] as XpmMapExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.MAP_CONSTRUCTOR_ENTRY)) assertThat(expr.expressionElement?.textOffset, `is`(14)) assertThat(expr.itemTypeClass, sameInstance(XdmObjectNode::class.java)) assertThat(expr.itemExpression, sameInstance(expr)) val entries = expr.entries.toList() assertThat(entries.size, `is`(2)) assertThat((entries[0].keyExpression as XPathStringLiteral).data, `is`("1")) assertThat((entries[0].valueExpression as XPathStringLiteral).data, `is`("one")) assertThat((entries[1].keyExpression as XPathStringLiteral).data, `is`("2")) assertThat((entries[1].valueExpression as XPathStringLiteral).data, `is`("two")) } } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (17) MapConstructorEntry") internal inner class MapConstructorEntry { @Test @DisplayName("MarkLogic") fun markLogic() { val entry = parse<XPathMapConstructorEntry>("object-node { \"1\" : \"one\" }")[0] assertThat(entry.separator.elementType, `is`(XPathTokenProvider.Colon)) assertThat((entry.keyExpression as XPathStringLiteral).data, `is`("1")) assertThat((entry.valueExpression as XPathStringLiteral).data, `is`("one")) assertThat(entry.keyName, `is`(nullValue())) } @Test @DisplayName("Saxon") fun saxon() { val entry = parse<XPathMapConstructorEntry>("map { \"1\" := \"one\" }")[0] assertThat(entry.separator.elementType, `is`(XPathTokenProvider.AssignEquals)) assertThat((entry.keyExpression as XPathStringLiteral).data, `is`("1")) assertThat((entry.valueExpression as XPathStringLiteral).data, `is`("one")) assertThat(entry.keyName, `is`(nullValue())) } } } @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (50) BooleanConstructor") fun booleanConstructor() { val expr = parse<PluginBooleanConstructor>("boolean-node { true() }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.BOOLEAN_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (54) NumberConstructor") fun numberConstructor() { val expr = parse<PluginNumberConstructor>("number-node { 1 }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.NUMBER_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (58) NullConstructor") fun nullConstructor() { val expr = parse<PluginNullConstructor>("null-node {}")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.NULL_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (62) ArrayConstructor") internal inner class CurlyArrayConstructor { @Test @DisplayName("empty") fun empty() { val expr = parse<XPathCurlyArrayConstructor>("array-node {}")[0] as XpmArrayExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) assertThat(expr.itemTypeClass, sameInstance(XdmArrayNode::class.java)) assertThat(expr.itemExpression, sameInstance(expr)) val entries = expr.memberExpressions.toList() assertThat(entries.size, `is`(0)) } @Test @DisplayName("single member") fun singleMember() { val expr = parse<XPathCurlyArrayConstructor>("array-node { 1 }")[0] as XpmArrayExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) assertThat(expr.itemTypeClass, sameInstance(XdmArrayNode::class.java)) assertThat(expr.itemExpression, sameInstance(expr)) val entries = expr.memberExpressions.toList() assertThat(entries.size, `is`(1)) assertThat(entries[0].text, `is`("1")) } @Test @DisplayName("multiple members") fun multipleMembers() { val expr = parse<XPathCurlyArrayConstructor>("array-node { 1, 2 + 3, 4 }")[0] as XpmArrayExpression assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) assertThat(expr.itemTypeClass, sameInstance(XdmArrayNode::class.java)) assertThat(expr.itemExpression, sameInstance(expr)) val entries = expr.memberExpressions.toList() assertThat(entries.size, `is`(3)) assertThat(entries[0].text, `is`("1")) assertThat(entries[1].text, `is`("2 + 3")) assertThat(entries[2].text, `is`("4")) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.9.1) Axes") internal inner class Axes { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (25) ForwardAxis") internal inner class ForwardAxis { @Test @DisplayName("namespace axis") fun namespaceAxis() { val step = parse<XPathForwardStep>("namespace::test")[0] as XpmPathStep assertThat(step.axisType, `is`(XpmAxisType.Namespace)) assertThat(step.nodeType, sameInstance(XdmNamespaceItem)) } @Test @DisplayName("property axis") fun propertyAxis() { val step = parse<XPathForwardStep>("property::test")[0] as XpmPathStep assertThat(step.axisType, `is`(XpmAxisType.Property)) assertThat(step.nodeType, sameInstance(XdmElementItem)) } @Test @DisplayName("principal node kind") fun principalNodeKind() { val steps = parse<XPathNameTest>("property::one") assertThat(steps.size, `is`(1)) assertThat(steps[0].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // property } @Test @DisplayName("usage type") fun usageType() { val steps = parse<XPathNameTest>("property::one").map { it.walkTree().filterIsInstance<XsQNameValue>().first().element!! } assertThat(steps.size, `is`(1)) assertThat(steps[0].getUsageType(), `is`(XpmUsageType.Element)) // property } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.12) Binary Constructors") internal inner class TryCatchExpressions { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (31) CatchClause") internal inner class CatchClause { @Test @DisplayName("NCName") fun ncname() { val expr = parse<XQueryCatchClause>("try { 1 } catch (\$x) { 2 }")[0] as XpmCatchClause assertThat(expr.catchExpression.text, `is`("2")) assertThat(expr.errorList.count(), `is`(0)) val qname = expr.variableName!! assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("x")) val localScope = expr.variableName?.element?.useScope as LocalSearchScope assertThat(localScope.scope.size, `is`(1)) assertThat(localScope.scope[0], `is`(instanceOf(XQueryCatchClause::class.java))) } @Test @DisplayName("QName") fun qname() { val expr = parse<XQueryCatchClause>("try { 1 } catch (\$a:x) { 2 }")[0] as XpmCatchClause assertThat(expr.catchExpression.text, `is`("2")) assertThat(expr.errorList.count(), `is`(0)) val qname = expr.variableName!! assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.prefix!!.data, `is`("a")) assertThat(qname.localName!!.data, `is`("x")) val localScope = expr.variableName?.element?.useScope as LocalSearchScope assertThat(localScope.scope.size, `is`(1)) assertThat(localScope.scope[0], `is`(instanceOf(XQueryCatchClause::class.java))) } @Test @DisplayName("URIQualifiedName") fun uriQualifiedName() { val expr = parse<XQueryCatchClause>( "try { 1 } catch (\$Q{http://www.example.com}x) { 2 }" )[0] as XpmCatchClause assertThat(expr.catchExpression.text, `is`("2")) assertThat(expr.errorList.count(), `is`(0)) val qname = expr.variableName!! assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.namespace!!.data, `is`("http://www.example.com")) assertThat(qname.localName!!.data, `is`("x")) val localScope = expr.variableName?.element?.useScope as LocalSearchScope assertThat(localScope.scope.size, `is`(1)) assertThat(localScope.scope[0], `is`(instanceOf(XQueryCatchClause::class.java))) } @Test @DisplayName("missing VarName") fun noVarName() { val expr = parse<XQueryCatchClause>("try { 1 } catch () { 2 }")[0] as XpmCatchClause assertThat(expr.variableName, `is`(nullValue())) assertThat(expr.catchExpression.text, `is`("2")) assertThat(expr.errorList.count(), `is`(0)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.12) Binary Constructors") internal inner class BinaryConstructors { @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (30) BinaryConstructor") fun binaryConstructor() { val expr = parse<PluginBinaryConstructor>("binary { \"AF\" }")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.BINARY_CONSTRUCTOR)) assertThat(expr.expressionElement?.textOffset, `is`(0)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.13) Logical Expressions") internal inner class LogicalExpressions { @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (19) OrExpr") fun orExpr() { val expr = parse<XPathOrExpr>("1 orElse 2")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(SaxonXPathTokenProvider.KOrElse)) assertThat(expr.expressionElement?.textOffset, `is`(2)) } @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (11) AndExpr") fun andExpr() { val expr = parse<XPathAndExpr>("1 andAlso 2")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(SaxonXPathTokenProvider.KAndAlso)) assertThat(expr.expressionElement?.textOffset, `is`(2)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (3.14) Conditional Expressions") internal inner class ConditionalExpressions { @Test @DisplayName("XQuery IntelliJ Plugin XQuery EBNF (93) ElvisExpr") fun elvisExpr() { val expr = parse<PluginElvisExpr>("1 ?: 2")[0] as XpmExpression assertThat(expr.expressionElement.elementType, `is`(XPathTokenType.ELVIS)) assertThat(expr.expressionElement?.textOffset, `is`(2)) } } @Nested @DisplayName("XQuery IntelliJ Plugin (4.1) Item Type Declaration") internal inner class TypeDeclaration { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (19) ItemTypeDecl") internal inner class ItemTypeDecl { @Test @DisplayName("NCName") fun ncname() { val expr = parse<XQueryItemTypeDecl>("declare type test := xs:string;")[0] val qname = expr.typeName!! assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("test")) val presentation = (expr as NavigationItem).presentation!! assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.TypeDecl))) assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.TypeDecl))) assertThat(presentation.presentableText, `is`("test")) assertThat(presentation.locationString, `is`(nullValue())) } @Test @DisplayName("with CompatibilityAnnotation") fun withCompatibiliyAnnotation() { val expr = parse<XQueryItemTypeDecl>("declare private type test := xs:string;")[0] val qname = expr.typeName!! assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("test")) val presentation = (expr as NavigationItem).presentation!! assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.TypeDecl))) assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.TypeDecl))) assertThat(presentation.presentableText, `is`("test")) assertThat(presentation.locationString, `is`(nullValue())) } @Test @DisplayName("NCName namespace resolution") fun ncnameResolution() { val qname = parse<XPathEQName>( """ declare default function namespace "http://www.example.co.uk/function"; declare default element namespace "http://www.example.co.uk/element"; declare type test = xs:string; """ )[0] as XsQNameValue assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType)) assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type)) assertThat(qname.isLexicalQName, `is`(true)) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("test")) assertThat(qname.element, sameInstance(qname as PsiElement)) val expanded = qname.expand().toList() assertThat(expanded.size, `is`(1)) assertThat(expanded[0].isLexicalQName, `is`(false)) assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element")) assertThat(expanded[0].prefix, `is`(nullValue())) assertThat(expanded[0].localName!!.data, `is`("test")) assertThat(expanded[0].element, sameInstance(qname as PsiElement)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (4.2) Annotations") internal inner class Annotations { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (26) CompatibilityAnnotation") internal inner class CompatibilityAnnotation { @Test @DisplayName("NCName namespace resolution") fun ncname() { val qname = parse<PluginCompatibilityAnnotation>("declare private function f() {};")[0] as XsQNameValue assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.XQuery)) assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Annotation)) assertThat(qname.isLexicalQName, `is`(true)) assertThat(qname.namespace, `is`(nullValue())) assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("private")) assertThat(qname.element, sameInstance(qname as PsiElement)) val expanded = qname.expand().toList() assertThat(expanded.size, `is`(1)) assertThat(expanded[0].isLexicalQName, `is`(false)) assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2012/xquery")) assertThat(expanded[0].prefix, `is`(nullValue())) assertThat(expanded[0].localName!!.data, `is`("private")) assertThat(expanded[0].element, sameInstance(qname as PsiElement)) } @Test @DisplayName("MarkLogic") fun markLogic() { val annotation = parse<PluginCompatibilityAnnotation>( "declare private function f() {};" )[0] as XdmAnnotation assertThat(qname_presentation(annotation.name!!), `is`("private")) val values = annotation.values.toList() assertThat(values.size, `is`(0)) val presentation = annotation as ItemPresentation assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation)) assertThat(presentation.locationString, `is`(nullValue())) assertThat(presentation.presentableText, `is`("private")) } @Test @DisplayName("XQuery Update Facility 3.0") fun updateFacility() { val annotation = parse<PluginCompatibilityAnnotation>( "declare updating function f() {};" )[0] as XdmAnnotation assertThat(qname_presentation(annotation.name!!), `is`("updating")) val values = annotation.values.toList() assertThat(values.size, `is`(0)) val presentation = annotation as ItemPresentation assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation)) assertThat(presentation.locationString, `is`(nullValue())) assertThat(presentation.presentableText, `is`("updating")) } @Test @DisplayName("Scripting Extension 1.0") fun scriptingExtension() { val annotation = parse<PluginCompatibilityAnnotation>( "declare sequential function f() {};" )[0] as XdmAnnotation assertThat(qname_presentation(annotation.name!!), `is`("sequential")) val values = annotation.values.toList() assertThat(values.size, `is`(0)) val presentation = annotation as ItemPresentation assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation)) assertThat(presentation.locationString, `is`(nullValue())) assertThat(presentation.presentableText, `is`("sequential")) } } @Nested @DisplayName("XQuery 3.1 EBNF (28) VarDecl") internal inner class VarDecl { @Test @DisplayName("visibility (public/private)") fun visibility() { val decls = parse<XpmAnnotated>( """ declare variable ${'$'}a := 1; declare private variable ${'$'}c := 3; """.trimIndent() ) assertThat(decls[0].accessLevel, `is`(XpmAccessLevel.Public)) assertThat(decls[1].accessLevel, `is`(XpmAccessLevel.Private)) } } @Nested @DisplayName("XQuery 3.1 EBNF (32) FunctionDecl") internal inner class FunctionDecl { @Test @DisplayName("visibility (%public/%private)") fun visibility() { val decls = parse<XpmAnnotated>( """ declare function a() {}; declare private function c() {}; """.trimIndent() ) assertThat(decls[0].accessLevel, `is`(XpmAccessLevel.Public)) assertThat(decls[1].accessLevel, `is`(XpmAccessLevel.Private)) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (4.3) Stylesheet Import") internal inner class StylesheetImport { @Nested @DisplayName("XQuery IntelliJ Plugin EBNF (33) StylesheetImport") internal inner class StylesheetImport { @Test @DisplayName("location uris; single uri") fun singleLocationUri() { val import = parse<PluginStylesheetImport>("import stylesheet at;")[0] val uris = import.locationUris.toList() assertThat(uris.size, `is`(0)) } @Test @DisplayName("missing location uri") fun missingLocationUri() { val import = parse<PluginStylesheetImport>("import stylesheet at 'test.xsl';")[0] val uris = import.locationUris.toList() assertThat(uris.size, `is`(1)) assertThat(uris[0].data, `is`("test.xsl")) assertThat(uris[0].context, `is`(XdmUriContext.Location)) assertThat(uris[0].moduleTypes, `is`(sameInstance(XdmModuleType.STYLESHEET))) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (4.5) Function Declaration") internal inner class FunctionDeclaration { @Nested @DisplayName("XQuery 3.1 EBNF (32) FunctionDecl ; XQuery IntelliJ Plugin EBNF (95) ParamList") internal inner class FunctionDecl { @Test @DisplayName("variadic") fun variadic() { val decl = parse<XpmFunctionDeclaration>("declare function test(\$one, \$two ...) external;")[0] assertThat(decl.returnType, `is`(nullValue())) assertThat(decl.parameters.size, `is`(2)) assertThat(qname_presentation(decl.parameters[0].variableName!!), `is`("one")) assertThat(qname_presentation(decl.parameters[1].variableName!!), `is`("two")) val qname = decl.functionName!! assertThat(qname.prefix, `is`(nullValue())) assertThat(qname.localName!!.data, `is`("test")) assertThat(qname.element, sameInstance(qname as PsiElement)) val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl))) assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl))) assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("test")) assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("test(\$one, \$two ...)")) assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("test")) assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("test(\$one, \$two ...)")) assertThat(presentation.presentableText, `is`("test")) assertThat(presentation.locationString, `is`(nullValue())) } } } @Nested @DisplayName("XQuery IntelliJ Plugin (4.6) Using Declaration") internal inner class UsingDeclaration { @Nested @DisplayName("XQuery 3.1 EBNF (105) UsingDecl") internal inner class UsingDecl { @Test @DisplayName("using declaration") fun using() { val decl = parse<XpmNamespaceDeclaration>( "using namespace 'http://www.w3.org/2005/xpath-functions/math';" )[0] assertThat(decl.namespacePrefix, `is`(nullValue())) assertThat(decl.namespaceUri?.data, `is`("http://www.w3.org/2005/xpath-functions/math")) assertThat(decl.namespaceUri?.context, `is`(XdmUriContext.Namespace)) assertThat(decl.namespaceUri?.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA))) assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(true)) assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.None), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false)) } @Test @DisplayName("empty namespace") fun emptyNamespace() { val decl = parse<XpmNamespaceDeclaration>("using namespace '';")[0] assertThat(decl.namespacePrefix, `is`(nullValue())) assertThat(decl.namespaceUri!!.data, `is`("")) assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.Namespace)) assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA))) assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(true)) assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.None), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false)) } @Test @DisplayName("missing namespace") fun missingNamespace() { val decl = parse<XpmNamespaceDeclaration>("using namespace;")[0] assertThat(decl.namespacePrefix, `is`(nullValue())) assertThat(decl.namespaceUri, `is`(nullValue())) assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(true)) assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.None), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false)) assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false)) } } } }
apache-2.0
2b356aa9b0a525a751a2fb4299460cab
44.471588
132
0.580662
4.773807
false
true
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/NoteImageAdapter.kt
1
1977
package de.westnordost.streetcomplete.quests.note_discussion import android.content.Context import androidx.appcompat.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.view.doOnLayout import java.io.File import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osmnotes.AttachPhotoUtils import de.westnordost.streetcomplete.view.ListAdapter class NoteImageAdapter(list: List<String>, private val context: Context) : ListAdapter<String>(list) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<String> { val inflater = LayoutInflater.from(parent.context) return NoteImageViewHolder(inflater.inflate(R.layout.cell_image_thumbnail, parent, false)) } private inner class NoteImageViewHolder(itemView: View) : ViewHolder<String>(itemView) { private val imageView: ImageView = itemView.findViewById(R.id.imageView) init { imageView.setOnClickListener { val index = adapterPosition if (index > -1) onClickDelete(index) } } override fun onBind(with: String) { itemView.doOnLayout { val bitmap = AttachPhotoUtils.resize(with, imageView.width) imageView.setImageBitmap(bitmap) } } } private fun onClickDelete(index: Int) { AlertDialog.Builder(context) .setMessage(R.string.quest_leave_new_note_photo_delete_title) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok) { _, _ -> delete(index) } .show() } private fun delete(index: Int) { val imagePath = list.removeAt(index) val image = File(imagePath) if (image.exists()) { image.delete() } notifyItemRemoved(index) } }
gpl-3.0
f96c6c235239f77d44d745e6acaa7149
32.508475
102
0.67476
4.524027
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/gist/GistFragment.kt
1
6159
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.gist import android.content.Context import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v7.app.AppCompatActivity import android.view.* import android.widget.Toast import es.dmoral.toasty.Toasty import giuliolodi.gitnav.R import giuliolodi.gitnav.ui.base.BaseFragment import giuliolodi.gitnav.ui.option.OptionActivity import kotlinx.android.synthetic.main.gist_fragment.* import javax.inject.Inject /** * Created by giulio on 28/06/2017. */ class GistFragment : BaseFragment(), GistContract.View { @Inject lateinit var mPresenter: GistContract.Presenter<GistContract.View> private var mGistId: String? = null private var mMenu: Menu? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true getActivityComponent()?.inject(this) mGistId = activity.intent.getStringExtra("gistId") } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.gist_fragment, container, false) } override fun initLayout(view: View?, savedInstanceState: Bundle?) { mPresenter.onAttach(this) setHasOptionsMenu(true) (activity as AppCompatActivity).setSupportActionBar(gist_fragment_toolbar) (activity as AppCompatActivity).supportActionBar?.title = getString(R.string.gist) (activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true) (activity as AppCompatActivity).supportActionBar?.setDisplayShowHomeEnabled(true) gist_fragment_toolbar.setNavigationOnClickListener { activity.onBackPressed() } gist_fragment_tab_layout.visibility = View.VISIBLE gist_fragment_tab_layout.setSelectedTabIndicatorColor(Color.WHITE) gist_fragment_tab_layout.setupWithViewPager(gist_fragment_viewpager) gist_fragment_viewpager.offscreenPageLimit = 2 mGistId?.let { gist_fragment_viewpager.adapter = MyAdapter(context, it, fragmentManager) } mGistId?.let { mPresenter.subscribe(isNetworkAvailable(), it) } } override fun onGistStarred() { mMenu?.findItem(R.id.follow_icon)?.isVisible = true mMenu?.findItem(R.id.unfollow_icon)?.isVisible = false Toasty.success(context, getString(R.string.gist_starred), Toast.LENGTH_LONG).show() } override fun onGistUnstarred() { mMenu?.findItem(R.id.follow_icon)?.isVisible = false mMenu?.findItem(R.id.unfollow_icon)?.isVisible = true Toasty.success(context, getString(R.string.gist_unstarred), Toast.LENGTH_LONG).show() } override fun showError(error: String) { Toasty.error(context, error, Toast.LENGTH_LONG).show() } override fun showNoConnectionError() { Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show() } override fun intentToBrowser(url: String) { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(browserIntent) } override fun createOptionsMenu(isGistStarred: Boolean) { when (isGistStarred) { true -> mMenu?.findItem(R.id.follow_icon)?.isVisible = true false -> mMenu?.findItem(R.id.unfollow_icon)?.isVisible = true } } override fun onCreateOptionsMenu(menu: Menu?, menuInflater: MenuInflater?) { menuInflater?.inflate(R.menu.gist_fragment_menu, menu) menu?.let { mMenu = it } mPresenter.onMenuCreated() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == R.id.action_options) { startActivity(OptionActivity.getIntent(context)) activity.overridePendingTransition(0,0) } if (isNetworkAvailable()) { when (item?.itemId) { R.id.follow_icon -> mGistId?.let { mPresenter.unstarGist(it) } R.id.unfollow_icon -> mGistId?.let { mPresenter.starGist(it) } R.id.open_in_browser -> mPresenter.onOpenInBrowser() } } else { Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show() } return super.onOptionsItemSelected(item) } override fun onDestroyView() { mPresenter.onDetachView() super.onDestroyView() } override fun onDestroy() { mPresenter.onDetach() super.onDestroy() } private class MyAdapter(context: Context, gistId: String, fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { private val mContext: Context = context private val mGistId: String = gistId override fun getItem(position: Int): Fragment { return when(position) { 0 -> GistFilesFragment.newInstance(mGistId) else -> GistCommentsFragment.newInstance(mGistId) } } override fun getPageTitle(position: Int): CharSequence { when (position) { 0 -> return mContext.getString(R.string.files) 1 -> return mContext.getString(R.string.comments) } return super.getPageTitle(position) } override fun getCount(): Int { return 2 } } }
apache-2.0
528f61332d5002a9d8e80a03cfabb480
35.666667
137
0.683065
4.515396
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/delegate/CourseCollectionAuthorListAdapterDelegate.kt
1
2758
package org.stepik.android.view.course_list.delegate import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_collection_horizontal_list.* import org.stepic.droid.R import org.stepic.droid.ui.util.CoursesSnapHelper import org.stepik.android.domain.catalog.model.CatalogAuthor import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager import org.stepik.android.view.catalog.ui.adapter.delegate.AuthorAdapterDelegate import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapters.DefaultDelegateAdapter class CourseCollectionAuthorListAdapterDelegate( private val onAuthorClick: (Long) -> Unit ) : AdapterDelegate<CourseListItem, DelegateViewHolder<CourseListItem>>() { private val sharedViewPool = RecyclerView.RecycledViewPool() override fun isForViewType(position: Int, data: CourseListItem): Boolean = data is CourseListItem.SimilarAuthors override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseListItem> = AuthorListViewHolder(createView(parent, R.layout.item_collection_horizontal_list)) private inner class AuthorListViewHolder( override val containerView: View ) : DelegateViewHolder<CourseListItem>(containerView), LayoutContainer { private val adapter = DefaultDelegateAdapter<CatalogAuthor>() .also { it += AuthorAdapterDelegate(onAuthorClick) } init { val rowCount = context.resources.getInteger(R.integer.author_lists_default_rows) horizontalListRecycler.layoutManager = TableLayoutManager( context, horizontalSpanCount = context.resources.getInteger(R.integer.author_lists_default_columns), verticalSpanCount = rowCount, orientation = RecyclerView.HORIZONTAL, reverseLayout = false ) horizontalListRecycler.setRecycledViewPool(sharedViewPool) horizontalListRecycler.setHasFixedSize(true) horizontalListRecycler.adapter = adapter val snapHelper = CoursesSnapHelper(rowCount) snapHelper.attachToRecyclerView(horizontalListRecycler) } override fun onBind(data: CourseListItem) { data as CourseListItem.SimilarAuthors containerTitle.setText(R.string.authors_title) adapter.items = data.similarAuthors } } }
apache-2.0
287eea8e054bd3289cdd91f8d2911310
42.109375
111
0.730602
5.314066
false
false
false
false
zlyne0/colonization
core/src/promitech/colonization/screen/debug/CommandDefinition.kt
1
29449
package promitech.colonization.screen.debug import net.sf.freecol.common.model.Colony import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.IndianSettlement import net.sf.freecol.common.model.Settlement import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.Tile import net.sf.freecol.common.model.TileImprovementType import net.sf.freecol.common.model.Unit import net.sf.freecol.common.model.UnitFactory import net.sf.freecol.common.model.UnitRole import net.sf.freecol.common.model.UnitType import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.SeekAndDestroyMission import net.sf.freecol.common.model.ai.missions.TransportUnitMission import net.sf.freecol.common.model.ai.missions.foreachMission import net.sf.freecol.common.model.ai.missions.goodsToSell.ColoniesProductionValue import net.sf.freecol.common.model.ai.missions.goodsToSell.TransportGoodsToSellMission import net.sf.freecol.common.model.ai.missions.indian.DemandTributeMission import net.sf.freecol.common.model.ai.missions.indian.IndianBringGiftMission import net.sf.freecol.common.model.ai.missions.pioneer.AddImprovementPolicy import net.sf.freecol.common.model.ai.missions.pioneer.PioneerDestination import net.sf.freecol.common.model.ai.missions.pioneer.PioneerMission import net.sf.freecol.common.model.ai.missions.pioneer.PioneerMissionPlaner import net.sf.freecol.common.model.ai.missions.pioneer.ReplaceColonyWorkerMission import net.sf.freecol.common.model.ai.missions.pioneer.TakeRoleEquipmentMission import net.sf.freecol.common.model.ai.missions.scout.ScoutMission import net.sf.freecol.common.model.ai.missions.scout.ScoutMissionPlaner import net.sf.freecol.common.model.ai.missions.transportunit.TransportUnitRequestMission import net.sf.freecol.common.model.ai.missions.workerrequest.ColonistsPurchaseRecommendations import net.sf.freecol.common.model.ai.missions.workerrequest.ColonyWorkerMission import net.sf.freecol.common.model.ai.missions.workerrequest.ColonyWorkerRequestPlaceCalculator import net.sf.freecol.common.model.ai.missions.workerrequest.EntryPointTurnRange import net.sf.freecol.common.model.ai.missions.workerrequest.ScorePolicy import net.sf.freecol.common.model.colonyproduction.ColonyPlan import net.sf.freecol.common.model.colonyproduction.GoodsCollection import net.sf.freecol.common.model.map.generator.MapGenerator import net.sf.freecol.common.model.map.generator.SmoothingTileTypes import net.sf.freecol.common.model.map.path.PathFinder import net.sf.freecol.common.model.player.Player import net.sf.freecol.common.model.player.Tension import net.sf.freecol.common.model.specification.AbstractGoods import net.sf.freecol.common.model.specification.GoodsType import net.sf.freecol.common.model.specification.GoodsTypeId import promitech.colonization.DI import promitech.colonization.Direction import promitech.colonization.ai.MissionExecutor import promitech.colonization.ai.MissionExecutorDebugRun import promitech.colonization.ai.MissionPlaner import promitech.colonization.ai.NavyExplorer import promitech.colonization.ai.SeekAndDestroyMissionHandler import promitech.colonization.ai.UnitTypeId import promitech.colonization.ai.findCarrier import promitech.colonization.infrastructure.ThreadsResources import promitech.colonization.savegame.SaveGameList import promitech.colonization.screen.colony.ColonyApplicationScreen import promitech.colonization.screen.ff.ContinentalCongress import promitech.colonization.screen.map.MapActor import promitech.colonization.screen.map.hud.DiplomacyContactDialog import promitech.colonization.screen.map.hud.GUIGameModel fun createCommands( di: DI, console: ConsoleOutput, mapActor: MapActor?, colonyApplicationScreen: ColonyApplicationScreen? ) : Commands { val guiGameModel = di.guiGameModel val gameController = di.guiGameController val tileDebugView = TileDebugView(mapActor, guiGameModel) return Commands().define { commandArg("add_gold") { args -> if (args.size == 1) { console.keepOpen() console.out("no args with gold amount") } else { val gold = args[1].toInt() guiGameModel.game.playingPlayer.addGold(gold) console.out("add $gold") } } command("map_show") { guiGameModel.game.playingPlayer.explorAllTiles(); guiGameModel.game.playingPlayer.fogOfWar.removeFogOfWar(); gameController.resetMapModel(); } command("map_generate") { guiGameModel.game.map = MapGenerator().generate(guiGameModel.game.players) gameController.resetMapModel() } command("map_smooth_tile_types") { val smoothing = SmoothingTileTypes(guiGameModel.game.map, Specification.instance.tileTypes) smoothing.smoothing(1) gameController.resetMapModel() } command("map_show_owners") { gameController.showTilesOwners() } command("map_hide_owners") { gameController.hideTilesOwners() } command("map_scout_all") { for (player : Player in guiGameModel.game.players.entities()) { if (player.isIndian()) { for (indianSettlement : Settlement in player.settlements.entities()) { if (indianSettlement is IndianSettlement) { indianSettlement.scoutBy(guiGameModel.game.playingPlayer) } } } } } command("map_turn_range") { if (!di.guiGameModel.isViewMode() || mapActor == null) { console.keepOpen() console.out("no view mode") } else { mapTurnRange(di, mapActor, tileDebugView) } } command("ai_generateTileScoresForNewColony") { generateTileScoresForNewColony(di, guiGameModel, tileDebugView) } command("ai_generateTheBestPlaceToBuildColony") { generateTheBestPlaceToBuildColony(di, guiGameModel, tileDebugView) } command("ai_generateWorkerReqScoreByValue") { generateWorkerReqScoreByValue(di, guiGameModel, tileDebugView) } command("ai_generateWorkerReqScoreByPriceToValue") { generateWorkerReqScoreByPriceToValue(di, guiGameModel, tileDebugView) } command("ai_generateWorkerReqBuyRecommendations") { generateWorkerReqBuyRecommendations(di, guiGameModel, tileDebugView) } command("ai_explore") { aiExplore(di, tileDebugView) } command("player_turn_as_ai") { if (mapActor != null) { playerTurnAsAi(di, guiGameModel, mapActor) } } command("pools") { console.keepOpen() console.out(PoolsStat.Stat.header()) PoolsStat().readStats() .map { it.toFormatedString() } .forEach { console.out(it) } } command("firstContactDialog") { val player = guiGameModel.game.players.getById("player:1") //val contactPlayer = guiGameModel.game.players.getById("player:9") val contactPlayer = guiGameModel.game.players.getById("player:133") //gameController.showDialog(FirstContactDialog(guiGameModel.game.playingPlayer, contactPlayer)) if (mapActor != null) { gameController.showDialog(DiplomacyContactDialog(mapActor, guiGameModel.game, player, contactPlayer)) } } command("add_liberty_for_founding_father") { guiGameModel.game.playingPlayer.foundingFathers.fullFillLibertyForFoundingFather() } commandArg("add_foundingFather") { args -> val player = guiGameModel.game.playingPlayer val ff = Specification.instance.foundingFathers.getById(args[1]) player.addFoundingFathers(guiGameModel.game, ff) gameController.resetMapModel() }.addParams { listOf<String>("model.foundingFather.adamSmith", "model.foundingFather.jacobFugger", "model.foundingFather.peterMinuit") } command("add_all_founding_fathers") { val player = guiGameModel.game.playingPlayer for (ff in Specification.instance.foundingFathers.entities()) { player.addFoundingFathers(guiGameModel.game, ff) } gameController.resetMapModel(); } command("add_immigration") { var player = guiGameModel.game.playingPlayer player.modifyImmigration(player.getImmigrationRequired() + 1) player.getEurope().handleImmigrationOnNewTurn() } command("add_conversion") { var tile = guiGameModel.game.map.getTile(19, 78) tile.getSettlement().asIndianSettlement().setConvertProgress(100) } command("show_continental_congress") { gameController.showDialog(ContinentalCongress(guiGameModel.game.playingPlayer)) } commandArg("colony_plan") { args -> if (colonyApplicationScreen == null) { console.keepOpen() .out("no colony selected") } else { var colony = colonyApplicationScreen.getColony() colony.updateProductionToMaxPossible(colony.tile) val plan = ColonyPlan.Plan.valueOf(args[1]) ColonyPlan(colonyApplicationScreen.colony) .withConsumeWarehouseResources(true) .withIgnoreIndianOwner() .execute(plan) colonyApplicationScreen.initColony(colony) } }.addParams { listOf<String>( "food", "bell", "building", "mostvaluable", "tools", "muskets" ) } commandArg("colonies_production_value") { val coloniesProductionValue = ColoniesProductionValue(guiGameModel.game.playingPlayer) val gold = coloniesProductionValue.goldValue() print(String.format("player[%s] colonies production gold value %s", guiGameModel.game.playingPlayer.id, gold)) } commandArg("indian_bring_gift") { indianBringGiftExample(di, guiGameModel, mapActor) } commandArg("indian_demand_tribute") { indianDemandTributeExample(di, guiGameModel, mapActor) } commandArg("show_missions") { showMissions(guiGameModel, tileDebugView) } commandArg("clear_all_missions") { val missionContainer = guiGameModel.game.aiContainer.missionContainer(guiGameModel.game.playingPlayer) missionContainer.clearAllMissions() println("cleat all missions") } commandArg("reset_debug") { resetDebug(tileDebugView) } command("simpleTest") { simpleTest(di, guiGameModel, tileDebugView, mapActor) } command("simpleTest2") { simpleTest2(di, guiGameModel, tileDebugView, mapActor) } command("nothing") { } } } fun generateTheBestPlaceToBuildColony(di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val transportUnit = player.findCarrier() val sut = ColonyWorkerRequestPlaceCalculator(player, guiGameModel.game.map, EntryPointTurnRange(guiGameModel.game.map, di.pathFinder, player, transportUnit)) val missionContainer = guiGameModel.game.aiContainer.missionContainer(player) val createColonyTiles = missionContainer.findMissions(ColonyWorkerMission::class.java).map { it -> it.tile } sut.debugTheBestBlaceToBuildColony(tileDebugView, createColonyTiles) } fun generateTileScoresForNewColony(di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val transportUnit = player.findCarrier() val entryPointTurnRange = EntryPointTurnRange(guiGameModel.game.map, di.pathFinder, player, transportUnit) val sut = ColonyWorkerRequestPlaceCalculator(player, guiGameModel.game.map, entryPointTurnRange) sut.debugGenerateTileScoresForNewColony(tileDebugView) } fun generateWorkerReqScoreByValue(di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val transportUnit = player.findCarrier() val entryPointTurnRange = EntryPointTurnRange(guiGameModel.game.map, di.pathFinder, player, transportUnit) val sut = ColonyWorkerRequestPlaceCalculator(player, guiGameModel.game.map, entryPointTurnRange) val colonyWorkerRequestScores = sut.score(PlayerMissionsContainer(player)) colonyWorkerRequestScores.prettyPrint() val scorePolicy = ScorePolicy.WorkerProductionValue(entryPointTurnRange) scorePolicy.calculateScore(colonyWorkerRequestScores) colonyWorkerRequestScores.prettyPrint() sut.debug(tileDebugView) } fun generateWorkerReqScoreByPriceToValue(di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val transportUnit = player.findCarrier() val entryPointTurnRange = EntryPointTurnRange(guiGameModel.game.map, di.pathFinder, player, transportUnit) val sut = ColonyWorkerRequestPlaceCalculator(player, guiGameModel.game.map, entryPointTurnRange) // create new player mission container to ignore actual mission destination val colonyWorkerRequestScores = sut.score(PlayerMissionsContainer(player)) val scorePolicy = ScorePolicy.WorkerPriceToValue(entryPointTurnRange, player) scorePolicy.calculateScore(colonyWorkerRequestScores) sut.debug(tileDebugView) } fun generateWorkerReqBuyRecommendations(di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val playerMissionContainer = guiGameModel.game.aiContainer.missionContainer(player) val transportUnit = player.findCarrier() val entryPointTurnRange = EntryPointTurnRange(guiGameModel.game.map, di.pathFinder, player, transportUnit) val workerPlaceCalculator = ColonyWorkerRequestPlaceCalculator(player, guiGameModel.game.map, entryPointTurnRange) val purchaseColonists = ColonistsPurchaseRecommendations(guiGameModel.game, player, playerMissionContainer) val buyRecomendations = purchaseColonists.generateRecommendations(workerPlaceCalculator, entryPointTurnRange, transportUnit!!) purchaseColonists.printToLog(buyRecomendations, entryPointTurnRange) purchaseColonists.printToMap(buyRecomendations, tileDebugView) } fun aiExplore(di: DI, tileDebugView: TileDebugView) { System.out.println("aiExplore - theBestMove") var guiGameModel = di.guiGameModel var moveController = di.moveController var unit = guiGameModel.getActiveUnit(); if (unit == null) { System.out.println("no unit selected"); return; } if (!unit.unitType.isNaval) { System.out.println("selected unit is not ship"); return } var pathFinder = PathFinder() pathFinder.generateRangeMap(guiGameModel.game.map, unit.getTile(), unit, PathFinder.includeUnexploredTiles); var navyExplorer = NavyExplorer(guiGameModel.game.map); navyExplorer.generateExploreDestination(pathFinder, unit.getOwner()); if (navyExplorer.isFoundExploreDestination()) { if (navyExplorer.isExploreDestinationInOneTurn()) { var direction = navyExplorer.getExploreDestinationAsDirection(); System.out.println("exploration destination " + direction); moveController.pressDirectionKey(direction); } else { System.out.println("exploration path " + navyExplorer.getExploreDestinationAsPath()); } } else { // maybe is everything explored or blocked in some how System.out.println("can not find tile to explore"); } //println("navyExplorer " + navyExplorer) //pathFinder.printTurnCost(tileDebugView) //navyExplorer.toStringsBorderValues(tileDebugView); } fun mapTurnRange(di: DI, mapActor: MapActor, tileDebugView: TileDebugView) { var guiGameModel = di.guiGameModel if (!guiGameModel.isViewMode()) { return } val dutch = guiGameModel.game.players.getById("player:1") var pathFinder = PathFinder() pathFinder.generateRangeMap( guiGameModel.game.map, mapActor.mapDrawModel().selectedTile, pathFinder.createPathUnit(dutch, Specification.instance.unitTypes.getById(UnitType.GALLEON)), PathFinder.excludeUnexploredTiles ) pathFinder.printTurnCost(tileDebugView) } fun aiAttack(di: DI) { var pathFinder = PathFinder() // private attack // var srcTile = guiGameModel.game.map.getSafeTile(12, 80) // val mission = SeekAndDestroyMission(srcTile.units.first()) // brave attack on dutch colony // var srcTile = guiGameModel.game.map.getSafeTile(20, 80) // val mission = SeekAndDestroyMission(srcTile.units.first()) // brave attack on spanish colony var srcTile = di.guiGameModel.game.map.getSafeTile(27, 55) val mission = SeekAndDestroyMission(srcTile.units.first()) val missionHandler = SeekAndDestroyMissionHandler(di.guiGameModel.game, di.moveService, di.combatService, pathFinder) //missionHandler.handle(null, mission) } fun indianBringGiftExample(di: DI, guiGameModel: GUIGameModel, mapActor: MapActor?) { val tile = guiGameModel.game.map.getSafeTile(19, 78) //val colonyTile = guiGameModel.game.map.getSafeTile(20, 79) val colonyTile = guiGameModel.game.map.getSafeTile(21, 72) val mission : IndianBringGiftMission val indianAiContainer = guiGameModel.game.aiContainer.missionContainer(tile.getSettlement().getOwner()) if (!indianAiContainer.hasMission(IndianBringGiftMission::class.java)) { val transportUnit = tile.getSettlement().asIndianSettlement().getUnits().getById("unit:6351") mission = IndianBringGiftMission( tile.getSettlement().asIndianSettlement(), colonyTile.getSettlement().asColony(), transportUnit, AbstractGoods("model.goods.tobacco", 77) ) indianAiContainer.addMission(mission) } else { mission = indianAiContainer.firstMissionByType(IndianBringGiftMission::class.java) } mission.getTransportUnit().resetMovesLeftOnNewTurn() ThreadsResources.instance.executeMovement(object : Runnable { override fun run() { MissionExecutorDebugRun(di.guiGameModel, di.moveService, mapActor, di.combatService, di.guiGameController, di.pathFinder, PathFinder()) .runMission(tile.getSettlement().getOwner(), mission) } }) } fun indianDemandTributeExample(di: DI, guiGameModel: GUIGameModel, mapActor: MapActor?) { val tile = guiGameModel.game.map.getSafeTile(19, 78) //val colonyTile = guiGameModel.game.map.getSafeTile(20, 79) val colonyTile = guiGameModel.game.map.getSafeTile(21, 72) val mission : DemandTributeMission val indianAiContainer = guiGameModel.game.aiContainer.missionContainer(tile.getSettlement().getOwner()) if (!indianAiContainer.hasMission(DemandTributeMission::class.java)) { val unit = tile.getSettlement().asIndianSettlement().getUnits().getById("unit:6351") tile.getSettlement().asIndianSettlement().setTension( colonyTile.getSettlement().getOwner(), Tension.Level.DISPLEASED.getLimit() ) mission = DemandTributeMission( tile.getSettlement().asIndianSettlement(), unit, colonyTile.getSettlement().asColony() ) indianAiContainer.addMission(mission) } else { mission = indianAiContainer.firstMissionByType(DemandTributeMission::class.java) } mission.getUnitToDemandTribute().resetMovesLeftOnNewTurn() ThreadsResources.instance.executeMovement(object : Runnable { override fun run() { MissionExecutorDebugRun(di.guiGameModel, di.moveService, mapActor, di.combatService, di.guiGameController, di.pathFinder, PathFinder()) .runMission(tile.getSettlement().getOwner(), mission) } }) } fun playerTurnAsAi(di: DI, guiGameModel: GUIGameModel, mapActor: MapActor) { val pathFinder2 = PathFinder() val missionExecutor = MissionExecutor( guiGameModel.game, di.moveService, di.combatService, di.guiGameController, di.pathFinder, pathFinder2 ) val missionPlaner = MissionPlaner(guiGameModel.game, di.pathFinder, missionExecutor, pathFinder2) val player = guiGameModel.game.playingPlayer val missionContainer = guiGameModel.game.aiContainer.missionContainer(player) guiGameModel.setActiveUnit(null) mapActor.mapDrawModel().setSelectedUnit(null) ThreadsResources.instance.executeMovement(object : Runnable { override fun run() { player.setAi(true) SaveGameList().saveAsAutosave(guiGameModel.game) di.newTurnService.newTurn(player) missionPlaner.planMissions(player) missionExecutor.executeMissions(player) // missionExecutor.executeMissions(missionContainer, PioneerMission::class.java) // missionExecutor.executeMissions(missionContainer, RequestGoodsMission::class.java) guiGameModel.game.increaseTurnNumber() mapActor.resetMapModel() mapActor.resetUnexploredBorders() player.setAi(false) } }) } // key 9 fun showMissions(guiGameModel: GUIGameModel, tileDebugView: TileDebugView) { tileDebugView.reset() val player = guiGameModel.game.playingPlayer val missionContainer = guiGameModel.game.aiContainer.missionContainer(player) fun showOnMap(mission: TransportUnitMission) { for (unitDest in mission.unitsDest) { tileDebugView.appendStr(unitDest.dest.x, unitDest.dest.y, "TransportUnit") } } fun showOnMap(mission: TransportGoodsToSellMission) { if (mission.phase == TransportGoodsToSellMission.Phase.MOVE_TO_EUROPE) { tileDebugView.appendStr(player.entryLocation.x, player.entryLocation.y, "SellGoods") } else { val settlement = mission.firstSettlementToVisit(player) tileDebugView.appendStr(settlement.tile.x, settlement.tile.y, "TakeForSale") } } fun showOnMap(mission: ScoutMission) { if (mission.scoutDistantDestination != null) { val tile: Tile = mission.scoutDistantDestination!! tileDebugView.appendStr(tile.x, tile.y, "ScoutDest") } } fun showOnMap(mission: TransportUnitRequestMission) { tileDebugView.appendStr(mission.destination.x, mission.destination.y, "TranUnitReq") } fun showOnMap(mission: ReplaceColonyWorkerMission) { val tile = mission.colony().tile tileDebugView.appendStr(tile.x, tile.y, "RplcWorker") } fun showOnMap(mission: PioneerMission) { val tile = mission.colony().tile tileDebugView.appendStr(tile.x, tile.y, "Pioneer") } for (mission in missionContainer.missions.entities()) { if (mission.isDone) { continue } when (mission) { is ColonyWorkerMission -> tileDebugView.strIfNull( mission.tile.x, mission.tile.y, "Worker" ) is TransportUnitMission -> showOnMap(mission) is TransportGoodsToSellMission -> showOnMap(mission) is ScoutMission -> showOnMap(mission) is TransportUnitRequestMission -> showOnMap(mission) is ReplaceColonyWorkerMission -> showOnMap(mission) is PioneerMission -> showOnMap(mission) else -> println("Can not print mission on map for " + mission.javaClass.name) } } } // key 7 fun simpleTest( di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView, mapActor: MapActor? ) { tileDebugView.reset() val game = guiGameModel.game val player = game.playingPlayer val dutch = game.playingPlayer val pathFinder = di.pathFinder val missionContainer = game.aiContainer.missionContainer(player) //val fortNassau = game.map.getTile(20, 79).settlement.asColony() val fortOranjeTile = game.map.getTile(25, 75) val nieuwAmsterdamTile = game.map.getTile(24, 78) val pioneer = DebugPioneer(di, guiGameModel, tileDebugView, mapActor!!) pioneer.showImprovementsPlan() /* missionContainer.clearAllMissions() val sourceTile = game.map.getTile(29, 71) val ship = UnitFactory.create(UnitType.CARAVEL, player, player.europe) ship.goodsContainer.increaseGoodsQuantity(GoodsType.SILVER, 100) val freeColonist = UnitFactory.create(UnitType.ELDER_STATESMAN, player, ship) val transportUnitMission = TransportUnitMission(ship) transportUnitMission.addUnitDest(freeColonist, fortOranjeTile) transportUnitMission.addCargoDest(nieuwAmsterdamTile, goodsType(GoodsType.SILVER), 100) missionContainer.addMission(transportUnitMission) */ player.fogOfWar.resetFogOfWar(guiGameModel.game, player) mapActor?.resetMapModel() mapActor?.resetUnexploredBorders() } // key 8 fun simpleTest2( di: DI, guiGameModel: GUIGameModel, tileDebugView: TileDebugView, mapActor: MapActor? ) { val game = guiGameModel.game val player = game.playingPlayer val dutch = game.playingPlayer val missionContainer = game.aiContainer.missionContainer(player) val playerAiContainer = game.aiContainer.playerAiContainer(player) val pathFinder = di.pathFinder val pathFinder2 = di.pathFinder2 val pathFinder3 = PathFinder() // val scout = Scout(di, guiGameModel, tileDebugView, mapActor!!) // scout.createScoutMission() missionContainer.clearAllMissions() val nieuAmsterdamTile = game.map.getTile(24, 78) val fortOrange = game.map.getTile(25, 75).settlement.asColony() val pioneerUnitRole = Specification.instance.unitRoles.getById(UnitRole.PIONEER) val workerFreeColonist = dutch.units.getById("unit:6436") fortOrange.goodsContainer.increaseGoodsQuantity(GoodsType.TOOLS, 100) val freeColonist = UnitFactory.create(UnitType.EXPERT_FARMER, player, nieuAmsterdamTile) val pioneerMission = PioneerMission(freeColonist, fortOrange) missionContainer.addMission(pioneerMission) // val takeRoleMission = TakeRoleEquipmentMission(freeColonist, fortOrange, pioneerUnitRole, 4) // missionContainer.addMission(pioneerMission, takeRoleMission) // // val replaceColonyWorkerMission = ReplaceColonyWorkerMission(fortOrange, workerFreeColonist, freeColonist) // missionContainer.addMission(takeRoleMission, replaceColonyWorkerMission) player.fogOfWar.resetFogOfWar(guiGameModel.game, player) mapActor?.resetMapModel() mapActor?.resetUnexploredBorders() } fun tileFrom(game: Game, settlement: Settlement, direction: Direction): Tile { return game.map.getTile(settlement.tile, direction) } fun unitRole(unitRoleId: String): UnitRole { return Specification.instance.unitRoles.getById(unitRoleId) } fun goodsType(goodsTypeId: GoodsTypeId): GoodsType { return Specification.instance.goodsTypes.getById(goodsTypeId) } fun resetDebug(tileDebugView: TileDebugView) { tileDebugView.reset() } class Scout( val di: DI, val guiGameModel: GUIGameModel, val tileDebugView: TileDebugView, val mapActor: MapActor ) { val game = guiGameModel.game val player = game.playingPlayer val missionContainer = game.aiContainer.missionContainer(player) fun createScoutMission() { val mission = missionContainer.findFirstMission(ScoutMission::class.java) if (mission == null) { var scout: Unit? = null for (unit in player.units) { if (unit.unitRole.equalsId(UnitRole.SCOUT)) { scout = unit break; } } if (scout == null) { // scout next3 savegame val tile = game.map.getTile(32, 19) scout = UnitFactory.create(UnitType.SCOUT, UnitRole.SCOUT, player, tile) } val scoutMission = ScoutMission(scout!!) missionContainer.addMission(scoutMission) } } fun printDestinations() { val scoutMissionPlaner = ScoutMissionPlaner( guiGameModel.game, di.pathFinder, di.pathFinder2 ) scoutMissionPlaner.printAllCandidates(player, tileDebugView) //printFirstDestination } } class DebugPioneer( val di: DI, val guiGameModel: GUIGameModel, val tileDebugView: TileDebugView, val mapActor: MapActor ) { val plowedType = Specification.instance.tileImprovementTypes.getById(TileImprovementType.PLOWED_IMPROVEMENT_TYPE_ID) val roadType = Specification.instance.tileImprovementTypes.getById(TileImprovementType.ROAD_MODEL_IMPROVEMENT_TYPE_ID) val clearForestType = Specification.instance.tileImprovementTypes.getById(TileImprovementType.CLEAR_FOREST_IMPROVEMENT_TYPE_ID) val game = guiGameModel.game val player = game.playingPlayer val missionContainer = game.aiContainer.missionContainer(player) fun createPioneerMission() { var pioneerMission = missionContainer.findFirstMission(PioneerMission::class.java) if (pioneerMission == null) { missionContainer.clearAllMissions() // scout next3 savegame val isabellaTile = game.map.getTile(32, 17) val isabellaColony = isabellaTile.settlement.asColony() //isabellaColony.goodsContainer.increaseGoodsQuantity(GoodsType.TOOLS, 100) val pioneer = UnitFactory.create( UnitType.HARDY_PIONEER, UnitRole.PIONEER, player, isabellaColony.tile ) pioneerMission = PioneerMission(pioneer, isabellaColony) missionContainer.addMission(pioneerMission) } } fun showImprovementsPlan() { val game = guiGameModel.game val player = game.playingPlayer val balanced = AddImprovementPolicy.Balanced() val pionierMissionPlaner = PioneerMissionPlaner(game, di.pathFinder) val generateImprovementsPlanScore = pionierMissionPlaner.generateImprovementsPlanScore( player, balanced ) println("generateImprovementsPlanScore.size = " + generateImprovementsPlanScore.size()) for (objectScore in generateImprovementsPlanScore) { println("colony: " + objectScore.obj.colony.name + ", score: " + objectScore.score()) objectScore.obj.printToMap(tileDebugView) } mapActor.resetMapModel() } fun showOnMapImprovementsDestinations() { val game = guiGameModel.game val pionnerMissionPlaner = PioneerMissionPlaner(game, di.pathFinder) missionContainer.foreachMission(PioneerMission::class.java) { mission -> val improvementDestination = pionnerMissionPlaner.findImprovementDestination(mission, missionContainer) when (improvementDestination) { is PioneerDestination.OtherIsland -> improvementDestination.plan.printToMap(tileDebugView) is PioneerDestination.TheSameIsland -> improvementDestination.plan.printToMap(tileDebugView) } } } fun removeAllImprovements(colony: Colony) { for (colonyTile in colony.colonyTiles) { colonyTile.tile.removeTileImprovement(TileImprovementType.PLOWED_IMPROVEMENT_TYPE_ID) if (!colonyTile.tile.equalsCoordinates(colony.tile)) { colonyTile.tile.removeTileImprovement(TileImprovementType.ROAD_MODEL_IMPROVEMENT_TYPE_ID) } } } }
gpl-2.0
af772e2f24f2196b5d9ed8e0732ae963
35.401731
158
0.771707
3.454023
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt
1
6918
package info.nightscout.androidaps.plugins.pump.medtronic.dialog import android.os.Bundle import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.DaggerActivity import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup import info.nightscout.androidaps.plugins.pump.medtronic.R import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject class MedtronicHistoryActivity : DaggerActivity() { @Inject lateinit var medtronicHistoryData: MedtronicHistoryData @Inject lateinit var rh: ResourceHelper lateinit var historyTypeSpinner: Spinner lateinit var statusView: TextView lateinit var recyclerView: RecyclerView lateinit var llm: LinearLayoutManager lateinit var recyclerViewAdapter: RecyclerViewAdapter var filteredHistoryList: MutableList<PumpHistoryEntry> = ArrayList() var manualChange = false lateinit var typeListFull: List<TypeList> //private var _binding: MedtronicHistoryActivityBinding? = null //@Inject //var fragmentInjector: DispatchingAndroidInjector<Fragment>? = null // This property is only valid between onCreateView and // onDestroyView. //private val binding get() = _binding!! private fun filterHistory(group: PumpHistoryEntryGroup) { filteredHistoryList.clear() val list: MutableList<PumpHistoryEntry> = ArrayList() list.addAll(medtronicHistoryData.allHistory) //LOG.debug("Items on full list: {}", list.size()); if (group === PumpHistoryEntryGroup.All) { filteredHistoryList.addAll(list) } else { for (pumpHistoryEntry in list) { if (pumpHistoryEntry.entryType.group === group) { filteredHistoryList.add(pumpHistoryEntry) } } } recyclerViewAdapter.setHistoryListInternal(filteredHistoryList) recyclerViewAdapter.notifyDataSetChanged() //LOG.debug("Items on filtered list: {}", filteredHistoryList.size()); } override fun onResume() { super.onResume() filterHistory(selectedGroup) setHistoryTypeSpinner() } private fun setHistoryTypeSpinner() { manualChange = true for (i in typeListFull.indices) { if (typeListFull[i].entryGroup === selectedGroup) { historyTypeSpinner.setSelection(i) break } } SystemClock.sleep(200) manualChange = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.medtronic_history_activity) historyTypeSpinner = findViewById(R.id.medtronic_historytype) statusView = findViewById(R.id.medtronic_historystatus) recyclerView = findViewById(R.id.medtronic_history_recyclerview) recyclerView.setHasFixedSize(true) llm = LinearLayoutManager(this) recyclerView.layoutManager = llm recyclerViewAdapter = RecyclerViewAdapter(filteredHistoryList) recyclerView.adapter = recyclerViewAdapter statusView.visibility = View.GONE typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(rh)) val spinnerAdapter = ArrayAdapter(this, R.layout.spinner_centered, typeListFull) historyTypeSpinner.adapter = spinnerAdapter historyTypeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (manualChange) return val selected = historyTypeSpinner.selectedItem as TypeList showingType = selected selectedGroup = selected.entryGroup filterHistory(selectedGroup) } override fun onNothingSelected(parent: AdapterView<*>?) { if (manualChange) return filterHistory(PumpHistoryEntryGroup.All) } } } private fun getTypeList(list: List<PumpHistoryEntryGroup>): List<TypeList> { val typeList = ArrayList<TypeList>() for (pumpHistoryEntryGroup in list) { typeList.add(TypeList(pumpHistoryEntryGroup)) } return typeList } class TypeList internal constructor(var entryGroup: PumpHistoryEntryGroup) { var name: String override fun toString(): String { return name } init { name = entryGroup.translated!! } } class RecyclerViewAdapter internal constructor(var historyList: List<PumpHistoryEntry>) : RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder>() { fun setHistoryListInternal(historyList: List<PumpHistoryEntry>) { // this.historyList.clear(); // this.historyList.addAll(historyList); this.historyList = historyList // this.notifyDataSetChanged(); } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): HistoryViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.medtronic_history_item, // viewGroup, false) return HistoryViewHolder(v) } override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { val record = historyList[position] holder.timeView.text = record.dateTimeString holder.typeView.text = record.entryType.description holder.valueView.text = record.displayableValue } override fun getItemCount(): Int { return historyList.size } class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var timeView: TextView var typeView: TextView var valueView: TextView init { // cv = (CardView)itemView.findViewById(R.id.rileylink_history_item); timeView = itemView.findViewById(R.id.medtronic_history_time) typeView = itemView.findViewById(R.id.medtronic_history_source) valueView = itemView.findViewById(R.id.medtronic_history_description) } } } companion object { var showingType: TypeList? = null var selectedGroup = PumpHistoryEntryGroup.All } }
agpl-3.0
89eca73e0a73cfb4c128c4d08abe8f97
36.198925
157
0.679532
5.293037
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.kt
1
36216
package info.nightscout.androidaps.plugins.pump.medtronic.comm import android.os.SystemClock import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryResult import info.nightscout.androidaps.plugins.pump.medtronic.comm.message.* import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BatteryStatusDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType.Companion.getSettings import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.createByteArray import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Companion.getByteArrayFromUnsignedShort import org.joda.time.LocalDateTime import java.util.* import javax.inject.Inject import javax.inject.Singleton /** * Original file created by geoff on 5/30/16. * * * Split into 2 implementations, so that we can split it by target device. - Andy * This was mostly rewritten from Original version, and lots of commands and * functionality added. */ @Singleton class MedtronicCommunicationManager // This empty constructor must be kept, otherwise dagger injection might break! @Inject constructor() : RileyLinkCommunicationManager<PumpMessage?>() { @Inject lateinit var medtronicPumpStatus: MedtronicPumpStatus @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var medtronicConverter: MedtronicConverter @Inject lateinit var medtronicUtil: MedtronicUtil @Inject lateinit var medtronicPumpHistoryDecoder: MedtronicPumpHistoryDecoder companion object { private const val MAX_COMMAND_TRIES = 3 private const val DEFAULT_TIMEOUT = 2000 private const val RILEYLINK_TIMEOUT: Long = 15 * 60 * 1000L // 15 min } var errorResponse: String? = null private set private val debugSetCommands = false private var doWakeUpBeforeCommand = true @Inject fun onInit() { // we can't do this in the constructor, as sp only gets injected after the constructor has returned medtronicPumpStatus.previousConnection = sp.getLong( RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L) } override fun createResponseMessage(payload: ByteArray): PumpMessage { return PumpMessage(aapsLogger, payload) } override fun setPumpDeviceState(pumpDeviceState: PumpDeviceState) { medtronicPumpStatus.pumpDeviceState = pumpDeviceState } fun setDoWakeUpBeforeCommand(doWakeUp: Boolean) { doWakeUpBeforeCommand = doWakeUp } override fun isDeviceReachable(): Boolean { return isDeviceReachable(false) } /** * We do actual wakeUp and compare PumpModel with currently selected one. If returned model is * not Unknown, pump is reachable. * * @return */ private fun isDeviceReachable(canPreventTuneUp: Boolean): Boolean { val state = medtronicPumpStatus.pumpDeviceState if (state !== PumpDeviceState.PumpUnreachable) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.WakingUp for (retry in 0..4) { aapsLogger.debug(LTag.PUMPCOMM, "isDeviceReachable. Waking pump... " + if (retry != 0) " (retry $retry)" else "") val connected = connectToDevice() if (connected) return true SystemClock.sleep(1000) } if (state !== PumpDeviceState.PumpUnreachable) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.PumpUnreachable if (!canPreventTuneUp) { val diff = System.currentTimeMillis() - medtronicPumpStatus.lastConnection if (diff > RILEYLINK_TIMEOUT) { serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) } } return false } private fun connectToDevice(): Boolean { val state = medtronicPumpStatus.pumpDeviceState // check connection val pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData) // simple val rfSpyResponse = rfspy.transmitThenReceive(RadioPacket(injector, pumpMsgContent), 0.toByte(), 200.toByte(), 0.toByte(), 0.toByte(), 25000, 0.toByte()) aapsLogger.info(LTag.PUMPCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.raw)) if (rfSpyResponse.wasTimeout()) { aapsLogger.error(LTag.PUMPCOMM, "isDeviceReachable. Failed to find pump (timeout).") } else if (rfSpyResponse.looksLikeRadioPacket()) { val radioResponse = RadioResponse(injector) try { radioResponse.init(rfSpyResponse.raw) if (radioResponse.isValid) { val pumpResponse = createResponseMessage(radioResponse.payload) if (!pumpResponse.isValid) { aapsLogger.warn( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Response is invalid ! [interrupted=%b, timeout=%b]", rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout())) } else { // radioResponse.rssi; val dataResponse = medtronicConverter.decodeModel(pumpResponse.rawContent) val pumpModel = dataResponse as MedtronicDeviceType? val valid = pumpModel !== MedtronicDeviceType.Unknown_Device if (!medtronicUtil.isModelSet && valid) { medtronicUtil.medtronicPumpModel = pumpModel!! medtronicUtil.isModelSet = true } aapsLogger.debug( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", medtronicUtil.medtronicPumpModel, valid, radioResponse.rssi)) if (valid) { if (state === PumpDeviceState.PumpUnreachable) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.WakingUp else medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping rememberLastGoodDeviceCommunicationTime() return true } else { if (state !== PumpDeviceState.PumpUnreachable) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.PumpUnreachable } } } else { aapsLogger.warn( LTag.PUMPCOMM, "isDeviceReachable. Failed to parse radio response: " + ByteUtil.shortHexString(rfSpyResponse.raw)) } } catch (e: RileyLinkCommunicationException) { aapsLogger.warn( LTag.PUMPCOMM, "isDeviceReachable. Failed to decode radio response: " + ByteUtil.shortHexString(rfSpyResponse.raw)) } } else { aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.raw)) } return false } override fun tryToConnectToDevice(): Boolean { return isDeviceReachable(true) } @Throws(RileyLinkCommunicationException::class) private fun runCommandWithArgs(msg: PumpMessage): PumpMessage { if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, "Run command with Args: ") val rval: PumpMessage val shortMessage = makePumpMessage(msg.commandType, CarelinkShortMessageBody(byteArrayOf(0))) // look for ack from short message val shortResponse = sendAndListen(shortMessage) return if (shortResponse.commandType === MedtronicCommandType.CommandACK) { if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, "Run command with Args: Got ACK response") rval = sendAndListen(msg) if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, "2nd Response: $rval") rval } else { aapsLogger.error(LTag.PUMPCOMM, "runCommandWithArgs: Pump did not ack Attention packet") PumpMessage(aapsLogger, "No ACK after Attention packet.") } } @Suppress("SameParameterValue") @Throws(RileyLinkCommunicationException::class) private fun runCommandWithFrames(commandType: MedtronicCommandType, frames: List<List<Byte>>): PumpMessage? { aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: " + commandType.name) var rval: PumpMessage? = null val shortMessage = makePumpMessage(commandType, CarelinkShortMessageBody(byteArrayOf(0))) // look for ack from short message val shortResponse = sendAndListen(shortMessage) if (shortResponse.commandType !== MedtronicCommandType.CommandACK) { aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ack Attention packet") return PumpMessage(aapsLogger, "No ACK after start message.") } else { aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for Attention packet") } var frameNr = 1 for (frame in frames) { val frameData = createByteArray(frame) // aapsLogger.debug(LTag.PUMPCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); val msg = makePumpMessage(commandType, CarelinkLongMessageBody(frameData)) rval = sendAndListen(msg) // aapsLogger.debug(LTag.PUMPCOMM,"PumpResponse: " + rval); if (rval.commandType !== MedtronicCommandType.CommandACK) { aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #$frameNr") aapsLogger.error( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Run command with Frames FAILED (command=%s, response=%s)", commandType.name, rval.toString())) return PumpMessage(aapsLogger, "No ACK after frame #$frameNr") } else { aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #$frameNr") } frameNr++ } return rval } fun getPumpHistory(lastEntry: PumpHistoryEntry?, targetDate: LocalDateTime?): PumpHistoryResult { val pumpTotalResult = PumpHistoryResult(aapsLogger, lastEntry, if (targetDate == null) null else DateTimeUtil.toATechDate(targetDate)) if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false) aapsLogger.debug(LTag.PUMPCOMM, "Current command: " + medtronicUtil.getCurrentCommand()) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Active var doneWithError = false for (pageNumber in 0..4) { val rawHistoryPage = RawHistoryPage(aapsLogger) // wakeUp(receiverDeviceAwakeForMinutes, false); val getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, GetHistoryPageCarelinkMessageBody(pageNumber)) aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page $pageNumber") // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); // Ask the pump to transfer history (we get first frame?) var firstResponse: PumpMessage? = null var failed = false medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null) for (retries in 0 until MAX_COMMAND_TRIES) { try { firstResponse = runCommandWithArgs(getHistoryMsg) failed = false break } catch (e: RileyLinkCommunicationException) { aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "First call for PumpHistory failed (retry=%d)", retries)) failed = true } } if (failed) { medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return pumpTotalResult } // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents())); val ackMsg = makePumpMessage(MedtronicCommandType.CommandACK, PumpAckMessageBody()) var currentResponse = GetHistoryPageCarelinkMessageBody(firstResponse!!.messageBody!!.txData) var expectedFrameNum = 1 var done = false // while (expectedFrameNum == currentResponse.getFrameNumber()) { var failures = 0 while (!done) { // examine current response for problems. val frameData = currentResponse.frameData if (frameData.isNotEmpty() && currentResponse.frameNumber == expectedFrameNum) { // success! got a frame. if (frameData.size != 64) { aapsLogger.warn(LTag.PUMPCOMM, "Expected frame of length 64, got frame of length " + frameData.size) // but append it anyway? } // handle successful frame data rawHistoryPage.appendData(currentResponse.frameData) // RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) * // currentResponse.getFrameNumber() + 1)); medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, currentResponse.frameNumber) aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Got frame %d of Page %d", currentResponse.frameNumber, pageNumber)) // Do we need to ask for the next frame? if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722 expectedFrameNum++ } else { done = true // successful completion } } else { if (frameData.isEmpty()) { aapsLogger.error(LTag.PUMPCOMM, "null frame data, retrying") } else if (currentResponse.frameNumber != expectedFrameNum) { aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Expected frame number %d, received %d (retrying)", expectedFrameNum, currentResponse.frameNumber)) } failures++ if (failures == 6) { aapsLogger.error( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: 6 failures in attempting to download frame %d of page %d, giving up.", expectedFrameNum, pageNumber)) done = true // failure completion. doneWithError = true } } if (!done) { // ask for next frame var nextMsg: PumpMessage? = null for (retries in 0 until MAX_COMMAND_TRIES) { try { nextMsg = sendAndListen(ackMsg) break } catch (e: RileyLinkCommunicationException) { aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Problem acknowledging frame response. (retry=%d)", retries)) } } if (nextMsg != null) currentResponse = GetHistoryPageCarelinkMessageBody(nextMsg.messageBody!!.txData) else { aapsLogger.error(LTag.PUMPCOMM, "We couldn't acknowledge frame from pump, aborting operation.") } } } if (rawHistoryPage.length != 1024) { aapsLogger.warn( LTag.PUMPCOMM, "getPumpHistory: short page. Expected length of 1024, found length of " + rawHistoryPage.length) doneWithError = true } if (!rawHistoryPage.isChecksumOK) { aapsLogger.error(LTag.PUMPCOMM, "getPumpHistory: checksum is wrong") doneWithError = true } if (doneWithError) { medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return pumpTotalResult } rawHistoryPage.dumpToDebug() val medtronicHistoryEntries = medtronicPumpHistoryDecoder.processPageAndCreateRecords(rawHistoryPage) aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Found %d history entries.", medtronicHistoryEntries.size)) pumpTotalResult.addHistoryEntries(medtronicHistoryEntries) //, pageNumber) aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Search status: Search finished: %b", pumpTotalResult.isSearchFinished)) if (pumpTotalResult.isSearchFinished) { medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return pumpTotalResult } } medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return pumpTotalResult } override fun createPumpMessageContent(type: RLMessageType): ByteArray { return when (type) { RLMessageType.PowerOn -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.RFPowerOn, byteArrayOf(2, 1, receiverDeviceAwakeForMinutes.toByte())) RLMessageType.ReadSimpleData -> medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.PumpModel, null) else -> ByteArray(0) } } private fun makePumpMessage(messageType: MedtronicCommandType, body: ByteArray? = null): PumpMessage { return makePumpMessage(messageType, body?.let { CarelinkShortMessageBody(it) } ?: CarelinkShortMessageBody()) } private fun makePumpMessage(messageType: MedtronicCommandType?, messageBody: MessageBody): PumpMessage { val msg = PumpMessage(aapsLogger) msg.init(PacketType.Carelink, rileyLinkServiceData.pumpIDBytes, messageType, messageBody) return msg } /** * Main wrapper method for sending data - (for getting responses) * * @param commandType * @param bodyData * @param timeoutMs * @return */ @Throws(RileyLinkCommunicationException::class) private fun sendAndGetResponse(commandType: MedtronicCommandType, bodyData: ByteArray? = null, timeoutMs: Int = DEFAULT_TIMEOUT): PumpMessage { // wakeUp if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Active // create message val msg: PumpMessage = bodyData?.let { makePumpMessage(commandType, it) } ?: makePumpMessage(commandType) // send and wait for response val response = sendAndListen(msg, timeoutMs) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return response } @Throws(RileyLinkCommunicationException::class) private fun sendAndListen(msg: PumpMessage): PumpMessage { return sendAndListen(msg, 4000) // 2000 } // All pump communications go through this function. @Throws(RileyLinkCommunicationException::class) private /*override*/ fun sendAndListen(msg: PumpMessage, timeout_ms: Int): PumpMessage { return super.sendAndListen(msg, timeout_ms)!! } private inline fun <reified T> sendAndGetResponseWithCheck( commandType: MedtronicCommandType, bodyData: ByteArray? = null, decode: (pumpType: PumpType, commandType: MedtronicCommandType, rawContent: ByteArray) -> T ): T? { aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: $commandType") for (retries in 0 until MAX_COMMAND_TRIES) { try { val response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + DEFAULT_TIMEOUT * retries) val check = checkResponseContent(response, commandType.commandDescription, commandType.expectedLength) if (check == null) { checkResponseRawContent(response.rawContent, commandType) { return@sendAndGetResponseWithCheck null } val dataResponse = decode(medtronicPumpStatus.pumpType, commandType, response.rawContent) if (dataResponse != null) { errorResponse = null aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Converted response for %s is %s.", commandType.name, dataResponse)) return dataResponse } else { errorResponse = "Error decoding response." } } else { errorResponse = check // return null; } } catch (e: RileyLinkCommunicationException) { aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1)) } } return null } private inline fun checkResponseRawContent(rawContent: ByteArray?, commandType: MedtronicCommandType, errorCase: () -> Unit) { if (rawContent?.isEmpty() != false && commandType != MedtronicCommandType.PumpModel) { aapsLogger.warn( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Content is empty or too short, no data to convert (type=%s,isNull=%b,length=%s)", commandType.name, rawContent == null, rawContent?.size ?: "-")) errorCase.invoke() } else { aapsLogger.debug(LTag.PUMPCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent)) } } private fun checkResponseContent(response: PumpMessage, method: String, expectedLength: Int): String? { if (!response.isValid) { val responseData = String.format("%s: Invalid response.", method) aapsLogger.warn(LTag.PUMPCOMM, responseData) return responseData } val contents = response.rawContent return if (contents.isNotEmpty()) { if (contents.size >= expectedLength) { aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: Content: %s", method, ByteUtil.shortHexString(contents))) null } else { val responseData = String.format( "%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, "" + expectedLength, "" + contents.size) aapsLogger.warn(LTag.PUMPCOMM, responseData) responseData } } else { val responseData = String.format("%s: Cannot return data. Zero length response.", method) aapsLogger.warn(LTag.PUMPCOMM, responseData) responseData } } // PUMP SPECIFIC COMMANDS fun getRemainingInsulin(): Double? { return sendAndGetResponseWithCheck(MedtronicCommandType.GetRemainingInsulin) { _, _, rawContent -> medtronicConverter.decodeRemainingInsulin(rawContent) } } fun getPumpModel(): MedtronicDeviceType? { return sendAndGetResponseWithCheck(MedtronicCommandType.PumpModel) { _, _, rawContent -> medtronicConverter.decodeModel(rawContent) } } fun getBasalProfile(): BasalProfile? { // wakeUp if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false) val commandType = MedtronicCommandType.GetBasalProfileSTD aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: $commandType") medtronicUtil.setCurrentCommand(commandType) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Active for (retries in 0..MAX_COMMAND_TRIES) { try { // create message val msg: PumpMessage = makePumpMessage(commandType) // send and wait for response var response = sendAndListen(msg, DEFAULT_TIMEOUT + DEFAULT_TIMEOUT * retries) // aapsLogger.debug(LTag.PUMPCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); // aapsLogger.debug(LTag.PUMPCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); val check = checkResponseContent(response, commandType.commandDescription, 1) var data: ByteArray = byteArrayOf() if (check == null) { data = response.rawContentOfFrame val ackMsg = makePumpMessage(MedtronicCommandType.CommandACK, PumpAckMessageBody()) while (checkIfWeHaveMoreData(commandType, response, data)) { response = sendAndListen(ackMsg, DEFAULT_TIMEOUT + DEFAULT_TIMEOUT * retries) // aapsLogger.debug(LTag.PUMPCOMM,"{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent())); // aapsLogger.debug(LTag.PUMPCOMM,"{} Response: {}", runs, // HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData())); val check2 = checkResponseContent(response, commandType.commandDescription, 1) if (check2 == null) { data = ByteUtil.concat(data, response.rawContentOfFrame) } else { errorResponse = check2 aapsLogger.error(LTag.PUMPCOMM, "Error with response got GetProfile: $check2") } } } else { errorResponse = check } aapsLogger.debug(LTag.PUMPCOMM, "End Response: {}", ByteUtil.getHex(data)) val basalProfile: BasalProfile? = medtronicConverter.decodeBasalProfile(medtronicPumpPlugin.pumpDescription.pumpType, data) // checkResponseRawContent(data, commandType) { // basalProfile = medtronicConverter.decodeBasalProfile(medtronicPumpPlugin.pumpDescription.pumpType, data) // } if (basalProfile != null) { aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Converted response for %s is %s.", commandType.name, basalProfile)) medtronicUtil.setCurrentCommand(null) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return basalProfile } } catch (e: RileyLinkCommunicationException) { aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1)) } } aapsLogger.warn(LTag.PUMPCOMM, "Error reading profile in max retries.") medtronicUtil.setCurrentCommand(null) medtronicPumpStatus.pumpDeviceState = PumpDeviceState.Sleeping return null } private fun checkIfWeHaveMoreData(commandType: MedtronicCommandType, response: PumpMessage, data: ByteArray): Boolean { if (commandType === MedtronicCommandType.GetBasalProfileSTD || // commandType === MedtronicCommandType.GetBasalProfileA || // commandType === MedtronicCommandType.GetBasalProfileB) { val responseRaw = response.rawContentOfFrame val last = responseRaw.size - 1 aapsLogger.debug(LTag.PUMPCOMM, "Length: " + data.size) if (data.size >= BasalProfile.MAX_RAW_DATA_SIZE) { return false } return if (responseRaw.size < 2) { false } else !(responseRaw[last] == 0x00.toByte() && responseRaw[last - 1] == 0x00.toByte() && responseRaw[last - 2] == 0x00.toByte()) } return false } fun getPumpTime(): ClockDTO? { val localTime = LocalDateTime() val responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.GetRealTimeClock) { _, _, rawContent -> medtronicConverter.decodeTime(rawContent) } if (responseObject != null) { return ClockDTO(localDeviceTime = localTime, pumpTime = responseObject) } return null } fun getTemporaryBasal(): TempBasalPair? { return sendAndGetResponseWithCheck(MedtronicCommandType.ReadTemporaryBasal) { _, _, rawContent -> if (rawContent.size >= 5) TempBasalPair(aapsLogger, rawContent) else { aapsLogger.debug(LTag.PUMPBTCOMM, "Received invalid TempBasal response" + ByteUtil.getHex(rawContent)) null } } } fun getPumpSettings(): Map<String, PumpSettingDTO>? { return sendAndGetResponseWithCheck(getSettings(medtronicUtil.medtronicPumpModel)) { _, _, rawContent -> medtronicConverter.decodeSettingsLoop(rawContent) } } fun setBolus(units: Double): Boolean { aapsLogger.info(LTag.PUMPCOMM, "setBolus: $units") return setCommand(MedtronicCommandType.SetBolus, medtronicUtil.getBolusStrokes(units)) } fun setTemporaryBasal(tbr: TempBasalPair): Boolean { aapsLogger.info(LTag.PUMPCOMM, "setTBR: " + tbr.description) return setCommand(MedtronicCommandType.SetTemporaryBasal, tbr.asRawData) } fun setPumpTime(): Boolean { val gc = GregorianCalendar() gc.add(Calendar.SECOND, 5) aapsLogger.info(LTag.PUMPCOMM, "setPumpTime: " + DateTimeUtil.toString(gc)) val yearByte = getByteArrayFromUnsignedShort(gc[Calendar.YEAR], true) // val i = 1 // val data = ByteArray(8) // data[0] = 7 // data[i] = gc[Calendar.HOUR_OF_DAY].toByte() // data[i + 1] = gc[Calendar.MINUTE].toByte() // data[i + 2] = gc[Calendar.SECOND].toByte() // val yearByte = getByteArrayFromUnsignedShort(gc[Calendar.YEAR], true) // data[i + 3] = yearByte[0] // data[i + 4] = yearByte[1] // data[i + 5] = (gc[Calendar.MONTH] + 1).toByte() // data[i + 6] = gc[Calendar.DAY_OF_MONTH].toByte() val timeData = byteArrayOf( 7, gc[Calendar.HOUR_OF_DAY].toByte(), gc[Calendar.MINUTE].toByte(), gc[Calendar.SECOND].toByte(), yearByte[0], yearByte[1], (gc[Calendar.MONTH] + 1).toByte(), gc[Calendar.DAY_OF_MONTH].toByte() ) //aapsLogger.info(LTag.PUMPCOMM,"setPumpTime: Body: " + ByteUtil.getHex(data)); return setCommand(MedtronicCommandType.SetRealTimeClock, timeData) } private fun setCommand(commandType: MedtronicCommandType, body: ByteArray): Boolean { for (retries in 0..MAX_COMMAND_TRIES) { try { if (doWakeUpBeforeCommand) wakeUp(false) if (debugSetCommands) aapsLogger.debug( LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: Body - %s", commandType.commandDescription, ByteUtil.getHex(body))) val msg = makePumpMessage(commandType, CarelinkLongMessageBody(body)) val pumpMessage = runCommandWithArgs(msg) if (debugSetCommands) aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: %s", commandType.commandDescription, pumpMessage.responseContent)) if (pumpMessage.commandType === MedtronicCommandType.CommandACK) { return true } else { aapsLogger.warn(LTag.PUMPCOMM, "We received non-ACK response from pump: " + pumpMessage.responseContent) } } catch (e: RileyLinkCommunicationException) { aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1)) } } return false } fun cancelTBR(): Boolean { return setTemporaryBasal(TempBasalPair(0.0, false, 0)) } fun getRemainingBattery(): BatteryStatusDTO? { return sendAndGetResponseWithCheck(MedtronicCommandType.GetBatteryStatus) { _, _, rawContent -> medtronicConverter.decodeBatteryStatus(rawContent) } } fun setBasalProfile(basalProfile: BasalProfile): Boolean { val basalProfileFrames = medtronicUtil.getBasalProfileFrames(basalProfile.rawData) for (retries in 0..MAX_COMMAND_TRIES) { var responseMessage: PumpMessage? = null try { responseMessage = runCommandWithFrames(MedtronicCommandType.SetBasalProfileSTD, basalProfileFrames) if (responseMessage!!.commandType === MedtronicCommandType.CommandACK) return true } catch (e: RileyLinkCommunicationException) { aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1)) } if (responseMessage != null) aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Set Basal Profile: Invalid response: commandType=%s,rawData=%s", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.rawContent))) else aapsLogger.warn( LTag.PUMPCOMM, "Set Basal Profile: Null response.") } return false } }
agpl-3.0
467f73bc4d4629923cee795a3ff27c29
51.486957
272
0.633643
5.123939
false
false
false
false
pambrose/prometheus-proxy
src/main/kotlin/io/prometheus/agent/AgentHttpService.kt
1
8766
/* * Copyright © 2020 Paul Ambrose ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction") package io.prometheus.agent import com.github.pambrose.common.dsl.KtorDsl.get import com.github.pambrose.common.util.isNotNull import com.github.pambrose.common.util.isNull import com.github.pambrose.common.util.simpleClassName import com.github.pambrose.common.util.zip import com.google.common.net.HttpHeaders import com.google.common.net.HttpHeaders.ACCEPT import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* import io.ktor.client.plugins.auth.* import io.ktor.client.plugins.auth.providers.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.HttpStatusCode.Companion.NotFound import io.ktor.network.sockets.* import io.prometheus.Agent import io.prometheus.common.ScrapeResults import io.prometheus.grpc.ScrapeRequest import kotlinx.coroutines.TimeoutCancellationException import mu.KLogging import java.io.IOException import java.net.URLDecoder import java.net.http.HttpConnectTimeoutException import java.util.concurrent.atomic.AtomicReference import kotlin.text.Charsets.UTF_8 import kotlin.time.Duration.Companion.seconds internal class AgentHttpService(val agent: Agent) { suspend fun fetchScrapeUrl(request: ScrapeRequest): ScrapeResults = ScrapeResults( agentId = request.agentId, scrapeId = request.scrapeId ).also { scrapeResults -> val scrapeMsg = AtomicReference("") val path = request.path val encodedQueryParams = request.encodedQueryParams val authHeader = when { request.authHeader.isNullOrBlank() -> null else -> request.authHeader } val pathContext = agent.pathManager[path] if (pathContext.isNull()) { logger.warn { "Invalid path in fetchScrapeUrl(): $path" } scrapeMsg.set("invalid_path") if (request.debugEnabled) scrapeResults.setDebugInfo("None", "Invalid path: $path") } else { val requestTimer = if (agent.isMetricsEnabled) agent.startTimer(agent) else null // Add the incoming query params to the url val url = pathContext.url + (if (encodedQueryParams.isNotEmpty()) "?${URLDecoder.decode(encodedQueryParams, UTF_8.name())}" else "") logger.debug { "Fetching $pathContext" } if (encodedQueryParams.isNotEmpty()) logger.debug { "URL: $url" } // Content is fetched here try { HttpClient(CIO) { expectSuccess = false engine { val timeout = agent.configVals.agent.internal.cioTimeoutSecs.seconds requestTimeout = timeout.inWholeMilliseconds val enableTrustAllX509Certificates = agent.configVals.agent.http.enableTrustAllX509Certificates if (enableTrustAllX509Certificates) { https { // trustManager = SslSettings.getTrustManager() trustManager = TrustAllX509TrustManager } } } install(HttpTimeout) install(HttpRequestRetry) { agent.options.scrapeMaxRetries.also { maxRetries -> if (maxRetries <= 0) noRetry() else { retryOnException(maxRetries) retryIf(maxRetries) { _, response -> !response.status.isSuccess() && response.status != NotFound } modifyRequest { it.headers.append("x-retry-count", retryCount.toString()) } exponentialDelay() } } } val urlObj = Url(url) val user = urlObj.user val passwd = urlObj.password if (user.isNotNull() && passwd.isNotNull()) { install(Auth) { basic { credentials { BasicAuthCredentials(user, passwd) } } } } }.use { client -> client.get( url, { request.accept?.also { if (it.isNotEmpty()) header(ACCEPT, it) } val scrapeTimeout = agent.options.scrapeTimeoutSecs.seconds logger.debug { "Setting scrapeTimeoutSecs = $scrapeTimeout" } timeout { requestTimeoutMillis = scrapeTimeout.inWholeMilliseconds } authHeader?.also { header(io.ktor.http.HttpHeaders.Authorization, it) } }, getBlock(url, scrapeResults, scrapeMsg, request.debugEnabled) ) } } catch (e: TimeoutCancellationException) { logger.warn(e) { "fetchScrapeUrl() $e - $url" } scrapeResults.statusCode = HttpStatusCode.RequestTimeout.value scrapeResults.failureReason = e.message ?: e.simpleClassName if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } catch (e: HttpConnectTimeoutException) { logger.warn(e) { "fetchScrapeUrl() $e - $url" } scrapeResults.statusCode = HttpStatusCode.RequestTimeout.value scrapeResults.failureReason = e.message ?: e.simpleClassName if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } catch (e: SocketTimeoutException) { logger.warn(e) { "fetchScrapeUrl() $e - $url" } scrapeResults.statusCode = HttpStatusCode.RequestTimeout.value scrapeResults.failureReason = e.message ?: e.simpleClassName if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } catch (e: HttpRequestTimeoutException) { logger.warn(e) { "fetchScrapeUrl() $e - $url" } scrapeResults.statusCode = HttpStatusCode.RequestTimeout.value scrapeResults.failureReason = e.message ?: e.simpleClassName if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } catch (e: IOException) { logger.info { "Failed HTTP request: $url [${e.simpleClassName}: ${e.message}]" } scrapeResults.statusCode = HttpStatusCode.NotFound.value scrapeResults.failureReason = e.message ?: e.simpleClassName if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } catch (e: Throwable) { logger.warn(e) { "fetchScrapeUrl() $e - $url" } scrapeResults.failureReason = e.message ?: e.simpleClassName scrapeResults.statusCode = HttpStatusCode.ServiceUnavailable.value if (request.debugEnabled) scrapeResults.setDebugInfo(url, "${e.simpleClassName} - ${e.message}") } finally { requestTimer?.observeDuration() } } agent.updateScrapeCounter(agent, scrapeMsg.get()) } private fun getBlock( url: String, responseArg: ScrapeResults, scrapeCounterMsg: AtomicReference<String>, debugEnabled: Boolean ): suspend (HttpResponse) -> Unit = { response -> responseArg.statusCode = response.status.value if (response.status.isSuccess()) { responseArg.apply { contentType = response.headers[HttpHeaders.CONTENT_TYPE].orEmpty() // Zip the content here val content = response.bodyAsText() zipped = content.length > agent.configVals.agent.minGzipSizeBytes if (zipped) contentAsZipped = content.zip() else contentAsText = content validResponse = true } if (debugEnabled) responseArg.setDebugInfo(url) scrapeCounterMsg.set("success") } else { if (debugEnabled) responseArg.setDebugInfo(url, "Unsuccessful response code ${responseArg.statusCode}") scrapeCounterMsg.set("unsuccessful") } } companion object : KLogging() }
apache-2.0
03dc50598f7759f24c414cf06b9353f8
37.61674
109
0.630918
4.674667
false
false
false
false
rinp/javaQuiz
src/main/kotlin/xxx/jq/controller/CategoryController.kt
1
1615
package xxx.jq.controller /** * @author rinp * @since 2015/11/30 */ import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import xxx.jq.consts.Authorizes import xxx.jq.entity.Category import xxx.jq.form.CategoryForm import xxx.jq.service.CategoryService @RestController @RequestMapping(value = "/v1/categories") @PreAuthorize(Authorizes.AUTHENTICATED) open class CategoryController { @Autowired lateinit private var service: CategoryService @RequestMapping(method = arrayOf(RequestMethod.GET)) open fun getList(): List<Category> { return service.findAll() } @RequestMapping(method = arrayOf(RequestMethod.POST), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE)) open fun update(@RequestBody @Validated list: MutableList<CategoryForm>) { val deleteList = list.filter { it.isDelete }.map { it.id }.filterNotNull() service.deleteAll(deleteList); val newList = list.filter { !it.isDelete }.filter { it.id == null }.map { it.toCategory() } service.insertAll(newList); val editList = list.filter { !it.isDelete }.filter { it.id != null }.map { it.toCategory() } service.updateAll(editList); } }
mit
ec889a0ffb4f657f53c00bedf07cac08
30.666667
111
0.751084
4.183938
false
false
false
false
PolymerLabs/arcs
java/arcs/android/crdt/CrdtSetProto.kt
1
4507
package arcs.android.crdt import android.os.Parcel import arcs.android.util.readProto import arcs.core.common.Referencable import arcs.core.crdt.CrdtSet /** Constructs a [CrdtSet.DataValue] from the given [CrdtSetProto.DataValue]. */ fun CrdtSetProto.DataValue.toDataValue() = CrdtSet.DataValue( versionMap = fromProto(versionMap), value = value.toReferencable()!! ) /** Constructs a [CrdtSet.Data] from the given [CrdtSetProto.Data]. */ fun CrdtSetProto.Data.toData() = CrdtSet.DataImpl<Referencable>( versionMap = fromProto(versionMap), values = valuesMap.mapValuesTo(mutableMapOf()) { it.value.toDataValue() } ) /** Constructs a [CrdtSet.Operation] from the given [CrdtSetProto.Operation]. */ fun CrdtSetProto.Operation.toOperation(): CrdtSet.Operation<Referencable> = when (operationCase) { CrdtSetProto.Operation.OperationCase.ADD -> with(add) { CrdtSet.Operation.Add( actor = actor, versionMap = fromProto(versionMap), added = added.toReferencable()!! ) } CrdtSetProto.Operation.OperationCase.REMOVE -> with(remove) { CrdtSet.Operation.Remove<Referencable>( actor = actor, versionMap = fromProto(versionMap), removed = removed ) } CrdtSetProto.Operation.OperationCase.CLEAR -> with(clear) { CrdtSet.Operation.Clear<Referencable>( actor = actor, versionMap = fromProto(versionMap) ) } CrdtSetProto.Operation.OperationCase.FAST_FORWARD -> with(fastForward) { CrdtSet.Operation.FastForward<Referencable>( oldVersionMap = fromProto(oldVersionMap), newVersionMap = fromProto(newVersionMap), added = addedList.mapTo(mutableListOf()) { it.toDataValue() }, removed = removedList.mapTo(mutableListOf()) { it.toReferencable()!! } ) } CrdtSetProto.Operation.OperationCase.OPERATION_NOT_SET, null -> throw UnsupportedOperationException("Unknown CrdtSet.Operation type: $operationCase.") } /** Serializes a [CrdtSet.DataValue] to its proto form. */ fun CrdtSet.DataValue<*>.toProto() = CrdtSetProto.DataValue.newBuilder() .setVersionMap(versionMap.toProto()) .setValue(value.toProto()) .build() /** Serializes a [CrdtSet.Data] to its proto form. */ fun CrdtSet.Data<*>.toProto() = CrdtSetProto.Data.newBuilder() .setVersionMap(versionMap.toProto()) .putAllValues(values.mapValues { it.value.toProto() }) .build() /** Serializes a [CrdtSet.Operation] to its proto form. */ fun CrdtSet.Operation<*>.toProto(): CrdtSetProto.Operation { val proto = CrdtSetProto.Operation.newBuilder() when (this) { is CrdtSet.Operation.Add<*> -> proto.add = toProto() is CrdtSet.Operation.Remove<*> -> proto.remove = toProto() is CrdtSet.Operation.Clear<*> -> proto.clear = toProto() is CrdtSet.Operation.FastForward<*> -> proto.fastForward = toProto() } return proto.build() } /** Serializes a [CrdtSet.Operation.Add] to its proto form. */ private fun CrdtSet.Operation.Add<*>.toProto() = CrdtSetProto.Operation.Add.newBuilder() .setVersionMap(versionMap.toProto()) .setActor(actor) .setAdded(added.toProto()) .build() /** Serializes a [CrdtSet.Operation.Remove] to its proto form. */ private fun CrdtSet.Operation.Remove<*>.toProto() = CrdtSetProto.Operation.Remove.newBuilder() .setVersionMap(versionMap.toProto()) .setActor(actor) .setRemoved(removed) .build() /** Serializes a [CrdtSet.Operation.Clear] to its proto form. */ private fun CrdtSet.Operation.Clear<*>.toProto() = CrdtSetProto.Operation.Clear.newBuilder() .setVersionMap(versionMap.toProto()) .setActor(actor) .build() /** Serializes a [CrdtSet.Operation.FastForward] to its proto form. */ private fun CrdtSet.Operation.FastForward<*>.toProto() = CrdtSetProto.Operation.FastForward.newBuilder() .setOldVersionMap(oldVersionMap.toProto()) .setNewVersionMap(newVersionMap.toProto()) .addAllAdded(added.map { it.toProto() }) .addAllRemoved(removed.map { it.toProto() }) .build() /** Reads a [CrdtSet.DataValue] out of a [Parcel]. */ fun Parcel.readCrdtSetDataValue(): CrdtSet.DataValue<Referencable>? = readProto(CrdtSetProto.DataValue.getDefaultInstance())?.toDataValue() /** Reads a [CrdtSet.Data] out of a [Parcel]. */ fun Parcel.readCrdtSetData(): CrdtSet.Data<Referencable>? = readProto(CrdtSetProto.Data.getDefaultInstance())?.toData() /** Reads a [CrdtSet.Operation] out of a [Parcel]. */ fun Parcel.readCrdtSetOperation(): CrdtSet.Operation<Referencable>? = readProto(CrdtSetProto.Operation.getDefaultInstance())?.toOperation()
bsd-3-clause
05c226b3073a47fc8e262fdc1f425a2e
37.521368
98
0.725094
4.049416
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ScriptHandlerScope.kt
3
8208
/* * Copyright 2016 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.kotlin.dsl import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.DependencyConstraint import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.MinimalExternalModuleDependency import org.gradle.api.artifacts.ModuleDependency import org.gradle.api.artifacts.dsl.DependencyConstraintHandler import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.api.initialization.dsl.ScriptHandler import org.gradle.api.initialization.dsl.ScriptHandler.CLASSPATH_CONFIGURATION import org.gradle.api.provider.Provider import org.gradle.api.provider.ProviderConvertible import org.gradle.kotlin.dsl.support.delegates.ScriptHandlerDelegate import org.gradle.kotlin.dsl.support.unsafeLazy /** * Receiver for the `buildscript` block. */ class ScriptHandlerScope private constructor( override val delegate: ScriptHandler ) : ScriptHandlerDelegate() { companion object { fun of(scriptHandler: ScriptHandler) = ScriptHandlerScope(scriptHandler) } /** * The dependencies of the script. */ val dependencies by unsafeLazy { DependencyHandlerScope.of(delegate.dependencies) } /** * The script classpath configuration. */ val NamedDomainObjectContainer<Configuration>.classpath: NamedDomainObjectProvider<Configuration> get() = named(CLASSPATH_CONFIGURATION) /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @return The dependency. * * @see [DependencyHandler.add] */ fun DependencyHandler.classpath(dependencyNotation: Any): Dependency? = add(CLASSPATH_CONFIGURATION, dependencyNotation) /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] */ inline fun DependencyHandler.classpath( dependencyNotation: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit ): ExternalModuleDependency = add(CLASSPATH_CONFIGURATION, dependencyNotation, dependencyConfiguration) /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] * @since 7.4 */ fun DependencyHandler.classpath( dependencyNotation: Provider<MinimalExternalModuleDependency>, dependencyConfiguration: ExternalModuleDependency.() -> Unit ) { addProvider(CLASSPATH_CONFIGURATION, dependencyNotation, dependencyConfiguration) } /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] * @since 7.4 */ fun DependencyHandler.classpath( dependencyNotation: ProviderConvertible<MinimalExternalModuleDependency>, dependencyConfiguration: ExternalModuleDependency.() -> Unit ) { addProviderConvertible(CLASSPATH_CONFIGURATION, dependencyNotation, dependencyConfiguration) } /** * Adds a dependency to the script classpath. * * @param group the group of the module to be added as a dependency. * @param name the name of the module to be added as a dependency. * @param version the optional version of the module to be added as a dependency. * @param configuration the optional configuration of the module to be added as a dependency. * @param classifier the optional classifier of the module artifact to be added as a dependency. * @param ext the optional extension of the module artifact to be added as a dependency. * @return The dependency. * * @see [DependencyHandler.add] */ fun DependencyHandler.classpath( group: String, name: String, version: String? = null, configuration: String? = null, classifier: String? = null, ext: String? = null ): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also { add(CLASSPATH_CONFIGURATION, it) } /** * Adds a dependency to the script classpath. * * @param group the group of the module to be added as a dependency. * @param name the name of the module to be added as a dependency. * @param version the optional version of the module to be added as a dependency. * @param configuration the optional configuration of the module to be added as a dependency. * @param classifier the optional classifier of the module artifact to be added as a dependency. * @param ext the optional extension of the module artifact to be added as a dependency. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.create] * @see [DependencyHandler.add] */ inline fun DependencyHandler.classpath( group: String, name: String, version: String? = null, configuration: String? = null, classifier: String? = null, ext: String? = null, dependencyConfiguration: ExternalModuleDependency.() -> Unit ): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also { add(CLASSPATH_CONFIGURATION, it, dependencyConfiguration) } /** * Adds a dependency to the script classpath. * * @param dependency dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] */ inline fun <T : ModuleDependency> DependencyHandler.classpath( dependency: T, dependencyConfiguration: T.() -> Unit ): T = add(CLASSPATH_CONFIGURATION, dependency, dependencyConfiguration) /** * Adds a dependency constraint to the script classpath configuration. * * @param dependencyConstraintNotation the dependency constraint notation * * @return the added dependency constraint * * @see [DependencyConstraintHandler.add] * @since 5.0 */ fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any): DependencyConstraint? = add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation) /** * Adds a dependency constraint to the script classpath configuration. * * @param dependencyConstraintNotation the dependency constraint notation * @param configuration the block to use to configure the dependency constraint * * @return the added dependency constraint * * @see [DependencyConstraintHandler.add] * @since 5.0 */ fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any, configuration: DependencyConstraint.() -> Unit): DependencyConstraint? = add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation, configuration) }
apache-2.0
154cf35a1eb45d8924f60b7b6ce2e6f4
37.900474
153
0.71345
5.191651
false
true
false
false
blindpirate/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/KotlinCompiler.kt
1
16291
/* * Copyright 2016 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.kotlin.dsl.support import org.gradle.internal.SystemProperties import org.gradle.internal.io.NullOutputStream import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CompilerSystemProperties.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoot import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoots import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageUtil import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileBunchOfSources import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoot import org.jetbrains.kotlin.codegen.CompilationException import org.jetbrains.kotlin.com.intellij.openapi.Disposable import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer.dispose import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer.newDisposable import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.CommonConfigurationKeys import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.config.JVMConfigurationKeys.JVM_TARGET import org.jetbrains.kotlin.config.JVMConfigurationKeys.OUTPUT_DIRECTORY import org.jetbrains.kotlin.config.JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY import org.jetbrains.kotlin.config.JvmAnalysisFlags import org.jetbrains.kotlin.config.JvmDefaultMode import org.jetbrains.kotlin.config.JvmTarget.JVM_1_8 import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor.Companion.registerExtension import org.jetbrains.kotlin.name.NameUtils import org.jetbrains.kotlin.samWithReceiver.CliSamWithReceiverComponentContributor import org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar import org.jetbrains.kotlin.scripting.configuration.ScriptingConfigurationKeys.SCRIPT_DEFINITIONS import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.utils.PathUtil import org.slf4j.Logger import java.io.ByteArrayOutputStream import java.io.File import java.io.OutputStream import java.io.PrintStream import kotlin.reflect.KClass import kotlin.script.experimental.api.KotlinType import kotlin.script.experimental.api.ScriptCompilationConfiguration import kotlin.script.experimental.api.baseClass import kotlin.script.experimental.api.defaultImports import kotlin.script.experimental.api.hostConfiguration import kotlin.script.experimental.api.implicitReceivers import kotlin.script.experimental.api.providedProperties import kotlin.script.experimental.host.ScriptingHostConfiguration import kotlin.script.experimental.host.configurationDependencies import kotlin.script.experimental.host.getScriptingClass import kotlin.script.experimental.jvm.JvmDependency import kotlin.script.experimental.jvm.JvmGetScriptingClass fun compileKotlinScriptModuleTo( outputDirectory: File, moduleName: String, scriptFiles: Collection<String>, scriptDef: ScriptDefinition, classPath: Iterable<File>, logger: Logger, pathTranslation: (String) -> String ) = compileKotlinScriptModuleTo( outputDirectory, moduleName, scriptFiles, scriptDef, classPath, LoggingMessageCollector(logger, pathTranslation) ) fun scriptDefinitionFromTemplate( template: KClass<out Any>, implicitImports: List<String>, implicitReceiver: KClass<*>? = null, injectedProperties: Map<String, KotlinType> = mapOf(), classPath: List<File> = listOf() ): ScriptDefinition { val hostConfiguration = ScriptingHostConfiguration { getScriptingClass(JvmGetScriptingClass()) configurationDependencies(JvmDependency(classPath)) } return ScriptDefinition.FromConfigurations( hostConfiguration = hostConfiguration, compilationConfiguration = ScriptCompilationConfiguration { baseClass(template) defaultImports(implicitImports) hostConfiguration(hostConfiguration) implicitReceiver?.let { implicitReceivers(it) } providedProperties(injectedProperties) }, evaluationConfiguration = null ) } internal fun compileKotlinScriptToDirectory( outputDirectory: File, scriptFile: File, scriptDef: ScriptDefinition, classPath: List<File>, messageCollector: LoggingMessageCollector ): String { compileKotlinScriptModuleTo( outputDirectory, "buildscript", listOf(scriptFile.path), scriptDef, classPath, messageCollector ) return NameUtils.getScriptNameForFile(scriptFile.name).asString() } private fun compileKotlinScriptModuleTo( outputDirectory: File, moduleName: String, scriptFiles: Collection<String>, scriptDef: ScriptDefinition, classPath: Iterable<File>, messageCollector: LoggingMessageCollector ) { withRootDisposable { withCompilationExceptionHandler(messageCollector) { val configuration = compilerConfigurationFor(messageCollector).apply { put(RETAIN_OUTPUT_IN_MEMORY, false) put(OUTPUT_DIRECTORY, outputDirectory) setModuleName(moduleName) addScriptingCompilerComponents() addScriptDefinition(scriptDef) scriptFiles.forEach { addKotlinSourceRoot(it) } classPath.forEach { addJvmClasspathRoot(it) } } val environment = kotlinCoreEnvironmentFor(configuration).apply { HasImplicitReceiverCompilerPlugin.apply(project) } compileBunchOfSources(environment) || throw ScriptCompilationException(messageCollector.errors) } } } private object HasImplicitReceiverCompilerPlugin { fun apply(project: Project) { registerExtension(project, samWithReceiverComponentContributor) } val samWithReceiverComponentContributor = CliSamWithReceiverComponentContributor( listOf("org.gradle.api.HasImplicitReceiver") ) } internal fun compileToDirectory( outputDirectory: File, moduleName: String, sourceFiles: Iterable<File>, logger: Logger, classPath: Iterable<File> ): Boolean { withRootDisposable { withMessageCollectorFor(logger) { messageCollector -> val configuration = compilerConfigurationFor(messageCollector).apply { addKotlinSourceRoots(sourceFiles.map { it.canonicalPath }) put(OUTPUT_DIRECTORY, outputDirectory) setModuleName(moduleName) classPath.forEach { addJvmClasspathRoot(it) } addJvmClasspathRoot(kotlinStdlibJar) } val environment = kotlinCoreEnvironmentFor(configuration) return compileBunchOfSources(environment) } } } private val kotlinStdlibJar: File get() = PathUtil.getResourcePathForClass(Unit::class.java) private inline fun <T> withRootDisposable(action: Disposable.() -> T): T { val rootDisposable = newDisposable() try { return action(rootDisposable) } finally { dispose(rootDisposable) } } private inline fun <T> withMessageCollectorFor(log: Logger, action: (MessageCollector) -> T): T { val messageCollector = messageCollectorFor(log) withCompilationExceptionHandler(messageCollector) { return action(messageCollector) } } private inline fun <T> withCompilationExceptionHandler(messageCollector: LoggingMessageCollector, action: () -> T): T { try { val log = messageCollector.log return when { log.isDebugEnabled -> { loggingOutputTo(log::debug) { action() } } else -> { ignoringOutputOf { action() } } } } catch (ex: CompilationException) { messageCollector.report( CompilerMessageSeverity.EXCEPTION, ex.localizedMessage, MessageUtil.psiElementToMessageLocation(ex.element) ) throw IllegalStateException("Internal compiler error: ${ex.localizedMessage}", ex) } } private inline fun <T> loggingOutputTo(noinline log: (String) -> Unit, action: () -> T): T = redirectingOutputTo({ LoggingOutputStream(log) }, action) private inline fun <T> ignoringOutputOf(action: () -> T): T = redirectingOutputTo({ NullOutputStream.INSTANCE }, action) private inline fun <T> redirectingOutputTo(noinline outputStream: () -> OutputStream, action: () -> T): T = redirecting(System.err, System::setErr, outputStream()) { redirecting(System.out, System::setOut, outputStream()) { action() } } private inline fun <T> redirecting( stream: PrintStream, set: (PrintStream) -> Unit, to: OutputStream, action: () -> T ): T = try { set(PrintStream(to, true)) action() } finally { set(stream) to.flush() } private class LoggingOutputStream(val log: (String) -> Unit) : OutputStream() { private val buffer = ByteArrayOutputStream() override fun write(b: Int) = buffer.write(b) override fun write(b: ByteArray, off: Int, len: Int) = buffer.write(b, off, len) override fun flush() { buffer.run { val string = toString("utf8") if (string.isNotBlank()) { log(string) } reset() } } override fun close() { flush() } } private fun compilerConfigurationFor(messageCollector: MessageCollector): CompilerConfiguration = CompilerConfiguration().apply { put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector) put(JVM_TARGET, JVM_1_8) put(CommonConfigurationKeys.LANGUAGE_VERSION_SETTINGS, gradleKotlinDslLanguageVersionSettings) } private val gradleKotlinDslLanguageVersionSettings = LanguageVersionSettingsImpl( languageVersion = LanguageVersion.KOTLIN_1_4, apiVersion = ApiVersion.KOTLIN_1_4, analysisFlags = mapOf( AnalysisFlags.skipMetadataVersionCheck to true, JvmAnalysisFlags.jvmDefaultMode to JvmDefaultMode.ENABLE, ), specificFeatures = mapOf( LanguageFeature.DisableCompatibilityModeForNewInference to LanguageFeature.State.ENABLED ) ) private fun CompilerConfiguration.setModuleName(name: String) { put(CommonConfigurationKeys.MODULE_NAME, name) } private fun CompilerConfiguration.addScriptingCompilerComponents() { add( ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar() ) } private fun CompilerConfiguration.addScriptDefinition(scriptDef: ScriptDefinition) { add(SCRIPT_DEFINITIONS, scriptDef) } private fun Disposable.kotlinCoreEnvironmentFor(configuration: CompilerConfiguration): KotlinCoreEnvironment { org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback() return SystemProperties.getInstance().withSystemProperty( KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY.property, "true" ) { KotlinCoreEnvironment.createForProduction( this, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES ) } } internal fun disposeKotlinCompilerContext() = KotlinCoreEnvironment.disposeApplicationEnvironment() internal fun messageCollectorFor(log: Logger, pathTranslation: (String) -> String = { it }): LoggingMessageCollector = LoggingMessageCollector(log, pathTranslation) internal data class ScriptCompilationError(val message: String, val location: CompilerMessageSourceLocation?) internal data class ScriptCompilationException(val errors: List<ScriptCompilationError>) : RuntimeException() { init { require(errors.isNotEmpty()) } val firstErrorLine get() = errors.asSequence().mapNotNull { it.location?.line }.firstOrNull() override val message: String get() = ( listOf("Script compilation $errorPlural:") + indentedErrorMessages() + "${errors.size} $errorPlural" ) .joinToString("\n\n") private fun indentedErrorMessages() = errors.asSequence().map(::errorMessage).map(::prependIndent).toList() private fun errorMessage(error: ScriptCompilationError): String = error.location?.let { location -> errorAt(location, error.message) } ?: error.message private fun errorAt(location: CompilerMessageSourceLocation, message: String): String { val columnIndent = " ".repeat(5 + maxLineNumberStringLength + 1 + location.column) return "Line ${lineNumber(location)}: ${location.lineContent}\n" + "^ $message".lines().joinToString( prefix = columnIndent, separator = "\n$columnIndent $indent" ) } private fun lineNumber(location: CompilerMessageSourceLocation) = location.line.toString().padStart(maxLineNumberStringLength, '0') private fun prependIndent(it: String) = it.prependIndent(indent) private val errorPlural get() = if (errors.size > 1) "errors" else "error" private val maxLineNumberStringLength: Int by lazy { errors.mapNotNull { it.location?.line }.maxOrNull()?.toString()?.length ?: 0 } } private const val indent = " " internal class LoggingMessageCollector( internal val log: Logger, private val pathTranslation: (String) -> String ) : MessageCollector { val errors = arrayListOf<ScriptCompilationError>() override fun hasErrors() = errors.isNotEmpty() override fun clear() = errors.clear() override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) { fun msg() = location?.run { path.let(pathTranslation).let { path -> when { line >= 0 && column >= 0 -> compilerMessageFor(path, line, column, message) else -> "$path: $message" } } } ?: message fun taggedMsg() = "${severity.presentableName[0]}: ${msg()}" when (severity) { CompilerMessageSeverity.ERROR, CompilerMessageSeverity.EXCEPTION -> { errors += ScriptCompilationError(message, location) log.error { taggedMsg() } } in CompilerMessageSeverity.VERBOSE -> log.trace { msg() } CompilerMessageSeverity.STRONG_WARNING -> log.info { taggedMsg() } CompilerMessageSeverity.WARNING -> log.info { taggedMsg() } CompilerMessageSeverity.INFO -> log.info { msg() } else -> log.debug { taggedMsg() } } } } internal fun compilerMessageFor(path: String, line: Int, column: Int, message: String) = "$path:$line:$column: $message"
apache-2.0
c191da9038f02c07a8f86dd2ed49d441
30.449807
119
0.710208
4.841308
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/evaluate/classLoading/ClassToLoad.kt
1
1556
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate.classLoading import org.jetbrains.annotations.ApiStatus import org.jetbrains.org.objectweb.asm.tree.MethodNode const val GENERATED_FUNCTION_NAME = "generated_for_debugger_fun" const val GENERATED_CLASS_NAME = "Generated_for_debugger_class" @Suppress("ArrayInDataClass") data class ClassToLoad(val className: String, val relativeFileName: String, val bytes: ByteArray) { val isMainClass: Boolean get() = className == GENERATED_CLASS_NAME } @ApiStatus.Internal fun isEvaluationEntryPoint(methodName: String): Boolean { /* Short of inspecting the metadata, there are no indications in the bytecode of what precisely is the entrypoint to the compiled fragment. It's either: - named precisely GENERATED_FUNCTION_NAME - named GENERATED_FUNCTION_NAME-abcdefg, as a result of inline class mangling if the fragment captures a value of inline class type. and should not be confused with - GENERATED_FUNCTION_NAME$lambda-nn, introduced by SAM conversion - GENERATED_FUNCTION_NAME$foo, introduced by local functions in the fragment */ return methodName == GENERATED_FUNCTION_NAME || methodName.startsWith("$GENERATED_FUNCTION_NAME-") } val MethodNode.isEvaluationEntryPoint: Boolean @ApiStatus.Internal get() = name != null && isEvaluationEntryPoint(name)
apache-2.0
1826553ef91ccaa5db473f08bf8d871c
41.081081
158
0.751285
4.49711
false
false
false
false
caarmen/FRCAndroidWidget
app/src/main/kotlin/ca/rmen/android/frcwidget/FRCPopupActivity.kt
1
4145
/* * French Revolutionary Calendar Android Widget * Copyright (C) 2011 - 2017 Carmen Alvarez * * 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 ca.rmen.android.frcwidget import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import ca.rmen.android.frccommon.Action import ca.rmen.android.frccommon.Constants import ca.rmen.android.frccommon.compat.ApiHelper import ca.rmen.android.frenchcalendar.R import ca.rmen.lfrc.FrenchRevolutionaryCalendarDate /** * Display a list of actions for the user. These are displayed in a context-menu style: * This activity has a transparent background and displays an alert dialog. * */ class FRCPopupActivity : Activity() { companion object { private val TAG = Constants.TAG + FRCPopupActivity::class.java.simpleName const val EXTRA_DATE = "extra_date" } override fun onCreate(savedInstanceState: Bundle?) { Log.v(TAG, "onCreate") super.onCreate(savedInstanceState) // Build our adapter with the list of actions val adapter = ActionsAdapter(this) val frenchDate = intent.getSerializableExtra(EXTRA_DATE) as FrenchRevolutionaryCalendarDate adapter.add(Action.getDarkShareAction(this, frenchDate)) adapter.add(Action.getSettingsAction(this)) if (ApiHelper.apiLevel >= Constants.MIN_API_LEVEL_TWO_WAY_CONVERTER) { adapter.add(Action.getConverterAction(this)) } else { adapter.add(Action.getLegacyConverterAction(this)) } adapter.add(Action.getDarkSearchAction(this, frenchDate)) // Build the alert dialog. val builder = AlertDialog.Builder(this) builder.setAdapter(adapter, mListener) val dialog = builder.create() dialog.setOnDismissListener(mDismissListener) dialog.show() } override fun onStart() { super.onStart() Log.v(TAG, "onStart") } override fun onResume() { super.onResume() Log.v(TAG, "onResume") } override fun onPause() { super.onPause() Log.v(TAG, "onPause") } override fun onStop() { super.onStop() Log.v(TAG, "onStop") } override fun onDestroy() { super.onDestroy() Log.v(TAG, "onDestroy") } private class ActionsAdapter constructor(context: Context) : ArrayAdapter<Action>(context, R.layout.popup_item) { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val textView = super.getView(position, convertView, parent) as TextView val action = getItem(position) if (action != null) { textView.text = action.title textView.setCompoundDrawablesWithIntrinsicBounds(action.iconId, 0, 0, 0) } return textView } } private val mListener = DialogInterface.OnClickListener { dialog, which -> val adapter = (dialog as AlertDialog).listView.adapter as ActionsAdapter val action = adapter.getItem(which) if (action != null) { Log.v(TAG, "clicked on action " + action.title) startActivity(action.intent) } finish() } private val mDismissListener = DialogInterface.OnDismissListener { _ -> finish() } }
gpl-3.0
25ba2d44e89a194a6cd3d8a7b3df916e
33.541667
117
0.681544
4.37698
false
false
false
false
nonylene/MackerelAgentAndroid
app/src/main/java/net/nonylene/mackerelagent/realm/CPU.kt
1
1163
package net.nonylene.mackerelagent.realm import io.realm.Realm import io.realm.RealmObject import io.realm.annotations.Index import net.nonylene.mackerelagent.host.metric.CPUStat import java.util.* open class RealmCPUStat : RealmObject() { open var user = 0.0 open var nice = 0.0 open var system = 0.0 open var idle = 0.0 open var iowait = 0.0 open var irq = 0.0 open var softirq = 0.0 open var steal = 0.0 open var guest = 0.0 open var guestNice = 0.0 @Index open var timeStamp = Date(0) fun createCPUStat(): CPUStat { return CPUStat(user, nice, system, idle, iowait, irq, softirq, steal, guest, guestNice, timeStamp) } } fun Realm.createRealmCPUStat(cpuStat: CPUStat): RealmCPUStat { return createObject(RealmCPUStat::class.java).apply { user = cpuStat.user nice = cpuStat.nice system = cpuStat.system idle = cpuStat.idle iowait = cpuStat.iowait irq = cpuStat.irq softirq = cpuStat.softirq steal = cpuStat.steal guest = cpuStat.guest guestNice = cpuStat.guestNice timeStamp = cpuStat.timeStamp } }
mit
b2ee5671323344b82a6b72b898e43200
26.714286
106
0.656922
3.46131
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/interactors/scanner/impl/PartitionIdentifierScanner.kt
1
4311
package com.onyx.interactors.scanner.impl import com.onyx.descriptor.EntityDescriptor import com.onyx.descriptor.recordInteractor import com.onyx.entity.SystemEntity import com.onyx.exception.OnyxException import com.onyx.interactors.record.data.Reference import com.onyx.interactors.scanner.TableScanner import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.query.Query import com.onyx.persistence.query.QueryCriteria import com.onyx.persistence.query.QueryPartitionMode import com.onyx.extension.common.async import com.onyx.extension.toManagedEntity import com.onyx.persistence.context.Contexts import java.util.concurrent.Future /** * Created by timothy.osborn on 1/3/15. * * This scans a partition for matching identifiers */ class PartitionIdentifierScanner @Throws(OnyxException::class) constructor(criteria: QueryCriteria, classToScan: Class<*>, descriptor: EntityDescriptor, query: Query, context: SchemaContext, persistenceManager: PersistenceManager) : IdentifierScanner(criteria, classToScan, descriptor, query, context, persistenceManager), TableScanner, RangeScanner { private var systemEntity: SystemEntity = context.getSystemEntityByName(query.entityType!!.name)!! /** * Scan existing values for identifiers * * @return Matching identifiers within partition * @throws OnyxException Cannot scan partition */ @Throws(OnyxException::class) override fun scan(): MutableSet<Reference> { val context = Contexts.get(contextId)!! val matching = HashSet<Reference>() if (query.partition === QueryPartitionMode.ALL) { val units = ArrayList<Future<MutableSet<Reference>>>() systemEntity.partition!!.entries.forEach { units.add( async { val partitionDescriptor = context.getDescriptorForEntity(query.entityType, it.value) val recordInteractor = context.getRecordInteractor(partitionDescriptor) scan(recordInteractor, false, it.index) } ) } units.forEach { val results = it.get() if(collector == null) matching += results } } else { val partitionId = context.getPartitionWithValue(query.entityType!!, query.partition)?.index ?: 0L if (partitionId == 0L) return HashSet() val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) matching += scan(descriptor.recordInteractor(), false, partitionId) } return matching } override fun scan(existingValues: Set<Reference>): MutableSet<Reference> { val context = Contexts.get(contextId)!! val matching = HashSet<Reference>() if (query.partition === QueryPartitionMode.ALL) { val units = ArrayList<Future<MutableSet<Reference>>>() systemEntity.partition!!.entries.forEach { units.add( async { val partitionDescriptor = context.getDescriptorForEntity(query.entityType, it.value) val recordInteractor = context.getRecordInteractor(partitionDescriptor) scan(recordInteractor, true, it.index) } ) } units.forEach { val results = it.get() if(collector == null) matching += results } } else { val partitionId = context.getPartitionWithValue(query.entityType!!, query.partition)?.index ?: 0L if (partitionId == 0L) return HashSet() val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) matching += scan(descriptor.recordInteractor(), true, partitionId) } return if(collector == null) matching.filterTo(HashSet()) { if(existingValues.contains(it)) { collector?.collect(it, it.toManagedEntity(context, descriptor)) return@filterTo collector == null } return@filterTo false } else HashSet() } }
agpl-3.0
618204b642c1a226d03bb2d9fabf8f22
38.916667
351
0.643702
5.101775
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/ClassAndProperties.kt
3
395
open class <lineMarker descr="Is subclassed by Bar Click or press ... to navigate Is overridden in Bar">Foo(open val x: Int, open val y</lineMarker>: Int) {} class Bar : Foo(1, 2) { override val <lineMarker descr="Overrides property in 'Foo'">x</lineMarker>: Int get() = 2 override val <lineMarker descr="Overrides property in 'Foo'">y</lineMarker>: Int get() = 3 }
apache-2.0
ae5d97261da9c814a7a3b2d89f2073a2
43
161
0.658228
3.95
false
false
false
false
jk1/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/GroovyInferenceSessionBuilder.kt
2
6296
// 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.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiElement import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.PsiTypeParameter import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.ArrayUtil import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil class GroovyInferenceSessionBuilder(val ref: GrReferenceExpression, val candidate: MethodCandidate) { private var left: PsiType? = null private var skipClosureBlock = true private var startFromTop = false private var siteTypeParams: Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY fun resolveMode(skipClosureBlock: Boolean): GroovyInferenceSessionBuilder { this.skipClosureBlock = skipClosureBlock return this } fun startFromTop(startFromTop: Boolean): GroovyInferenceSessionBuilder { this.startFromTop = startFromTop return this } fun addReturnConstraint(returnType: PsiType?): GroovyInferenceSessionBuilder { left = returnType return this } fun addReturnConstraint(): GroovyInferenceSessionBuilder { val methodCall = ref.parent as? GrMethodCall ?: return this left = getReturnConstraintType(getMostTopLevelCall(methodCall)) return this } fun addTypeParams(typeParams: Array<PsiTypeParameter>): GroovyInferenceSessionBuilder { siteTypeParams = ArrayUtil.mergeArrays(siteTypeParams, typeParams) return this } fun build(): GroovyInferenceSession { if (!startFromTop) { val typeParameters = ArrayUtil.mergeArrays(siteTypeParams, candidate.method.typeParameters) val session = GroovyInferenceSession(typeParameters, candidate.siteSubstitutor, ref, skipClosureBlock) session.addConstraint(MethodCallConstraint(ref, candidate)) val returnType = PsiUtil.getSmartReturnType(candidate.method) //TODO: Fix with startFromTop in GroovyResolveProcessor val left = left if (left == null || returnType == null || PsiType.VOID == returnType) return session session.repeatInferencePhases() session.addConstraint(TypeConstraint(left, returnType, ref)) return session } else { val session = GroovyInferenceSession(siteTypeParams, PsiSubstitutor.EMPTY, ref, skipClosureBlock) val methodCall = ref.parent as? GrMethodCall ?: return session session.addConstraint(ExpressionConstraint(getMostTopLevelCall(methodCall), left)) return session } } private fun getMostTopLevelCall(call: GrMethodCall): GrMethodCall { var topLevel: GrMethodCall = call while (true) { val parent = topLevel.parent val gparent = parent?.parent topLevel = if (parent is GrMethodCall) { parent } else if (parent is GrArgumentList && gparent is GrMethodCall) { gparent } else { return topLevel } } } private fun getReturnConstraintType(call: GrMethodCall): PsiType? { val parent = call.parent val gparent = parent?.parent val parentMethod = PsiTreeUtil.getParentOfType(parent, GrMethod::class.java, true, GrClosableBlock::class.java) if (parent is GrReturnStatement && parentMethod != null) { return parentMethod.returnType } else if (isExitPoint(call) && parentMethod != null) { val returnType = parentMethod.returnType if (TypeConversionUtil.isVoidType(returnType)) return null return returnType } else if (parent is GrAssignmentExpression && call == parent.rValue) { val lValue = PsiUtil.skipParentheses(parent.lValue, false) return if (lValue is GrExpression && lValue !is GrIndexProperty) lValue.nominalType else null } else if (parent is GrArgumentList && gparent is GrNewExpression) { // TODO: fix with moving constructor resolve to new API val resolveResult = gparent.advancedResolve() val parameters = GrClosureSignatureUtil.mapArgumentsToParameters( resolveResult, gparent, false, true, gparent.namedArguments, gparent.expressionArguments, gparent.closureArguments) return parameters?.get(call)?.second } else if (parent is GrVariable) { return parent.declaredType } return null } private fun isExitPoint(place: GrMethodCall): Boolean { return collectExitPoints(place).contains(place) } private fun collectExitPoints(place: GrMethodCall): List<GrStatement> { return if (canBeExitPoint(place)) { val flowOwner = ControlFlowUtils.findControlFlowOwner(place) ControlFlowUtils.collectReturns(flowOwner) } else { emptyList() } } private fun canBeExitPoint(element: PsiElement?): Boolean { var place = element while (place != null) { if (place is GrMethod || place is GrClosableBlock || place is GrClassInitializer) return true if (place is GrThrowStatement || place is GrTypeDefinitionBody || place is GroovyFile) return false place = place.parent } return false } }
apache-2.0
af75da6e52fdea38154b96aaee7491b5
39.88961
140
0.755559
4.730278
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/badges/gifts/Gifts.kt
2
2663
package org.thoughtcrime.securesms.badges.gifts import android.content.Context import org.signal.libsignal.zkgroup.InvalidInputException import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.database.ThreadDatabase import org.thoughtcrime.securesms.database.model.StoryType import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge import org.thoughtcrime.securesms.mms.OutgoingMediaMessage import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.Base64 import java.lang.Integer.min import java.util.concurrent.TimeUnit /** * Helper object for Gift badges */ object Gifts { /** * Request Code for getting token from Google Pay */ const val GOOGLE_PAY_REQUEST_CODE = 3000 /** * Creates an OutgoingSecureMediaMessage which contains the given gift badge. */ fun createOutgoingGiftMessage( recipient: Recipient, giftBadge: GiftBadge, sentTimestamp: Long, expiresIn: Long ): OutgoingMediaMessage { return OutgoingSecureMediaMessage( recipient, Base64.encodeBytes(giftBadge.toByteArray()), listOf(), sentTimestamp, ThreadDatabase.DistributionTypes.CONVERSATION, expiresIn, false, StoryType.NONE, null, false, null, listOf(), listOf(), listOf(), giftBadge ) } /** * @return the expiration time from the redemption token, in UNIX epoch seconds. */ private fun GiftBadge.getExpiry(): Long { return try { ReceiptCredentialPresentation(redemptionToken.toByteArray()).receiptExpirationTime } catch (e: InvalidInputException) { return 0L } } fun GiftBadge.formatExpiry(context: Context): String { val expiry = getExpiry() val timeRemaining = TimeUnit.SECONDS.toMillis(expiry) - System.currentTimeMillis() if (timeRemaining <= 0) { return context.getString(R.string.Gifts__expired) } val days = TimeUnit.MILLISECONDS.toDays(timeRemaining).toInt() if (days > 0) { return context.resources.getQuantityString(R.plurals.Gifts__d_days_remaining, days, days) } val hours = TimeUnit.MILLISECONDS.toHours(timeRemaining).toInt() if (hours > 0) { return context.resources.getQuantityString(R.plurals.Gifts__d_hours_remaining, hours, hours) } val minutes = min(1, TimeUnit.MILLISECONDS.toMinutes(timeRemaining).toInt()) return context.resources.getQuantityString(R.plurals.Gifts__d_minutes_remaining, minutes, minutes) } }
gpl-3.0
4ff6fb0068f9fc34c49c617e65c461e1
29.965116
102
0.73451
4.40894
false
false
false
false
cicdevelopmentnz/Android-BLE
library/src/main/java/nz/co/cic/ble/scanner/RadioService.kt
1
1445
package nz.co.cic.ble.scanner import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattService import org.json.JSONArray import org.json.JSONObject /** * Created by dipshit on 5/03/17. */ data class RadioService(val service: BluetoothGattService) { var serviceId: String? = null var messages: MutableList<RadioMessage>? = null init { this.serviceId = service.uuid.toString() this.messages = mutableListOf() } fun addMessage(char: BluetoothGattCharacteristic) { this.messages?.add(RadioMessage(char)) } fun toJSON(): JSONObject { var serviceObject = JSONObject() serviceObject.put("id", serviceId) var messageObject = JSONArray() messages?.forEach { messageObject.put(it.toJSON()) } serviceObject.put("messages", messageObject) return serviceObject } } data class RadioMessage(val characteristic: BluetoothGattCharacteristic) { var messageId: String? = null var message: String? = null init { this.messageId = characteristic.uuid.toString() if (characteristic.value != null) { this.message = String(characteristic.value) } } fun toJSON(): JSONObject { var messageObject = JSONObject() messageObject.put("id", messageId) messageObject.put("value", message) return messageObject } }
gpl-3.0
f4557ee33218570f1c180eb59a7681e7
23.913793
74
0.658824
4.722222
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/Http.kt
1
2883
package com.beust.kobalt.maven import com.beust.kobalt.KobaltException import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.misc.CountingFileRequestBody import com.beust.kobalt.misc.log import com.google.inject.Inject import okhttp3.* import java.io.File import java.io.IOException import javax.inject.Singleton @Singleton class Http @Inject constructor(val settings:KobaltSettings) { companion object { // HTTP statuses val CREATED = 201 } class TypedFile(val mimeType: String, val file: File) { override fun toString() = file.name } fun get(user: String?, password: String?, url: String) : Response { val client = OkHttpClient.Builder().proxy(settings.proxyConfig?.toProxy()).build() val request = Request.Builder().url(url) if (user != null) { request.header("Authorization", Credentials.basic(user, password)) } try { return client.newCall(request.build()).execute() } catch(ex: IOException) { throw KobaltException("Could not load URL $url, error: " + ex.message, ex) } } fun get(url: String) : Response { return get(null, null, url) } fun percentProgressCallback(totalSize: Long) : (Long) -> Unit { return { num: Long -> val progress = num * 100 / totalSize log(1, "\rUploaded: $progress%", newLine = false) } } val DEFAULT_ERROR_RESPONSE = { r: Response -> error("Couldn't upload file: " + r.message()) } fun uploadFile(user: String? = null, password: String? = null, url: String, file: TypedFile, post: Boolean, progressCallback: (Long) -> Unit = {}, headers: Headers = Headers.of(), success: (Response) -> Unit = {}, error: (Response) -> Unit = DEFAULT_ERROR_RESPONSE) { val fullHeaders = Headers.Builder() fullHeaders.set("Content-Type", file.mimeType) headers.names().forEach { fullHeaders.set(it, headers.get(it)) } user?.let { fullHeaders.set("Authorization", Credentials.basic(user, password)) } val requestBuilder = Request.Builder() .headers(fullHeaders.build()) .url(url) val request = (if (post) requestBuilder.post(CountingFileRequestBody(file.file, file.mimeType, progressCallback)) else requestBuilder.put(CountingFileRequestBody(file.file, file.mimeType, progressCallback))) .build() log(2, "Uploading $file to $url") val response = OkHttpClient.Builder().proxy(settings.proxyConfig?.toProxy()).build().newCall(request).execute() if (! response.isSuccessful) { error(response) } else { success(response) } } }
apache-2.0
7a73496db61f04f42d77d33463cee6bf
32.917647
119
0.60666
4.328829
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/framework/di/Injector.kt
1
1383
/* * Copyright 2017-2018 the original author or authors. * Copyright (C) 2018 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.particleswallpaper.framework.di import android.content.Context import org.koin.core.parameter.ParameterDefinition import org.koin.core.parameter.emptyParameterDefinition import org.koin.core.scope.Scope inline fun <reified T : Any> inject( context: Context, name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ) = lazy { get<T>(context, name, scope, parameters) } inline fun <reified T : Any> get( context: Context, name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = emptyParameterDefinition() ): T = KoinContextProvider.getKoinContext(context).get(name, scope, parameters)
apache-2.0
02f17896dc82b72d468edcabbc7424eb
37.416667
79
0.744035
4.140719
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/resettodefaults/ResetToDefaultsPreference.kt
1
1882
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.particleswallpaper.userprefs.resettodefaults import android.app.AlertDialog import android.content.Context import android.preference.Preference import android.util.AttributeSet import com.doctoror.particleswallpaper.R import com.doctoror.particleswallpaper.framework.di.inject import org.koin.core.parameter.parametersOf /** * Preference for resetting configuration to default values. */ class ResetToDefaultsPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : Preference(context, attrs), ResetToDefaultsPreferenceView { private val presenter: ResetToDefaultsPreferencePresenter by inject( context = context, parameters = { parametersOf(this as ResetToDefaultsPreferenceView) } ) init { isPersistent = false } override fun onClick() { presenter.onClick() } override fun showWarningDialog() { AlertDialog.Builder(context) .setTitle(title) .setMessage(R.string.Are_you_sure_you_want_to_reset_all_settings_to_default_values) .setPositiveButton(R.string.Reset) { _, _ -> presenter.onResetClick() } .setNegativeButton(R.string.Cancel, null) .show() } }
apache-2.0
0373e99edfda10485996b12870ab3171
32.607143
95
0.721041
4.407494
false
false
false
false
google/android-fhir
workflow/src/test/java/com/google/android/fhir/workflow/FhirOperatorLibraryEvaluateJavaTest.kt
1
4186
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.workflow import androidx.test.core.app.ApplicationProvider import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.FhirEngine import com.google.android.fhir.FhirEngineProvider import com.google.android.fhir.testing.FhirEngineProviderTestRule import com.google.common.truth.Truth.assertThat import java.io.InputStream import kotlinx.coroutines.runBlocking import org.hl7.fhir.r4.model.Bundle import org.hl7.fhir.r4.model.Parameters import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class FhirOperatorLibraryEvaluateJavaTest { @get:Rule val fhirEngineProviderRule = FhirEngineProviderTestRule() private lateinit var fhirEngine: FhirEngine private lateinit var fhirOperator: FhirOperator private val fhirContext = FhirContext.forCached(FhirVersionEnum.R4) private val jsonParser = fhirContext.newJsonParser() private fun open(asset: String): InputStream? { return javaClass.getResourceAsStream(asset) } private fun load(asset: String): Bundle { return jsonParser.parseResource(open(asset)) as Bundle } @Before fun setUp() = runBlocking { fhirEngine = FhirEngineProvider.getInstance(ApplicationProvider.getApplicationContext()) fhirOperator = FhirOperator(fhirContext, fhirEngine) } /** * Evaluates a compiled CQL that was exported to Json and included inside a FHIRLibrary. The * compiled CQL file is encoded in Base64 and placed inside the JSON Library. The expression * `CompletedImmunization` simply checks if a vaccination protocol has been finished as below. * * This test requires the CQLEvaluator to * 1. load the patient using a `FhirEngineRetrieveProvider`, * 2. load the Immunization records of that patient, * 3. load the CQL Library using a `FhirEngineLibraryContentProvider` * 4. evaluate if the immunization record presents a Protocol where the number of doses taken * matches the number of required doses or if the number of required doses is null. * * ``` * library ImmunityCheck version '1.0.0' * * using FHIR version '4.0.0' * include "FHIRHelpers" version '4.0.0' called FHIRHelpers * context Immunization * * define "CompletedImmunization": * exists(GetFinalDose) or exists(GetSingleDose) * * define "GetFinalDose": * [Immunization] I * where exists(I.protocolApplied) * and I.protocolApplied.doseNumber.value = I.protocolApplied.seriesDoses.value * * define "GetSingleDose": * [Immunization] I * where exists(I.protocolApplied) * and exists(I.protocolApplied.doseNumber.value) * and not exists(I.protocolApplied.seriesDoses.value) * ``` */ @Test fun evaluateImmunityCheck() = runBlocking { // Load patient val patientImmunizationHistory = load("/immunity-check/ImmunizationHistory.json") for (entry in patientImmunizationHistory.entry) { fhirEngine.create(entry.resource) } // Load Library that checks if Patient has taken a vaccine fhirOperator.loadLibs(load("/immunity-check/ImmunityCheck.json")) // Evaluates a specific Patient val results = fhirOperator.evaluateLibrary( "http://localhost/Library/ImmunityCheck|1.0.0", "d4d35004-24f8-40e4-8084-1ad75924514f", setOf("CompletedImmunization") ) as Parameters assertThat(results.getParameterBool("CompletedImmunization")).isTrue() } }
apache-2.0
07359b7fe74f9fbb30abf7a7a1eb7f45
35.086207
96
0.747253
3.901212
false
true
false
false
code-disaster/lwjgl3
modules/lwjgl/zstd/src/templates/kotlin/zstd/templates/Zstd.kt
4
57656
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package zstd.templates import org.lwjgl.generator.* import zstd.* val Zstd = "Zstd".nativeClass(Module.ZSTD, prefix = "ZSTD", prefixMethod = "ZSTD_") { nativeDirective( """DISABLE_WARNINGS() #define ZSTD_STATIC_LINKING_ONLY #include "zstd.h" ENABLE_WARNINGS()""") documentation = """ Native bindings to ${url("http://facebook.github.io/zstd/", "Zstandard")} (zstd), a fast lossless compression algorithm, targeting real-time compression scenarios at zlib-level and better compression ratios. <h3>Introduction</h3> zstd, short for Zstandard, is a fast lossless compression algorithm, targeting real-time compression scenarios at zlib-level and better compression ratios. The zstd compression library provides in-memory compression and decompression functions. The library supports regular compression levels from 1 up to #maxCLevel(), which is currently 22. Levels &ge; 20, labeled {@code --ultra}, should be used with caution, as they require more memory. The library also offers negative compression levels, which extend the range of speed vs. ratio preferences. The lower the level, the faster the speed (at the cost of compression). Compression can be done in: ${ul( "a single step (described as Simple API)", "a single step, reusing a context (described as Explicit context)", "unbounded multiple steps (described as Streaming compression)" )} The compression ratio achievable on small data can be highly improved using a dictionary. Dictionary compression can be performed in: ${ul( "a single step (described as Simple dictionary API)", "a single step, reusing a dictionary (described as Bulk-processing dictionary API)" )} Advanced experimental functions can be accessed using {@code \#define ZSTD_STATIC_LINKING_ONLY} before including {@code zstd.h}. Advanced experimental APIs should never be used with a dynamically-linked library. They are not "stable", their definitions or signatures may change in the future. Only static linking is allowed. <h3>Streaming compression - HowTo</h3> A {@code ZSTD_CStream} object is required to track streaming operation. Use #createCStream() and #freeCStream() to create/release resources. {@code ZSTD_CStream} objects can be reused multiple times on consecutive compression operations. It is recommended to re-use {@code ZSTD_CStream} since it will play nicer with system's memory, by re-using already allocated memory. For parallel execution, use one separate {@code ZSTD_CStream}. Since v1.3.0, {@code ZSTD_CStream} and {@code ZSTD_CCtx} are the same thing. Parameters are sticky: when starting a new compression on the same context, it will re-use the same sticky parameters as previous compression session. When in doubt, it's recommended to fully initialize the context before usage. Use #CCtx_reset() to reset the context and #CCtx_setParameter(), #CCtx_setPledgedSrcSize(), or #CCtx_loadDictionary() and friends to set more specific parameters, the pledged source size, or load a dictionary. Use #compressStream2() with #e_continue as many times as necessary to consume input stream. The function will automatically update both {@code pos} fields within {@code input} and {@code output}. Note that the function may not consume the entire input, for example, because the output buffer is already full, in which case {@code input.pos < input.size}. The caller must check if input has been entirely consumed. If not, the caller must make some room to receive more compressed data, and then present again remaining input data. Note: {@code ZSTD_e_continue} is guaranteed to make some forward progress when called, but doesn't guarantee maximal forward progress. This is especially relevant when compressing with multiple threads. The call won't block if it can consume some input, but if it can't it will wait for some, but not all, output to be flushed. At any moment, it's possible to flush whatever data might remain stuck within internal buffer, using {@code ZSTD_compressStream2()} with #e_flush. {@code output->pos} will be updated. Note that, if {@code output->size} is too small, a single invocation with {@code ZSTD_e_flush} might not be enough (return code &gt; 0). In which case, make some room to receive more compressed data, and call again {@code ZSTD_compressStream2()} with {@code ZSTD_e_flush}. You must continue calling {@code ZSTD_compressStream2()} with {@code ZSTD_e_flush} until it returns 0, at which point you can change the operation. Note: {@code ZSTD_e_flush} will flush as much output as possible, meaning when compressing with multiple threads, it will block until the flush is complete or the output buffer is full. Calling {@code ZSTD_compressStream2()} with #e_end instructs to finish a frame. It will perform a flush and write frame epilogue. The epilogue is required for decoders to consider a frame completed. Flush operation is the same, and follows same rules as calling {@code ZSTD_compressStream2()} with {@code ZSTD_e_flush}. You must continue calling {@code ZSTD_compressStream2()} with {@code ZSTD_e_end} until it returns 0, at which point you are free to start a new frame. Note: {@code ZSTD_e_end} will flush as much output as possible, meaning when compressing with multiple threads, it will block until the flush is complete or the output buffer is full. <h3>Streaming decompression - HowTo</h3> A {@code ZSTD_DStream} object is required to track streaming operations. Use #createDStream() and #freeDStream() to create/release resources. {@code ZSTD_DStream} objects can be re-used multiple times. Use #DCtx_reset() and #DCtx_refDDict() to start a new decompression operation. Alternatively, use advanced API to set specific properties. Use #decompressStream() repetitively to consume your input. The function will update both {@code pos} fields. If {@code input.pos < input.size}, some input has not been consumed. It's up to the caller to present again remaining data. The function tries to flush all data decoded immediately, respecting output buffer size. If {@code output.pos < output.size}, decoder has flushed everything it could. But if {@code output.pos == output.size}, there might be some data left within internal buffers. In which case, call {@code ZSTD_decompressStream()} again to flush whatever remains in the buffer. Note: with no additional input provided, amount of data flushed is necessarily &le; #BLOCKSIZE_MAX. """ IntConstant( "Version number part.", "VERSION_MAJOR".."1", "VERSION_MINOR".."5", "VERSION_RELEASE".."2" ) IntConstant("Version number.", "VERSION_NUMBER".."(ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)") StringConstant("Version string.", "VERSION_STRING".."""ZSTD_VERSION_MAJOR + "." + ZSTD_VERSION_MINOR + "." + ZSTD_VERSION_RELEASE""") unsigned("versionNumber", "Returns runtime library version, the value is {@code (MAJOR*100*100 + MINOR*100 + RELEASE)}.", void()) Nonnull..charASCII.const.p("versionString", "Returns runtime library version, like \"1.4.5\".", void()) IntConstant( "Default compression level.", "CLEVEL_DEFAULT".."3" ) IntConstant("", "MAGICNUMBER".."0xFD2FB528") IntConstant("", "MAGIC_DICTIONARY".."0xEC30A437") IntConstant("", "MAGIC_SKIPPABLE_START".."0x184D2A50") IntConstant("", "MAGIC_SKIPPABLE_MASK".."0xFFFFFFF0") IntConstant("", "BLOCKSIZELOG_MAX".."17") IntConstant("", "BLOCKSIZE_MAX".."(1<<ZSTD_BLOCKSIZELOG_MAX)") LongConstant( "Content size.", "CONTENTSIZE_UNKNOWN"..("-1L"), "CONTENTSIZE_ERROR"..("-2L") ) EnumConstant( "Compression strategies, listed from fastest to strongest. ({@code ZSTD_strategy})", "fast".enum("", "1"), "dfast".enum, "greedy".enum, "lazy".enum, "lazy2".enum, "btlazy2".enum, "btopt".enum, "btultra".enum, "btultra2".enum ) val cParameters = EnumConstant( """ Compression parameters. ({@code ZSTD_cParameter}) Note: When compressing with a {@code ZSTD_CDict} these parameters are superseded by the parameters used to construct the {@code ZSTD_CDict}. See #CCtx_refCDict() for more info. """, "c_compressionLevel".enum( """ Set compression parameters according to pre-defined {@code cLevel} table. Note that exact compression parameters are dynamically determined, depending on both compression level and {@code srcSize} (when known). Default level is #CLEVEL_DEFAULT{@code ==3}. Special: value 0 means default, which is controlled by {@code ZSTD_CLEVEL_DEFAULT}. Note 1: it's possible to pass a negative compression level. Note 2: setting a level does not automatically set all other compression parameters to default. Setting this will however eventually dynamically impact the compression parameters which have not been manually set. The manually set ones will 'stick'. """, "100" ), "c_windowLog".enum( """ Maximum allowed back-reference distance, expressed as power of 2. This will set a memory budget for streaming decompression, with larger values requiring more memory and typically compressing more. Must be clamped between #WINDOWLOG_MIN and #WINDOWLOG_MAX. Special: value 0 means "use default {@code windowLog}". Note: Using a {@code windowLog} greater than #WINDOWLOG_LIMIT_DEFAULT requires explicitly allowing such size at streaming decompression stage. """ ), "c_hashLog".enum( """ Size of the initial probe table, as a power of 2. Resulting memory usage is (1 &lt;&lt; {@code (hashLog+2)}). Must be clamped between #HASHLOG_MIN and #HASHLOG_MAX. Larger tables improve compression ratio of strategies &le; dFast, and improve speed of strategies &gt; dFast. Special: value 0 means "use default {@code hashLog}". """ ), "c_chainLog".enum( """ Size of the multi-probe search table, as a power of 2. Resulting memory usage is (1 &lt;&lt; {@code (chainLog+2)}). Must be clamped between #CHAINLOG_MIN and #CHAINLOG_MAX. Larger tables result in better and slower compression. This parameter is useless for "fast" strategy. It's still useful when using "dfast" strategy, in which case it defines a secondary probe table. Special: value 0 means "use default {@code chainLog}". """ ), "c_searchLog".enum( """ Number of search attempts, as a power of 2. More attempts result in better and slower compression. This parameter is useless for "fast" and "dFast" strategies. Special: value 0 means "use default {@code searchLog}". """ ), "c_minMatch".enum( """ Minimum size of searched matches. Note that Zstandard can still find matches of smaller size, it just tweaks its search algorithm to look for this size and larger. Larger values increase compression and decompression speed, but decrease ratio. Must be clamped between #MINMATCH_MIN and #MINMATCH_MAX. Note that currently, for all strategies &lt;btopt, effective minimum is 4. , for all strategies &gt; fast, effective maximum is 6. Special: value 0 means "use default {@code minMatchLength}". """ ), "c_targetLength".enum( """ Impact of this field depends on strategy. For strategies btopt, btultra &amp; btultra2: Length of Match considered "good enough" to stop search. Larger values make compression stronger, and slower. For strategy fast: Distance between match sampling. Larger values make compression faster, and weaker. Special: value 0 means "use default targetLength". """ ), "c_strategy".enum( """ See {@code ZSTD_strategy} enum definition. The higher the value of selected strategy, the more complex it is, resulting in stronger and slower compression. Special: value 0 means "use default strategy". """ ), "c_enableLongDistanceMatching".enum( """ Enable long distance matching. This parameter is designed to improve compression ratio for large inputs, by finding large matches at long distance. It increases memory usage and window size. Note: enabling this parameter increases default #c_windowLog to 128 MB except when expressly set to a different value. Note: will be enabled by default if {@code ZSTD_c_windowLog &ge; 128 MB} and compression strategy {@code &ge; ZSTD_btopt (== compression level 16+)}. """, "160" ), "c_ldmHashLog".enum( """ Size of the table for long distance matching, as a power of 2. Larger values increase memory usage and compression ratio, but decrease compression speed. Must be clamped between #HASHLOG_MIN and #HASHLOG_MAX default: windowlog - 7. Special: value 0 means "automatically determine hashlog". """ ), "c_ldmMinMatch".enum( """ Minimum match size for long distance matcher. Larger/too small values usually decrease compression ratio. Must be clamped between #LDM_MINMATCH_MIN and #LDM_MINMATCH_MAX. Special: value 0 means "use default value" (default: 64). """ ), "c_ldmBucketSizeLog".enum( """ Log size of each bucket in the LDM hash table for collision resolution. Larger values improve collision resolution but decrease compression speed. The maximum value is #LDM_BUCKETSIZELOG_MAX. Special: value 0 means "use default value" (default: 3). """ ), "c_ldmHashRateLog".enum( """ Frequency of inserting/looking up entries into the LDM hash table. Must be clamped between 0 and (#WINDOWLOG_MAX - #HASHLOG_MIN). Default is {@code MAX(0, (windowLog - ldmHashLog))}, optimizing hash table usage. Larger values improve compression speed. Deviating far from default value will likely result in a compression ratio decrease. Special: value 0 means "automatically determine {@code hashRateLog}". """ ), "c_contentSizeFlag".enum( """ Content size will be written into frame header _whenever known_ (default:1) Content size must be known at the beginning of compression. This is automatically the case when using #compress2(), For streaming scenarios, content size must be provided with #CCtx_setPledgedSrcSize(). """, "200" ), "c_checksumFlag".enum("A 32-bits checksum of content is written at end of frame (default:0)"), "c_dictIDFlag".enum("When applicable, dictionary's ID is written into frame header (default:1)"), "c_nbWorkers".enum( """ Select how many threads will be spawned to compress in parallel. When {@code nbWorkers &ge; 1}, triggers asynchronous mode when invoking {@code ZSTD_compressStream*()}: {@code ZSTD_compressStream*()} consumes input and flush output if possible, but immediately gives back control to caller, while compression work is performed in parallel, within worker thread(s). (note: a strong exception to this rule is when first invocation of #compressStream2() sets #e_end: in which case, {@code ZSTD_compressStream2()} delegates to #compress2(), which is always a blocking call). More workers improve speed, but also increase memory usage. Default value is {@code 0}, aka "single-threaded mode": no worker is spawned, compression is performed inside Caller's thread, and all invocations are blocking. """, "400" ), "c_jobSize".enum( """ Size of a compression job. This value is enforced only when {@code nbWorkers &ge; 1}. Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads. 0 means default, which is dynamically determined based on compression parameters. Job size must be a minimum of overlap size, or {@code ZSTDMT_JOBSIZE_MIN} (= 512 KB), whichever is largest. The minimum size is automatically and transparently enforced. """ ), "c_overlapLog".enum( """ Control the overlap size, as a fraction of window size. The overlap size is an amount of data reloaded from previous job at the beginning of a new job. It helps preserve compression ratio, while each job is compressed in parallel. This value is enforced only when {@code nbWorkers &ge; 1}. Larger values increase compression ratio, but decrease speed. Possible values range from 0 to 9: ${ul( "0 means \"default\" : value will be determined by the library, depending on strategy", "1 means \"no overlap\"", """ 9 means "full overlap", using a full window size. Each intermediate rank increases/decreases load size by a factor 2: 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default default value varies between 6 and 9, depending on strategy """ )} """ ), "c_experimentalParam1".enum("", "500"), "c_experimentalParam2".enum("", "10"), "c_experimentalParam3".enum("", "1000"), "c_experimentalParam4".enum, "c_experimentalParam5".enum, "c_experimentalParam6".enum, "c_experimentalParam7".enum, "c_experimentalParam8".enum, "c_experimentalParam9".enum, "c_experimentalParam10".enum, "c_experimentalParam11".enum, "c_experimentalParam12".enum, "c_experimentalParam13".enum, "c_experimentalParam14".enum, "c_experimentalParam15".enum ).javaDocLinks val resetDirectives = EnumConstant( "{@code ZSTD_ResetDirective}", "reset_session_only".enum("", "1"), "reset_parameters".enum, "reset_session_and_parameters".enum ).javaDocLinks val dParameters = EnumConstant( """ The advanced API pushes parameters one by one into an existing {@code DCtx} context. Parameters are sticky, and remain valid for all following frames using the same {@code DCtx} context. It's possible to reset parameters to default values using #DCtx_reset(). Note: This API is compatible with existing #decompressDCtx() and #decompressStream(). Therefore, no new decompression function is necessary. ({@code ZSTD_dParameter}) """, "d_windowLogMax".enum( """ Select a size limit (in power of 2) beyond which the streaming API will refuse to allocate memory buffer in order to protect the host from unreasonable memory requirements. This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. By default, a decompression context accepts window sizes &le; (1 &lt;&lt; #WINDOWLOG_LIMIT_DEFAULT) Special: value 0 means "use default maximum windowLog". """, "100" ), "d_experimentalParam1".enum( """ Note: additional experimental parameters are also available within the experimental section of the API. At the time of this writing, they include: ${ul( "#d_format", "#d_stableOutBuffer" )} Note: never ever use {@code experimentalParam}? names directly """, "1000" ), "d_experimentalParam2".enum, "d_experimentalParam3".enum, "d_experimentalParam4".enum ).javaDocLinks val endDirectives = EnumConstant( "{@code ZSTD_EndDirective}", "e_continue".enum("collect more data, encoder decides when to output compressed result, for optimal compression ratio", "0"), "e_flush".enum( """ flush any data provided so far, it creates (at least) one new block, that can be decoded immediately on reception; frame will continue: any future data can still reference previously compressed data, improving compression. """ ), "e_end".enum( """ flush any remaining data <em>and</em> close current frame. note that frame is only closed after compressed data is fully flushed (return {@code value == 0}). After that point, any additional data starts a new frame. Note: each frame is independent (does not reference any content from previous frame). """ ) ).javaDocLinks /*************************************** * Simple API ***************************************/ val compress = size_t( "compress", """ Compresses {@code src} content as a single zstd compressed frame into already allocated {@code dst}. Hint: compression runs faster if {@code dstCapacity} &ge; #compressBound(){@code (srcSize)} """, void.p("dst", ""), AutoSize("dst")..size_t("dstCapacity", ""), void.const.p("src", ""), AutoSize("src")..size_t("srcSize", ""), int("compressionLevel", ""), returnDoc = "compressed size written into {@code dst} (&le; {@code dstCapacity}), or an error code if it fails (which can be tested using #isError())." ) size_t( "decompress", "", void.p("dst", ""), AutoSize("dst")..size_t( "dstCapacity", """ is an upper bound of {@code originalSize} to regenerate. If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. """ ), void.const.p("src", ""), AutoSize("src")..size_t("compressedSize", "must be the <b>exact</b> size of some number of compressed and/or skippable frames"), returnDoc = """ the number of bytes decompressed into {@code dst} (&le; {@code dstCapacity}), or an {@code errorCode} if it fails (which can be tested using #isError()). """ ) unsigned_long_long( "getFrameContentSize", """ Notes: ${ol( "a 0 return value means the frame is valid but \"empty\"", """ decompressed size is an optional field, it may not be present, typically in streaming mode. When {@code return==ZSTD_CONTENTSIZE_UNKNOWN}, data to decompress could be any size. In which case, it's necessary to use streaming mode to decompress data. Optionally, application can rely on some implicit limit, as #decompress() only needs an upper bound of decompressed size. (For example, data could be necessarily cut into blocks &le; 16 KB). """, """ decompressed size is always present when compression is completed using single-pass functions, such as #compress(), #compressCCtx(), #compress_usingDict() or #compress_usingCDict(). """, """ decompressed size can be very large (64-bits value), potentially larger than what local system can handle as a single memory segment. In which case, it's necessary to use streaming mode to decompress data. """, """ If source is untrusted, decompressed size could be wrong or intentionally modified. Always ensure return value fits within application's authorized limits. Each application can set its own limits. """ )} """, void.const.p("src", "should point to the start of a ZSTD encoded frame"), AutoSize("src")..size_t("srcSize", "must be at least as large as the frame header. Hint: any size &ge; #FRAMEHEADERSIZE_MAX is large enough."), returnDoc = """ decompressed size of {@code src} frame content, if known ${ul( "#CONTENTSIZE_UNKNOWN if the size cannot be determined", "#CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, {@code srcSize} too small)" )} """ ) size_t( "findFrameCompressedSize", "", void.const.p("src", "should point to the start of a ZSTD frame or skippable frame"), AutoSize("src")..size_t("srcSize", "must be &ge; first frame size"), returnDoc = """ the compressed size of the first frame starting at {@code src}, suitable to pass as {@code srcSize} to #decompress() or similar, or an error code if input is invalid """ ) customMethod(""" /** Pure Java version of {@link #ZSTD_compressBound}. */ public static long ZSTD_COMPRESSBOUND(long srcSize) { /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ return srcSize + (srcSize >> 8) + (srcSize < (128 << 10) ? (128 << 10) - srcSize >> 11 /* margin, from 64 to 0 */ : 0 ); }""") size_t( "compressBound", "Returns the maximum compressed size in worst case single-pass scenario.", size_t("srcSize", "") ) unsigned_intb( "isError", "Tells if a {@code size_t} function result is an error code.", size_t("code", "") ) Nonnull..charASCII.const.p( "getErrorName", "Provides readable string from an error code.", size_t("code", "") ) int("minCLevel", "Returns the minimum compression level available.", void()) int("maxCLevel", "Returns the maximum compression level available.", void()) int("defaultCLevel", "Returns the default compression level, specified by #CLEVEL_DEFAULT", void()) /*************************************** * Explicit context ***************************************/ ZSTD_CCtx.p( "createCCtx", """ Creates a compression context. When compressing many times, it is recommended to allocate a context just once, and re-use it for each successive compression operation. This will make workload friendlier for system's memory. Use one context per thread for parallel execution in multi-threaded environments. """, void() ) size_t( "freeCCtx", "Frees memory allocated by #createCCtx().", nullable..ZSTD_CCtx.p("cctx", "accepts #NULL pointer") ) size_t( "compressCCtx", """ Same as #compress(), using an explicit {@code ZSTD_CCtx}. Important: in order to behave similarly to {@code ZSTD_compress()}, this function compresses at requested compression level, <b>ignoring any other parameter</b>. If any advanced parameter was set using the advanced API, they will all be reset. Only {@code compressionLevel} remains. """, ZSTD_CCtx.p("ctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"], int("compressionLevel", "") ) ZSTD_DCtx.p( "createDCtx", """ Creates a decompression context. When decompressing many times, it is recommended to allocate a context only once, and re-use it for each successive compression operation. This will make workload friendlier for system's memory. Use one context per thread for parallel execution. """, void() ) size_t( "freeDCtx", "Frees memory allocated by #createDCtx().", nullable..ZSTD_DCtx.p("dctx", "accepts #NULL pointer") ) size_t( "decompressDCtx", "Same as #decompress(), requires an allocated {@code ZSTD_DCtx}. Compatible with sticky parameters.", ZSTD_DCtx.p("ctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"] ) /**************************** * Advanced compression API *****************************/ ZSTD_bounds( "cParam_getBounds", "All parameters must belong to an interval with lower and upper bounds, otherwise they will either trigger an error or be automatically clamped.", ZSTD_cParameter("cParam", "", cParameters), returnDoc = """ a structure, {@code ZSTD_bounds}, which contains ${ul( "an error status field, which must be tested using #isError()", "lower and upper bounds, both inclusive" )} """ ) size_t( "CCtx_setParameter", """ Set one compression parameter, selected by enum {@code ZSTD_cParameter}. All parameters have valid bounds. Bounds can be queried using #cParam_getBounds(). Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). Setting a parameter is generally only possible during frame initialization (before starting compression). Exception: when using multi-threading mode (nbWorkers &ge; 1), the following parameters can be updated <b>during</b> compression (within same frame): =&lt; compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. new parameters will be active for next job only (after a {@code flush()}). """, ZSTD_CCtx.p("cctx", ""), ZSTD_cParameter("param", "", cParameters), int("value", ""), returnDoc = "an error code (which can be tested using #isError())" ) size_t( "CCtx_setPledgedSrcSize", """ Total input data size to be compressed as a single frame. Value will be written in frame header, unless if explicitly forbidden using #c_contentSizeFlag. This value will also be controlled at end of frame, and trigger an error if not respected. Note 1: {@code pledgedSrcSize==0} actually means zero, aka an empty frame. In order to mean "unknown content size", pass constant #CONTENTSIZE_UNKNOWN. {@code ZSTD_CONTENTSIZE_UNKNOWN} is default value for any new frame. Note 2: {@code pledgedSrcSize} is only valid once, for the next frame. It's discarded at the end of the frame, and replaced by {@code ZSTD_CONTENTSIZE_UNKNOWN}. Note 3 : Whenever all input data is provided and consumed in a single round, for example with #compress2(), or invoking immediately {@code ZSTD_compressStream2(,,,ZSTD_e_end)}, this value is automatically overridden by {@code srcSize} instead. """, ZSTD_CCtx.p("cctx", ""), unsigned_long_long("pledgedSrcSize", ""), returnDoc = "0, or an error code (which can be tested with #isError())." ) size_t( "CCtx_reset", """ There are 2 different things that can be reset, independently or jointly : ${ul( """ The session: will stop compressing current frame, and make {@code CCtx} ready to start a new one. Useful after an error, or to interrupt any ongoing compression. Any internal data not yet flushed is cancelled. Compression parameters and dictionary remain unchanged. They will be used to compress next frame. Resetting session never fails. """, """ The parameters: changes all parameters back to "default". This removes any reference to any dictionary too. Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) otherwise the reset fails, and function returns an error value (which can be tested using #isError()) """, "Both: similar to resetting the session, followed by resetting parameters." )} """, ZSTD_CCtx.p("cctx", ""), ZSTD_ResetDirective("reset", "", resetDirectives) ) size_t( "compress2", """ Behaves the same as #compressCCtx(), but compression parameters are set using the advanced API. {@code ZSTD_compress2()} always starts a new frame. Should cctx hold data from a previously unfinished frame, everything about it is forgotten. - Compression parameters are pushed into {@code CCtx} before starting compression, using {@code ZSTD_CCtx_set*()} - The function is always blocking, returns when compression is completed. Hint: compression runs faster if {@code dstCapacity} &ge; {@code ZSTD_compressBound(srcSize)}. """, ZSTD_CCtx.p("cctx", ""), void.p("dst", ""), AutoSize("dst")..size_t("dstCapacity", ""), void.const.p("src", ""), AutoSize("src")..size_t("srcSize", ""), returnDoc = "compressed size written into {@code dst} (&le; {@code dstCapacity}), or an error code if it fails (which can be tested using #isError())" ) /*************************************** * Advanced decompression API ***************************************/ ZSTD_bounds( "dParam_getBounds", "All parameters must belong to an interval with lower and upper bounds, otherwise they will either trigger an error or be automatically clamped.", ZSTD_dParameter("dParam", ""), returnDoc = """ returns a structure, {@code ZSTD_bounds}, which contains - an error status field, which must be tested using #isError() - both lower and upper bounds, inclusive """ ) size_t( "DCtx_setParameter", """ Set one compression parameter, selected by {@code enum ZSTD_dParameter}. All parameters have valid bounds. Bounds can be queried using #dParam_getBounds(). Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). Setting a parameter is only possible during frame initialization (before starting decompression). """, ZSTD_DCtx.p("dctx", ""), ZSTD_dParameter("param", "", dParameters), int("value", ""), returnDoc = "0, or an error code (which can be tested using #isError())" ) size_t( "DCtx_reset", """ Returns a {@code DCtx} to clean state. Session and parameters can be reset jointly or separately. Parameters can only be reset when no active frame is being decompressed. """, ZSTD_DCtx.p("dctx", ""), ZSTD_ResetDirective("reset", "", resetDirectives), returnDoc = "0, or an error code, which can be tested with #isError()" ) /**************************** * Streaming ****************************/ ZSTD_CStream.p( "createCStream", """ A {@code ZSTD_CStream} object is required to track streaming operation. Use {@code ZSTD_createCStream()} and #freeCStream() to create/release resources. {@code ZSTD_CStream} objects can be reused multiple times on consecutive compression operations. It is recommended to re-use {@code ZSTD_CStream} in situations where many streaming operations will be achieved consecutively, since it will play nicer with system's memory, by re-using already allocated memory. Use one separate {@code ZSTD_CStream} per thread for parallel execution. """, void() ) size_t( "freeCStream", "Frees memory allocated by #createCStream().", nullable..ZSTD_CStream.p("zcs", "accepts #NULL pointer") ) size_t( "compressStream2", """ Behaves about the same as {@code ZSTD_compressStream()}, with additional control on end directive. ${ul( "Compression parameters are pushed into {@code CCtx} before starting compression, using {@code ZSTD_CCtx_set*()}.", "Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode).", "{@code outpot->pos} must be &le; {@code dstCapacity}, {@code input->pos} must be &le; {@code srcSize}.", "{@code outpot->pos} and {@code input->pos} will be updated. They are guaranteed to remain below their respective limit.", "{@code endOp} must be a valid directive.", "When {@code nbWorkers==0} (default), function is blocking: it completes its job before returning to caller.", """ When {@code nbWorkers&ge;1}, function is non-blocking: it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available, and then immediately returns, just indicating that there is some data remaining to be flushed. The function nonetheless guarantees forward progress: it will return only after it reads or write at least 1+ byte. """, """ Exception: if the first call requests a #e_end directive and provides enough {@code dstCapacity}, the function delegates to #compress2() which is always blocking. """ )} """, ZSTD_CCtx.p("cctx", ""), Input..ZSTD_outBuffer.p("output", ""), Input..ZSTD_inBuffer.p("input", ""), ZSTD_EndDirective("endOp", "", endDirectives), returnDoc = """ provides a minimum amount of data remaining to be flushed from internal buffers or an error code, which can be tested using #isError(). If {@code != 0}, flush is not fully completed, there is still some data left within internal buffers. This is useful for #e_flush, since in this case more flushes are necessary to empty all buffers. For #e_end, {@code == 0} when internal buffers are fully flushed and frame is completed. - after a {@code ZSTD_e_end} directive, if internal buffer is not fully flushed ({@code != 0}), only {@code ZSTD_e_end} or {@code ZSTD_e_flush} operations are allowed. Before starting a new compression job, or changing compression parameters, it is required to fully flush internal buffers. """ ) size_t( "CStreamInSize", """ Returns the recommended size for input buffer. These buffer sizes are softly recommended. They are not required: {@code ZSTD_compressStream*()} happily accepts any buffer size, for both input and output. Respecting the recommended size just makes it a bit easier for {@code ZSTD_compressStream*()}, reducing the amount of memory shuffling and buffering, resulting in minor performance savings. However, note that these recommendations are from the perspective of a C caller program. If the streaming interface is invoked from some other language, especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo, a major performance rule is to reduce crossing such interface to an absolute minimum. It's not rare that performance ends being spent more into the interface, rather than compression itself. In which cases, prefer using large buffers, as large as practical, for both input and output, to reduce the nb of roundtrips. """, void() ) size_t( "CStreamOutSize", "Returns the recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block.", void() ) ZSTD_DStream.p( "createDStream", """ A {@code ZSTD_DStream} object is required to track streaming operations. Use {@code ZSTD_createDStream()} and #freeDStream() to create/release resources. {@code ZSTD_DStream} objects can be re-used multiple times. """, void() ) size_t( "freeDStream", "Frees memory allocated by #createDStream().", nullable..ZSTD_DStream.p("zds", "accepts #NULL pointer") ) size_t( "decompressStream", """ Use {@code ZSTD_decompressStream()} repetitively to consume your input. The function will update both {@code pos} fields. If {@code input.pos < input.size}, some input has not been consumed. It's up to the caller to present again remaining data. The function tries to flush all data decoded immediately, respecting output buffer size. If {@code output.pos < output.size}, decoder has flushed everything it could. But if {@code output.pos == output.size}, there might be some data left within internal buffers. In which case, call {@code ZSTD_decompressStream()} again to flush whatever remains in the buffer. With no additional input provided, amount of data flushed is necessarily &le; #BLOCKSIZE_MAX. """, ZSTD_DStream.p("zds", ""), Input..ZSTD_outBuffer.p("output", ""), Input..ZSTD_inBuffer.p("input", ""), returnDoc = """ 0 when a frame is completely decoded and fully flushed, an error code, which can be tested using #isError(), any other value &gt; 0, which means there is still some decoding to do to complete current frame. The return value is a suggested next input size (just a hint to improve latency) that will never request more than the remaining frame size. """ ) size_t( "DStreamInSize", "Returns the recommended size for input buffer.", void() ) size_t( "DStreamOutSize", "Returns the recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block in all circumstances.", void() ) /************************** * Simple dictionary API ***************************/ size_t( "compress_usingDict", """ Compression at an explicit compression level using a Dictionary. A dictionary can be any arbitrary data segment (also called a prefix), or a buffer with specified information (see {@code zdict.h}). This function loads the dictionary, resulting in significant startup delay. It's intended for a dictionary used only once. When {@code dict == NULL || dictSize < 8} no dictionary is used. """, ZSTD_CCtx.p("ctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"], nullable..void.const.p("dict", ""), AutoSize("dict")..size_t("dictSize", ""), int("compressionLevel", "") ) size_t( "decompress_usingDict", """ Decompression using a known Dictionary. Dictionary must be identical to the one used during compression. This function loads the dictionary, resulting in significant startup delay. It's intended for a dictionary used only once. When {@code dict == NULL || dictSize < 8} no dictionary is used. """, ZSTD_DCtx.p("dctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"], nullable..void.const.p("dict", ""), AutoSize("dict")..size_t("dictSize", "") ) /********************************** * Bulk processing dictionary API *********************************/ ZSTD_CDict.p( "createCDict", """ When compressing multiple messages or blocks using the same dictionary, it's recommended to digest the dictionary only once, since it's a costly operation. {@code ZSTD_createCDict()} will create a state from digesting a dictionary. The resulting state can be used for future compression operations with very limited startup cost. {@code ZSTD_CDict} can be created once and shared by multiple threads concurrently, since its usage is read-only. {@code dictBuffer} can be released after {@code ZSTD_CDict} creation, because its content is copied within CDict. Consider experimental function #createCDict_byReference() if you prefer to not duplicate {@code dictBuffer} content. Note 1: Consider experimental function #createCDict_byReference() if you prefer to not duplicate {@code dictBuffer} content. Note 2: A {@code ZSTD_CDict} can be created from an empty {@code dictBuffer}, in which case the only thing that it transports is the {@code compressionLevel}. This can be useful in a pipeline featuring #compress_usingCDict() exclusively, expecting a {@code ZSTD_CDict} parameter with any data, including those without a known dictionary. """, void.const.p("dictBuffer", ""), AutoSize("dictBuffer")..size_t("dictSize", ""), int("compressionLevel", "") ) size_t( "freeCDict", "Frees memory allocated by #createCDict().", nullable..ZSTD_CDict.p("CDict", "accepts #NULL pointer") ) size_t( "compress_usingCDict", """ Compression using a digested Dictionary. Recommended when same dictionary is used multiple times. Compression level is <b>decided at dictionary creation time</b>, and frame parameters are hardcoded ({@code dictID=yes, contentSize=yes, checksum=no}) """, ZSTD_CCtx.p("cctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"], ZSTD_CDict.const.p("cdict", "") ) ZSTD_DDict.p( "createDDict", """ Creates a digested dictionary, ready to start decompression operation without startup delay. {@code dictBuffer} can be released after {@code DDict} creation, as its content is copied inside {@code DDict}. """, void.const.p("dictBuffer", ""), AutoSize("dictBuffer")..size_t("dictSize", "") ) size_t( "freeDDict", "Frees memory allocated with #createDDict().", nullable..ZSTD_DDict.p("ddict", "accepts #NULL pointer") ) size_t( "decompress_usingDDict", """ Decompression using a digested Dictionary. Recommended when same dictionary is used multiple times. """, ZSTD_DCtx.p("dctx", ""), compress["dst"], compress["dstCapacity"], compress["src"], compress["srcSize"], ZSTD_DDict.const.p("ddict", "") ) unsigned_int( "getDictID_fromDict", "Provides the {@code dictID} stored within dictionary.", void.const.p("dict", ""), AutoSize("dict")..size_t("dictSize", ""), returnDoc = "if {@code == 0}, the dictionary is not conformant with Zstandard specification. It can still be loaded, but as a content-only dictionary." ) unsigned( "getDictID_fromCDict", """ Provides the {@code dictID} of the dictionary loaded into {@code cdict}. If {@code @return == 0}, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries. """, ZSTD_CDict.const.p("cdict", "") ) unsigned_int( "getDictID_fromDDict", "Provides the {@code dictID} of the dictionary loaded into {@code ddict}.", ZSTD_DDict.const.p("ddict", ""), returnDoc = """ if {@code == 0}, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries. """ ) unsigned_int( "getDictID_fromFrame", "Provides the dictID required to decompressed the frame stored within {@code src}.", void.const.p("src", ""), AutoSize("src")..size_t("srcSize", ""), returnDoc = """ if {@code == 0}, the {@code dictID} could not be decoded. This could for one of the following reasons : ${ul( "The frame does not require a dictionary to be decoded (most common case).", """ The frame was built with {@code dictID} intentionally removed. Whatever dictionary is necessary is a hidden information. Note: this use case also happens when using a non-conformant dictionary. """, "{@code srcSize} is too small, and as a result, the frame header could not be decoded (only possible if {@code srcSize} &lt; #FRAMEHEADERSIZE_MAX).", """ This is not a Zstandard frame. When identifying the exact failure cause, it's possible to use #getFrameHeader(), which will provide a more precise error code. """ )} """ ) size_t( "CCtx_loadDictionary", """ Creates an internal {@code CDict} from {@code dict} buffer. Decompression will have to use same dictionary. Special: Loading a #NULL (or 0-size) dictionary invalidates previous dictionary, meaning "return to no-dictionary mode". Note 1: Dictionary is sticky, it will be used for all future compressed frames. To return to "no-dictionary" situation, load a #NULL dictionary (or reset parameters). Note 2: Loading a dictionary involves building tables. It's also a CPU consuming operation, with non-negligible impact on latency. Tables are dependent on compression parameters, and for this reason, compression parameters can no longer be changed after loading a dictionary. Note 3: {@code dict} content will be copied internally. Use experimental #CCtx_loadDictionary_byReference() to reference content instead. In such a case, dictionary buffer must outlive its users. Note 4: Use #CCtx_loadDictionary_advanced() to precisely select how dictionary content must be interpreted. """, ZSTD_CCtx.p("cctx", ""), nullable..void.const.p("dict", ""), AutoSize("dict")..size_t("dictSize", ""), returnDoc = "0, or an error code (which can be tested with #isError())." ) size_t( "CCtx_refCDict", """ References a prepared dictionary, to be used for all next compressed frames. Note that compression parameters are enforced from within {@code CDict}, and supercede any compression parameter previously set within {@code CCtx}. The parameters ignored are labelled as "superseded-by-cdict" in the {@code ZSTD_cParameter} enum docs. The ignored parameters will be used again if the {@code CCtx} is returned to no-dictionary mode. The dictionary will remain valid for future compressed frames using same {@code CCtx}. Special: Referencing a #NULL {@code CDict} means "return to no-dictionary mode". Note 1: Currently, only one dictionary can be managed. Referencing a new dictionary effectively "discards" any previous one. Note 2: {@code CDict} is just referenced, its lifetime must outlive its usage within {@code CCtx}. """, ZSTD_CCtx.p("cctx", ""), nullable..ZSTD_CDict.const.p("cdict", ""), returnDoc = "0, or an error code (which can be tested with #isError())." ) size_t( "CCtx_refPrefix", """ References a prefix (single-usage dictionary) for next compressed frame. A prefix is <b>only used once</b>. Tables are discarded at end of frame (#e_end). Decompression will need same prefix to properly regenerate data. Compressing with a prefix is similar in outcome as performing a diff and compressing it, but performs much faster, especially during decompression (compression speed is tunable with compression level). Special: Adding any prefix (including #NULL) invalidates any previous prefix or dictionary Note 1: Prefix buffer is referenced. It <b>must</b> outlive compression. Its content must remain unmodified during compression. Note 2: If the intention is to diff some large {@code src} data blob with some prior version of itself, ensure that the window size is large enough to contain the entire source. See #c_windowLog. Note 3: Referencing a prefix involves building tables, which are dependent on compression parameters. It's a CPU consuming operation, with non-negligible impact on latency. If there is a need to use the same prefix multiple times, consider {@code loadDictionary} instead. Note 4: By default, the prefix is interpreted as raw content (#dct_rawContent). Use experimental #CCtx_refPrefix_advanced() to alter dictionary interpretation. """, ZSTD_CCtx.p("cctx", ""), nullable..void.const.p("prefix", ""), AutoSize("prefix")..size_t("prefixSize", ""), returnDoc = "0, or an error code (which can be tested with #isError())." ) size_t( "DCtx_loadDictionary", """ Create an internal {@code DDict} from {@code dict} buffer, to be used to decompress next frames. The dictionary remains valid for all future frames, until explicitly invalidated. Special: Adding a #NULL (or 0-size) dictionary invalidates any previous dictionary, meaning "return to no-dictionary mode". Note 1: Loading a dictionary involves building tables, which has a non-negligible impact on CPU usage and latency. It's recommended to "load once, use many times", to amortize the cost. Note 2: {@code dict} content will be copied internally, so {@code dict} can be released after loading. Use #DCtx_loadDictionary_byReference() to reference dictionary content instead. Note 3: Use #DCtx_loadDictionary_advanced() to take control of how dictionary content is loaded and interpreted. """, ZSTD_DCtx.p("dctx", ""), nullable..void.const.p("dict", ""), AutoSize("dict")..size_t("dictSize", ""), returnDoc = "0, or an error code (which can be tested with ZSTD_isError())" ) size_t( "DCtx_refDDict", """ References a prepared dictionary, to be used to decompress next frames. The dictionary remains active for decompression of future frames using same {@code DCtx}. If called with {@code ZSTD_d_refMultipleDDicts} enabled, repeated calls of this function will store the {@code DDict} references in a table, and the {@code DDict} used for decompression will be determined at decompression time, as per the {@code dict ID} in the frame. The memory for the table is allocated on the first call to {@code refDDict}, and can be freed with #freeDCtx(). Note 1: Currently, only one dictionary can be managed. Referencing a new dictionary effectively "discards" any previous one. Special: referencing a #NULL {@code DDict} means "return to no-dictionary mode". Note 2: {@code DDict} is just referenced, its lifetime must outlive its usage from {@code DCtx}. """, ZSTD_DCtx.p("dctx", ""), nullable..ZSTD_DDict.const.p("ddict", ""), returnDoc = "0, or an error code (which can be tested with #isError())" ) size_t( "DCtx_refPrefix", """ References a prefix (single-usage dictionary) to decompress next frame. This is the reverse operation of #CCtx_refPrefix(), and must use the same prefix as the one used during compression. Prefix is <b>only used once</b>. Reference is discarded at end of frame. End of frame is reached when #decompressStream() returns 0. Note 1: Adding any prefix (including #NULL) invalidates any previously set prefix or dictionary. Note 2: Prefix buffer is referenced. It <b>must</b> outlive decompression. Prefix buffer must remain unmodified up to the end of frame, reached when {@code ZSTD_decompressStream()} returns 0. Note 3: By default, the prefix is treated as raw content (#dct_rawContent). Use #CCtx_refPrefix_advanced() to alter {@code dictMode}. Note 4: Referencing a raw content prefix has almost no cpu nor memory cost. A full dictionary is more costly, as it requires building tables. """, ZSTD_DCtx.p("dctx", ""), void.const.p("prefix", ""), AutoSize("prefix")..size_t("prefixSize", ""), returnDoc = "0, or an error code (which can be tested with #isError())" ) size_t("sizeof_CCtx", "", ZSTD_CCtx.const.p("cctx", "")) size_t("sizeof_DCtx", "", ZSTD_DCtx.const.p("dctx", "")) size_t("sizeof_CStream", "", ZSTD_CStream.const.p("zcs", "")) size_t("sizeof_DStream", "", ZSTD_DStream.const.p("zds", "")) size_t("sizeof_CDict", "", ZSTD_CDict.const.p("cdict", "")) size_t("sizeof_DDict", "", ZSTD_DDict.const.p("ddict", "")) }
bsd-3-clause
bbc33581589a4531229d53f63558f9c5
45.273676
161
0.634366
4.523458
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/GalleryFunnel.kt
2
2102
package org.wikipedia.analytics import org.json.JSONObject import org.wikipedia.WikipediaApp import org.wikipedia.dataclient.WikiSite import org.wikipedia.page.PageTitle class GalleryFunnel(app: WikipediaApp, wiki: WikiSite?, private val source: Int) : TimedFunnel(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_100, wiki) { override fun preprocessData(eventData: JSONObject): JSONObject { preprocessData(eventData, "source", source) return super.preprocessData(eventData) } private fun logGalleryAction(action: String, currentPageTitle: PageTitle?, currentMediaTitle: String) { log( "action", action, "pageTitle", currentPageTitle?.displayText ?: "FeedFeaturedImage", "imageTitle", currentMediaTitle ) } fun logGalleryOpen(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("open", currentPageTitle, currentMediaTitle) } fun logGalleryClose(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("close", currentPageTitle, currentMediaTitle) } fun logGallerySwipeLeft(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("swipeLeft", currentPageTitle, currentMediaTitle) } fun logGallerySwipeRight(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("swipeRight", currentPageTitle, currentMediaTitle) } fun logGalleryShare(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("share", currentPageTitle, currentMediaTitle) } fun logGallerySave(currentPageTitle: PageTitle?, currentMediaTitle: String) { logGalleryAction("save", currentPageTitle, currentMediaTitle) } companion object { private const val SCHEMA_NAME = "MobileWikiAppMediaGallery" private const val REV_ID = 18115560 const val SOURCE_LEAD_IMAGE = 0 const val SOURCE_NON_LEAD_IMAGE = 1 const val SOURCE_LINK_PREVIEW = 2 const val SOURCE_FEED_FEATURED_IMAGE = 3 } }
apache-2.0
229539a1b2a0ebfd505ecf606d85137e
36.535714
107
0.712179
4.713004
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectView/KtDeclarationTreeNode.kt
2
3985
// 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.projectView import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.psi.* internal class KtDeclarationTreeNode( project: Project?, ktDeclaration: KtDeclaration?, viewSettings: ViewSettings? ) : AbstractPsiBasedNode<KtDeclaration?>(project, ktDeclaration!!, viewSettings) { override fun extractPsiFromValue(): PsiElement? = value override fun getChildrenImpl(): Collection<AbstractTreeNode<*>> = emptyList() override fun updateImpl(data: PresentationData) { val declaration = value ?: return data.presentableText = tryGetRepresentableText(declaration) } override fun isDeprecated(): Boolean = value?.let { KtPsiUtil.isDeprecated(it) } ?: false companion object { private val CLASS_INITIALIZER = "<" + KotlinBundle.message("project.view.class.initializer") + ">" private val ERROR_NAME = "<" + KotlinBundle.message("project.view.class.error.name") + ">" private fun String?.orErrorName() = if (!isNullOrBlank()) this else ERROR_NAME @NlsSafe fun tryGetRepresentableText(declaration: KtDeclaration): String { val settings = declaration.containingKtFile.kotlinCustomSettings fun StringBuilder.appendColon() { if (settings.SPACE_BEFORE_TYPE_COLON) append(" ") append(":") if (settings.SPACE_AFTER_TYPE_COLON) append(" ") } fun KtProperty.presentableText() = buildString { append(name.orErrorName()) typeReference?.text?.let { reference -> appendColon() append(reference) } } fun KtFunction.presentableText() = buildString { receiverTypeReference?.text?.let { receiverReference -> append(receiverReference) append('.') } append(name.orErrorName()) append("(") val valueParameters = valueParameters valueParameters.forEachIndexed { index, parameter -> parameter.name?.let { parameterName -> append(parameterName) appendColon() } parameter.typeReference?.text?.let { typeReference -> append(typeReference) } if (index != valueParameters.size - 1) { append(", ") } } append(")") typeReference?.text?.let { returnTypeReference -> appendColon() append(returnTypeReference) } } fun KtObjectDeclaration.presentableText(): String = buildString { if (isCompanion()) { append("companion object") } else { append(name.orErrorName()) } } return when (declaration) { is KtProperty -> declaration.presentableText() is KtFunction -> declaration.presentableText() is KtObjectDeclaration -> declaration.presentableText() is KtAnonymousInitializer -> CLASS_INITIALIZER else -> declaration.name.orErrorName() } } } }
apache-2.0
488b12bf0703e6131ac15b34ce9cf550
38.455446
120
0.5867
5.775362
false
false
false
false
dahlstrom-g/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/components/ComboBoxTableCellEditorComponent.kt
4
4350
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. 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 * * 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.jetbrains.packagesearch.intellij.plugin.ui.components import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.ui.TableUtil import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBLabel import com.intellij.ui.table.JBTable import com.intellij.util.containers.ContainerUtil import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import com.jetbrains.packagesearch.intellij.plugin.ui.util.bottom import com.jetbrains.packagesearch.intellij.plugin.ui.util.left import com.jetbrains.packagesearch.intellij.plugin.ui.util.top import java.awt.Dimension import java.awt.Point import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.ListCellRenderer import javax.swing.event.TableModelEvent // Adapted from JBComboBoxTableCellEditorComponent internal class ComboBoxTableCellEditorComponent<T : Any>( private val table: JBTable, private var cellRenderer: ListCellRenderer<T> ) : JBLabel() { var options: Iterable<T> = emptyList() var isForcePopupMatchCellWidth = true var isShowBelowCell = true var value: T? = null private var row = 0 private var column = 0 private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<ActionListener>() init { isOpaque = true background = table.colors.selectionBackground } fun setCell(row: Int? = null, column: Int? = null) { if (row != null) this.row = row if (column != null) this.column = column } override fun addNotify() { super.addNotify() initAndShowPopup() } private fun initAndShowPopup() { val cellRect = table.getCellRect(row, column, true) val surrendersFocusOnKeystrokeOldValue = table.surrendersFocusOnKeyStroke() val popup = JBPopupFactory.getInstance() .createPopupChooserBuilder(options.toList()) .setRenderer(cellRenderer) .setItemChosenCallback { selectedItem -> value = selectedItem val event = ActionEvent(this, ActionEvent.ACTION_PERFORMED, "elementChosen") for (listener in listeners) { listener.actionPerformed(event) } TableUtil.stopEditing(table) table.setValueAt(value, row, column) // on Mac getCellEditorValue() is called before myValue is set. table.tableChanged(TableModelEvent(table.model, row)) // force repaint } .setCancelCallback { TableUtil.stopEditing(table) true } .addListener(object : JBPopupListener { override fun beforeShown(event: LightweightWindowEvent) { table.surrendersFocusOnKeystroke = false } override fun onClosed(event: LightweightWindowEvent) { table.surrendersFocusOnKeystroke = surrendersFocusOnKeystrokeOldValue } }) .setMinSize(if (isForcePopupMatchCellWidth) Dimension(cellRect.size.getWidth().toInt(), -1) else null) .createPopup() val popupLocation = Point(cellRect.left, if (isShowBelowCell) cellRect.bottom else cellRect.top) popup.show(RelativePoint(table, popupLocation)) } fun addActionListener(listener: ActionListener) { listeners.add(listener) } }
apache-2.0
c89dcb6e51b7e4c6d032c1141d09620f
38.189189
116
0.669655
4.7593
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/internal/IdeaKotlinUastResolveProviderService.kt
7
2739
// 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.uast.kotlin.internal import com.intellij.psi.PsiElement import org.jetbrains.kotlin.codegen.ClassBuilderMode import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveCandidates import org.jetbrains.kotlin.idea.util.actionUnderSafeAnalyzeBlock import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.uast.kotlin.KotlinUastResolveProviderService import org.jetbrains.uast.kotlin.resolveToDeclarationImpl class IdeaKotlinUastResolveProviderService : KotlinUastResolveProviderService { override fun getBindingContext(element: KtElement) = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA) override fun getBindingContextIfAny(element: KtElement): BindingContext? = element.actionUnderSafeAnalyzeBlock({ getBindingContext(element) }, { null }) @Deprecated("For binary compatibility, please, use KotlinUastTypeMapper") override fun getTypeMapper(element: KtElement): KotlinTypeMapper { return KotlinTypeMapper( getBindingContext(element), ClassBuilderMode.LIGHT_CLASSES, JvmProtoBufUtil.DEFAULT_MODULE_NAME, element.languageVersionSettings, useOldInlineClassesManglingScheme = false ) } override fun isJvmElement(psiElement: PsiElement): Boolean = psiElement.isJvmElement override fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings = element.languageVersionSettings override fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement> { val resolutionFacade = ktExpression.getResolutionFacade() val bindingContext = ktExpression.safeAnalyzeNonSourceRootCode(resolutionFacade) val call = ktExpression.getCall(bindingContext) ?: return emptySequence() return call.resolveCandidates(bindingContext, resolutionFacade) .mapNotNull { resolveToDeclarationImpl(ktExpression, it.candidateDescriptor) } .asSequence() } }
apache-2.0
7f3d617d29e001a40941253776a007b3
52.705882
122
0.81015
5.217143
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/util/ToastUtils.kt
1
6666
package jp.juggler.util import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.util.Log import android.view.View import android.view.animation.Animation import android.widget.PopupWindow import android.widget.Toast import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.R import kotlinx.coroutines.CancellationException import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout import me.drakeet.support.toast.ToastCompat import java.lang.ref.WeakReference import kotlin.coroutines.resume private val log = LogCategory("ToastUtils") private var refToast: WeakReference<Toast>? = null private var oldApplication: WeakReference<Application>? = null private var lastActivity: WeakReference<Activity>? = null private var lastPopup: WeakReference<PopupWindow>? = null private val activityCallback = object : Application.ActivityLifecycleCallbacks { override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { } override fun onActivityStarted(activity: Activity) { lastActivity = WeakReference(activity) } override fun onActivityResumed(activity: Activity) { lastActivity = WeakReference(activity) } override fun onActivityPaused(activity: Activity) { if (lastActivity?.get() == activity) { lastActivity = null } } override fun onActivityStopped(activity: Activity) { if (lastActivity?.get() == activity) { lastActivity = null } } override fun onActivityDestroyed(activity: Activity) { if (lastActivity?.get() == activity) { lastActivity = null } } } /** * App1.onCreateから呼ばれる */ fun initializeToastUtils(app: Application) { try { oldApplication?.get()?.unregisterActivityLifecycleCallbacks(activityCallback) } catch (ex: Throwable) { Log.e("SubwayTooter", "unregisterActivityLifecycleCallbacks failed.", ex) } try { app.registerActivityLifecycleCallbacks(activityCallback) } catch (ex: Throwable) { Log.e("SubwayTooter", "registerActivityLifecycleCallbacks failed.", ex) } oldApplication = WeakReference(app) } /** * Animationを開始して終了を非同期待機する */ suspend fun Animation.startAndAwait(duration: Long, v: View) = try { withTimeout(duration + 333L) { suspendCancellableCoroutine { cont -> v.clearAnimation() [email protected] = duration [email protected] = true setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) {} override fun onAnimationRepeat(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) { cont.resume(Unit) } }) v.startAnimation(this@startAndAwait) } } } catch (ex: TimeoutCancellationException) { log.w(ex, "startAndAwait timeout.") Unit } internal fun showToastImpl(context: Context, bLong: Boolean, message: String): Boolean { runOnMainLooper { if (message.length >= 32 || message.count { it == '\n' } > 1) { // Android 12以降はトーストを全文表示しない // 長いメッセージの場合は可能ならダイアログを使う lastActivity?.get()?.let { try { AlertDialog.Builder(it) .setMessage(message) .setPositiveButton(android.R.string.ok, null) .show() return@runOnMainLooper } catch (ex: Throwable) { log.trace(ex, "showPopup failed.") } } // 画面がない、または失敗したら普通のトーストにフォールバック } // 前回のトーストの表示を終了する try { refToast?.get()?.cancel() } catch (ex: Throwable) { log.trace(ex) } finally { refToast = null } // 新しいトーストを作る try { val duration = if (bLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT val t = ToastCompat.makeText(context, message, duration) t.setBadTokenListener { } t.show() refToast = WeakReference(t) } catch (ex: Throwable) { log.trace(ex) } } return false } fun Context.showToast(bLong: Boolean, caption: String?): Boolean = showToastImpl(this, bLong, caption ?: "(null)") fun Context.showToast(ex: Throwable, caption: String? = null): Boolean = showToastImpl(this, true, ex.withCaption(caption)) fun Context.showToast(bLong: Boolean, stringId: Int, vararg args: Any): Boolean = showToastImpl(this, bLong, getString(stringId, *args)) fun Context.showToast(ex: Throwable, stringId: Int, vararg args: Any): Boolean = showToastImpl(this, true, ex.withCaption(resources, stringId, *args)) fun AppCompatActivity.showError(ex: Throwable, caption: String? = null) { log.e(ex, caption ?: "(showError)") // キャンセル例外はUIに表示しない if (ex is CancellationException) return try { AlertDialog.Builder(this) .setTitle(R.string.error) .setMessage( listOf( caption, when (ex) { is IllegalStateException -> null else -> ex.javaClass.simpleName }, ex.message, ) .filter { !it.isNullOrBlank() } .joinToString("\n") ) .setPositiveButton(R.string.ok, null) .show() } catch (ignored: Throwable) { showToast(ex, caption) } } fun Context.errorString(@StringRes stringId: Int, vararg args: Any?): Nothing = error(getString(stringId, *args))
apache-2.0
6e0d9fd4762b7136d125a01e76c2bb8c
31.747368
88
0.601061
4.646377
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/utils/MobileWearableClient.kt
1
5431
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.utils import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.localbroadcastmanager.content.LocalBroadcastManager import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.shared.models.TrainingInfo import de.dreier.mytargets.shared.models.augmented.AugmentedEnd import de.dreier.mytargets.shared.models.augmented.AugmentedTraining import de.dreier.mytargets.shared.models.db.End import de.dreier.mytargets.shared.models.db.Round import de.dreier.mytargets.shared.models.db.Shot import de.dreier.mytargets.shared.utils.marshall import de.dreier.mytargets.shared.wearable.WearableClientBase import timber.log.Timber class MobileWearableClient(context: Context) : WearableClientBase(context) { private val updateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val training = intent.getParcelableExtra<AugmentedTraining>(EXTRA_TRAINING) updateTraining(training) } } init { LocalBroadcastManager.getInstance(context).registerReceiver( updateReceiver, IntentFilter(BROADCAST_UPDATE_TRAINING_FROM_LOCAL) ) } override fun disconnect() { LocalBroadcastManager.getInstance(context).unregisterReceiver(updateReceiver) super.disconnect() } fun sendUpdateTrainingFromLocalBroadcast(training: AugmentedTraining) { val intent = Intent(BROADCAST_UPDATE_TRAINING_FROM_LOCAL) intent.putExtra(EXTRA_TRAINING, training) LocalBroadcastManager.getInstance(context).sendBroadcast(intent) } fun sendUpdateTrainingFromRemoteBroadcast(round: Round, end: End) { val intent = Intent(BROADCAST_UPDATE_TRAINING_FROM_REMOTE) intent.putExtra(EXTRA_TRAINING_ID, round.trainingId) intent.putExtra(EXTRA_ROUND_ID, round.id) intent.putExtra(EXTRA_END, end) LocalBroadcastManager.getInstance(context).sendBroadcast(intent) } fun sendCreateTrainingFromRemoteBroadcast() { val intent = Intent(BROADCAST_CREATE_TRAINING_FROM_REMOTE) LocalBroadcastManager.getInstance(context).sendBroadcast(intent) } fun updateTraining(training: AugmentedTraining) { val rounds = training.rounds val roundCount = rounds.size if (roundCount < 1) { return } val round = rounds .firstOrNull { it.round.maxEndCount != null && it.ends.size < it.round.maxEndCount!! } ?: rounds.last() val target = round.round.target val roundCopy = round.copy(ends = round.ends.toMutableList() .filter { (_, shots) -> shots.all { (_, _, _, _, _, scoringRing) -> scoringRing != Shot.NOTHING_SELECTED } } .map { end -> if (!SettingsManager.shouldSortTarget(target)) { end } else { AugmentedEnd( end.end, end.shots.toMutableList().sorted().toMutableList(), end.images ) } } .toMutableList()) val trainingInfo = TrainingInfo(training, roundCopy) sendTrainingInfo(trainingInfo) sendTimerSettings(SettingsManager.timerSettings) } private fun sendTrainingInfo(trainingInfo: TrainingInfo) { val data = trainingInfo.marshall() sendMessage(WearableClientBase.TRAINING_UPDATE, data) } fun sendTrainingTemplate(training: AugmentedTraining) { val data = training.marshall() sendMessage(WearableClientBase.REQUEST_TRAINING_TEMPLATE, data) } abstract class EndUpdateReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val trainingId = intent.getLongExtra(EXTRA_TRAINING_ID, -1) val roundId = intent.getLongExtra(EXTRA_ROUND_ID, -1) val end = intent.getParcelableExtra<End>(EXTRA_END) if (trainingId == -1L || roundId == -1L) { Timber.w("Incomplete request!") } onUpdate(trainingId, roundId, end) } protected abstract fun onUpdate(trainingId: Long, roundId: Long, end: End) } companion object { private const val BROADCAST_UPDATE_TRAINING_FROM_LOCAL = "update_from_local" const val BROADCAST_UPDATE_TRAINING_FROM_REMOTE = "update_from_remote" const val BROADCAST_CREATE_TRAINING_FROM_REMOTE = "create_from_remote" private const val EXTRA_TRAINING = "training" private const val EXTRA_TRAINING_ID = "training_id" private const val EXTRA_ROUND_ID = "round_id" private const val EXTRA_END = "end_index" } }
gpl-2.0
907e8ed2f043ddbe5b2ae160a84e63d2
37.792857
98
0.672252
4.598645
false
false
false
false
kmagiera/react-native-gesture-handler
android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
1
4652
package com.swmansion.gesturehandler.react import android.os.SystemClock import android.util.Log import android.view.MotionEvent import android.view.ViewGroup import android.view.ViewParent import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.common.ReactConstants import com.facebook.react.uimanager.RootView import com.facebook.react.views.modal.ReactModalHostView import com.swmansion.gesturehandler.GestureHandler import com.swmansion.gesturehandler.GestureHandlerOrchestrator class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: ViewGroup) { private val orchestrator: GestureHandlerOrchestrator? private val jsGestureHandler: GestureHandler<*>? val rootView: ViewGroup private var shouldIntercept = false private var passingTouch = false init { UiThreadUtil.assertOnUiThread() val wrappedViewTag = wrappedView.id check(wrappedViewTag >= 1) { "Expect view tag to be set for $wrappedView" } val module = context.getNativeModule(RNGestureHandlerModule::class.java)!! val registry = module.registry rootView = findRootViewTag(wrappedView) Log.i( ReactConstants.TAG, "[GESTURE HANDLER] Initialize gesture handler for root view $rootView") orchestrator = GestureHandlerOrchestrator( wrappedView, registry, RNViewConfigurationHelper()).apply { minimumAlphaForTraversal = MIN_ALPHA_FOR_TOUCH } jsGestureHandler = RootViewGestureHandler().apply { tag = -wrappedViewTag } with(registry) { registerHandler(jsGestureHandler) attachHandlerToView(jsGestureHandler.tag, wrappedViewTag) } module.registerRootHelper(this) } fun tearDown() { Log.i( ReactConstants.TAG, "[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView") val module = context.getNativeModule(RNGestureHandlerModule::class.java)!! with(module) { registry.dropHandler(jsGestureHandler!!.tag) unregisterRootHelper(this@RNGestureHandlerRootHelper) } } private inner class RootViewGestureHandler : GestureHandler<RootViewGestureHandler>() { override fun onHandle(event: MotionEvent) { val currentState = state if (currentState == STATE_UNDETERMINED) { begin() shouldIntercept = false } if (event.actionMasked == MotionEvent.ACTION_UP) { end() } } override fun onCancel() { shouldIntercept = true val time = SystemClock.uptimeMillis() val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply { action = MotionEvent.ACTION_CANCEL } if (rootView is RootView) { rootView.onChildStartedNativeGesture(event) } } } fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { // If this method gets called it means that some native view is attempting to grab lock for // touch event delivery. In that case we cancel all gesture recognizers if (orchestrator != null && !passingTouch) { // if we are in the process of delivering touch events via GH orchestrator, we don't want to // treat it as a native gesture capturing the lock tryCancelAllHandlers() } } fun dispatchTouchEvent(ev: MotionEvent): Boolean { // We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell // if `requestDisallow` has been called as a result of a normal gesture handling process or // as a result of one of the gesture handlers activating passingTouch = true orchestrator!!.onTouchEvent(ev) passingTouch = false return shouldIntercept } private fun tryCancelAllHandlers() { // In order to cancel handlers we activate handler that is hooked to the root view jsGestureHandler?.apply { if (state == GestureHandler.STATE_BEGAN) { // Try activate main JS handler activate() end() } } } /*package*/ fun handleSetJSResponder(viewTag: Int, blockNativeResponder: Boolean) { if (blockNativeResponder) { UiThreadUtil.runOnUiThread { tryCancelAllHandlers() } } } companion object { private const val MIN_ALPHA_FOR_TOUCH = 0.1f private fun findRootViewTag(viewGroup: ViewGroup): ViewGroup { UiThreadUtil.assertOnUiThread() var parent: ViewParent? = viewGroup while (parent != null && parent !is RootView) { parent = parent.parent } checkNotNull(parent) { "View $viewGroup has not been mounted under ReactRootView" } return parent as ViewGroup } } }
mit
018b20d0e2b7675407a78dc84e17687e
34.242424
98
0.716251
4.605941
false
false
false
false
paplorinc/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ui/RepositoryChangesBrowserNode.kt
1
3549
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.dvcs.ui import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.dvcs.repo.Repository import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNodeRenderer import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent.Companion.TEXT_COLOR import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent.Companion.getBranchPresentationBackground import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent.Companion.getCurrentBranch import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent.Companion.getPresentableText import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent.Companion.getSingleTooltip import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES import com.intellij.ui.SimpleTextAttributes.STYLE_OPAQUE import com.intellij.util.FontUtil.spaceAndThinSpace import com.intellij.util.ui.ColorIcon import com.intellij.util.ui.JBUI.insets import com.intellij.util.ui.JBUI.scale import com.intellij.util.ui.UIUtil.getTreeBackground import com.intellij.vcs.log.impl.VcsLogManager.findLogProviders import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.VcsLogColorManagerImpl.getBackgroundColor import java.awt.Color private val ICON_SIZE = scale(14) private val BRANCH_BACKGROUND_INSETS = insets(1, 0) private fun getBranchLabelAttributes(background: Color) = SimpleTextAttributes(getBranchPresentationBackground(background), TEXT_COLOR, null, STYLE_OPAQUE) class RepositoryChangesBrowserNode(repository: Repository) : ChangesBrowserNode<Repository>(repository) { private val colorManager = getColorManager(repository.project) override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { renderer.icon = ColorIcon(ICON_SIZE, getBackgroundColor(colorManager.getRootColor(getUserObject().root))) renderer.append(" $textPresentation", REGULAR_ATTRIBUTES) appendCount(renderer) if (renderer.isShowingLocalChanges) { appendCurrentBranch(renderer) } } private fun appendCurrentBranch(renderer: ChangesBrowserNodeRenderer) { val repository = getUserObject() val branch = getCurrentBranch(repository.project, repository.root) if (branch != null) { renderer.append(spaceAndThinSpace()) renderer.append(" ${getPresentableText(branch)} ", getBranchLabelAttributes(renderer.background ?: getTreeBackground())) renderer.setBackgroundInsets(BRANCH_BACKGROUND_INSETS) renderer.toolTipText = getSingleTooltip(branch) } } override fun getSortWeight(): Int = REPOSITORY_SORT_WEIGHT override fun compareUserObjects(o2: Repository): Int = compareFileNames(getShortRepositoryName(getUserObject()), getShortRepositoryName(o2)) override fun getTextPresentation(): String = getShortRepositoryName(getUserObject()) companion object { fun getColorManager(project: Project): VcsLogColorManagerImpl = VcsProjectLog.getInstance(project).logManager?.colorManager ?: VcsLogColorManagerImpl( findLogProviders(ProjectLevelVcsManagerImpl.getInstance(project).allVcsRoots.asList(), project).keys) } }
apache-2.0
87428beedfc695a00e0c49976debbd39
49
154
0.819949
4.579355
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/ui/tree/treeTable/TreeTableModelWithColumns.kt
1
1369
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tree.treeTable import com.intellij.ui.tree.AsyncTreeModel import com.intellij.ui.tree.TreeVisitor import com.intellij.ui.treeStructure.treetable.TreeTableModel import com.intellij.util.ui.ColumnInfo import org.jetbrains.concurrency.Promise import javax.swing.JTree import javax.swing.tree.TreeModel import javax.swing.tree.TreePath class TreeTableModelWithColumns(val delegate: AsyncTreeModel, val columns: Array<ColumnInfo<Any?, Any?>>) : TreeTableModel, TreeModel by delegate, TreeVisitor.Acceptor { override fun getColumnCount(): Int = columns.size override fun getColumnName(column: Int): String = columns[column].name override fun getColumnClass(column: Int): Class<*> = columns[column].columnClass override fun getValueAt(node: Any?, column: Int): Any? = columns[column].valueOf(node) override fun setValueAt(aValue: Any?, node: Any?, column: Int) = columns[column].setValue(node, aValue) override fun isCellEditable(node: Any?, column: Int): Boolean = columns[column].isCellEditable(node) override fun setTree(tree: JTree?) { // do nothing } override fun accept(visitor: TreeVisitor): Promise<TreePath> = delegate.accept(visitor) }
apache-2.0
0bebc000f69dad5a3a0feaaf6dc5b96e
39.294118
140
0.757487
4.123494
false
false
false
false
google/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/IdeaPluginDescriptorImpl.kt
1
21618
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty", "OVERRIDE_DEPRECATION") package com.intellij.ide.plugins import com.intellij.AbstractBundle import com.intellij.DynamicBundle import com.intellij.core.CoreBundle import com.intellij.idea.AppMode import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.ExtensionDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.util.registry.EarlyAccessRegistryManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey import org.jetbrains.annotations.VisibleForTesting import java.io.File import java.io.IOException import java.nio.file.Path import java.time.ZoneOffset import java.util.* private val LOG: Logger get() = PluginManagerCore.getLogger() fun Collection<String>.toPluginIds(): Set<PluginId> = PluginManagerCore.toPluginIds(this) fun Iterable<IdeaPluginDescriptor>.toPluginIdSet(): Set<PluginId> = mapTo(LinkedHashSet()) { it.pluginId } fun Iterable<PluginId>.toPluginDescriptors(): List<IdeaPluginDescriptorImpl> { val pluginIdMap = PluginManagerCore.buildPluginIdMap() return mapNotNull { pluginIdMap[it] } } internal fun Iterable<PluginId>.joinedPluginIds(operation: String): String { return joinToString( prefix = "Plugins to $operation: [", postfix = "]", ) { it.idString } } @ApiStatus.Internal class IdeaPluginDescriptorImpl(raw: RawPluginDescriptor, @JvmField val path: Path, private val isBundled: Boolean, id: PluginId?, @JvmField val moduleName: String?, @JvmField val useCoreClassLoader: Boolean = false) : IdeaPluginDescriptor { private val id: PluginId = id ?: PluginId.getId(raw.id ?: raw.name ?: throw RuntimeException("Neither id nor name are specified")) private val name = raw.name ?: id?.idString ?: raw.id @Suppress("EnumEntryName") enum class OS { mac, linux, windows, unix, freebsd } // only for sub descriptors @JvmField internal var descriptorPath: String? = null @Volatile private var description: String? = null private val productCode = raw.productCode private var releaseDate: Date? = raw.releaseDate?.let { Date.from(it.atStartOfDay(ZoneOffset.UTC).toInstant()) } private val releaseVersion = raw.releaseVersion private val isLicenseOptional = raw.isLicenseOptional @NonNls private var resourceBundleBaseName: String? = null private val changeNotes = raw.changeNotes private var version: String? = raw.version private var vendor = raw.vendor private val vendorEmail = raw.vendorEmail private val vendorUrl = raw.vendorUrl private var category: String? = raw.category @JvmField internal val url = raw.url @JvmField val pluginDependencies: List<PluginDependency> @JvmField val incompatibilities: List<PluginId> = raw.incompatibilities ?: Collections.emptyList() init { // https://youtrack.jetbrains.com/issue/IDEA-206274 val list = raw.depends if (list != null) { val iterator = list.iterator() while (iterator.hasNext()) { val item = iterator.next() if (!item.isOptional) { for (a in list) { if (a.isOptional && a.pluginId == item.pluginId) { a.isOptional = false iterator.remove() break } } } } } pluginDependencies = list ?: Collections.emptyList() } companion object { @ApiStatus.Experimental @VisibleForTesting const val ON_DEMAND_ENABLED_KEY: String = "ide.plugins.allow.on.demand" @JvmStatic val isOnDemandEnabled: Boolean by lazy(LazyThreadSafetyMode.NONE) { !AppMode.isHeadless() && EarlyAccessRegistryManager.getBoolean(ON_DEMAND_ENABLED_KEY) } } @Transient @JvmField var jarFiles: List<Path>? = null private var _pluginClassLoader: ClassLoader? = null @JvmField val actions: List<RawPluginDescriptor.ActionDescriptor> = raw.actions ?: Collections.emptyList() // extension point name -> list of extension descriptors val epNameToExtensions: Map<String, MutableList<ExtensionDescriptor>>? = raw.epNameToExtensions @JvmField val appContainerDescriptor = raw.appContainerDescriptor @JvmField val projectContainerDescriptor = raw.projectContainerDescriptor @JvmField val moduleContainerDescriptor = raw.moduleContainerDescriptor @JvmField val content: PluginContentDescriptor = raw.contentModules?.let { PluginContentDescriptor(it) } ?: PluginContentDescriptor.EMPTY @JvmField val dependencies = raw.dependencies @JvmField val modules: List<PluginId> = raw.modules ?: Collections.emptyList() private val descriptionChildText = raw.description @JvmField val isUseIdeaClassLoader = raw.isUseIdeaClassLoader @JvmField val isBundledUpdateAllowed = raw.isBundledUpdateAllowed @JvmField internal val implementationDetail = raw.implementationDetail @ApiStatus.Experimental @JvmField internal val onDemand = isOnDemandEnabled && raw.onDemand @JvmField internal val isRestartRequired = raw.isRestartRequired @JvmField val packagePrefix = raw.`package` private val sinceBuild = raw.sinceBuild private val untilBuild = raw.untilBuild private var isEnabled = true var isDeleted = false @JvmField internal var isIncomplete: PluginLoadingError? = null override fun getDescriptorPath() = descriptorPath override fun getDependencies(): List<IdeaPluginDependency> { return if (pluginDependencies.isEmpty()) Collections.emptyList() else Collections.unmodifiableList(pluginDependencies) } override fun getPluginPath() = path private fun createSub(raw: RawPluginDescriptor, descriptorPath: String, pathResolver: PathResolver, context: DescriptorListLoadingContext, dataLoader: DataLoader, moduleName: String?): IdeaPluginDescriptorImpl { raw.name = name val result = IdeaPluginDescriptorImpl(raw, path = path, isBundled = isBundled, id = id, moduleName = moduleName, useCoreClassLoader = useCoreClassLoader) result.descriptorPath = descriptorPath result.vendor = vendor result.version = version result.resourceBundleBaseName = resourceBundleBaseName result.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = true, dataLoader = dataLoader) return result } fun readExternal(raw: RawPluginDescriptor, pathResolver: PathResolver, context: DescriptorListLoadingContext, isSub: Boolean, dataLoader: DataLoader) { // include module file descriptor if not specified as `depends` (old way - xi:include) // must be first because merged into raw descriptor if (!isSub) { for (module in content.modules) { val subDescriptorFile = module.configFile ?: "${module.name}.xml" val subDescriptor = createSub(raw = pathResolver.resolveModuleFile(readContext = context, dataLoader = dataLoader, path = subDescriptorFile, readInto = null), descriptorPath = subDescriptorFile, pathResolver = pathResolver, context = context, dataLoader = dataLoader, moduleName = module.name) module.descriptor = subDescriptor } } if (raw.resourceBundleBaseName != null) { if (id == PluginManagerCore.CORE_ID && !isSub) { LOG.warn("<resource-bundle>${raw.resourceBundleBaseName}</resource-bundle> tag is found in an xml descriptor" + " included into the platform part of the IDE but the platform part uses predefined bundles " + "(e.g. ActionsBundle for actions) anyway; this tag must be replaced by a corresponding attribute in some inner tags " + "(e.g. by 'resource-bundle' attribute in 'actions' tag)") } if (resourceBundleBaseName != null && resourceBundleBaseName != raw.resourceBundleBaseName) { LOG.warn("Resource bundle redefinition for plugin $id. " + "Old value: $resourceBundleBaseName, new value: ${raw.resourceBundleBaseName}") } resourceBundleBaseName = raw.resourceBundleBaseName } if (version == null) { version = context.defaultVersion } if (!isSub) { if (context.isPluginDisabled(id)) { markAsIncomplete(disabledDependency = null, shortMessage = null) } else { checkCompatibility(context) if (isIncomplete != null) { return } for (pluginDependency in dependencies.plugins) { if (context.isPluginDisabled(pluginDependency.id)) { markAsIncomplete(pluginDependency.id, shortMessage = "plugin.loading.error.short.depends.on.disabled.plugin") } } } } if (isIncomplete == null && moduleName == null) { processOldDependencies(descriptor = this, context = context, pathResolver = pathResolver, dependencies = pluginDependencies, dataLoader = dataLoader) } } private fun processOldDependencies(descriptor: IdeaPluginDescriptorImpl, context: DescriptorListLoadingContext, pathResolver: PathResolver, dependencies: List<PluginDependency>, dataLoader: DataLoader) { var visitedFiles: MutableList<String>? = null for (dependency in dependencies) { // context.isPluginIncomplete must be not checked here as another version of plugin maybe supplied later from another source if (context.isPluginDisabled(dependency.pluginId)) { if (!dependency.isOptional && isIncomplete == null) { markAsIncomplete(dependency.pluginId, "plugin.loading.error.short.depends.on.disabled.plugin") } } // because of https://youtrack.jetbrains.com/issue/IDEA-206274, configFile maybe not only for optional dependencies val configFile = dependency.configFile ?: continue if (pathResolver.isFlat && context.checkOptionalConfigShortName(configFile, descriptor)) { continue } var resolveError: Exception? = null val raw: RawPluginDescriptor? = try { pathResolver.resolvePath(readContext = context, dataLoader = dataLoader, relativePath = configFile, readInto = null) } catch (e: IOException) { resolveError = e null } if (raw == null) { val message = "Plugin $descriptor misses optional descriptor $configFile" if (context.isMissingSubDescriptorIgnored) { LOG.info(message) if (resolveError != null) { LOG.debug(resolveError) } } else { throw RuntimeException(message, resolveError) } continue } if (visitedFiles == null) { visitedFiles = context.visitedFiles } checkCycle(descriptor, configFile, visitedFiles) visitedFiles.add(configFile) val subDescriptor = descriptor.createSub(raw = raw, descriptorPath = configFile, pathResolver = pathResolver, context = context, dataLoader = dataLoader, moduleName = null) dependency.subDescriptor = subDescriptor visitedFiles.clear() } } private fun checkCompatibility(context: DescriptorListLoadingContext) { if (isBundled) { return } fun markAsIncompatible(error: PluginLoadingError) { if (isIncomplete != null) { return } isIncomplete = error isEnabled = false } if (AppMode.isDisableNonBundledPlugins()) { markAsIncompatible(PluginLoadingError( plugin = this, detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.custom.plugin.loading.disabled", getName()) }, shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.custom.plugin.loading.disabled") }, isNotifyUser = false )) return } PluginManagerCore.checkBuildNumberCompatibility(this, context.productBuildNumber())?.let { markAsIncompatible(it) return } // "Show broken plugins in Settings | Plugins so that users can uninstall them and resolve "Plugin Error" (IDEA-232675)" if (context.isBroken(this)) { markAsIncompatible(PluginLoadingError( plugin = this, detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.marked.as.broken", name, version) }, shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.marked.as.broken") } )) } } private fun markAsIncomplete(disabledDependency: PluginId?, @PropertyKey(resourceBundle = CoreBundle.BUNDLE) shortMessage: String?, pluginId: PluginId? = disabledDependency) { if (isIncomplete != null) { return } if (shortMessage == null) { isIncomplete = PluginLoadingError(plugin = this, detailedMessageSupplier = null, shortMessageSupplier = PluginLoadingError.DISABLED) } else { isIncomplete = PluginLoadingError(plugin = this, detailedMessageSupplier = null, shortMessageSupplier = { CoreBundle.message(shortMessage, pluginId!!) }, isNotifyUser = false, disabledDependency = disabledDependency) } isEnabled = false } @ApiStatus.Internal fun registerExtensions(nameToPoint: Map<String, ExtensionPointImpl<*>>, containerDescriptor: ContainerDescriptor, listenerCallbacks: MutableList<in Runnable>?) { containerDescriptor.extensions?.let { if (!it.isEmpty()) { @Suppress("JavaMapForEach") it.forEach { name, list -> nameToPoint.get(name)?.registerExtensions(list, this, listenerCallbacks) } } return } val unsortedMap = epNameToExtensions ?: return // app container: in most cases will be only app-level extensions - to reduce map copying, assume that all extensions are app-level and then filter out // project container: rest of extensions wil be mostly project level // module container: just use rest, area will not register unrelated extension anyway as no registered point if (containerDescriptor == appContainerDescriptor) { val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks) containerDescriptor.distinctExtensionPointCount = registeredCount if (registeredCount == unsortedMap.size) { projectContainerDescriptor.extensions = Collections.emptyMap() moduleContainerDescriptor.extensions = Collections.emptyMap() } } else if (containerDescriptor == projectContainerDescriptor) { val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks) containerDescriptor.distinctExtensionPointCount = registeredCount if (registeredCount == unsortedMap.size) { containerDescriptor.extensions = unsortedMap moduleContainerDescriptor.extensions = Collections.emptyMap() } else if (registeredCount == (unsortedMap.size - appContainerDescriptor.distinctExtensionPointCount)) { moduleContainerDescriptor.extensions = Collections.emptyMap() } } else { val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks) if (registeredCount == 0) { moduleContainerDescriptor.extensions = Collections.emptyMap() } } } private fun doRegisterExtensions(unsortedMap: Map<String, MutableList<ExtensionDescriptor>>, nameToPoint: Map<String, ExtensionPointImpl<*>>, listenerCallbacks: MutableList<in Runnable>?): Int { var registeredCount = 0 for (entry in unsortedMap) { val point = nameToPoint.get(entry.key) ?: continue point.registerExtensions(entry.value, this, listenerCallbacks) registeredCount++ } return registeredCount } @Suppress("HardCodedStringLiteral") override fun getDescription(): String? { var result = description if (result != null) { return result } result = (resourceBundleBaseName?.let { baseName -> try { AbstractBundle.messageOrDefault( DynamicBundle.getResourceBundle(classLoader, baseName), "plugin.$id.description", descriptionChildText ?: "", ) } catch (_: MissingResourceException) { LOG.info("Cannot find plugin $id resource-bundle: $baseName") null } }) ?: descriptionChildText description = result return result } override fun getChangeNotes() = changeNotes override fun getName(): String = name!! override fun getProductCode() = productCode override fun getReleaseDate() = releaseDate override fun getReleaseVersion() = releaseVersion override fun isLicenseOptional() = isLicenseOptional override fun getOptionalDependentPluginIds(): Array<PluginId> { val pluginDependencies = pluginDependencies return if (pluginDependencies.isEmpty()) PluginId.EMPTY_ARRAY else pluginDependencies.asSequence() .filter { it.isOptional } .map { it.pluginId } .toList() .toTypedArray() } override fun getVendor() = vendor override fun getVersion() = version override fun getResourceBundleBaseName() = resourceBundleBaseName override fun getCategory() = category /* This setter was explicitly defined to be able to set a category for a descriptor outside its loading from the xml file. Problem was that most commonly plugin authors do not publish the plugin's category in its .xml file so to be consistent in plugins representation (e.g. in the Plugins form) we have to set this value outside. */ fun setCategory(category: String?) { this.category = category } val unsortedEpNameToExtensionElements: Map<String, List<ExtensionDescriptor>> get() { return Collections.unmodifiableMap(epNameToExtensions ?: return Collections.emptyMap()) } override fun getVendorEmail() = vendorEmail override fun getVendorUrl() = vendorUrl override fun getUrl() = url override fun getPluginId() = id override fun getPluginClassLoader(): ClassLoader? = _pluginClassLoader @ApiStatus.Internal fun setPluginClassLoader(classLoader: ClassLoader?) { _pluginClassLoader = classLoader } override fun isEnabled() = isEnabled override fun setEnabled(enabled: Boolean) { isEnabled = enabled } override fun getSinceBuild() = sinceBuild override fun getUntilBuild() = untilBuild override fun isBundled() = isBundled override fun allowBundledUpdate() = isBundledUpdateAllowed override fun isImplementationDetail() = implementationDetail override fun isOnDemand() = onDemand override fun isRequireRestart() = isRestartRequired override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is IdeaPluginDescriptorImpl) { return false } return id == other.id && descriptorPath == other.descriptorPath } override fun hashCode(): Int { return 31 * id.hashCode() + (descriptorPath?.hashCode() ?: 0) } override fun toString(): String { return "PluginDescriptor(" + "name=$name, " + "id=$id, " + (if (moduleName == null) "" else "moduleName=$moduleName, ") + "descriptorPath=${descriptorPath ?: "plugin.xml"}, " + "path=${pluginPathToUserString(path)}, " + "version=$version, " + "package=$packagePrefix, " + "isBundled=$isBundled" + ")" } } // don't expose user home in error messages internal fun pluginPathToUserString(file: Path): String { return file.toString().replace("${System.getProperty("user.home")}${File.separatorChar}", "~${File.separatorChar}") } private fun checkCycle(descriptor: IdeaPluginDescriptorImpl, configFile: String, visitedFiles: List<String>) { var i = 0 val n = visitedFiles.size while (i < n) { if (configFile == visitedFiles[i]) { val cycle = visitedFiles.subList(i, visitedFiles.size) throw RuntimeException("Plugin $descriptor optional descriptors form a cycle: ${java.lang.String.join(", ", cycle)}") } i++ } }
apache-2.0
050d555dbc1d805d620adcf4eae3d873
36.861646
155
0.656675
5.250911
false
false
false
false
DevCharly/kobalt-ant
examples/kobalt/src/Build.kt
1
2706
import com.beust.kobalt.* import com.devcharly.kobalt.plugin.ant.* import com.devcharly.kotlin.ant.* // use command line parameter "--profiles dev" to set this to true val dev by profile() val bs = buildScript { if (!dev) { plugins("com.devcharly:kobalt-ant:") } else { // To run this examples build on a development machine, it is expected that projects // https://github.com/DevCharly/kobalt-ant // and // https://github.com/DevCharly/kotlin-ant-dsl // are checked out into the same parent folder. E.g.: // /some-path/kobalt-ant // /some-path/kotlin-ant-dsl buildFileClasspath(file("../../kotlin-ant-dsl/kobaltBuild/classes")) plugins(file("../kobaltBuild/classes")) } } val project = project { name = "project" antTask("echo") { echo("Hello World") echo { +"aa" +"bb" +"cc" } echo(level = EchoLevel.ERROR) { +""" 111 22 3 """ } } antTask("property") { property("place", "World") echo("Hello ${p("place")}") } antTask("files", basedir = "_files_") { touch("file.txt") echo("content2\n", file = "file2.txt", append = true) copy("file.txt", todir = "dir", overwrite = true) copy("file2.txt", tofile = "dir/file2.txt") delete("file.txt") } antTask("fileset", basedir = "_fileset_") { mkdir("dir1") mkdir("dir2") touch("dir1/file1.java") touch("dir2/file2.java") touch("dir2/fileTest.java") copy(todir = "dir") { fileset("dir1") fileset("dir2") { include(name = "**/*.java") exclude(name = "**/*Test*") } } } antTask("zip", basedir = "_zip_") { echo("content1", file = "dir/file1.txt") echo("content2", file = "dir/file2.txt") zip("out1.zip", basedir = "dir") zip("out2.zip", basedir = "dir", includes = "file1.txt") zip("out3.zip") { fileset(dir = "dir", includes = "file2.txt") } zip("out4.zip") { zipfileset(dir = "dir", prefix = "pre-dir") } } antTask("tar", basedir = "_zip_", logLevel = LogLevel.VERBOSE) { tar("out1.tar") { tarfileset(dir = "dir", username = "user1", uid = 123, filemode = "600") } bzip2(src = "out1.tar", destfile = "out1.tar.bz2") gzip(src = "out1.tar", destfile = "out1.tar.gz") bunzip2(src = "out1.tar.bz2", dest = "out1b.tar") gunzip(src = "out1.tar.gz", dest = "out1g.tar") } antTask("jar", basedir = "_zip_", inputFiles = arrayOf("_zip_/dir", "_files_"), outputFiles = arrayOf("_zip_/out1.jar") ) { jar("out1.jar", basedir = "dir") { manifest { attribute("Main-Class", "com.myapp.Main") attribute("Class-Path", "common.jar") } service("javax.script.ScriptEngineFactory") { provider("org.acme.PinkyLanguage") provider("org.acme.BrainLanguage") } } } }
apache-2.0
0c0993702cfe0d540da0764ed522a0aa
22.530435
86
0.601626
2.744422
false
false
false
false
allotria/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.kt
2
7311
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.remote import com.intellij.execution.rmi.RemoteObject import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.util.EventDispatcher import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly class ExternalSystemProgressNotificationManagerImpl : RemoteObject(), ExternalSystemProgressNotificationManager, RemoteExternalSystemProgressNotificationManager { private val dispatcher = EventDispatcher.create(ExternalSystemTaskNotificationListener::class.java) override fun addNotificationListener(listener: ExternalSystemTaskNotificationListener): Boolean { return addListener(ALL_TASKS_KEY, listener) } override fun addNotificationListener(listener: ExternalSystemTaskNotificationListener, parentDisposable: Disposable): Boolean { return addListener(ALL_TASKS_KEY, listener, parentDisposable) } override fun addNotificationListener(taskId: ExternalSystemTaskId, listener: ExternalSystemTaskNotificationListener): Boolean { return addListener(taskId, listener) } override fun removeNotificationListener(listener: ExternalSystemTaskNotificationListener): Boolean { val toRemove = dispatcher.listeners.filter { (it as TaskListenerWrapper).delegate === listener } dispatcher.listeners.removeAll(toRemove) return toRemove.isNotEmpty() } override fun onStart(id: ExternalSystemTaskId, workingDir: String) { forEachListener { it.onStart(id, workingDir) } } override fun onStatusChange(event: ExternalSystemTaskNotificationEvent) { forEachListener { it.onStatusChange(event) } } override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { forEachListener { it.onTaskOutput(id, text, stdOut) } } override fun onEnd(id: ExternalSystemTaskId) { try { forEachListener { it.onEnd(id) } } finally { val toRemove = dispatcher.listeners.filter { (it as TaskListenerWrapper).taskId === id } dispatcher.listeners.removeAll(toRemove) } } override fun onSuccess(id: ExternalSystemTaskId) { forEachListener { it.onSuccess(id) } } override fun onFailure(id: ExternalSystemTaskId, e: Exception) { forEachListener { it.onFailure(id, e) } } override fun beforeCancel(id: ExternalSystemTaskId) { forEachListener { it.beforeCancel(id) } } override fun onCancel(id: ExternalSystemTaskId) { forEachListener { it.onCancel(id) } } private fun addListener(tasksKey: Any, listener: ExternalSystemTaskNotificationListener, parentDisposable: Disposable? = null): Boolean { val wrapper = TaskListenerWrapper(tasksKey, listener) if (dispatcher.listeners.contains(wrapper)) return false if (parentDisposable == null) { dispatcher.addListener(wrapper) } else { dispatcher.addListener(wrapper, parentDisposable) } return true } private fun forEachListener(action: (ExternalSystemTaskNotificationListener) -> Unit) { LOG.runAndLogException { action.invoke(dispatcher.multicaster) ExternalSystemTaskNotificationListener.EP_NAME.forEachExtensionSafe(action::invoke) } } private class TaskListenerWrapper( val taskId: Any, val delegate: ExternalSystemTaskNotificationListener ) : ExternalSystemTaskNotificationListener { override fun onSuccess(id: ExternalSystemTaskId) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onSuccess(id) } override fun onFailure(id: ExternalSystemTaskId, e: java.lang.Exception) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onFailure(id, e) } override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onTaskOutput(id, text, stdOut) } override fun onStatusChange(event: ExternalSystemTaskNotificationEvent) { if (taskId !== ALL_TASKS_KEY && taskId !== event.id) return delegate.onStatusChange(event) } override fun onCancel(id: ExternalSystemTaskId) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onCancel(id) } override fun onEnd(id: ExternalSystemTaskId) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onEnd(id) } override fun beforeCancel(id: ExternalSystemTaskId) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.beforeCancel(id) } override fun onStart(id: ExternalSystemTaskId, workingDir: String?) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return delegate.onStart(id, workingDir) } override fun onStart(id: ExternalSystemTaskId) { if (taskId !== ALL_TASKS_KEY && taskId !== id) return @Suppress("DEPRECATION") delegate.onStart(id) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TaskListenerWrapper if (taskId !== other.taskId) return false if (delegate !== other.delegate) return false return true } override fun hashCode(): Int { var result = taskId.hashCode() result = 31 * result + delegate.hashCode() return result } } companion object { private val LOG = logger<ExternalSystemProgressNotificationManager>() private val ALL_TASKS_KEY = Any() @JvmStatic fun getInstanceImpl(): ExternalSystemProgressNotificationManagerImpl { val application = ApplicationManager.getApplication() return application.getService(ExternalSystemProgressNotificationManager::class.java) as ExternalSystemProgressNotificationManagerImpl } @JvmStatic @TestOnly @ApiStatus.Internal fun getListeners(): Map<Any, List<ExternalSystemTaskNotificationListener>> { return getInstanceImpl().dispatcher.listeners.groupBy({ (it as TaskListenerWrapper).taskId }, { (it as TaskListenerWrapper).delegate }) } @JvmStatic @TestOnly @ApiStatus.Internal fun assertListenersReleased(taskId: Any? = null) { val listeners = getListeners() if (taskId == null && listeners.isNotEmpty()) { throw AssertionError("Leaked listeners: $listeners") } if (taskId != null && listeners.containsKey(taskId)) { throw AssertionError("Leaked listeners for task '$taskId': ${listeners[taskId]}") } } @JvmStatic @TestOnly @ApiStatus.Internal fun cleanupListeners() { getInstanceImpl().dispatcher.listeners.clear() } } }
apache-2.0
e3691757e83f5139aed1e781f623acea
35.56
162
0.724251
4.916611
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/native/src/flow/internal/SafeCollector.kt
2
1064
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow.internal import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlin.coroutines.* internal actual class SafeCollector<T> actual constructor( internal actual val collector: FlowCollector<T>, internal actual val collectContext: CoroutineContext ) : FlowCollector<T> { // Note, it is non-capturing lambda, so no extra allocation during init of SafeCollector internal actual val collectContextSize = collectContext.fold(0) { count, _ -> count + 1 } private var lastEmissionContext: CoroutineContext? = null override suspend fun emit(value: T) { val currentContext = currentCoroutineContext() currentContext.ensureActive() if (lastEmissionContext !== currentContext) { checkContext(currentContext) lastEmissionContext = currentContext } collector.emit(value) } public actual fun releaseIntercepted() { } }
apache-2.0
fcaed30918c5ba7dee716a8f3fd963b3
32.25
102
0.714286
4.836364
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/AnalysisConfig.kt
1
3234
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.analysis class AnalysisConfig( val perClassOptions: PerClassOptions, val histogramOptions: HistogramOptions = HistogramOptions(), val disposerOptions: DisposerOptions = DisposerOptions(), val traverseOptions: TraverseOptions = TraverseOptions(), val metaInfoOptions: MetaInfoOptions = MetaInfoOptions() ) { class PerClassOptions( val classNames: List<String>, val includeClassList: Boolean = true, val treeDisplayOptions: TreeDisplayOptions = TreeDisplayOptions.default() ) class TreeDisplayOptions( val minimumObjectSize: Int = 20_000_000, val minimumObjectCount: Int = 20_000, val minimumSubgraphSize: Long = 100_000_000, val minimumObjectCountPercent: Int = 10, val maximumTreeDepth: Int = 80, val maximumIndent: Int = 40, val minimumPaths: Int = 2, val headLimit: Int = 100, val tailLimit: Int = 25, val showFieldNames: Boolean = false, val smartIndent: Boolean = true ) { companion object { fun default() = TreeDisplayOptions() fun all(showFieldNames: Boolean = false, smartIndent: Boolean = true) = TreeDisplayOptions(minimumObjectSize = 0, minimumObjectCount = 0, minimumSubgraphSize = 0, minimumObjectCountPercent = 0, headLimit = Int.MAX_VALUE, tailLimit = 0, minimumPaths = Int.MAX_VALUE, showFieldNames = showFieldNames, smartIndent = smartIndent) } } class HistogramOptions( val includeByCount: Boolean = true, val includeBySize: Boolean = true, val classByCountLimit: Int = 50, val classBySizeLimit: Int = 10 ) class DisposerOptions( val includeDisposerTree: Boolean = true, val includeDisposedObjectsSummary: Boolean = true, val includeDisposedObjectsDetails: Boolean = true, val disposedObjectsDetailsTreeDisplayOptions: TreeDisplayOptions = TreeDisplayOptions(minimumSubgraphSize = 5_000_000, headLimit = 70, tailLimit = 5) ) class TraverseOptions( val onlyStrongReferences: Boolean = false ) class MetaInfoOptions( val include: Boolean = true ) companion object { fun getDefaultConfig(nominatedClasses: List<String>) = AnalysisConfig(PerClassOptions(nominatedClasses)) } }
apache-2.0
bdf4aac1cbe9c7c41a7587c123b05159
35.75
122
0.642548
4.714286
false
false
false
false
JuliusKunze/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/jvm/ToolConfig.kt
1
2749
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.tool import org.jetbrains.kotlin.konan.file.* import org.jetbrains.kotlin.konan.properties.* import org.jetbrains.kotlin.konan.target.* import org.jetbrains.kotlin.konan.util.* import kotlin.reflect.KFunction class ToolConfig(userProvidedTargetName: String?, userProvidedKonanProperties: String?, runnerProvidedKonanHome: String) { private val targetManager = TargetManager(userProvidedTargetName) private val host = TargetManager.host private val target = targetManager.target private val konanHome = File(runnerProvidedKonanHome).absolutePath private val konanPropertiesFile = userProvidedKonanProperties ?. File() ?: File(konanHome, "konan/konan.properties") private val properties = konanPropertiesFile.loadProperties() private val dependencies = DependencyProcessor.defaultDependenciesRoot private val targetProperties = KonanProperties(target, properties, dependencies.path) val substitutions = mapOf<String, String> ( "target" to target.detailedName, "arch" to target.architecture.visibleName) fun downloadDependencies() = targetProperties.downloadDependencies() val llvmHome = targetProperties.absoluteLlvmHome val sysRoot get() = targetProperties.absoluteTargetSysRoot val defaultCompilerOpts = targetProperties.defaultCompilerOpts() val libclang = when (host) { KonanTarget.MINGW -> "$llvmHome/bin/libclang.dll" else -> "$llvmHome/lib/${System.mapLibraryName("clang")}" } } private fun maybeExecuteHelper(dependenciesRoot: String, properties: Properties, dependencies: List<String>) { try { val kClass = Class.forName("org.jetbrains.kotlin.konan.util.Helper0").kotlin @Suppress("UNCHECKED_CAST") val ctor = kClass.constructors.single() as KFunction<Runnable> val result = ctor.call(dependenciesRoot, properties, dependencies) result.run() } catch (notFound: ClassNotFoundException) { // Just ignore, no helper. } catch (e: Throwable) { throw IllegalStateException("Cannot download dependencies.", e) } }
apache-2.0
a7ce5cd8d8fcad8f2ac7c39cf7acd206
37.71831
122
0.740997
4.543802
false
false
false
false
MGaetan89/Kolumbus
kolumbus/src/main/kotlin/io/kolumbus/adapter/TableAdapter.kt
1
4443
/* * Copyright (C) 2016 MGaetan89 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.kolumbus.adapter import android.graphics.Color import android.support.v7.widget.RecyclerView import android.util.Patterns import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import io.kolumbus.Kolumbus import io.kolumbus.R import io.kolumbus.extension.prettify import io.realm.RealmList import io.realm.RealmModel import io.realm.annotations.PrimaryKey import java.lang.reflect.Field import java.lang.reflect.Method import java.lang.reflect.ParameterizedType class TableAdapter(val entries: List<RealmModel>, val fields: List<Field>, val methods: Map<String, Method?>) : RecyclerView.Adapter<TableAdapter.ViewHolder>() { private val VIEW_TYPE_HEADER = 0 private val VIEW_TYPE_FIELD = 1 override fun getItemCount() = this.entries.size + 1 override fun getItemViewType(position: Int): Int { return if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_FIELD } override fun onBindViewHolder(holder: ViewHolder, position: Int) { when (this.getItemViewType(position)) { VIEW_TYPE_FIELD -> this.bindFieldRow(this.entries[position - 1], holder) VIEW_TYPE_HEADER -> this.bindHeaderRow(holder) } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? { val childLayoutRes = this.getLayoutForViewType(viewType) val layoutInflater = LayoutInflater.from(parent?.context) val view = layoutInflater.inflate(R.layout.kolumbus_adapter_table, parent, false) as ViewGroup this.fields.forEach { layoutInflater.inflate(childLayoutRes, view, true) } return ViewHolder(view) } private fun bindFieldRow(entry: RealmModel, holder: ViewHolder) { this.processField(holder) { fieldView, field -> val result = this.methods[field.name]?.invoke(entry) when { result is Boolean -> Kolumbus.architect.displayBoolean(fieldView, result) result is Float -> Kolumbus.architect.displayFloat(fieldView, result) result is Int -> Kolumbus.architect.displayInt(fieldView, result) result is RealmList<*> -> { val resultCasted = result as RealmList<RealmModel> val returnType = field.genericType as ParameterizedType val type = returnType.actualTypeArguments[0] as Class<RealmModel> Kolumbus.architect.displayRealmList(fieldView, resultCasted, type) } result is RealmModel -> Kolumbus.architect.displayRealmModel(fieldView, result) result is String -> if (result.isEmpty()) { Kolumbus.architect.displayEmpty(fieldView) } else { if (Patterns.WEB_URL.matcher(result).matches()) { Kolumbus.architect.displayUrl(fieldView, result) } else { try { val color = Color.parseColor(result) Kolumbus.architect.displayColor(fieldView, result, color) } catch (exception: IllegalArgumentException) { Kolumbus.architect.displayString(fieldView, result) } } } result != null -> Kolumbus.architect.displayAny(fieldView, result) else -> Kolumbus.architect.displayNull(fieldView) } } } private fun bindHeaderRow(holder: ViewHolder) { this.processField(holder) { fieldView, field -> fieldView.text = when { field.isAnnotationPresent(PrimaryKey::class.java) -> "#${field.name.prettify()}" else -> field.name.prettify() } } } private fun getLayoutForViewType(viewType: Int): Int { return when (viewType) { VIEW_TYPE_HEADER -> R.layout.kolumbus_adapter_table_header else -> R.layout.kolumbus_adapter_table_text } } private fun processField(holder: ViewHolder, callback: (fieldView: TextView, field: Field) -> Unit) { val parent = holder.itemView as ViewGroup? ?: return this.fields.forEachIndexed { index, field -> val fieldView = parent.getChildAt(index) as TextView callback(fieldView, field) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) }
apache-2.0
f68e6d331560b25e336dd17fda16a8f5
33.44186
161
0.73869
3.644791
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/world/chat/ChatManager.kt
1
3239
package au.com.codeka.warworlds.server.world.chat import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.ChatMessage import au.com.codeka.warworlds.common.proto.ChatRoom import au.com.codeka.warworlds.server.store.DataStore import au.com.codeka.warworlds.server.world.chat.Participant.OnlineCallback import com.google.common.base.Preconditions import java.util.* /** * Manages chat rooms and stuff. */ class ChatManager { private val participants: MutableMap<Long, Participant> = HashMap() private val rooms: Map<Long, Room> = HashMap() private val globalRoom: Room = Room(ChatRoom(name = "Global")) /** "Send" the given message to the given room. */ fun send(roomId: Long?, msg: ChatMessage) { val room = getRoom(roomId) if (room == null) { log.error("No room with id %d", roomId) return } // TODO: validate the action, message_en, etc etc. room.send(msg.copy( date_posted = System.currentTimeMillis(), id = DataStore.i.seq().nextIdentifier())) } /** Get the history of all messages in the given room, between the given start and end time. */ fun getMessages(roomId: Long?, startTime: Long, endTime: Long): List<ChatMessage> { val room = getRoom(roomId) return room!!.getMessages(startTime, endTime) } /** * Called when a player connects. We'll start sending them messages and stuff. * * @param empireId The ID of the empire connecting. * @param lastChatTime The time this player last received a chat message. We'll straight away * send them any new ones since then. * @param callback A callback to call to send chat messages across. */ fun connectPlayer(empireId: Long, lastChatTime: Long, callback: OnlineCallback) { var participant: Participant? synchronized(participants) { participant = participants[empireId] if (participant == null) { participant = Participant(empireId) participants[empireId] = participant!! } } // Players are only in the global room when they first connect. globalRoom.addParticipant(participant) // TODO: rooms val msgs = globalRoom.getMessages(lastChatTime, System.currentTimeMillis()) callback.onChatMessage(msgs) participant!!.setOnlineCallback(callback) } /** Called when a player disconnects. */ fun disconnectPlayer(empireId: Long) { var participant: Participant? synchronized(participants) { participant = participants[empireId] if (participant == null) { return } } globalRoom.removeParticipant(participant) participant!!.setOnlineCallback(null) } /** * Gets the [ChatRoom] with the given identifier. * * @param id the identifier of the room, or null for the global room. * @return the room, or null if no room with that ID exists. */ private fun getRoom(id: Long?): Room? { if (id == null) { return globalRoom } synchronized(rooms) { val room = rooms[id] if (room == null) { //TODO room = new WatchableObject<>(DataStore.i.chat().getRoom(id)); } return room } } companion object { private val log = Log("ChatManager") val i = ChatManager() } }
mit
edb39b3e8fdecb48b9e4124d7d0e9a39
30.456311
98
0.679839
4.079345
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/views/BaseAlarmView.kt
1
5350
package com.thanksmister.iot.mqtt.alarmpanel.ui.views import android.content.Context import android.media.AudioManager import android.util.AttributeSet import android.widget.LinearLayout import com.thanksmister.iot.mqtt.alarmpanel.R import com.thanksmister.iot.mqtt.alarmpanel.utils.SoundUtils import kotlinx.android.synthetic.main.dialog_alarm_code_set.view.* import kotlinx.android.synthetic.main.view_keypad.view.* abstract class BaseAlarmView : LinearLayout { var currentCode: Int = 0 var codeComplete = false var enteredCode = "" private var soundUtils: SoundUtils? = null constructor(context: Context) : super(context) { } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} override fun onFinishInflate() { super.onFinishInflate() button0.setOnClickListener { playButtonPress() addPinCode("0") } button1.setOnClickListener { playButtonPress() addPinCode("1") } button2.setOnClickListener { playButtonPress() addPinCode("2") } button3.setOnClickListener { playButtonPress() addPinCode("3") } button4.setOnClickListener { playButtonPress() addPinCode("4") } button5.setOnClickListener { playButtonPress() addPinCode("5") } button6.setOnClickListener { playButtonPress() addPinCode("6") } button7.setOnClickListener { playButtonPress() addPinCode("7") } button8.setOnClickListener { playButtonPress() addPinCode("8") } button9.setOnClickListener { playButtonPress() addPinCode("9") } buttonDel.setOnClickListener { playButtonPress() removePinCode() } if (buttonCancel != null) { buttonCancel.setOnClickListener { playButtonPress() onCancel() } } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() destroySoundUtils() } fun setCode(code: Int) { currentCode = code } abstract fun onCancel() abstract fun removePinCode() abstract fun addPinCode(code: String) abstract fun reset() fun destroySoundUtils() { if (soundUtils != null) { soundUtils?.destroyBuzzer() } } private fun playButtonPress() { if (soundUtils == null) { soundUtils = SoundUtils(context) soundUtils?.init() } soundUtils?.playBuzzerOnButtonPress() } fun playContinuousBeep() { if (soundUtils == null) { soundUtils = SoundUtils(context) soundUtils?.init() soundUtils?.playBuzzerRepeat() } } protected fun showFilledPins(pinsShown: Int) { if (pinCode1 != null && pinCode2 != null && pinCode3 != null && pinCode4 != null) { when (pinsShown) { 1 -> { pinCode1.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode2.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode3.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode4.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) } 2 -> { pinCode1.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode2.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode3.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode4.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) } 3 -> { pinCode1.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode2.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode3.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode4.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) } 4 -> { pinCode1.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode2.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode3.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) pinCode4.setImageResource(R.drawable.ic_radio_button_checked_black_32dp) } else -> { pinCode1.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode2.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode3.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) pinCode4.setImageResource(R.drawable.ic_radio_button_unchecked_black_32dp) } } } } companion object { val MAX_CODE_LENGTH = 4 } }
apache-2.0
760173d622415f460ade8a962232cafe
30.292398
94
0.585607
4.443522
false
false
false
false
smmribeiro/intellij-community
platform/core-api/src/com/intellij/openapi/progress/sink.kt
6
2262
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:ApiStatus.Experimental package com.intellij.openapi.progress import kotlinx.coroutines.CoroutineScope import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext /** * Usage example: * ``` * val sink = new MyCoolSink() * // launch a coroutine to update UI with data from MyCoolSink * withContext(sink.asContextElement()) { * // available on CoroutineScope as a property * // safe null operator allows to skip the evaluation of the resource bundle part * progressSink?.text(ResourceBundle.message("starting.progress.text")) * ... * doStuff() * } * suspend fun doStuff() { * // available inside suspend functions as a function * progressSink()?.details("stuff") * } * ``` */ fun ProgressSink.asContextElement(): CoroutineContext.Element { return ProgressSinkElement(this) } internal val CoroutineContext.progressSink: ProgressSink? get() = this[ProgressSinkKey]?.sink val CoroutineScope.progressSink: ProgressSink? get() = coroutineContext.progressSink // kotlin doesn't allow 'suspend' modifier on properties suspend fun progressSink(): ProgressSink? = coroutineContext.progressSink private object ProgressSinkKey : CoroutineContext.Key<ProgressSinkElement> private class ProgressSinkElement(val sink: ProgressSink) : AbstractCoroutineContextElement(ProgressSinkKey) internal class ProgressIndicatorSink(private val indicator: ProgressIndicator) : ProgressSink { override fun text(text: String) { indicator.text = text } override fun details(details: String) { indicator.text2 = details } override fun fraction(fraction: Double) { indicator.fraction = fraction } } internal class ProgressSinkIndicator(private val sink: ProgressSink) : EmptyProgressIndicator() { override fun setText(text: String?) { if (text != null) { sink.text(text) } } override fun setText2(text: String?) { if (text != null) { sink.details(text) } } override fun setFraction(fraction: Double) { sink.fraction(fraction) } }
apache-2.0
9826989bdae2ca68b19ed4e6084fd118
28.763158
120
0.746684
4.461538
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt
1
8030
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.mapArgumentsToParameters import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeSignatureConfiguration import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.changeSignature.modify import org.jetbrains.kotlin.idea.refactoring.changeSignature.runChangeSignature import org.jetbrains.kotlin.idea.util.getDataFlowAwareTypes import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.callUtil.getCall import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.checker.KotlinTypeChecker abstract class ChangeFunctionSignatureFix( element: PsiElement, protected val functionDescriptor: FunctionDescriptor ) : KotlinQuickFixAction<PsiElement>(element) { override fun getFamilyName() = FAMILY_NAME override fun startInWriteAction() = false override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val declarations = DescriptorToSourceUtilsIde.getAllDeclarations(project, functionDescriptor) return declarations.isNotEmpty() && declarations.all { it.isValid && it.canRefactor() } } protected fun getNewArgumentName(argument: ValueArgument, validator: Function1<String, Boolean>): String { val expression = KtPsiUtil.deparenthesize(argument.getArgumentExpression()) val argumentName = argument.getArgumentName()?.asName?.asString() ?: (expression as? KtNameReferenceExpression)?.getReferencedName()?.takeIf { !isSpecialName(it) } return when { argumentName != null -> KotlinNameSuggester.suggestNameByName(argumentName, validator) expression != null -> { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val expressionText = expression.text if (isSpecialName(expressionText)) { val type = expression.getType(bindingContext) if (type != null) { return KotlinNameSuggester.suggestNamesByType(type, validator, "param").first() } } KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first() } else -> KotlinNameSuggester.suggestNameByName("param", validator) } } private fun isSpecialName(name: String): Boolean { return name == "it" || name == "field" } companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtCallElement, CallableDescriptor>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? = diagnostic.psiElement.getStrictParentOfType() override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): CallableDescriptor? { return DiagnosticFactory.cast(diagnostic, Errors.TOO_MANY_ARGUMENTS, Errors.NO_VALUE_FOR_PARAMETER).a } override fun createFix(originalElement: KtCallElement, data: CallableDescriptor): ChangeFunctionSignatureFix? { val functionDescriptor = data as? FunctionDescriptor ?: (data as? ValueParameterDescriptor)?.containingDeclaration as? FunctionDescriptor ?: return null if (functionDescriptor.kind == SYNTHESIZED) return null if (data is ValueParameterDescriptor) { return RemoveParameterFix(originalElement, functionDescriptor, data) } else { val parameters = functionDescriptor.valueParameters val arguments = originalElement.valueArguments if (arguments.size > parameters.size) { val bindingContext = originalElement.analyze() val call = originalElement.getCall(bindingContext) ?: return null val argumentToParameter = call.mapArgumentsToParameters(functionDescriptor) val hasTypeMismatches = argumentToParameter.any { (argument, parameter) -> val argumentTypes = argument.getArgumentExpression()?.let { getDataFlowAwareTypes( it, bindingContext ) } argumentTypes?.none { dataFlowAwareType -> KotlinTypeChecker.DEFAULT.isSubtypeOf(dataFlowAwareType, parameter.type) } ?: true } val kind = when { hasTypeMismatches -> AddFunctionParametersFix.Kind.ChangeSignature else -> AddFunctionParametersFix.Kind.AddParameterGeneric } return AddFunctionParametersFix(originalElement, functionDescriptor, kind) } } return null } private class RemoveParameterFix( element: PsiElement, functionDescriptor: FunctionDescriptor, private val parameterToRemove: ValueParameterDescriptor ) : ChangeFunctionSignatureFix(element, functionDescriptor) { override fun getText() = KotlinBundle.message("fix.change.signature.remove.parameter", parameterToRemove.name.asString()) override fun invoke(project: Project, editor: Editor?, file: KtFile) { runRemoveParameter(parameterToRemove, element ?: return, editor) } } val FAMILY_NAME = KotlinBundle.message("fix.change.signature.family") fun runRemoveParameter(parameterDescriptor: ValueParameterDescriptor, context: PsiElement, editor: Editor?) { val functionDescriptor = parameterDescriptor.containingDeclaration as FunctionDescriptor runChangeSignature( context.project, editor, functionDescriptor, object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { descriptor -> val index = if (descriptor.receiver != null) parameterDescriptor.index + 1 else parameterDescriptor.index descriptor.removeParameter(index) } } override fun performSilently(affectedFunctions: Collection<PsiElement>) = true override fun forcePerformForSelectedFunctionOnly() = false }, context, KotlinBundle.message("fix.change.signature.remove.parameter.command", parameterDescriptor.name.asString()) ) } } }
apache-2.0
caf670eb1e2ed26a68f92a9ebfdc5400
50.146497
158
0.67858
6.051243
false
false
false
false
smmribeiro/intellij-community
plugins/filePrediction/src/com/intellij/filePrediction/logger/FileNavigationLogger.kt
2
3647
// 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.filePrediction.logger import com.intellij.filePrediction.candidates.FilePredictionCandidateSource import com.intellij.filePrediction.predictor.FilePredictionCompressedCandidate import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project internal class FileNavigationLogger : CounterUsagesCollector() { companion object { private val GROUP = EventLogGroup("file.prediction", 13) private var session: IntEventField = EventFields.Int("session") private var performance: LongListEventField = EventFields.LongList("performance") private var anonymized_path: CandidateAnonymizedPath = CandidateAnonymizedPath() private var opened: EncodedBooleanEventField = EncodedBooleanEventField("opened") private var source: EncodedEnumEventField<FilePredictionCandidateSource> = EncodedEnumEventField("source") private var probability: EncodedDoubleEventField = EncodedDoubleEventField("prob") private var features: StringEventField = EventFields.StringValidatedByCustomRule("features", "file_features") private var candidates: ObjectListEventField = ObjectListEventField( "candidates", anonymized_path, opened.field, source.field, probability.field, features ) private val cacheCandidates = GROUP.registerEvent("calculated", session, performance, candidates) fun logEvent(project: Project, sessionId: Int, opened: FilePredictionCompressedCandidate?, candidates: List<FilePredictionCompressedCandidate>, totalDuration: Long, refsComputation: Long) { val allCandidates: MutableList<ObjectEventData> = arrayListOf() if (opened != null) { allCandidates.add(toObject(opened, true)) } for (candidate in candidates) { allCandidates.add(toObject(candidate, false)) } val performanceMs = toPerformanceMetrics(totalDuration, refsComputation, opened, candidates) cacheCandidates.log(project, sessionId, performanceMs, allCandidates) } private fun toObject(candidate: FilePredictionCompressedCandidate, wasOpened: Boolean): ObjectEventData { val data = arrayListOf<EventPair<*>>( anonymized_path.with(candidate.path), opened.with(wasOpened), source.with(candidate.source) ) if (candidate.probability != null) { data.add(probability.with(candidate.probability)) } data.add(features.with(candidate.features)) return ObjectEventData(data) } private fun toPerformanceMetrics(totalDuration: Long, refsComputation: Long, openCandidate: FilePredictionCompressedCandidate?, candidates: List<FilePredictionCompressedCandidate>): List<Long> { var featuresMs: Long = 0 var predictionMs: Long = 0 openCandidate?.let { featuresMs += it.featuresComputation predictionMs += it.duration ?: 0 } for (candidate in candidates) { featuresMs += candidate.featuresComputation predictionMs += candidate.duration ?: 0 } return arrayListOf(totalDuration, refsComputation, featuresMs, predictionMs) } } override fun getGroup(): EventLogGroup { return GROUP } }
apache-2.0
5407e1e8f950db4ef788f6501c495eab
39.087912
140
0.71456
5.202568
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/TextArea.kt
1
31369
package de.fabmax.kool.modules.ui2 import de.fabmax.kool.Clipboard import de.fabmax.kool.InputManager import de.fabmax.kool.LocalKeyCode import de.fabmax.kool.math.MutableVec2f import de.fabmax.kool.math.MutableVec2i import de.fabmax.kool.math.Vec2i import de.fabmax.kool.math.clamp import de.fabmax.kool.util.Color import de.fabmax.kool.util.MsdfFont import de.fabmax.kool.util.TextCaretNavigation import kotlin.math.max import kotlin.math.min interface TextAreaScope : UiScope { override val modifier: TextAreaModifier val linesHolder: LazyListScope fun installDefaultSelectionHandler() { val selStartLine = weakRememberState(-1) val selCaretLine = weakRememberState(-1) val selStartChar = weakRememberState(0) val selCaretChar = weakRememberState(0) modifier.onSelectionChanged = { startLine, caretLine, startChar, caretChar -> selStartLine.set(startLine) selCaretLine.set(caretLine) selStartChar.set(startChar) selCaretChar.set(caretChar) } modifier.selectionStartLine = selStartLine.use() modifier.selectionCaretLine = selCaretLine.use() modifier.selectionStartChar = selStartChar.use() modifier.selectionCaretChar = selCaretChar.use() } } open class TextAreaModifier(surface: UiSurface) : UiModifier(surface) { var lineStartPadding: Dp by property(Dp(0f)) var lineEndPadding: Dp by property(Dp(100f)) var lastLineBottomPadding: Dp by property(Dp(16f)) var editorHandler: TextEditorHandler? by property(null) var selectionStartLine: Int by property(-1) var selectionCaretLine: Int by property(-1) var selectionStartChar: Int by property(0) var selectionCaretChar: Int by property(0) var onSelectionChanged: ((Int, Int, Int, Int) -> Unit)? by property(null) } fun <T: TextAreaModifier> T.lineStartPadding(padding: Dp): T { lineStartPadding = padding; return this } fun <T: TextAreaModifier> T.lineEndPadding(padding: Dp): T { lineEndPadding = padding; return this } fun <T: TextAreaModifier> T.lastLineBottomPadding(padding: Dp): T { lastLineBottomPadding = padding; return this } fun <T: TextAreaModifier> T.onSelectionChanged(block: ((Int, Int, Int, Int) -> Unit)?): T { onSelectionChanged = block return this } fun <T: TextAreaModifier> T.editorHandler(handler: TextEditorHandler): T { editorHandler = handler; return this } fun <T: TextAreaModifier> T.setCaretPos(line: Int, caretPos: Int): T { selectionStartLine = line selectionCaretLine = line selectionStartChar = caretPos selectionCaretChar = caretPos onSelectionChanged?.invoke(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) return this } fun <T: TextAreaModifier> T.setSelectionRange(startLine: Int, caretLine: Int, startPos: Int, caretPos: Int): T { selectionStartLine = startLine selectionCaretLine = caretLine selectionStartChar = startPos selectionCaretChar = caretPos onSelectionChanged?.invoke(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) return this } fun UiScope.TextArea( lineProvider: TextLineProvider, width: Dimension = Grow.Std, height: Dimension = Grow.Std, withVerticalScrollbar: Boolean = true, withHorizontalScrollbar: Boolean = true, scrollbarColor: Color? = null, scrollPaneModifier: ((ScrollPaneModifier) -> Unit)? = null, vScrollbarModifier: ((ScrollbarModifier) -> Unit)? = null, hScrollbarModifier: ((ScrollbarModifier) -> Unit)? = null, state: LazyListState = weakRememberListState(), block: TextAreaScope.() -> Unit ) { val textArea = uiNode.createChild(TextAreaNode::class, TextAreaNode.factory) textArea.listState = state textArea.modifier .size(width, height) .onWheelX { state.scrollDpX(it.pointer.deltaScrollX.toFloat() * -20f) } .onWheelY { state.scrollDpY(it.pointer.deltaScrollY.toFloat() * -50f) } textArea.setupContent( lineProvider, withVerticalScrollbar, withHorizontalScrollbar, scrollbarColor, scrollPaneModifier, vScrollbarModifier, hScrollbarModifier, block ) } open class TextAreaNode(parent: UiNode?, surface: UiSurface) : BoxNode(parent, surface), TextAreaScope, Focusable { override val modifier = TextAreaModifier(surface) override val isFocused = mutableStateOf(false) private lateinit var lineProvider: TextLineProvider lateinit var listState: LazyListState override lateinit var linesHolder: LazyListNode private val selectionHandler = SelectionHandler() fun setupContent( lineProvider: TextLineProvider, withVerticalScrollbar: Boolean, withHorizontalScrollbar: Boolean, scrollbarColor: Color?, scrollPaneModifier: ((ScrollPaneModifier) -> Unit)?, vScrollbarModifier: ((ScrollbarModifier) -> Unit)?, hScrollbarModifier: ((ScrollbarModifier) -> Unit)?, block: TextAreaScope.() -> Unit ) { this.lineProvider = lineProvider ScrollPane(listState) { modifier.width(Grow.MinFit) scrollPaneModifier?.let { it(modifier) } linesHolder = uiNode.createChild(LazyListNode::class, LazyListNode.factory) linesHolder.state = listState linesHolder.modifier .orientation(ListOrientation.Vertical) .layout(ColumnLayout) .width(Grow.MinFit) block.invoke(this@TextAreaNode) setText(lineProvider) } if (withVerticalScrollbar) { VerticalScrollbar { lazyListAware(listState, ScrollbarOrientation.Vertical, ListOrientation.Vertical, scrollbarColor, vScrollbarModifier) } } if (withHorizontalScrollbar) { HorizontalScrollbar { lazyListAware(listState, ScrollbarOrientation.Horizontal, ListOrientation.Vertical, scrollbarColor, hScrollbarModifier) } } } private fun setText(lineProvider: TextLineProvider) { val textAreaMod = [email protected] selectionHandler.updateSelectionRange() linesHolder.indices(lineProvider.size) { lineIndex -> val line = lineProvider[lineIndex] AttributedText(line) { modifier.width(Grow.MinFit) if ([email protected] != null) { modifier .onClick { when (it.pointer.leftButtonRepeatedClickCount) { 1 -> selectionHandler.onSelectStart(this, lineIndex, it, false) 2 -> selectionHandler.selectWord(this, line.text, lineIndex, it) 3 -> selectionHandler.selectLine(this, line.text, lineIndex) } } .onDragStart { selectionHandler.onSelectStart(this, lineIndex, it, true) } .onDrag { selectionHandler.onDrag(it) } .onDragEnd { selectionHandler.onSelectEnd() } .onPointer { selectionHandler.onPointer(this, lineIndex, it) } modifier.padding(start = textAreaMod.lineStartPadding, end = textAreaMod.lineEndPadding) if (lineIndex == lineProvider.lastIndex) { modifier .textAlignY(AlignmentY.Top) .padding(bottom = textAreaMod.lastLineBottomPadding) } selectionHandler.applySelectionRange(this, line, lineIndex) } } } } override fun onKeyEvent(keyEvent: InputManager.KeyEvent) { if (keyEvent.isCharTyped) { editText("${keyEvent.typedChar}") } else if (keyEvent.isPressed) { when (keyEvent.keyCode) { InputManager.KEY_BACKSPACE -> { if (selectionHandler.isEmptySelection) { selectionHandler.moveCaretLeft(wordWise = keyEvent.isCtrlDown, select = true) } editText("") } InputManager.KEY_DEL -> { if (selectionHandler.isEmptySelection) { selectionHandler.moveCaretRight(wordWise = keyEvent.isCtrlDown, select = true) } editText("") } InputManager.KEY_ENTER -> editText("\n") InputManager.KEY_NP_ENTER -> editText("\n") InputManager.KEY_CURSOR_LEFT -> selectionHandler.moveCaretLeft(wordWise = keyEvent.isCtrlDown, select = keyEvent.isShiftDown) InputManager.KEY_CURSOR_RIGHT -> selectionHandler.moveCaretRight(wordWise = keyEvent.isCtrlDown, select = keyEvent.isShiftDown) InputManager.KEY_CURSOR_UP -> selectionHandler.moveCaretLineUp(select = keyEvent.isShiftDown) InputManager.KEY_CURSOR_DOWN -> selectionHandler.moveCaretLineDown(select = keyEvent.isShiftDown) InputManager.KEY_PAGE_UP -> selectionHandler.moveCaretPageUp(select = keyEvent.isShiftDown) InputManager.KEY_PAGE_DOWN -> selectionHandler.moveCaretPageDown(select = keyEvent.isShiftDown) InputManager.KEY_HOME -> selectionHandler.moveCaretLineStart(select = keyEvent.isShiftDown) InputManager.KEY_END -> selectionHandler.moveCaretLineEnd(select = keyEvent.isShiftDown) InputManager.KEY_ESC -> { selectionHandler.clearSelection() surface.requestFocus(null) } else -> { if (keyEvent.isCtrlDown) { when (keyEvent.localKeyCode) { KEY_CODE_SELECT_ALL -> selectionHandler.selectAll() KEY_CODE_PASTE -> Clipboard.getStringFromClipboard { paste -> paste?.let { editText(it) } } KEY_CODE_COPY -> selectionHandler.copySelection()?.let { Clipboard.copyToClipboard(it) } KEY_CODE_CUT -> { selectionHandler.copySelection()?.let { Clipboard.copyToClipboard(it) editText("") } } else -> { } } } } } } } private fun editText(text: String) { val editor = modifier.editorHandler ?: return val caretPos = if (selectionHandler.isEmptySelection) { editor.insertText(selectionHandler.selectionCaretLine, selectionHandler.selectionCaretChar, text, this) } else { editor.replaceText( selectionHandler.selectionFromLine, selectionHandler.selectionToLine, selectionHandler.selectionFromChar, selectionHandler.selectionToChar, text, this ) } selectionHandler.selectionChanged(caretPos.y, caretPos.y, caretPos.x, caretPos.x) } private inner class SelectionHandler { private var isSelecting = false var selectionStartLine = 0 var selectionCaretLine = 0 var selectionStartChar = 0 var selectionCaretChar = 0 private val caretLine: TextLine? get() = if (selectionCaretLine in 0 until lineProvider.size) lineProvider[selectionCaretLine] else null private var caretLineScope: AttributedTextScope? = null val isReverseSelection: Boolean get() = selectionCaretLine < selectionStartLine val isEmptySelection: Boolean get() = selectionStartLine == selectionCaretLine && selectionStartChar == selectionCaretChar val selectionFromLine: Int get() = min(selectionStartLine, selectionCaretLine) val selectionToLine: Int get() = max(selectionStartLine, selectionCaretLine) val selectionFromChar: Int get() = when { isReverseSelection -> selectionCaretChar selectionStartLine == selectionCaretLine -> min(selectionStartChar, selectionCaretChar) else -> selectionStartChar } val selectionToChar: Int get() = when { isReverseSelection -> selectionStartChar selectionStartLine == selectionCaretLine -> max(selectionStartChar, selectionCaretChar) else -> selectionCaretChar } fun updateSelectionRange() { selectionStartLine = modifier.selectionStartLine selectionCaretLine = modifier.selectionCaretLine selectionStartChar = modifier.selectionStartChar selectionCaretChar = modifier.selectionCaretChar caretLineScope = null } fun applySelectionRange(attributedText: AttributedTextScope, line: TextLine, lineIndex: Int) { val from = selectionFromLine val to = selectionToLine var selCaretPos = 0 var selStartPos = 0 if (lineIndex in (from + 1) until to) { // line is completely in selection range selStartPos = 0 selCaretPos = line.length } else if (lineIndex == selectionStartLine && selectionStartLine == selectionCaretLine) { // single-line selection selStartPos = selectionStartChar selCaretPos = selectionCaretChar } else if (lineIndex == selectionFromLine) { // multi-line selection, first selected line if (isReverseSelection) { // reverse selection selStartPos = line.length selCaretPos = selectionCaretChar } else { // forward selection selStartPos = selectionStartChar selCaretPos = line.length } } else if (lineIndex == selectionToLine) { // multi-line selection, last selected line if (isReverseSelection) { // reverse selection selStartPos = selectionStartChar selCaretPos = 0 } else { // forward selection selStartPos = 0 selCaretPos = selectionCaretChar } } if (lineIndex == selectionCaretLine) { caretLineScope = attributedText } attributedText.modifier .selectionRange(selStartPos, selCaretPos) .isCaretVisible(isFocused.use() && lineIndex == selectionCaretLine) } fun copySelection(): String? { return if (isEmptySelection) { null } else if (selectionStartLine == selectionCaretLine) { // single-line selection val fromChar = min(selectionStartChar, selectionCaretChar) val toChar = max(selectionStartChar, selectionCaretChar) lineProvider[selectionFromLine].text.substring(fromChar, toChar) } else { // multi-line selection return buildString { append(lineProvider[selectionFromLine].text.substring(selectionFromChar)).append('\n') for (i in (selectionFromLine + 1) until selectionToLine) { append(lineProvider[i].text).append('\n') } append(lineProvider[selectionToLine].text.substring(0, selectionToChar)) } } } fun clearSelection() { selectionChanged(selectionCaretLine, selectionCaretLine, selectionCaretChar, selectionCaretChar, false) } fun selectAll() { selectionChanged(0, lineProvider.lastIndex, 0, lineProvider[lineProvider.lastIndex].length, false) } fun selectWord(attributedText: AttributedTextScope, text: String, lineIndex: Int, ev: PointerEvent) { val charIndex = attributedText.charIndexFromLocalX(ev.position.x) val startChar = TextCaretNavigation.startOfWord(text, charIndex) val caretChar = TextCaretNavigation.endOfWord(text, charIndex) caretLineScope = attributedText selectionChanged(lineIndex, lineIndex, startChar, caretChar) } fun selectLine(attributedText: AttributedTextScope, text: String, lineIndex: Int) { selectionChanged(lineIndex, lineIndex, 0, text.length) caretLineScope = attributedText } fun onSelectStart(attributedText: AttributedTextScope, lineIndex: Int, ev: PointerEvent, isSelecting: Boolean) { requestFocus() this.isSelecting = isSelecting val charIndex = attributedText.charIndexFromLocalX(ev.position.x) caretLineScope = attributedText selectionChanged(lineIndex, lineIndex, charIndex, charIndex) } fun onDrag(ev: PointerEvent) { caretLineScope?.apply { val dragLocalPos = MutableVec2f() uiNode.toLocal(ev.screenPosition, dragLocalPos) val charIndex = charIndexFromLocalX(dragLocalPos.x) selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, charIndex, false) } } fun onSelectEnd() { isSelecting = false } fun onPointer(attributedText: AttributedTextScope, lineIndex: Int, ev: PointerEvent) { if (isSelecting && ev.pointer.isDrag) { caretLineScope = attributedText selectionChanged(selectionStartLine, lineIndex, selectionStartChar, selectionCaretChar, false) } } fun moveCaretLeft(wordWise: Boolean, select: Boolean) { caretLine?.text?.let { txt -> if (selectionCaretChar == 0 && selectionCaretLine > 0) { selectionCaretLine-- val line = lineProvider[selectionCaretLine] val newTxt = line.text selectionCaretChar = line.length if (wordWise) { selectionCaretChar = TextCaretNavigation.moveWordLeft(newTxt, selectionCaretChar) } if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } } else if (wordWise) { selectionCaretChar = TextCaretNavigation.moveWordLeft(txt, selectionCaretChar) } else { selectionCaretChar = (selectionCaretChar - 1).clamp(0, txt.length) } } if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) } fun moveCaretRight(wordWise: Boolean, select: Boolean) { caretLine?.text?.let { txt -> if (selectionCaretChar == txt.length && selectionCaretLine < lineProvider.lastIndex) { selectionCaretLine++ val line = lineProvider[selectionCaretLine] val newTxt = line.text selectionCaretChar = 0 if (wordWise) { selectionCaretChar = TextCaretNavigation.moveWordRight(newTxt, selectionCaretChar) } if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } } else if (wordWise) { selectionCaretChar = TextCaretNavigation.moveWordRight(txt, selectionCaretChar) } else { selectionCaretChar = (selectionCaretChar + 1).clamp(0, txt.length) } } if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) } fun moveCaretLineUp(select: Boolean) { moveCaretToLine(selectionCaretLine - 1, select) } fun moveCaretLineDown(select: Boolean) { moveCaretToLine(selectionCaretLine + 1, select) } fun moveCaretPageUp(select: Boolean) { val bottomLinePad = 2 val numPageLines = max(1, linesHolder.state.numVisibleItems - bottomLinePad) moveCaretToLine(selectionCaretLine - numPageLines, select) } fun moveCaretPageDown(select: Boolean) { val bottomLinePad = 2 val numPageLines = max(1, linesHolder.state.numVisibleItems - bottomLinePad) moveCaretToLine(selectionCaretLine + numPageLines, select) } private fun moveCaretToLine(targetLine: Int, select: Boolean) { val line = caretLine ?: return val caretX = line.charIndexToPx(selectionCaretChar) if (targetLine in 0 until lineProvider.size) { selectionCaretChar = lineProvider[targetLine].charIndexFromPx(caretX) selectionCaretLine = targetLine } else if (targetLine < 0) { selectionCaretChar = 0 selectionCaretLine = 0 } else if (targetLine > lineProvider.lastIndex) { selectionCaretChar = lineProvider[lineProvider.lastIndex].length selectionCaretLine = lineProvider.lastIndex } if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) } fun moveCaretLineStart(select: Boolean) { selectionCaretChar = 0 if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) } fun moveCaretLineEnd(select: Boolean) { val line = caretLine ?: return selectionCaretChar = line.length if (!select) { selectionStartLine = selectionCaretLine selectionStartChar = selectionCaretChar } selectionChanged(selectionStartLine, selectionCaretLine, selectionStartChar, selectionCaretChar) } fun selectionChanged(startLine: Int, caretLine: Int, startChar: Int, caretChar: Int, scrollToCaret: Boolean = true) { selectionStartLine = startLine selectionCaretLine = caretLine selectionStartChar = startChar selectionCaretChar = caretChar if (startLine != modifier.selectionStartLine || caretLine != modifier.selectionCaretLine || startChar != modifier.selectionStartChar || caretChar != modifier.selectionCaretChar) { modifier.setSelectionRange(startLine, caretLine, startChar, caretChar) resetCaretBlinkState() if (scrollToCaret) { scrollToCaret() } } } fun resetCaretBlinkState() { (caretLineScope as? AttributedTextNode)?.resetCaretBlinkState() } fun scrollToCaret() { val scrState = linesHolder.state scrState.scrollToItem.set(selectionCaretLine) val scrollPad = 16f val caretX = Dp.fromPx(caretLine?.charIndexToPx(selectionCaretChar) ?: 0f).value val scrLt = scrState.xScrollDp.value val scrRt = scrState.xScrollDp.value + scrState.viewWidthDp.value if (caretX - scrollPad < scrLt) { scrState.scrollDpX(caretX - scrLt - scrollPad) } else if (caretX + scrollPad * 4 > scrRt) { scrState.scrollDpX(caretX - scrRt + scrollPad * 4) } } } companion object { private val KEY_CODE_SELECT_ALL = LocalKeyCode('a') private val KEY_CODE_CUT = LocalKeyCode('x') private val KEY_CODE_COPY = LocalKeyCode('c') private val KEY_CODE_PASTE = LocalKeyCode('v') val factory: (UiNode, UiSurface) -> TextAreaNode = { parent, surface -> TextAreaNode(parent, surface) } } } interface TextLineProvider { val size: Int val lastIndex: Int get() = size - 1 operator fun get(index: Int): TextLine } class ListTextLineProvider(val lines: MutableList<TextLine> = mutableStateListOf()) : TextLineProvider { override val size: Int get() = lines.size override operator fun get(index: Int) = lines[index] } interface TextEditorHandler { fun insertText(line: Int, caret: Int, insertion: String, textAreaScope: TextAreaScope): Vec2i fun replaceText(selectionStartLine: Int, selectionEndLine: Int, selectionStartChar: Int, selectionEndChar: Int, replacement: String, textAreaScope: TextAreaScope): Vec2i } class DefaultTextEditorHandler(val text: MutableList<TextLine> = mutableStateListOf()) : TextEditorHandler { var editAttribs: TextAttributes? = null override fun insertText(line: Int, caret: Int, insertion: String, textAreaScope: TextAreaScope): Vec2i { return replaceText(line, line, caret, caret, insertion, textAreaScope) } override fun replaceText( selectionStartLine: Int, selectionEndLine: Int, selectionStartChar: Int, selectionEndChar: Int, replacement: String, textAreaScope: TextAreaScope ): Vec2i { val startLine = this[selectionStartLine] ?: return Vec2i(selectionEndChar, selectionEndLine) val endLine = this[selectionEndLine] ?: return Vec2i(selectionEndChar, selectionEndLine) val before = startLine.before(selectionStartChar) val after = endLine.after(selectionEndChar) val caretPos = MutableVec2i() val attr = editAttribs ?: before.lastAttribs() ?: after.firstAttribs() ?: TextAttributes(MsdfFont.DEFAULT_FONT, Color.GRAY) val replaceLines = replacement.toLines(attr) caretPos.y = selectionStartLine + replaceLines.lastIndex val insertion = if (replaceLines.size == 1) { caretPos.x = before.length + replaceLines[0].length listOf(before + replaceLines[0] + after) } else { caretPos.x = replaceLines.last().length listOf(before + replaceLines[0]) + replaceLines.subList(1, replaceLines.lastIndex) + (replaceLines.last() + after) } insertLines(insertion, selectionStartLine, selectionEndLine) return caretPos } private fun insertLines(insertLines: List<TextLine>, insertFrom: Int, insertTo: Int) { val linesBefore = mutableListOf<TextLine>() val linesAfter = mutableListOf<TextLine>() if (insertFrom > 0) { linesBefore += text.subList(0, insertFrom) } if (insertTo < text.lastIndex) { linesAfter += text.subList(insertTo + 1, text.size) } text.clear() text += linesBefore text += insertLines text += linesAfter } fun String.toLines(attributes: TextAttributes): List<TextLine> { return lines().map { str -> TextLine(listOf(str to attributes)) } } operator fun get(line: Int): TextLine? { return if (text.isEmpty()) { null } else { text[line.clamp(0, text.lastIndex)] } } operator fun TextLine.plus(other: TextLine): TextLine { return TextLine(sanitize(spans + other.spans)) } fun TextLine.firstAttribs(): TextAttributes? { return if (spans.isNotEmpty()) { spans.first().second } else { null } } fun TextLine.lastAttribs(): TextAttributes? { return if (spans.isNotEmpty()) { spans.last().second } else { null } } fun TextLine.before(charIndex: Int): TextLine { val newSpans = mutableListOf<Pair<String, TextAttributes>>() var i = 0 var spanI = 0 while (spanI < spans.size && i + spans[spanI].first.length < charIndex) { newSpans += spans[spanI] i += spans[spanI].first.length spanI++ } newSpans += spans[spanI].before(charIndex - i) return TextLine(sanitize(newSpans)) } fun TextLine.after(charIndex: Int): TextLine { val newSpans = mutableListOf<Pair<String, TextAttributes>>() var i = 0 var spanI = 0 while (spanI < spans.size && i + spans[spanI].first.length < charIndex) { i += spans[spanI].first.length spanI++ } if (spanI < spans.size) { newSpans += spans[spanI].after(charIndex - i) for (j in spanI + 1 until spans.size) { newSpans += spans[j] } } return TextLine(sanitize(newSpans)) } fun TextLine.append(text: String): TextLine { val newSpans = mutableListOf<Pair<String, TextAttributes>>() newSpans += spans newSpans[spans.lastIndex] = spans.last().append(text) return TextLine(sanitize(newSpans)) } fun Pair<String, TextAttributes>.before(index: Int): Pair<String, TextAttributes> { return first.substring(0, index) to second } fun Pair<String, TextAttributes>.after(index: Int): Pair<String, TextAttributes> { return first.substring(index) to second } fun Pair<String, TextAttributes>.append(text: String): Pair<String, TextAttributes> { return (first + text) to second } fun sanitize(spans: List<Pair<String, TextAttributes>>): List<Pair<String, TextAttributes>> { val newSpans = mutableListOf<Pair<String, TextAttributes>>() if (spans.isNotEmpty()) { var prevSpan = spans[0] newSpans += prevSpan for (i in 1 until spans.size) { val span = spans[i] if (span.second == prevSpan.second) { prevSpan = prevSpan.append(span.first) newSpans[newSpans.lastIndex] = prevSpan } else if (span.first.isNotEmpty()) { prevSpan = span newSpans += span } } } if (newSpans.size > 1 && newSpans[0].first.isEmpty()) { newSpans.removeAt(0) } return newSpans } }
apache-2.0
36aa7b529dd032a3211d9810ee32d064
39.846354
173
0.604897
4.985537
false
false
false
false
byu-oit-appdev/android-byu-suite-v2
support/src/main/java/edu/byu/support/utils/Extensions.kt
1
11552
package edu.byu.support.utils import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.graphics.Point import android.location.Location import android.os.Build import android.os.Parcel import android.text.Html import android.text.Spanned import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import edu.byu.support.R import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit import java.util.regex.Pattern import kotlin.math.PI import kotlin.math.cos import kotlin.math.pow /** * Created by geogor37 on 2/27/18 */ // Words that shouldn't follow normal title case rules private val REPLACEMENTS = arrayOf("and", "for", "in", "McDonald", "McKay", "of", "the", "www", "YNews", "to") // Make the replacements case insensitive. Also check to make sure we didn't just find the string inside another word. Should be used with the strings in REPLACEMENTS private const val REPLACEMENT_REGEX = "(?i)(?<=\\b)%s(?=\\b)" // Words that should be left as all caps. This assumes that the string passed in is already all caps private val EXCEPTIONS = arrayOf("BYU", "BYUSA", "CAEDM", "CB", "CIO", "CITES", "CES", "CNA", "CTB", "DNA", "FLAS", "FM", "ICLA", "ID", "KBYU", "LDS", "MTC", "MPH", "N7BYU", "NMELRC", "OIT", "ORCA", "RB", "ROTC", "SAS", "SFH", "TEC", "TV", "WSC", "YSA") private const val RADIUS_EARTH_METERS = 6378000 /** * FIRST CAPTURING GROUP: (^|[ (/-]) * This is the list of characters that should be followed by a capital. ^ is the start of the string but if we put it inside the brackets it means not, so we have to leave it outside the brackets. * Putting it inside and escaping it doesn't work because that just makes it the literal ^ character. Then we have that or a space, opening parenthesis, slash, or dash. The dash has to be at the end * (right before the closing bracket) or else it is interpreted as all the characters between the two surrounding characters (e.g. [a-e] is a, b, c, d, and e and [ae-] is a, e, and -. * SECOND (NOT CAPTURING) GROUP: (?!(?:" + EXCEPTIONS.joinToString("|") + ")[ (/-]) * (?!example) negative lookahead - don't match if the next thing is example * (" + EXCEPTIONS.joinToString("|") + ")\\b) The exceptions are all the things that we want to stay in all caps (again, this assumes that the input string is all caps, which is the case in * Department Directory. This ors all of them together. Then it makes sure that the exception found is not the beginning of another word by checking for a word boundary (\b). We know this is at * the start of a word because of the first capturing group, this makes sure it's not just at the start of another word * SECOND CAPTURING GROUP: ([a-zA-Z]) * Captures the first letter of the word, so we can capitalize it * THIRD CAPTURING GROUP: ([\\w'\\.]*) * Capture the rest of the word (including apostrophes, periods (for web addresses), and possibly numbers) so we can lowercase it */ private val PATTERN = Pattern.compile("(^|[ (/-])(?!(?:" + EXCEPTIONS.joinToString("|") + ")\\b)([a-zA-Z])([\\w'.]*)") fun AlertDialog.Builder.setPositiveButton(callback: (DialogInterface, Int) -> Unit): AlertDialog.Builder { return this.setPositiveButton(android.R.string.ok, callback) } fun Boolean?.orFalse(): Boolean { return this == true } fun Activity.hideKeyboard() { try { (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(currentFocus.windowToken, 0) } catch (ignore: NullPointerException) { } } fun Date.isBetween(startDate: Date?, endDate: Date?): Boolean { return (startDate?.before(this).orFalse() || startDate == this) && (endDate?.after(this).orFalse() || endDate == this) } fun Date.format(pattern: String): String { return SimpleDateFormat(pattern, Locale.US).format(this) } fun Date.getDayOfWeek(): String { return format("EEEE") } fun Date?.getElapsedTimeSince(): String { if (this == null) { return "In progress" } val millis = Date().time - time val minutes = TimeUnit.MILLISECONDS.toMinutes(millis).toInt() val hours = TimeUnit.MILLISECONDS.toHours(millis).toInt() val days = TimeUnit.MILLISECONDS.toDays(millis).toInt() val months = days / 30 val years = days / 365 return when { minutes < 1 -> "moments" hours < 1 -> "$minutes minute${getPluralSuffix(minutes > 1)}" days < 1 -> "$hours hour${getPluralSuffix(hours > 1)}" months < 1 -> "$days day${getPluralSuffix(days > 1)}" years < 1 -> "$months month${getPluralSuffix(months > 1)}" else -> "$years year${getPluralSuffix(years > 1)}" } } private fun getPluralSuffix(isPlural: Boolean): String = if (isPlural) "s" else "" /** * Returns an integer equivalent to the first specified number of digits. (e.g. 123.firstXDigits(2) returns 12 * * @return An integer equivalent to the first specified number of digits, null if number of digits is non-positive */ fun Int.firstXDigits(numDigits: Int): Int? { return if (numDigits > 0) { var firstDigits = this while (firstDigits >= (10 * numDigits)) { firstDigits /= 10 } firstDigits } else { null } } /** * @return Number of digits in an integer */ fun Int.numDigits(): Int { if (this == 0) { return 1 } var length = 0 var temp: Long = 1 while (temp <= Math.abs(this)) { length++ temp *= 10 } return length } /** * @return the distance between the two points in meters as a float */ fun LatLng.distanceTo(other: LatLng): Float { //Results of the Location.distanceBetween is stored in the results array val results = FloatArray(1) Location.distanceBetween(latitude, longitude, other.latitude, other.longitude, results) return results[0] } /** * This returns new bounds that ensures that the zoom level passed in is not exceeded. The documentation on zoom level explains that a zoom level 1 will show * the whole Earth and that each zoom level after that shows half of the previous zoom level. Using this we can determine that the the meters shown is the result * of the function (2 * EARTH_DIAMETER) / (2^zoomLevel)). We then can ensure that at least that many meters are shown while maintaining the center of the original * bounds in the center. * * @return LatLngBounds that include the area viewable from the minimum zoom */ fun LatLngBounds.Builder.adjustToMaxZoom(bounds: LatLngBounds, zoom: Float): LatLngBounds { // This calculates the number of meters shown on the screen at a given zoom level // The equation is (2 * EARTH_DIAMETER) / (2^zoomLevel)) val meters = ((RADIUS_EARTH_METERS * 4).toFloat() / (2f.pow(zoom))).toDouble() // This calculates where the new boundary corners should be to maintain the given zoom val newLatitude1 = bounds.center.latitude + (((meters / 2) / RADIUS_EARTH_METERS) * (180 / PI)) val newLongitude1 = bounds.center.longitude + ((meters / 2) / RADIUS_EARTH_METERS) * (180 / PI) / cos(bounds.center.latitude * PI / 180) val newLatitude2 = bounds.center.latitude + (((-meters / 2) / RADIUS_EARTH_METERS) * (180 / PI)) val newLongitude2 = bounds.center.longitude + ((-meters / 2) / RADIUS_EARTH_METERS) * (180 / PI) / cos(bounds.center.latitude * PI / 180) include(LatLng(newLatitude1, newLongitude1)) include(LatLng(newLatitude2, newLongitude2)) // Include previous bounds so that if it is bigger than the zoom window it doesn't zoom in include(bounds.northeast) include(bounds.southwest) return build() } /** * This computes the next day with the given name. It should only be called on a string that represents a day in the week ("Monday", "Tuesday", etc.) * * @return Date object of the next day with the given name and null if the day is invalid */ fun String.getNextDateWithDayName(): Date? { val calendar = GregorianCalendar() calendar.time = Date() calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) return getNumDaysUntilDay()?.let { calendar.add(Calendar.DATE, it) return calendar.time } } /** * How many days in the future is the next occurrence of day. It should only be called on a string that represents a day in the week ("Monday", "Tuesday", etc.) * * @return Int of the number of days until the next occurrence of that day, null if the day is invalid */ fun String.getNumDaysUntilDay(): Int? { val today = Date().getDayOfWeek() val daysOfWeek = arrayListOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") return if (daysOfWeek.contains(this.toLowerCase())) ((daysOfWeek.indexOf(this.toLowerCase()) - daysOfWeek.indexOf(today.toLowerCase()) + 7) % 7) else null } /** * @return A string that has been changed to title case */ fun String.toTitleCase(): String { val matcher = PATTERN.matcher(this) val stringBuffer = StringBuffer() // Find the next match in the string while (matcher.find()) { // append everything we skipped, and then append group 1 (the delimiter that separated this match from the last word), group 2 (the first letter) uppercased, and group 3 (the rest of the word) lowercased matcher.appendReplacement(stringBuffer, matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3).toLowerCase()) } // append the rest of the string matcher.appendTail(stringBuffer) return stringBuffer.toString().titleCaseExceptionCorrection() } private fun String.titleCaseExceptionCorrection(): String { var returnString = this REPLACEMENTS.forEach { returnString = returnString.replace(String.format(REPLACEMENT_REGEX, it).toRegex(), it) } return returnString } @Suppress("DEPRECATION") fun String.fromHtml() = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY) else Html.fromHtml(this)).trim() as? Spanned fun <DataType> Spinner.setUpAdapter(context: Context, list: List<DataType>?, onItemSelectedListener: AdapterView.OnItemSelectedListener?): ArrayAdapter<DataType> { val arrayAdapter = ArrayAdapter<DataType>(context, R.layout.byu_simple_spinner_dropdown_item, list.orEmpty()) arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) onItemSelectedListener?.let { setOnItemSelectedListener(it) } adapter = arrayAdapter return arrayAdapter } fun Context.inflate(parent: ViewGroup?, layoutResId: Int): View = LayoutInflater.from(this).inflate(layoutResId, parent, false) fun Activity.getDisplaySize(): Point { val display = windowManager.defaultDisplay val size = Point() display.getSize(size) return size } fun Parcel.writeBoolean(boolean: Boolean) = writeByte(if (boolean) 1 else 0) fun Parcel.readBoolean() = readByte().compareTo(0) != 0 fun Parcel.writeBoolean(boolean: Boolean?) = writeInt(when (boolean) { null -> 0 false -> 1 true -> 2 }) fun Parcel.readBooleanOpt() = when (readInt()) { 0 -> null 1 -> false else -> true } fun Parcel.writeDouble(double: Double?) = writeValue(double) fun Parcel.readDoubleOpt() = readValue(Double::class.java.classLoader) as? Double fun Parcel.writeInt(int: Int?) = writeValue(int) fun Parcel.readIntOpt() = readValue(Int::class.java.classLoader) as? Int fun Parcel.writeDate(date: Date?) = writeValue(date?.time) fun Parcel.readDate() = (readValue(Long::class.java.classLoader) as? Long)?.let { Date(it) }
apache-2.0
b415998007c135de70912c10df5d4aa2
39.533333
205
0.727407
3.59204
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt
1
21298
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.rename import com.google.gson.JsonObject import com.google.gson.JsonParser.parseString import com.intellij.codeInsight.TargetElementUtil import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.lang.properties.psi.Property import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.psi.* import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.BaseRefactoringProcessor.ConflictsInTestsException import com.intellij.refactoring.rename.* import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory import com.intellij.refactoring.util.CommonRefactoringUtil.RefactoringErrorHintException import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.fixtures.CodeInsightTestUtil import org.jetbrains.kotlin.asJava.finder.KtLightPackage import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts import org.jetbrains.kotlin.idea.base.util.allScope import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.jsonUtils.getNullableString import org.jetbrains.kotlin.idea.jsonUtils.getString import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.* import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.junit.Assert import java.io.File enum class RenameType { JAVA_CLASS, JAVA_METHOD, KOTLIN_CLASS, KOTLIN_FUNCTION, KOTLIN_PROPERTY, KOTLIN_PACKAGE, MARKED_ELEMENT, FILE, BUNDLE_PROPERTY, AUTO_DETECT } abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { inner class TestContext( val testFile: File, val project: Project = getProject(), val javaFacade: JavaPsiFacade = myFixture.javaFacade, val module: Module = myFixture.module ) override fun getProjectDescriptor(): LightProjectDescriptor { val testConfigurationFile = File(testDataPath, fileName()) val renameObject = loadTestConfiguration(testConfigurationFile) val withRuntime = renameObject.getNullableString("withRuntime") val libraryInfos = renameObject.getAsJsonArray("libraries")?.map { it.asString!! } if (libraryInfos != null) { val jarPaths = listOf(TestKotlinArtifacts.kotlinStdlib) + libraryInfos.map { File(PlatformTestUtil.getCommunityPath(), it.substringAfter("@")) } return KotlinWithJdkAndRuntimeLightProjectDescriptor(jarPaths, listOf(TestKotlinArtifacts.kotlinStdlibSources)) } if (withRuntime != null) { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } return KotlinLightProjectDescriptor.INSTANCE } open fun doTest(path: String) { val testFile = File(path) val renameObject = loadTestConfiguration(testFile) val renameTypeStr = renameObject.getString("type") val hintDirective = renameObject.getNullableString("hint") val fixtureClasses = renameObject.getAsJsonArray("fixtureClasses")?.map { it.asString } ?: emptyList() try { fixtureClasses.forEach { TestFixtureExtension.loadFixture(it, module) } val context = TestContext(testFile) when (RenameType.valueOf(renameTypeStr)) { RenameType.JAVA_CLASS -> renameJavaClassTest(renameObject, context) RenameType.JAVA_METHOD -> renameJavaMethodTest(renameObject, context) RenameType.KOTLIN_CLASS -> renameKotlinClassTest(renameObject, context) RenameType.KOTLIN_FUNCTION -> renameKotlinFunctionTest(renameObject, context) RenameType.KOTLIN_PROPERTY -> renameKotlinPropertyTest(renameObject, context) RenameType.KOTLIN_PACKAGE -> renameKotlinPackageTest(renameObject, context) RenameType.MARKED_ELEMENT -> renameMarkedElement(renameObject, context) RenameType.FILE -> renameFile(renameObject, context) RenameType.BUNDLE_PROPERTY -> renameBundleProperty(renameObject, context) RenameType.AUTO_DETECT -> renameWithAutoDetection(renameObject, context) } if (hintDirective != null) { Assert.fail("""Hint "$hintDirective" was expected""") } if (renameObject["checkErrorsAfter"]?.asBoolean == true) { val psiManager = myFixture.psiManager val visitor = object : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { (psiManager.findFile(file) as? KtFile)?.let { DirectiveBasedActionUtils.checkForUnexpectedErrors(it) } return true } } for (sourceRoot in ModuleRootManager.getInstance(module).sourceRoots) { VfsUtilCore.visitChildrenRecursively(sourceRoot, visitor) } } } catch (e: Exception) { if (e !is RefactoringErrorHintException && e !is ConflictsInTestsException) throw e val hintExceptionUnquoted = StringUtil.unquoteString(e.message!!) if (hintDirective != null) { Assert.assertEquals(hintDirective, hintExceptionUnquoted) } else { Assert.fail("""Unexpected "hint: $hintExceptionUnquoted" """) } } finally { fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) } } } protected open fun configExtra(rootDir: VirtualFile, renameParamsObject: JsonObject) { } private fun renameMarkedElement(renameParamsObject: JsonObject, context: TestContext) { val mainFilePath = renameParamsObject.getString("mainFile") doTestCommittingDocuments(context) { rootDir -> configExtra(rootDir, renameParamsObject) val psiFile = myFixture.configureFromTempProjectFile(mainFilePath) doRenameMarkedElement(renameParamsObject, psiFile) } } private fun renameJavaClassTest(renameParamsObject: JsonObject, context: TestContext) { val classFQN = renameParamsObject.getString("classId").toClassId().asSingleFqName().asString() val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val aClass = context.javaFacade.findClass(classFQN, context.project.allScope())!! val substitution = RenamePsiElementProcessor.forElement(aClass).substituteElementToRename(aClass, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameJavaMethodTest(renameParamsObject: JsonObject, context: TestContext) { val classFQN = renameParamsObject.getString("classId").toClassId().asSingleFqName().asString() val methodSignature = renameParamsObject.getString("methodSignature") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val aClass = context.javaFacade.findClass(classFQN, GlobalSearchScope.moduleScope(context.module))!! val methodText = context.javaFacade.elementFactory.createMethodFromText("$methodSignature{}", null) val method = aClass.findMethodBySignature(methodText, false) if (method == null) throw IllegalStateException("Method with signature '$methodSignature' wasn't found in class $classFQN") val substitution = RenamePsiElementProcessor.forElement(method).substituteElementToRename(method, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, false, false) } } private fun renameKotlinFunctionTest(renameParamsObject: JsonObject, context: TestContext) { val oldMethodName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> scope.getContributedFunctions( oldMethodName, NoLookupLocation.FROM_TEST ).first() } } private fun renameKotlinPropertyTest(renameParamsObject: JsonObject, context: TestContext) { val oldPropertyName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> scope.getContributedVariables( oldPropertyName, NoLookupLocation.FROM_TEST ).first() } } private fun renameKotlinClassTest(renameParamsObject: JsonObject, context: TestContext) { renameParamsObject.getString("classId") //assertion doRenameInKotlinClassOrPackage(renameParamsObject, context) { declaration, _ -> declaration as ClassDescriptor } } private fun renameKotlinPackageTest(renameParamsObject: JsonObject, context: TestContext) { val fqn = FqNameUnsafe(renameParamsObject.getString("fqn")).toSafe() val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" doTestCommittingDocuments(context) { val mainFile = myFixture.configureFromTempProjectFile(mainFilePath) as KtFile val fileFqn = mainFile.packageFqName Assert.assertTrue("File '${mainFilePath}' should have package containing ${fqn}", fileFqn.isSubpackageOf(fqn)) val packageDirective = mainFile.packageDirective!! val packageSegment = packageDirective.packageNames[fqn.pathSegments().size - 1] val segmentReference = packageSegment.mainReference val psiElement = segmentReference.resolve() ?: error("unable to resolve '${segmentReference.element.text}' from $packageDirective '${packageDirective.text}'") val substitution = RenamePsiElementProcessor.forElement(psiElement).substituteElementToRename(psiElement, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameFile(renameParamsObject: JsonObject, context: TestContext) { val file = renameParamsObject.getString("file") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val psiFile = myFixture.configureFromTempProjectFile(file) runRenameProcessor(context.project, newName, psiFile, renameParamsObject, true, true) } } private fun renameBundleProperty(renameParamsObject: JsonObject, context: TestContext) { val file = renameParamsObject.getString("file") val oldName = renameParamsObject.getString("oldName") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val mainFile = myFixture.configureFromTempProjectFile(file) as PropertiesFile val property = mainFile.findPropertyByKey(oldName) as Property runRenameProcessor(context.project, newName, property, renameParamsObject, true, true) } } private fun doRenameInKotlinClassOrPackage( renameParamsObject: JsonObject, context: TestContext, findDescriptorToRename: (DeclarationDescriptor, MemberScope) -> DeclarationDescriptor ) { val classIdStr = renameParamsObject.getNullableString("classId") val packageFqnStr = renameParamsObject.getNullableString("packageFqn") if (classIdStr != null && packageFqnStr != null) { throw AssertionError("Both classId and packageFqn are defined. Where should I search: in class or in package?") } else if (classIdStr == null && packageFqnStr == null) { throw AssertionError("Define classId or packageFqn") } val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" doTestCommittingDocuments(context) { val ktFile = myFixture.configureFromTempProjectFile(mainFilePath) as KtFile val module = ktFile.analyzeWithAllCompilerChecks().moduleDescriptor val (declaration, scopeToSearch) = if (classIdStr != null) { module.findClassAcrossModuleDependencies(classIdStr.toClassId())!!.let { it to it.defaultType.memberScope } } else { module.getPackage(FqName(packageFqnStr!!)).let { it to it.memberScope } } val psiElement = DescriptorToSourceUtils.descriptorToDeclaration(findDescriptorToRename(declaration, scopeToSearch))!! // The Java processor always chooses renaming the base element when running in unit test mode, // so if we want to rename only the inherited element, we need to skip the substitutor. val skipSubstitute = renameParamsObject["skipSubstitute"]?.asBoolean ?: false val substitution = if (skipSubstitute) psiElement else RenamePsiElementProcessor.forElement(psiElement).substituteElementToRename(psiElement, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameWithAutoDetection(renameParamsObject: JsonObject, context: TestContext) { val mainFilePath = renameParamsObject.getString("mainFile") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { rootDir -> configExtra(rootDir, renameParamsObject) val psiFile = myFixture.configureFromTempProjectFile(mainFilePath) val doc = PsiDocumentManager.getInstance(project).getDocument(psiFile)!! val marker = doc.extractMarkerOffset(project, "/*rename*/") assert(marker != -1) editor.caretModel.moveToOffset(marker) val currentCaret = editor.caretModel.currentCaret val dataContext = createTextEditorBasedDataContext(project, editor, currentCaret) { add(PsiElementRenameHandler.DEFAULT_NAME, newName) } var handler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext) ?: return@doTestCommittingDocuments Assert.assertTrue(handler.isAvailableOnDataContext(dataContext)) if (handler is KotlinRenameDispatcherHandler) { handler = handler.getRenameHandler(dataContext)!! } if (handler is VariableInplaceRenameHandler) { val elementToRename = psiFile.findElementAt(currentCaret.offset)!!.getNonStrictParentOfType<PsiNamedElement>()!! CodeInsightTestUtil.doInlineRename(handler, newName, editor, elementToRename) } else { handler.invoke(project, editor, psiFile, dataContext) } } } protected fun getTestDirName(lowercaseFirstLetter: Boolean): String { val testName = getTestName(lowercaseFirstLetter) return testName.substring(0, testName.indexOf('_')) } protected fun doTestCommittingDocuments(context: TestContext, action: (VirtualFile) -> Unit) { val beforeDir = context.testFile.parentFile.name + "/before" val beforeVFile = myFixture.copyDirectoryToProject(beforeDir, "") PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments() val afterDir = File(context.testFile.parentFile, "after") action(beforeVFile) PsiDocumentManager.getInstance(project).commitAllDocuments() FileDocumentManager.getInstance().saveAllDocuments() val afterVFile = LocalFileSystem.getInstance().findFileByIoFile(afterDir)?.apply { UsefulTestCase.refreshRecursively(this) } ?: error("`after` directory not found") PlatformTestUtil.assertDirectoriesEqual(afterVFile, beforeVFile) } } private fun String.toClassId(): ClassId { val relativeClassName = FqName(substringAfterLast('/')) val packageFqName = FqName(substringBeforeLast('/', "").replace('/', '.')) return ClassId(packageFqName, relativeClassName, false) } fun loadTestConfiguration(testFile: File): JsonObject { val fileText = FileUtil.loadFile(testFile, true) return parseString(fileText) as JsonObject } fun runRenameProcessor( project: Project, newName: String, substitution: PsiElement?, renameParamsObject: JsonObject, isSearchInComments: Boolean, isSearchTextOccurrences: Boolean ) { if (substitution == null) return fun createProcessor(): BaseRefactoringProcessor { if (substitution is PsiPackage && substitution !is KtLightPackage) { val oldName = substitution.qualifiedName if (StringUtil.getPackageName(oldName) != StringUtil.getPackageName(newName)) { return RenamePsiPackageProcessor.createRenameMoveProcessor( newName, substitution, isSearchInComments, isSearchTextOccurrences ) } } return RenameProcessor(project, substitution, newName, isSearchInComments, isSearchTextOccurrences) } val processor = createProcessor() if (renameParamsObject["overloadRenamer.onlyPrimaryElement"]?.asBoolean == true) { with(AutomaticOverloadsRenamer) { substitution.elementFilter = { false } } } if (processor is RenameProcessor) { @Suppress("DEPRECATION") Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME).forEach { processor.addRenamerFactory(it) } } processor.run() } fun doRenameMarkedElement(renameParamsObject: JsonObject, psiFile: PsiFile) { val project = psiFile.project val newName = renameParamsObject.getString("newName") val doc = PsiDocumentManager.getInstance(project).getDocument(psiFile)!! val marker = doc.extractMarkerOffset(project, "/*rename*/") assert(marker != -1) val editorFactory = EditorFactory.getInstance() var editor = editorFactory.getEditors(doc).firstOrNull() var shouldReleaseEditor = false if (editor == null) { editor = editorFactory.createEditor(doc) shouldReleaseEditor = true } try { val isByRef = renameParamsObject["byRef"]?.asBoolean ?: false val isInjected = renameParamsObject["injected"]?.asBoolean ?: false var currentEditor = editor!! var currentFile: PsiFile = psiFile if (isByRef || isInjected) { currentEditor.caretModel.moveToOffset(marker) if (isInjected) { currentFile = InjectedLanguageUtil.findInjectedPsiNoCommit(psiFile, marker)!! currentEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, currentFile) } } val toRename = if (isByRef) { TargetElementUtil.findTargetElement(currentEditor, TargetElementUtil.getInstance().allAccepted)!! } else { currentFile.findElementAt(marker)!!.getNonStrictParentOfType<PsiNamedElement>()!! } val substitution = RenamePsiElementProcessor.forElement(toRename).substituteElementToRename(toRename, null) val searchInComments = renameParamsObject["searchInComments"]?.asBoolean ?: true val searchInTextOccurrences = renameParamsObject["searchInTextOccurrences"]?.asBoolean ?: true runRenameProcessor(project, newName, substitution, renameParamsObject, searchInComments, searchInTextOccurrences) } finally { if (shouldReleaseEditor) { editorFactory.releaseEditor(editor!!) } } }
apache-2.0
6ce9e2ad7fd716ca19e7ec486adf046b
44.802151
170
0.70739
5.35664
false
true
false
false
JetBrains/xodus
query/src/main/kotlin/jetbrains/exodus/query/QueryEngine.kt
1
17367
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.query import jetbrains.exodus.entitystore.Entity import jetbrains.exodus.entitystore.EntityIterable import jetbrains.exodus.entitystore.PersistentEntityStoreImpl import jetbrains.exodus.entitystore.StoreTransaction import jetbrains.exodus.entitystore.iterate.EntityIdSet import jetbrains.exodus.entitystore.iterate.EntityIterableBase import jetbrains.exodus.entitystore.iterate.EntityIterableBase.EMPTY import jetbrains.exodus.entitystore.iterate.SingleEntityIterable import jetbrains.exodus.entitystore.util.EntityIdSetFactory import jetbrains.exodus.kotlin.notNull import jetbrains.exodus.query.Or.Companion.or import jetbrains.exodus.query.Utils.isTypeOf import jetbrains.exodus.query.metadata.ModelMetaData import jetbrains.exodus.util.doIfTrue import mu.KLogging open class QueryEngine(val modelMetaData: ModelMetaData?, val persistentStore: PersistentEntityStoreImpl) : KLogging() { private var _sortEngine: SortEngine? = null open var sortEngine: SortEngine? get() = _sortEngine set(value) { _sortEngine = value.notNull.apply { queryEngine = this@QueryEngine } } val uniqueKeyIndicesEngine = MetaDataAwareUniqueKeyIndicesEngine(persistentStore, modelMetaData) open fun queryGetAll(entityType: String): TreeKeepingEntityIterable = query(null, entityType, NodeFactory.all()) open fun query(entityType: String, tree: NodeBase): TreeKeepingEntityIterable = query(null, entityType, tree) open fun query(instance: Iterable<Entity>?, entityType: String, tree: NodeBase): TreeKeepingEntityIterable { return TreeKeepingEntityIterable(instance, entityType, tree, this) } open fun intersect(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { if (left === right) { return left } if (left.isEmpty || right.isEmpty) { return EMPTY } if (left is TreeKeepingEntityIterable) { val leftType = left.getEntityType() if (right is TreeKeepingEntityIterable) { if (left.instance === right.instance) { val rightType = right.getEntityType() if (isTypeOf(leftType, rightType, modelMetaData.notNull)) { return TreeKeepingEntityIterable( right.instance, leftType, And.and(left.tree, right.tree), left.annotatedTree, right.annotatedTree, this ) } else if (isTypeOf(rightType, leftType, modelMetaData.notNull)) { return TreeKeepingEntityIterable( right.instance, rightType, And.and(left.tree, right.tree), left.annotatedTree, right.annotatedTree, this ) } } } } var staticType: String? = null if (left is StaticTypedEntityIterable) { val leftType = left.getEntityType() if (right is StaticTypedEntityIterable) { val rightType = right.getEntityType() if (isTypeOf(rightType, leftType, modelMetaData.notNull)) { staticType = rightType } else if (isTypeOf(leftType, rightType, modelMetaData.notNull)) { staticType = leftType } if (leftType == rightType) { if (left.isGetAllTree) { return ExcludeNullStaticTypedEntityIterable(rightType, right, this) } if (right.isGetAllTree) { return ExcludeNullStaticTypedEntityIterable(leftType, left, this) } } } } val result = intersectNonTrees(instantiateAndAdjust(left), instantiateAndAdjust(right)) return staticType?.let { StaticTypedIterableDecorator(staticType, result, this) } ?: result } open fun union(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { if (left === right) { return left } if (left.isEmpty) { return right } if (right.isEmpty) { return left } if (left is TreeKeepingEntityIterable) { val leftType = left.getEntityType() if (right is TreeKeepingEntityIterable) { if (left.instance === right.instance && leftType == right.getEntityType()) { return TreeKeepingEntityIterable( right.instance, leftType, or(left.tree, right.tree), left.annotatedTree, right.annotatedTree, this ) } } } var staticType: String? = null if (left is StaticTypedEntityIterable) { val leftType = left.getEntityType() if (right is StaticTypedEntityIterable) { val rightType = right.getEntityType() if (leftType == rightType) { staticType = rightType if (left.isGetAllTree) { return AddNullStaticTypedEntityIterable(staticType, left, right, this) } if (right.isGetAllTree) { return AddNullStaticTypedEntityIterable(staticType, right, left, this) } } } } val result = unionNonTrees(instantiateAndAdjust(left), instantiateAndAdjust(right)) return staticType?.let { StaticTypedIterableDecorator(staticType, result, this) } ?: result } open fun concat(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { if (left.isEmpty) { return right } if (right.isEmpty) { return left } if (left is TreeKeepingEntityIterable) { val leftType = left.getEntityType() if (right is TreeKeepingEntityIterable) { if (left.instance === right.instance && leftType == right.getEntityType()) { return TreeKeepingEntityIterable( right.instance, leftType, Concat(left.tree, right.tree), left.annotatedTree, right.annotatedTree, this ) } } } val staticType = retrieveStaticType(left, right) val result = concatNonTrees(instantiateAndAdjust(left), instantiateAndAdjust(right)) return staticType?.let { StaticTypedIterableDecorator(staticType, result, this) } ?: result } open fun exclude(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { if (left.isEmpty || left === right) { return EMPTY } if (right.isEmpty) { return left } if (left is TreeKeepingEntityIterable) { val leftType = left.getEntityType() if (right is TreeKeepingEntityIterable) { if (left.instance === right.instance && leftType == right.getEntityType()) { return TreeKeepingEntityIterable( right.instance, leftType, Minus(left.tree, right.tree), left.annotatedTree, right.annotatedTree, this ) } } } val staticType = retrieveStaticType(left, right) val result = excludeNonTrees(instantiateAndAdjust(left), instantiateAndAdjust(right)) return staticType?.let { StaticTypedIterableDecorator(staticType, result, this) } ?: result } open fun selectDistinct(it: Iterable<Entity>?, linkName: String): Iterable<Entity> { it ?: return EMPTY if (modelMetaData != null) { if (it is StaticTypedEntityIterable) { val entityType = it.getEntityType() toEntityIterable(it).let { if (it.isPersistent) { val emd = modelMetaData.getEntityMetaData(entityType) if (emd != null) { emd.getAssociationEndMetaData(linkName)?.let { aemd -> return StaticTypedIterableDecorator( aemd.oppositeEntityMetaData.type, selectDistinctImpl(it as EntityIterableBase, linkName), this ) } } } } } else if (it.isPersistent) { return selectDistinctImpl(it as EntityIterableBase, linkName) } } return inMemorySelectDistinct(it, linkName) } open fun selectManyDistinct(it: Iterable<Entity>?, linkName: String): Iterable<Entity> { it ?: return EMPTY if (modelMetaData != null) { if (it is StaticTypedEntityIterable) { val entityType = it.getEntityType() toEntityIterable(it).let { if (it.isPersistent) { val emd = modelMetaData.getEntityMetaData(entityType) if (emd != null) { emd.getAssociationEndMetaData(linkName)?.let { aemd -> return StaticTypedIterableDecorator( aemd.oppositeEntityMetaData.type, selectManyDistinctImpl(it as EntityIterableBase, linkName), this ) } } } } } else if (it.isPersistent) { return selectManyDistinctImpl(it as EntityIterableBase, linkName) } } return inMemorySelectManyDistinct(it, linkName) } open fun toEntityIterable(it: Iterable<Entity>): Iterable<Entity> { return adjustEntityIterable(if (it is StaticTypedEntityIterable) it.instantiate() else it) } open fun intersectNonTrees(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return if (left.isPersistent && right.isPersistent) { wrap((left as EntityIterableBase).source.intersect((right as EntityIterableBase).source)) } else inMemoryIntersect(left, right) } open fun unionNonTrees(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return if (left.isPersistent && right.isPersistent) { wrap((left as EntityIterableBase).source.union((right as EntityIterableBase).source)) } else inMemoryUnion(left, right) } open fun concatNonTrees(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return if (left.isPersistent && right.isPersistent) { wrap((left as EntityIterableBase).source.concat((right as EntityIterableBase).source)) } else inMemoryConcat(left, right) } open fun excludeNonTrees(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return if (left.isPersistent && right.isPersistent) { wrap((left as EntityIterableBase).source.minus((right as EntityIterableBase).source)) } else inMemoryExclude(left, right) // subtract } open fun adjustEntityIterable(it: Iterable<Entity>): Iterable<Entity> { if (it === EMPTY) { return it } // try to convert collection to entity iterable. if (it is Collection<*>) { (it as Collection<Entity>).run { if (isEmpty()) return EMPTY if (size == 1) { wrap(iterator().next())?.let { return adjustEntityIterable(it) } } } } // wrap with transient iterable return if (it.isPersistent && !isWrapped(it)) wrap((it as EntityIterableBase).source) else it } open fun intersectAdjusted(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return intersectNonTrees(adjustEntityIterable(left), adjustEntityIterable(right)) } open fun unionAdjusted(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return unionNonTrees(adjustEntityIterable(left), adjustEntityIterable(right)) } open fun concatAdjusted(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return concatNonTrees(adjustEntityIterable(left), adjustEntityIterable(right)) } open fun excludeAdjusted(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { return excludeNonTrees(adjustEntityIterable(left), adjustEntityIterable(right)) } open fun instantiateGetAll(entityType: String): EntityIterable { return instantiateGetAll(persistentStore.andCheckCurrentTransaction, entityType) } open fun instantiateGetAll(txn: StoreTransaction, entityType: String): EntityIterable { return txn.getAll(entityType) } open fun isPersistentIterable(it: Iterable<Entity>): Boolean = it.isPersistent open fun assertOperational() {} open fun isWrapped(it: Iterable<Entity>?): Boolean = true open fun wrap(it: EntityIterable): EntityIterable = it protected open fun inMemorySelectDistinct(it: Iterable<Entity>, linkName: String): Iterable<Entity> { reportInMemoryError() return it.toList().mapNotNull { it.getLink(linkName) }.distinct() } protected open fun inMemorySelectManyDistinct(it: Iterable<Entity>, linkName: String): Iterable<Entity> { reportInMemoryError() return it.toList().flatMap { it.getLinks(linkName) }.filterNotNull().distinct() } protected open fun inMemoryIntersect(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { reportInMemoryError() val ids = right.asEntityIdSet return if (ids.isEmpty) right else left.filter { it.id in ids } } protected open fun inMemoryUnion(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { reportInMemoryError() return left.union(right) } protected open fun inMemoryConcat(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { reportInMemoryError() return left.toMutableList().apply { addAll(right) } } protected open fun inMemoryExclude(left: Iterable<Entity>, right: Iterable<Entity>): Iterable<Entity> { reportInMemoryError() val ids = right.asEntityIdSet return if (ids.isEmpty) left else left.filter { it.id !in ids } } protected open fun wrap(entity: Entity): Iterable<Entity>? { return SingleEntityIterable(persistentStore.andCheckCurrentTransaction, entity.id) } private fun instantiateAndAdjust(it: Iterable<Entity>): Iterable<Entity> { return adjustEntityIterable(StaticTypedEntityIterable.instantiate(it)) } private fun selectDistinctImpl(it: EntityIterableBase, linkName: String): Iterable<Entity> { assertOperational() return wrap(it.source.selectDistinct(linkName)) } private fun selectManyDistinctImpl(it: EntityIterableBase, linkName: String): Iterable<Entity> { assertOperational() return wrap(it.source.selectManyDistinct(linkName)) } private fun reportInMemoryError() { doIfTrue("jetbrains.exodus.query.reportInMemoryQueries") { logger.error("QueryEngine does in-memory computations", Throwable()) } } } private val Iterable<Entity>?.isEmpty: Boolean get() { return this == null || this === EMPTY || this is StaticTypedIterableDecorator && decorated === EMPTY } private val Iterable<Entity>?.isPersistent: Boolean get() = this is EntityIterableBase private val StaticTypedEntityIterable?.isGetAllTree: Boolean get() = this is TreeKeepingEntityIterable && tree is GetAll private fun retrieveStaticType(left: Iterable<Entity>, right: Iterable<Entity>): String? { if (left is StaticTypedEntityIterable) { val leftType = left.getEntityType() if (right is StaticTypedEntityIterable) { val rightType = right.getEntityType() if (leftType == rightType) { return rightType } } } return null } private val Iterable<Entity>.asEntityIdSet: EntityIdSet get() { var ids = EntityIdSetFactory.newSet() forEach { ids = ids.add(it.id) } return ids } private fun List<Entity>.distinct(): Iterable<Entity> { var ids = EntityIdSetFactory.newSet() return filter { (it.id !in ids).apply { if (this) ids = ids.add(it.id) } } }
apache-2.0
2210120bebd404b99b7ffad923ed76b8
41.358537
120
0.614038
4.966257
false
false
false
false
kivensolo/UiUsingListView
module-Demo/src/main/java/com/zeke/demo/customview/views/ChartTextView.kt
1
6552
package com.zeke.demo.customview.views import android.animation.Animator import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.text.TextUtils import android.util.AttributeSet import android.view.animation.LinearInterpolator import androidx.annotation.Keep import androidx.appcompat.widget.AppCompatTextView import java.util.* /** * 模拟音乐跳动的随机柱状图效果 * TODO 增加自定义view的属性配置 */ class ChartTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr){ var aniColumnC:ObjectAnimator ? = null var aniColumnB:ObjectAnimator ? = null var aniColumnA:ObjectAnimator ? = null var random: Random = Random() @Keep var offset_y:Float = 0f @Keep var offset_y2:Float = 0f @Keep var offset_y3:Float = 0f var isPlaying:Boolean = false private var rectA = RectF(chartLeft, y + chartTop + Y_OFFSET_MAX, columnWidth, BUTTOM) private var rectB = RectF(rectA) private var rectC = RectF(rectA) var chartPaint = Paint() init { init() } companion object{ const val RESTART_DELAY:Long = 250 const val DURATION:Long = 2100 const val DELAY_COLUMN_A:Long = DURATION / 6 const val chartLeft:Float = 20f var chartTop:Float = 20f const val Y_OFFSET_MAX:Float = 30f const val Y_OFFSET_MID:Float = 10f const val Y_OFFSET_MIN:Float = 0f const val BUTTOM:Float = 60f const val columnWidth:Float = 4f const val columnMargin:Float = 4f const val columnRightOffset:Float = columnWidth + columnMargin } private fun init() { text = "这只是测试数据啦啦啦啦啦啦啦啦啦啦啦啦啊啦啦啦啦啦只是测试数只是测试数只是测试数只是测试数." setTextColor(Color.RED) textSize = 28f maxLines = 2 ellipsize = TextUtils.TruncateAt.END chartPaint.color = Color.RED chartPaint.isAntiAlias = true chartPaint.isDither = true setBackgroundColor(Color.TRANSPARENT) val vHolder1 = PropertyValuesHolder.ofFloat("offset_y", Y_OFFSET_MAX, Y_OFFSET_MIN, Y_OFFSET_MAX, Y_OFFSET_MAX) aniColumnA = ObjectAnimator.ofPropertyValuesHolder(this, vHolder1) aniColumnA?.duration = DURATION aniColumnA?.interpolator = LinearInterpolator() // lengthAnimation?.repeatMode = ValueAnimator.RESTART // lengthAnimation?.repeatCount = ValueAnimator.INFINITE aniColumnA?.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) { } override fun onAnimationEnd(animation: Animator?) { postDelayed({ aniColumnA?.start() },RESTART_DELAY) } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) val vHolder2 = PropertyValuesHolder.ofFloat("offset_y2", Y_OFFSET_MAX, Y_OFFSET_MID, Y_OFFSET_MID, Y_OFFSET_MAX) aniColumnB = ObjectAnimator.ofPropertyValuesHolder(this, vHolder2) aniColumnB?.duration = DURATION aniColumnB?.interpolator = LinearInterpolator() aniColumnB?.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { postDelayed({ aniColumnB?.start() },RESTART_DELAY) } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) val vHolder3 = PropertyValuesHolder.ofFloat("offset_y3", Y_OFFSET_MAX, Y_OFFSET_MIN, Y_OFFSET_MAX, Y_OFFSET_MAX) aniColumnC = ObjectAnimator.ofPropertyValuesHolder(this, vHolder3) aniColumnC?.duration = DURATION aniColumnC?.interpolator = LinearInterpolator() aniColumnC?.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { postDelayed({ aniColumnC?.start() },RESTART_DELAY) } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) // start() postDelayed({ setPlayerPlaying(true) },1500) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { setMeasuredDimension(900, 300) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) drawMusicPlayView(canvas) } private fun drawMusicPlayView(canvas: Canvas) { if (isPlaying) { rectA.set(x + chartLeft, y + chartTop + offset_y, x + chartLeft + columnMargin, BUTTOM) rectB.set(rectA.right + columnMargin, y + chartTop + offset_y2, rectA.right + columnRightOffset, BUTTOM) rectC.set(rectB.right + columnMargin, y + chartTop + offset_y3, rectB.right + columnRightOffset, BUTTOM) canvas.drawRoundRect(rectA, 3f, 3f, paint) canvas.drawRoundRect(rectB, 3f, 3f, paint) canvas.drawRoundRect(rectC, 3f, 3f, paint) invalidate() } } fun stop(){ isPlaying = false aniColumnA?.cancel() aniColumnB?.cancel() aniColumnC?.cancel() } fun start(){ postDelayed({aniColumnA?.start()},DELAY_COLUMN_A) aniColumnB?.start() aniColumnC?.start() } private fun setPlayerPlaying(playing:Boolean){ isPlaying = true if(playing){ val content = text text = "\u3000$content" start() invalidate() }else{ stop() } } fun recycle(){ stop() aniColumnA = null aniColumnB = null aniColumnC = null } override fun onDetachedFromWindow() { super.onDetachedFromWindow() recycle() } }
gpl-2.0
8c05e593f341740e588fd470dcecb0ad
31.897436
120
0.627534
4.472803
false
false
false
false