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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jean79/yested | src/main/docsite/bootstrap/rowpanelcontainer.kt | 2 | 3232 | package bootstrap
import net.yested.div
import net.yested.bootstrap.row
import net.yested.bootstrap.Medium
import net.yested.bootstrap.PanelStyle
import net.yested.Div
import net.yested.bootstrap.DeviceSize
import net.yested.bootstrap.Panel
import net.yested.with
import net.yested.bootstrap.btsForm
import net.yested.bootstrap.FormStyle
import net.yested.bootstrap.Select
import net.yested.bootstrap.btsButton
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.ButtonSize
import net.yested.bootstrap.ButtonLook
import net.yested.bootstrap.alert
import net.yested.bootstrap.AlertStyle
import net.yested.TextArea
import net.yested.bootstrap.RowPanelContainer
fun createRowPanelContainerSection(id: String): Div {
val panelContainer = RowPanelContainer()
var counter = 1
fun addPanel(size:DeviceSize, panelStyle: PanelStyle) {
val textArea = TextArea(2) with { data = "Resize me!" }
val panel = Panel(style = panelStyle, dismissible = true) with {
heading { +"A panel ${counter++} ($size)" }
content { +textArea }
}
panelContainer.add(panel, size)
}
addPanel(Medium(4), PanelStyle.PRIMARY)
addPanel(Medium(4), PanelStyle.DEFAULT)
addPanel(Medium(6), PanelStyle.SUCCESS)
addPanel(Medium(4), PanelStyle.INFO)
val sizes = arrayListOf(Medium(4), Medium(6), Medium(8))
val selectSize = Select<DeviceSize>(options = sizes) { "${it.size}" }
val looks = arrayListOf(PanelStyle.DEFAULT, PanelStyle.PRIMARY, PanelStyle.SUCCESS, PanelStyle.INFO, PanelStyle.WARNING, PanelStyle.DANGER)
//PanelStyle.values.toList()
val selectLook = Select(options = looks) { it.name }
return div(id = id) {
row {
col(Medium(12)) {
pageHeader { h3 { +"Row Panel Container" } }
}
col(Medium(6)) {
+"""Panel Container is based on JQuery.sortable function (from JQuery UI).
It allows user to change layout of panels or remove panels from the container.
This implementation allows you to specify width of panels via Bootstrap columns sizes."""
}
col(Medium(6)) {
alert(style = AlertStyle.WARNING, dismissible = true) {
+"Try Drag&Drop the Panels below!"
}
a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/bootstrap/rowpanelcontainer.kt") {+"Source code"}
}
}
row {
btsForm(formStyle = FormStyle.INLINE) {
item(label = { +"Size:"; nbsp() }) {
+selectSize
}
item(label = { nbsp(); +"Look:" ; nbsp() }) {
+selectLook
}
item(label = { nbsp() }) {
btsButton(label = {+"Add Panel"}, size = ButtonSize.SMALL, look = ButtonLook.PRIMARY) {
addPanel(selectSize.selectedItems.first(), selectLook.selectedItems.first())
}
}
}
}
br()
row {
col(Medium(12)) {
+panelContainer
}
}
}
} | mit | f8351fc17f70bfaa136d0429936b6d46 | 34.141304 | 143 | 0.601795 | 4.186528 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/test/core/json/Problem.kt | 1 | 726 | package org.elm.ide.test.core.json
import com.google.gson.JsonElement
class Problem {
var title: String? = null
var region: Region? = null
var message: List<JsonElement>? = null
val textMessage: String
get() {
val hasText = { element:JsonElement -> element.isJsonPrimitive || element.isJsonObject && element.asJsonObject.has("string") }
val toText = { element:JsonElement ->
if (element.isJsonPrimitive)
element.asString
else
element.asJsonObject.get("string").asString
}
return message!!
.filter(hasText).joinToString("", transform = toText)
}
}
| mit | 938b7dd3665bf60033d2008b60dee597 | 26.923077 | 138 | 0.571625 | 5.041667 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mcp/gradle/datahandler/McpModelFG3Handler.kt | 1 | 3185 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.gradle.datahandler
import com.demonwav.mcdev.platform.mcp.McpModuleSettings
import com.demonwav.mcdev.platform.mcp.at.AtFileType
import com.demonwav.mcdev.platform.mcp.gradle.McpModelData
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3
import com.demonwav.mcdev.platform.mcp.srg.SrgType
import com.demonwav.mcdev.util.runWriteTaskLater
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.fileTypes.ExactFileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.vfs.LocalFileSystem
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
object McpModelFG3Handler : McpModelDataHandler {
override fun build(
gradleModule: IdeaModule,
node: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val data = resolverCtx.getExtraProject(gradleModule, McpModelFG3::class.java) ?: return
var mcVersion: String? = null
var forgeVersion: String? = null
for (minecraftDepVersion in data.minecraftDepVersions) {
val index = minecraftDepVersion.indexOf('-')
if (index == -1) {
continue
}
mcVersion = minecraftDepVersion.substring(0, index)
val forgeVersionEnd = minecraftDepVersion.indexOf('_')
if (forgeVersionEnd != -1 && forgeVersionEnd > index) {
forgeVersion = minecraftDepVersion.substring(index + 1, forgeVersionEnd)
}
break
}
val state = McpModuleSettings.State(
mcVersion,
data.mcpVersion,
data.taskOutputLocation.absolutePath,
SrgType.TSRG,
forgeVersion
)
val gradleProjectPath = gradleModule.gradleProject.projectIdentifier.projectPath
val suffix = if (gradleProjectPath.endsWith(':')) "" else ":"
val taskName = gradleProjectPath + suffix + data.taskName
val ats = data.accessTransformers
if (ats != null && ats.isNotEmpty()) {
runWriteTaskLater {
for (at in ats) {
val fileTypeManager = FileTypeManager.getInstance()
val atFile = LocalFileSystem.getInstance().findFileByIoFile(at) ?: continue
fileTypeManager.associate(AtFileType, ExactFileNameMatcher(atFile.name))
}
}
}
val modelData = McpModelData(node.data, state, taskName, data.accessTransformers)
node.createChild(McpModelData.KEY, modelData)
for (child in node.children) {
val childData = child.data
if (childData is GradleSourceSetData) {
child.createChild(McpModelData.KEY, modelData.copy(module = childData))
}
}
}
}
| mit | e155a2a04bfb0aaeec2dac0a467cfc63 | 36.034884 | 95 | 0.671272 | 4.636099 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/service/QueueExecutor.kt | 1 | 4514 | package org.andstatus.app.service
import io.vavr.control.Try
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.os.AsyncEnum
import org.andstatus.app.os.AsyncResult
import org.andstatus.app.service.CommandQueue.AccessorType
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.TryUtils
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicLong
class QueueExecutor(myService: MyService, val accessorType: AccessorType) :
AsyncResult<Unit, Boolean>(QueueExecutor::class, AsyncEnum.SYNC), CommandExecutorParent {
private val myServiceRef: WeakReference<MyService> = WeakReference(myService)
val executedCounter: AtomicLong = AtomicLong()
override suspend fun doInBackground(params: Unit): Try<Boolean> {
val myService = myServiceRef.get()
if (myService == null) {
MyLog.v(this) { "Didn't start, no reference to MyService" }
return TryUtils.TRUE
}
val accessor = myService.myContext.queues.getAccessor(accessorType)
MyLog.v(this) { "Started, to process in ${accessorType.title}:" + accessor.countToExecute }
val breakReason: String
do {
if (isStopping()) {
breakReason = "isStopping"
break
}
if (isCancelled) {
breakReason = "Cancelled"
break
}
if (RelativeTime.secondsAgo(backgroundStartedAt.get()) > MAX_EXECUTION_TIME_SECONDS) {
breakReason = "Executed too long"
break
}
if (!myService.executors.contains(this)) {
breakReason = "Removed"
break
}
val commandData = accessor.nextToExecute(this)
if (commandData.isEmpty) {
breakReason = "No more commands"
break
}
executedCounter.incrementAndGet()
currentlyExecutingSince.set(System.currentTimeMillis())
currentlyExecutingDescription = commandData.toString()
myService.broadcastBeforeExecutingCommand(commandData)
CommandExecutorStrategy.executeCommand(commandData, this)
when {
commandData.getResult().shouldWeRetry() -> {
myService.myContext.queues.addToQueue(QueueType.RETRY, commandData)
}
commandData.getResult().hasError() -> {
myService.myContext.queues.addToQueue(QueueType.ERROR, commandData)
}
else -> addSyncAfterNoteWasSent(myService, commandData)
}
accessor.onPostExecute(commandData)
myService.broadcastAfterExecutingCommand(commandData)
} while (true)
MyLog.v(this) { "Ended:$breakReason, left:" + accessor.countToExecute + ", $this" }
myService.myContext.queues.save()
currentlyExecutingDescription = breakReason
return TryUtils.TRUE
}
private fun addSyncAfterNoteWasSent(myService: MyService, cdExecuted: CommandData) {
if (cdExecuted.getResult().hasError() ||
(cdExecuted.command != CommandEnum.UPDATE_NOTE && cdExecuted.command != CommandEnum.UPDATE_MEDIA) ||
!SharedPreferencesUtil.getBoolean(MyPreferences.KEY_SYNC_AFTER_NOTE_WAS_SENT, false)
) {
return
}
myService.myContext.queues.addToQueue(QueueType.CURRENT, CommandData.newTimelineCommand(CommandEnum.GET_TIMELINE,
cdExecuted.getTimeline().myAccountToSync, TimelineType.SENT)
.setInForeground(cdExecuted.isInForeground()))
}
override suspend fun onPostExecute(result: Try<Boolean>) {
myServiceRef.get()?.onExecutorFinished()
}
override fun isStopping(): Boolean {
return myServiceRef.get()?.isStopping() ?: true
}
override fun toString(): String {
val sb = MyStringBuilder()
if (isStopping()) {
sb.withComma("stopping")
}
sb.withComma(accessorType.title)
sb.withComma("commands executed", executedCounter.get())
sb.withComma(super.toString())
return sb.toString()
}
companion object {
const val MAX_EXECUTION_TIME_SECONDS: Long = 60
}
}
| apache-2.0 | f326aeb04ec87fbce36ee7fe18d418e9 | 39.666667 | 121 | 0.642003 | 4.761603 | false | false | false | false |
tommyettinger/SquidLib-Demos | JTranscDemo/src/com/jtransc/examples/tictactoe/model.kt | 1 | 2119 | package com.jtransc.examples.tictactoe
import jtransc.game.math.IPoint
import jtransc.game.util.Signal
object Model {
class Cell(val x: Int, val y: Int) {
var value = ChipType.EMPTY
val pos = IPoint(x, y)
override fun toString(): String = "C($x,$y,$value)"
}
interface Result {
object PLAYING : Result
object DRAW : Result
data class WIN(val cells: List<Cell>) : Result
}
class Game {
private val data = Array2(3, 3) { x, y -> Cell(x, y) }
val onCellUpdated = Signal<Cell>()
val onGameFinished = Signal<Result>()
fun isEmpty(x: Int, y: Int): Boolean = _isEmpty(x, y)
fun hasChip(x: Int, y: Int): Boolean = !_isEmpty(x, y)
private fun _isEmpty(x: Int, y: Int): Boolean = data[x, y].value == ChipType.EMPTY
operator fun get(x: Int, y: Int): ChipType = data[x, y].value
operator fun set(x: Int, y: Int, chip: ChipType) {
if (data[x, y].value == chip) return
data[x, y].value = chip
onCellUpdated.dispatch(data[x, y])
val result = checkResult()
if (result != Result.PLAYING) onGameFinished.dispatch(result)
}
fun checkResult():Result {
return if (hasWin()) {
Result.WIN(getWin()!!)
} else if (isBoardFull()) {
Result.DRAW
} else {
Result.PLAYING
}
}
fun reset() {
this.data.forEach { x, y, cell ->
cell.value = ChipType.EMPTY
}
this.data.forEach { x, y, cell ->
onCellUpdated.dispatch(cell)
}
}
fun isBoardFull() = this.data.getCells().all { it.value != ChipType.EMPTY }
fun hasWin() = getWin() != null
fun getWin(): List<Cell>? {
return getWinSets().firstOrNull { cells ->
val value1 = cells[0].value
value1 != ChipType.EMPTY && cells.all { it.value == value1 }
}
}
private fun getWinSets(): List<List<Cell>> = (
(0 until 3).map { data.getRow(it) } +
(0 until 3).map { data.getColumn(it) } +
listOf(data.getDiagonal1()) +
listOf(data.getDiagonal2())
)
fun getCells() = data.getCells()
fun getEmptyCells() = getCells().filter { it.value == ChipType.EMPTY }
}
}
enum class ChipType(val s: String) {
EMPTY("."), O("O"), X("X");
override fun toString() = s
}
| apache-2.0 | 48f0e17e9f69dba2d6e1c3f1b3211c01 | 24.22619 | 84 | 0.624823 | 2.906722 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/feedback/FeedbackActivity.kt | 1 | 2304 | package com.intfocus.template.dashboard.feedback
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.util.Log
import android.view.View
import com.intfocus.template.R
import com.intfocus.template.dashboard.feedback.content.FeedbackContentFragment
import com.intfocus.template.dashboard.feedback.list.FeedbackListFragment
import com.intfocus.template.ui.BaseActivity
import kotlinx.android.synthetic.main.item_action_bar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* @author liuruilin
* @data 2017/11/28
* @describe 问题反馈页面
*/
class FeedbackActivity : BaseActivity() {
private lateinit var mFragmentManager: FragmentManager
private lateinit var mFragmentTransaction: FragmentTransaction
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feedback)
EventBus.getDefault().register(this)
initView()
onCreateFinish()
}
private fun initView() {
tv_banner_title.text = resources.getText(R.string.activity_feedback)
iv_banner_setting.visibility = View.INVISIBLE
mFragmentManager = supportFragmentManager
}
private fun onCreateFinish() {
showList()
}
override fun onBackPressed() {
Log.i("fragment", "mFragmentManager: " + mFragmentManager.fragments.size)
Log.i("fragment", "backStackEntryCount: " + mFragmentManager.backStackEntryCount)
super.onBackPressed()
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
private fun showList() {
mFragmentTransaction = mFragmentManager.beginTransaction()
mFragmentTransaction.add(R.id.fl_container, FeedbackListFragment()).commit()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun showContent(content: EventFeedbackContent) {
mFragmentTransaction = mFragmentManager.beginTransaction()
mFragmentTransaction.replace(R.id.fl_container, FeedbackContentFragment.getInstance(content.id)).commit()
mFragmentTransaction.addToBackStack("list").commit()
}
}
| gpl-3.0 | dd10e917683aa1f93f303b915edd6884 | 32.705882 | 113 | 0.739529 | 4.735537 | false | false | false | false |
sebastiansokolowski/AuctionHunter---Allegro | server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/allegro_api/AllegroApi.kt | 1 | 1443 | package com.sebastiansokolowski.auctionhunter.allegro_api
import com.sebastiansokolowski.auctionhunter.allegro_api.response.Categories
import com.sebastiansokolowski.auctionhunter.allegro_api.response.CategoryDto
import com.sebastiansokolowski.auctionhunter.allegro_api.response.CategoryParameters
import com.sebastiansokolowski.auctionhunter.allegro_api.response.Listing
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.QueryMap
interface AllegroApi {
companion object {
const val baseUrl = "https://api.allegro.pl"
}
@GET("/sale/categories")
fun getCategories(@Query("parent.id") parentId: String?): Call<Categories>
@GET("/sale/categories/{id}")
fun getCategory(@Path("id") id: Int): Call<CategoryDto>
@GET("/sale/categories/{categoryId}/parameters")
fun getCategoryParameters(@Path("categoryId") categoryId: String): Call<CategoryParameters>
@GET("/offers/listing")
fun getOffers(
@Query("category.id") categoryId: String? = null,
@Query("phrase") phrase: String? = null,
@Query("fallback") fallback: Boolean = false,
@Query("sort") sort: String = "+price",
@Query("include") excludeObjects: String = "-all",
@Query("include") includeObjects: String = "items",
@QueryMap parameters: Map<String, String>
): Call<Listing>
} | apache-2.0 | 9f3c2a631fc19f0979504502f45b375d | 38.027027 | 95 | 0.709633 | 3.921196 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/CardAdapter.kt | 1 | 5394 | package de.tum.`in`.tumcampusapp.component.ui.overview
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import de.tum.`in`.tumcampusapp.component.tumui.calendar.NextLectureCard
import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.TuitionFeesCard
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaMenuCard
import de.tum.`in`.tumcampusapp.component.ui.chat.ChatMessagesCard
import de.tum.`in`.tumcampusapp.component.ui.eduroam.EduroamCard
import de.tum.`in`.tumcampusapp.component.ui.eduroam.EduroamFixCard
import de.tum.`in`.tumcampusapp.component.ui.news.NewsCard
import de.tum.`in`.tumcampusapp.component.ui.news.TopNewsCard
import de.tum.`in`.tumcampusapp.component.ui.onboarding.LoginPromptCard
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import de.tum.`in`.tumcampusapp.component.ui.ticket.EventCard
import de.tum.`in`.tumcampusapp.component.ui.transportation.MVVCard
import de.tum.`in`.tumcampusapp.component.ui.updatenote.UpdateNoteCard
import java.util.*
/**
* Adapter for the cards start page used in [MainActivity]
*/
class CardAdapter(private val interactionListener: CardInteractionListener) : RecyclerView.Adapter<CardViewHolder>() {
private val mItems = ArrayList<Card>()
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): CardViewHolder {
when (viewType) {
CardManager.CARD_CAFETERIA -> return CafeteriaMenuCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_TUITION_FEE -> return TuitionFeesCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_NEXT_LECTURE -> return NextLectureCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_RESTORE -> return RestoreCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_NO_INTERNET -> return NoInternetCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_MVV -> return MVVCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_NEWS, CardManager.CARD_NEWS_FILM -> return NewsCard.inflateViewHolder(viewGroup, viewType, interactionListener)
CardManager.CARD_EDUROAM -> return EduroamCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_EDUROAM_FIX -> return EduroamFixCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_CHAT -> return ChatMessagesCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_SUPPORT -> return SupportCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_LOGIN -> return LoginPromptCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_TOP_NEWS -> return TopNewsCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_EVENT -> return EventCard.inflateViewHolder(viewGroup, interactionListener)
CardManager.CARD_UPDATE_NOTE -> return UpdateNoteCard.inflateViewHolder(viewGroup, interactionListener)
else -> throw UnsupportedOperationException()
}
}
override fun onBindViewHolder(viewHolder: CardViewHolder, position: Int) {
val card = mItems[position]
viewHolder.currentCard = card
card.updateViewHolder(viewHolder)
}
override fun getItemViewType(position: Int) = mItems[position].cardType
override fun getItemId(position: Int): Long {
val card = mItems[position]
return (card.cardType + (card.getId() shl 4)).toLong()
}
override fun getItemCount() = mItems.size
internal fun updateItems(newCards: List<Card>) {
val diffResult = DiffUtil.calculateDiff(Card.DiffCallback(mItems, newCards))
mItems.clear()
mItems.addAll(newCards)
diffResult.dispatchUpdatesTo(this)
}
fun remove(position: Int): Card {
val card = mItems.removeAt(position)
notifyItemRemoved(position)
return card
}
fun insert(position: Int, card: Card) {
mItems.add(position, card)
notifyItemInserted(position)
}
internal fun onItemMove(fromPosition: Int, toPosition: Int) {
val toValidatedPosition = validatePosition(fromPosition, toPosition)
val card = mItems.removeAt(fromPosition)
mItems.add(toValidatedPosition, card)
// Update card positions so they stay the same even when the app is closed
for (index in mItems.indices) {
mItems[index].position = index
}
notifyItemMoved(fromPosition, toValidatedPosition)
}
private fun validatePosition(fromPosition: Int, toPosition: Int): Int {
val selectedCard = mItems[fromPosition]
val cardAtPosition = mItems[toPosition]
// If there is a support card, it should always be the first one
// except when it's been dismissed.
// Restore card should stay at the bottom
if (selectedCard is RestoreCard || selectedCard is SupportCard) {
return fromPosition
}
return when (cardAtPosition) {
is SupportCard -> toPosition + 1
is RestoreCard -> toPosition - 1
else -> toPosition
}
}
}
| gpl-3.0 | 02f36e0a0649bdd1c07537fa31408ee9 | 46.315789 | 140 | 0.730627 | 4.626072 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/core/presenters/StoreManagementPresenter.kt | 2 | 3433 | package org.stepic.droid.core.presenters
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.subjects.PublishSubject
import org.stepic.droid.core.presenters.contracts.StoreManagementView
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.persistence.downloads.interactor.RemovalDownloadsInteractor
import org.stepic.droid.persistence.files.ExternalStorageManager
import org.stepic.droid.persistence.model.StorageLocation
import org.stepic.droid.persistence.service.FileTransferService
import org.stepic.droid.util.size
import javax.inject.Inject
class StoreManagementPresenter
@Inject
constructor(
private val externalStorageManager: ExternalStorageManager,
private val removalDownloadsInteractor: RemovalDownloadsInteractor,
private val fileTransferEventSubject: PublishSubject<FileTransferService.Event>,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<StoreManagementView>() {
private val compositeDisposable = CompositeDisposable()
override fun attachView(view: StoreManagementView) {
super.attachView(view)
fetchStorage()
}
private fun fetchStorage() {
val optionsObservable = Single
.fromCallable(externalStorageManager::getAvailableStorageLocations)
.cache()
val currentStorageSource = Single
.fromCallable(externalStorageManager::getSelectedStorageLocation)
compositeDisposable += Singles
.zip(optionsObservable, currentStorageSource)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { (locations, selectedLocation) ->
view?.setStorageOptions(locations, selectedLocation)
},
onError = { view?.setStorageOptions(emptyList(), null) }
)
compositeDisposable += optionsObservable
.map { it.map { location -> location.path.size() }.sum() }
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { view?.setUpClearCacheButton(it) },
onError = { view?.setUpClearCacheButton(0) }
)
}
fun removeAllDownloads() {
view?.showLoading()
removalDownloadsInteractor
.removeAllDownloads()
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.doFinally { fetchStorage() }
.subscribeBy(
onComplete = { view?.hideLoading() },
onError = { view?.hideLoading() }
)
}
fun changeStorageLocation(storage: StorageLocation) {
view?.showLoading(true)
fileTransferEventSubject
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribe { view?.hideLoading() }
externalStorageManager.setStorageLocation(storage)
}
override fun detachView(view: StoreManagementView) {
compositeDisposable.clear()
super.detachView(view)
}
} | apache-2.0 | db691f0ff20fd22cfe2ce12bbaeb27e6 | 35.531915 | 84 | 0.693854 | 5.380878 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectScalableImageView/app/src/main/java/me/liuqingwen/android/projectscalableimageview/ScalableImageView.kt | 1 | 5107 | package me.liuqingwen.android.projectscalableimageview
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ImageView
import org.jetbrains.anko.AnkoLogger
/**
* Created by Qingwen on 2017-8-23.
*/
enum class OperationMode
{
DRAG, ZOOM, NONE
}
class ScalableImageView:ImageView, AnkoLogger
{
constructor(context: Context):super(context)
constructor(context: Context, attributes: AttributeSet, defStyleAttr : Int, defStyleRes: Int):super(context, attributes, defStyleAttr, defStyleRes)
constructor(context: Context, attributes: AttributeSet, defStyleAttr: Int):this(context, attributes, defStyleAttr, 0)
constructor(context: Context, attributes: AttributeSet):this(context, attributes, 0)
companion object
{
private const val MIN_ZOOM_POINTER_DISTANCE = 5.0
}
private var opMode = OperationMode.NONE
override fun performClick(): Boolean
{
return super.performClick()
}
override fun onTouchEvent(event: MotionEvent?): Boolean
{
this.performClick()
when(event?.actionMasked)
{
MotionEvent.ACTION_DOWN -> {
this.opMode = OperationMode.DRAG
this.touchDown(event)
}
MotionEvent.ACTION_POINTER_DOWN -> {
if (this.opMode != OperationMode.ZOOM)
{
this.opMode = OperationMode.ZOOM
this.touchZoomDown(event)
}
}
MotionEvent.ACTION_MOVE -> {
if (this.opMode != OperationMode.NONE)
{
this.touchMove(event)
}
}
MotionEvent.ACTION_POINTER_UP -> {
this.opMode = OperationMode.NONE
this.resizeImage()
}
MotionEvent.ACTION_UP -> {
this.opMode = OperationMode.NONE
this.replaceImage()
}
}
return true
}
private fun replaceImage()
{
}
private var originalX = 0f
private var originalY = 0f
private var originalDistance = 0.0
private fun touchDown(event: MotionEvent)
{
this.originalX = event.x
this.originalY = event.y
}
private fun touchZoomDown(event: MotionEvent)
{
this.originalDistance = this.getDistanceOfPointers(event)
}
private fun touchMove(event: MotionEvent)
{
val deltaX = event.x - this.originalX
val deltaY = event.y - this.originalY
if (this.opMode == OperationMode.DRAG)
{
this.left += deltaX.toInt()
this.right += deltaX.toInt()
this.top += deltaY.toInt()
this.bottom += deltaY.toInt()
super.layout(this.left, this.top, this.right, this.bottom)
}else if (this.opMode == OperationMode.ZOOM)
{
val distance = this.getDistanceOfPointers(event)
val deltaDistance = Math.abs(distance - this.originalDistance)
if (deltaDistance > ScalableImageView.MIN_ZOOM_POINTER_DISTANCE)
{
this.scaleImage(distance)
this.originalDistance = distance //!importance
}
//this.originalDistance = distance
}
}
private fun scaleImage(newDistance: Double)
{
val ratio = newDistance / this.originalDistance
if (ratio > 1)
{
val sizeX = this.width * (ratio - 1) / 2
val sizeY = this.height * (ratio - 1) / 2
val left = this.left - sizeX
val right = this.right + sizeX
val top = this.top - sizeY
val bottom = this.bottom + sizeY
this.setFrame(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}else if (ratio < 1)
{
val sizeX = this.width * (1- ratio) / 2
val sizeY = this.height * (1 - ratio) / 2
val left = this.left + sizeX
val right = this.right - sizeX
val top = this.top + sizeY
val bottom = this.bottom - sizeY
this.setFrame(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
}
private fun getDistanceOfPointers(event: MotionEvent): Double
{
val deltaX = event.getX(0) - event.getX(1)
val deltaY = event.getY(0) - event.getY(1)
return Math.sqrt((deltaX * deltaX + deltaY * deltaY).toDouble())
}
private fun resizeImage()
{
}
/*override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int)
{
super.onLayout(changed, left, top, right, bottom)
}*/
/*override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}*/
/*override fun onDraw(canvas: Canvas?)
{
super.onDraw(canvas)
}*/
} | mit | 40278b1b1d4c6a07abdd9b32ea639199 | 28.871345 | 151 | 0.563344 | 4.5885 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt | 1 | 6493 | package info.nightscout.androidaps.utils
import android.content.Context
import android.content.Intent
import android.os.Bundle
import info.nightscout.androidaps.R
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.receivers.Intents
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("SpellCheckingInspection")
@OpenForTesting
@Singleton
class XDripBroadcast @Inject constructor(
private val context: Context,
private val aapsLogger: AAPSLogger,
private val sp: SP,
private val rh: ResourceHelper,
private val profileFunction: ProfileFunction
) {
fun sendCalibration(bg: Double): Boolean {
val bundle = Bundle()
bundle.putDouble("glucose_number", bg)
bundle.putString("units", if (profileFunction.getUnits() == GlucoseUnit.MGDL) "mgdl" else "mmol")
bundle.putLong("timestamp", System.currentTimeMillis())
val intent = Intent(Intents.ACTION_REMOTE_CALIBRATION)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
context.sendBroadcast(intent)
val q = context.packageManager.queryBroadcastReceivers(intent, 0)
return if (q.size < 1) {
ToastUtils.showToastInUiThread(context, rh.gs(R.string.xdripnotinstalled))
aapsLogger.debug(rh.gs(R.string.xdripnotinstalled))
false
} else {
ToastUtils.showToastInUiThread(context, rh.gs(R.string.calibrationsent))
aapsLogger.debug(rh.gs(R.string.calibrationsent))
true
}
}
// sent in 640G mode
fun send(glucoseValue: GlucoseValue) {
if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US)
try {
val entriesBody = JSONArray()
val json = JSONObject()
json.put("sgv", glucoseValue.value)
json.put("direction", glucoseValue.trendArrow.text)
json.put("device", "G5")
json.put("type", "sgv")
json.put("date", glucoseValue.timestamp)
json.put("dateString", format.format(glucoseValue.timestamp))
entriesBody.put(json)
val bundle = Bundle()
bundle.putString("action", "add")
bundle.putString("collection", "entries")
bundle.putString("data", entriesBody.toString())
val intent = Intent(Intents.XDRIP_PLUS_NS_EMULATOR)
intent.putExtras(bundle).addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
context.sendBroadcast(intent)
val receivers = context.packageManager.queryBroadcastReceivers(intent, 0)
if (receivers.size < 1) {
//NSUpload.log.debug("No xDrip receivers found. ")
aapsLogger.debug(LTag.BGSOURCE, "No xDrip receivers found.")
} else {
aapsLogger.debug(LTag.BGSOURCE, "${receivers.size} xDrip receivers")
}
} catch (e: JSONException) {
aapsLogger.error(LTag.BGSOURCE, "Unhandled exception", e)
}
}
}
// sent in NSClient dbaccess mode
fun sendProfile(profileStoreJson: JSONObject) {
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false))
broadcast(
Intent(Intents.ACTION_NEW_PROFILE).apply {
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
putExtras(Bundle().apply { putString("profile", profileStoreJson.toString()) })
}
)
}
// sent in NSClient dbaccess mode
fun sendTreatments(addedOrUpdatedTreatments: JSONArray) {
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false))
splitArray(addedOrUpdatedTreatments).forEach { part ->
broadcast(
Intent(Intents.ACTION_NEW_TREATMENT).apply {
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
putExtras(Bundle().apply { putString("treatments", part.toString()) })
}
)
}
}
// sent in NSClient dbaccess mode
fun sendSgvs(sgvs: JSONArray) {
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false))
splitArray(sgvs).forEach { part ->
broadcast(
Intent(Intents.ACTION_NEW_SGV).apply {
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
putExtras(Bundle().apply { putString("sgvs", part.toString()) })
}
)
}
}
private fun splitArray(array: JSONArray): List<JSONArray> {
var ret: MutableList<JSONArray> = ArrayList()
try {
val size = array.length()
var count = 0
var newarr: JSONArray? = null
for (i in 0 until size) {
if (count == 0) {
if (newarr != null) ret.add(newarr)
newarr = JSONArray()
count = 20
}
newarr?.put(array[i])
--count
}
if (newarr != null && newarr.length() > 0) ret.add(newarr)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
ret = ArrayList()
ret.add(array)
}
return ret
}
private fun broadcast(intent: Intent) {
context.packageManager.queryBroadcastReceivers(intent, 0).forEach { resolveInfo ->
resolveInfo.activityInfo.packageName?.let {
intent.setPackage(it)
context.sendBroadcast(intent)
aapsLogger.debug(LTag.CORE, "Sending broadcast " + intent.action + " to: " + it)
}
}
}
} | agpl-3.0 | 0312bb38bd990542d8d53e6ea0753cc1 | 39.335404 | 105 | 0.602341 | 4.601701 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/utils/AnalyticsHelper.kt | 1 | 2364 | package com.sjn.stamp.utils
import android.content.Context
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import com.sjn.stamp.ui.DrawerMenu
import com.sjn.stamp.utils.MediaIDHelper.getHierarchy
import java.util.*
object AnalyticsHelper {
private const val CREATE_STAMP = "create_stamp"
private const val PLAY_CATEGORY = "play_category"
private const val CHANGE_SCREEN = "change_screen"
private const val CHANGE_SETTING = "change_setting"
private const val CHANGE_RANKING_TERM = "change_ranking_term"
fun trackCategory(context: Context, mediaId: String) {
val hierarchy = getHierarchy(mediaId)
if (hierarchy.isEmpty()) {
return
}
FirebaseAnalytics.getInstance(context).logEvent(PLAY_CATEGORY, Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_CATEGORY, hierarchy[0])
})
}
fun trackScreen(context: Context, drawerMenu: DrawerMenu?) {
drawerMenu?.let {
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SCREEN, Bundle().apply {
putString(FirebaseAnalytics.Param.CONTENT, drawerMenu.toString())
})
}
}
fun trackStamp(context: Context, stamp: String) {
FirebaseAnalytics.getInstance(context).logEvent(CREATE_STAMP, Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_NAME, stamp)
})
}
fun trackSetting(context: Context, name: String) {
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_NAME, name)
})
}
fun trackSetting(context: Context, name: String, value: String) {
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_NAME, name)
putString(FirebaseAnalytics.Param.VALUE, value)
})
}
fun trackRankingTerm(context: Context, start: Date?, end: Date?) {
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_RANKING_TERM, Bundle().apply {
start?.let {
putString(FirebaseAnalytics.Param.START_DATE, it.toString())
}
end?.let {
putString(FirebaseAnalytics.Param.END_DATE, it.toString())
}
})
}
}
| apache-2.0 | e2f2ddcb04f2796e3dcef6d808ad8490 | 35.9375 | 93 | 0.662014 | 4.554913 | false | false | false | false |
Maccimo/intellij-community | plugins/gradle/java/src/service/resolve/GradleNamedDomainCollectionContributor.kt | 3 | 2690 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.resolve
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.PsiUtil.substituteTypeParameter
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.getName
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties
class GradleNamedDomainCollectionContributor : NonCodeMembersContributor() {
override fun getParentClassName(): String = GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER
override fun processDynamicElements(qualifierType: PsiType,
clazz: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (clazz == null) return
if (state[DELEGATED_TYPE] == true) return
val domainObjectName = processor.getName(state) ?: return // don't complete anything because we don't know what is in container
val processProperties = processor.shouldProcessProperties()
val processMethods = processor.shouldProcessMethods()
if (!processProperties && !processMethods) {
return
}
val domainObjectType = substituteTypeParameter(qualifierType, GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER, 0, false) ?: return
val containingFile = place.containingFile
val manager = containingFile.manager
if (processProperties) {
val property = GradleDomainObjectProperty(domainObjectName, domainObjectType, containingFile)
if (!processor.execute(property, state)) {
return
}
}
if (processMethods) {
val method = GrLightMethodBuilder(manager, domainObjectName).apply {
returnType = domainObjectType
addParameter("configuration", createType(GROOVY_LANG_CLOSURE, containingFile))
}
if (!processor.execute(method, state)) {
return
}
}
}
}
| apache-2.0 | 03e49dd0c969ab8392f06e33fca13b8b | 45.37931 | 131 | 0.737918 | 4.855596 | false | false | false | false |
android/connectivity-samples | UwbRanging/app/src/main/java/com/google/apps/hellouwb/ui/theme/Theme.kt | 1 | 2438 | /*
*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.apps.hellouwb.ui.theme
import android.app.Activity
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme =
darkColorScheme(primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80)
private val LightColorScheme =
lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun HellouwbTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val colorScheme =
when {
dynamicColor -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController((view.context as Activity).window, view)
.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content)
}
| apache-2.0 | 8162682ae3ff61030fe7b52a48ea76ae | 30.662338 | 92 | 0.735439 | 4.40868 | false | false | false | false |
Turbo87/intellij-rust | src/main/kotlin/org/rust/ide/structure/RustTraitTreeElement.kt | 1 | 996 | package org.rust.ide.structure
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import org.rust.lang.core.psi.RustTraitItem
class RustTraitTreeElement(element: RustTraitItem) : PsiTreeElementBase<RustTraitItem>(element) {
override fun getPresentableText(): String? {
var text = element?.identifier?.text ?: return "<unknown>"
val generics = element?.genericParams?.text
if (generics != null)
text += generics
val typeBounds = element?.typeParamBounds?.polyboundList?.map { it.text }?.joinToString(" + ")
if (typeBounds != null)
text += ": $typeBounds"
return text
}
override fun getChildrenBase(): Collection<StructureViewTreeElement> {
return element?.traitMethodList?.let { methods ->
methods .filterNotNull()
.map { RustTraitMethodTreeElement(it) }
}.orEmpty();
}
}
| mit | 7c47eb270c1ef5d4aa68ca4df408fccc | 32.2 | 102 | 0.668675 | 4.906404 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PrepublishingBottomSheetFragment.kt | 1 | 10649 | package org.wordpress.android.ui.posts
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.databinding.PostPrepublishingBottomSheetBinding
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.WPBottomSheetDialogFragment
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ActionType
import org.wordpress.android.ui.posts.PrepublishingScreen.ADD_CATEGORY
import org.wordpress.android.ui.posts.PrepublishingScreen.CATEGORIES
import org.wordpress.android.ui.posts.PrepublishingScreen.HOME
import org.wordpress.android.ui.posts.prepublishing.PrepublishingBottomSheetListener
import org.wordpress.android.ui.posts.prepublishing.PrepublishingPublishSettingsFragment
import org.wordpress.android.util.ActivityUtils
import org.wordpress.android.util.KeyboardResizeViewUtil
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.observeEvent
import javax.inject.Inject
class PrepublishingBottomSheetFragment : WPBottomSheetDialogFragment(),
PrepublishingScreenClosedListener, PrepublishingActionClickedListener {
@Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject internal lateinit var analyticsTrackerWrapper: AnalyticsTrackerWrapper
private lateinit var viewModel: PrepublishingViewModel
private lateinit var keyboardResizeViewUtil: KeyboardResizeViewUtil
private var prepublishingBottomSheetListener: PrepublishingBottomSheetListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(requireNotNull(activity).application as WordPress).component().inject(this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
prepublishingBottomSheetListener = if (context is PrepublishingBottomSheetListener) {
context
} else {
throw RuntimeException("$context must implement PrepublishingBottomSheetListener")
}
}
override fun onDetach() {
super.onDetach()
prepublishingBottomSheetListener = null
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.post_prepublishing_bottom_sheet, container)
keyboardResizeViewUtil = KeyboardResizeViewUtil(requireActivity(), view)
keyboardResizeViewUtil.enable()
return view
}
override fun onResume() {
super.onResume()
/**
* The back button normally closes the bottom sheet so now instead of doing that it goes back to
* the home screen with the actions and only if pressed again will it close the bottom sheet.
*/
dialog?.setOnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (event.action != KeyEvent.ACTION_DOWN) {
true
} else {
viewModel.onDeviceBackPressed()
true
}
} else {
false
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(PostPrepublishingBottomSheetBinding.bind(view)) {
initViewModel(savedInstanceState)
dialog?.setOnShowListener { dialogInterface ->
val sheetDialog = dialogInterface as? BottomSheetDialog
val bottomSheet = sheetDialog?.findViewById<View>(
com.google.android.material.R.id.design_bottom_sheet
) as? FrameLayout
bottomSheet?.let {
val behavior = BottomSheetBehavior.from(it)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
}
}
setupMinimumHeightForFragmentContainer()
}
}
override fun onDismiss(dialog: DialogInterface) {
analyticsTrackerWrapper.track(Stat.PREPUBLISHING_BOTTOM_SHEET_DISMISSED)
super.onDismiss(dialog)
}
private fun PostPrepublishingBottomSheetBinding.setupMinimumHeightForFragmentContainer() {
val isPage = checkNotNull(arguments?.getBoolean(IS_PAGE)) {
"arguments can't be null."
}
if (isPage) {
prepublishingContentFragment.minimumHeight =
resources.getDimensionPixelSize(R.dimen.prepublishing_fragment_container_min_height_for_page)
} else {
prepublishingContentFragment.minimumHeight =
resources.getDimensionPixelSize(R.dimen.prepublishing_fragment_container_min_height)
}
}
private fun initViewModel(savedInstanceState: Bundle?) {
viewModel = ViewModelProvider(this, viewModelFactory)
.get(PrepublishingViewModel::class.java)
viewModel.navigationTarget.observeEvent(this, { navigationState ->
navigateToScreen(navigationState)
})
viewModel.dismissBottomSheet.observeEvent(this, {
dismiss()
})
viewModel.triggerOnSubmitButtonClickedListener.observeEvent(this, { publishPost ->
prepublishingBottomSheetListener?.onSubmitButtonClicked(publishPost)
})
viewModel.dismissKeyboard.observeEvent(this, {
ActivityUtils.hideKeyboardForced(view)
})
val prepublishingScreenState = savedInstanceState?.getParcelable<PrepublishingScreen>(
KEY_SCREEN_STATE
)
val site = arguments?.getSerializable(SITE) as SiteModel
viewModel.start(site, prepublishingScreenState)
}
private fun navigateToScreen(navigationTarget: PrepublishingNavigationTarget) {
val (fragment, tag) = when (navigationTarget.targetScreen) {
HOME -> {
val isStoryPost = checkNotNull(arguments?.getBoolean(IS_STORY_POST)) {
"arguments can't be null."
}
Pair(
PrepublishingHomeFragment.newInstance(isStoryPost),
PrepublishingHomeFragment.TAG
)
}
PrepublishingScreen.PUBLISH -> Pair(
PrepublishingPublishSettingsFragment.newInstance(),
PrepublishingPublishSettingsFragment.TAG
)
PrepublishingScreen.TAGS -> {
val isStoryPost = checkNotNull(arguments?.getBoolean(IS_STORY_POST)) {
"arguments can't be null."
}
Pair(
PrepublishingTagsFragment.newInstance(navigationTarget.site, isStoryPost),
PrepublishingTagsFragment.TAG
)
}
CATEGORIES -> {
val isStoryPost = checkNotNull(arguments?.getBoolean(IS_STORY_POST)) {
"arguments can't be null."
}
Pair(
PrepublishingCategoriesFragment.newInstance(
navigationTarget.site,
isStoryPost,
navigationTarget.bundle
),
PrepublishingCategoriesFragment.TAG
)
}
ADD_CATEGORY -> {
val isStoryPost = checkNotNull(arguments?.getBoolean(IS_STORY_POST)) {
"arguments can't be null."
}
Pair(
PrepublishingAddCategoryFragment.newInstance(
navigationTarget.site,
isStoryPost,
navigationTarget.bundle
),
PrepublishingAddCategoryFragment.TAG
)
}
}
fadeInFragment(fragment, tag)
}
private fun fadeInFragment(fragment: Fragment, tag: String) {
childFragmentManager.let { fragmentManager ->
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentManager.findFragmentById(R.id.prepublishing_content_fragment)?.run {
fragmentTransaction.addToBackStack(null).setCustomAnimations(
R.anim.prepublishing_fragment_fade_in,
R.anim.prepublishing_fragment_fade_out,
R.anim.prepublishing_fragment_fade_in,
R.anim.prepublishing_fragment_fade_out
)
}
fragmentTransaction.replace(R.id.prepublishing_content_fragment, fragment, tag)
fragmentTransaction.commit()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewModel.writeToBundle(outState)
}
override fun onBackClicked(bundle: Bundle?) {
viewModel.onBackClicked(bundle)
}
override fun onActionClicked(actionType: ActionType, bundle: Bundle?) {
viewModel.onActionClicked(actionType, bundle)
}
override fun onSubmitButtonClicked(publishPost: PublishPost) {
viewModel.onSubmitButtonClicked(publishPost)
}
companion object {
const val TAG = "prepublishing_bottom_sheet_fragment_tag"
const val SITE = "prepublishing_bottom_sheet_site_model"
const val IS_PAGE = "prepublishing_bottom_sheet_is_page"
const val IS_STORY_POST = "prepublishing_bottom_sheet_is_story_post"
@JvmStatic
fun newInstance(@NonNull site: SiteModel, isPage: Boolean, isStoryPost: Boolean) =
PrepublishingBottomSheetFragment().apply {
arguments = Bundle().apply {
putSerializable(SITE, site)
putBoolean(IS_PAGE, isPage)
putBoolean(IS_STORY_POST, isStoryPost)
}
}
}
}
| gpl-2.0 | 41b2193d1cf56bee4891700c9c89189e | 39.337121 | 113 | 0.640248 | 5.703803 | false | false | false | false |
android/architecture-components-samples | ViewBindingSample/app/src/main/java/com/android/example/viewbindingsample/BindFragment.kt | 1 | 1811 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.viewbindingsample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.android.example.viewbindingsample.R.string
import com.android.example.viewbindingsample.databinding.FragmentBlankBinding
/**
* View Binding example with a fragment that uses the alternate constructor for inflation and
* [onViewCreated] for binding.
*/
class BindFragment : Fragment(R.layout.fragment_blank) {
// Scoped to the lifecycle of the fragment's view (between onCreateView and onDestroyView)
private var fragmentBlankBinding: FragmentBlankBinding? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentBlankBinding.bind(view)
fragmentBlankBinding = binding
binding.textViewFragment.text = getString(string.hello_from_vb_bindfragment)
}
override fun onDestroyView() {
// Consider not storing the binding instance in a field, if not needed.
fragmentBlankBinding = null
super.onDestroyView()
}
}
| apache-2.0 | 409e6d411a9e5dba900a741fd0b5f6b3 | 36.729167 | 94 | 0.754832 | 4.471605 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-kotlin/cache/src/test/java/org/buffer/android/boilerplate/cache/test/factory/BufferooFactory.kt | 1 | 1191 | package <%= appPackage %>.cache.test.factory
import <%= appPackage %>.cache.model.CachedBufferoo
import <%= appPackage %>.data.model.BufferooEntity
import <%= appPackage %>.cache.test.factory.DataFactory.Factory.randomUuid
/**
* Factory class for Bufferoo related instances
*/
class BufferooFactory {
companion object Factory {
fun makeCachedBufferoo(): CachedBufferoo {
return CachedBufferoo(randomUuid(), randomUuid(), randomUuid())
}
fun makeBufferooEntity(): BufferooEntity {
return BufferooEntity(randomUuid(), randomUuid(), randomUuid())
}
fun makeBufferooEntityList(count: Int): List<BufferooEntity> {
val bufferooEntities = mutableListOf<BufferooEntity>()
repeat(count) {
bufferooEntities.add(makeBufferooEntity())
}
return bufferooEntities
}
fun makeCachedBufferooList(count: Int): List<CachedBufferoo> {
val cachedBufferoos = mutableListOf<CachedBufferoo>()
repeat(count) {
cachedBufferoos.add(makeCachedBufferoo())
}
return cachedBufferoos
}
}
} | mit | 2c4634cb3c2974330641e3fb5b40437c | 28.8 | 75 | 0.633081 | 5.438356 | false | true | false | false |
sjoblomj/TravellingAntColony | src/main/kotlin/org/sjoblomj/travellingantcolony/TravellingantcolonyApplication.kt | 1 | 1147 | package org.sjoblomj.travellingantcolony
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import org.sjoblomj.travellingantcolony.domain.Place
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class TravellingAntColonyApplication
fun main(args: Array<String>) {
val places = parsePlaces(args)
bruteforce(places)
SpringApplication.run(TravellingAntColonyApplication::class.java, *args)
}
fun parsePlaces(args: Array<String>): ImmutableList<Place> {
return args.mapNotNull { parsePlace(it) }.toImmutableList()
}
private fun parsePlace(place: String): Place? {
val strings = place.split(",")
if (strings.size != 2 && strings.size != 3) {
println("'$place' did not contain two coordinates")
return null
}
return try {
val c0 = strings[0].toDouble()
val c1 = strings[1].toDouble()
val name = if (strings.size == 2) "" else strings[2]
Place(c0, c1, name)
} catch (e: Exception) {
println("'$place' did not contain parseable coordinates")
null
}
}
| mit | 7763cf593bc8cad1b5b728a2e0db5c2f | 27.675 | 74 | 0.742807 | 3.773026 | false | false | false | false |
android/nowinandroid | core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/testdoubles/TestAuthorDao.kt | 1 | 2314 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.data.testdoubles
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
/**
* Test double for [AuthorDao]
*/
class TestAuthorDao : AuthorDao {
private var entitiesStateFlow = MutableStateFlow(
listOf(
AuthorEntity(
id = "1",
name = "Topic",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
)
)
override fun getAuthorEntitiesStream(): Flow<List<AuthorEntity>> =
entitiesStateFlow
override fun getAuthorEntityStream(authorId: String): Flow<AuthorEntity> {
throw NotImplementedError("Unused in tests")
}
override suspend fun insertOrIgnoreAuthors(authorEntities: List<AuthorEntity>): List<Long> {
entitiesStateFlow.value = authorEntities
// Assume no conflicts on insert
return authorEntities.map { it.id.toLong() }
}
override suspend fun updateAuthors(entities: List<AuthorEntity>) {
throw NotImplementedError("Unused in tests")
}
override suspend fun upsertAuthors(entities: List<AuthorEntity>) {
entitiesStateFlow.value = entities
}
override suspend fun deleteAuthors(ids: List<String>) {
val idSet = ids.toSet()
entitiesStateFlow.update { entities ->
entities.filterNot { idSet.contains(it.id) }
}
}
}
| apache-2.0 | 67dde4de6ba93cba34d52903cba8a6d0 | 32.057143 | 96 | 0.679343 | 4.582178 | false | true | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/show/ChallengeViewController.kt | 1 | 38239 | package io.ipoli.android.challenge.show
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.annotation.ColorRes
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.*
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.github.mikephil.charting.charts.CombinedChart
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import io.ipoli.android.Constants
import io.ipoli.android.Constants.Companion.DECIMAL_FORMATTER
import io.ipoli.android.MainActivity
import io.ipoli.android.R
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.common.ViewUtils
import io.ipoli.android.common.chart.AwesomenessScoreMarker
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.text.DateFormatter
import io.ipoli.android.common.view.*
import io.ipoli.android.common.view.anim.AccelerateDecelerateEasingFunction
import io.ipoli.android.common.view.recyclerview.*
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.RepeatingQuest
import io.ipoli.android.tag.Tag
import kotlinx.android.synthetic.main.controller_challenge.view.*
import kotlinx.android.synthetic.main.item_challenge_average_value.view.*
import kotlinx.android.synthetic.main.item_challenge_progress.view.*
import kotlinx.android.synthetic.main.item_challenge_quest.view.*
import kotlinx.android.synthetic.main.item_challenge_target_value.view.*
import kotlinx.android.synthetic.main.item_quest_tag_list.view.*
import org.threeten.bp.LocalDate
import org.threeten.bp.YearMonth
import org.threeten.bp.format.TextStyle
import java.util.*
/**
* Created by Venelin Valkov <[email protected]>
* on 03/05/2018.
*/
class ChallengeViewController(args: Bundle? = null) :
ReduxViewController<ChallengeAction, ChallengeViewState, ChallengeReducer>(args) {
override val reducer = ChallengeReducer
private var challengeId = ""
private var showEdit = true
private var showComplete = true
private val appBarOffsetListener = object :
AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout, state: State) {
appBarLayout.post {
if (state == State.EXPANDED) {
val supportActionBar = (activity as MainActivity).supportActionBar
supportActionBar?.setDisplayShowTitleEnabled(false)
} else if (state == State.COLLAPSED) {
val supportActionBar = (activity as MainActivity).supportActionBar
supportActionBar?.setDisplayShowTitleEnabled(true)
}
}
}
}
constructor(
challengeId: String
) : this() {
this.challengeId = challengeId
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
applyStatusBarColors = false
val view = inflater.inflate(R.layout.controller_challenge, container, false)
setToolbar(view.toolbar)
view.collapsingToolbarContainer.isTitleEnabled = false
view.questList.layoutManager = LinearLayoutManager(container.context)
view.questList.adapter = QuestAdapter()
view.habitList.layoutManager = LinearLayoutManager(container.context)
view.habitList.adapter = HabitAdapter()
val questSwipeHandler = object : SimpleSwipeCallback(
R.drawable.ic_done_white_24dp,
R.color.md_green_500,
R.drawable.ic_delete_white_24dp,
R.color.md_red_500
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
if (direction == ItemTouchHelper.START) {
dispatch(ChallengeAction.RemoveQuestFromChallenge(viewHolder.adapterPosition))
}
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
) = ItemTouchHelper.START
}
val questTouchHelper = ItemTouchHelper(questSwipeHandler)
questTouchHelper.attachToRecyclerView(view.questList)
val habitSwipeHandler = object : SimpleSwipeCallback(
R.drawable.ic_done_white_24dp,
R.color.md_green_500,
R.drawable.ic_delete_white_24dp,
R.color.md_red_500
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
if (direction == ItemTouchHelper.START) {
dispatch(ChallengeAction.RemoveHabitFromChallenge(habitId(viewHolder)))
}
}
private fun habitId(holder: RecyclerView.ViewHolder): String {
val adapter = view.habitList.adapter as HabitAdapter
return adapter.getItemAt(holder.adapterPosition).id
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
) = ItemTouchHelper.START
}
val habitTouchHelper = ItemTouchHelper(habitSwipeHandler)
habitTouchHelper.attachToRecyclerView(view.habitList)
view.addQuests.onDebounceClick {
navigateFromRoot().toQuestPicker(challengeId)
}
view.trackedValueList.layoutManager = LinearLayoutManager(view.context)
view.trackedValueList.isNestedScrollingEnabled = false
view.trackedValueList.addItemDecoration(TopMarginDecoration(8))
view.trackedValueList.adapter = TrackedValueAdapter()
view.appbar.addOnOffsetChangedListener(appBarOffsetListener)
return view
}
private fun setupLineChart(chart: LineChart) {
with(chart) {
description = null
setExtraOffsets(0f, 0f, 0f, 0f)
isDoubleTapToZoomEnabled = false
setTouchEnabled(true)
setPinchZoom(false)
extraTopOffset = 16f
extraBottomOffset = 16f
setDrawGridBackground(false)
axisRight.axisMinimum = 0f
axisRight.spaceTop = 0f
axisRight.granularity = 1f
axisRight.setDrawAxisLine(false)
axisRight.textSize = ViewUtils.spToPx(4, activity!!).toFloat()
axisRight.textColor = colorRes(colorTextSecondaryResource)
axisRight.setValueFormatter { value, _ -> " ${value.toInt()}" }
axisLeft.isEnabled = false
xAxis.yOffset = ViewUtils.dpToPx(2f, activity!!)
xAxis.isGranularityEnabled = true
xAxis.granularity = 1f
xAxis.textSize = ViewUtils.spToPx(4, activity!!).toFloat()
xAxis.textColor = colorRes(colorTextSecondaryResource)
xAxis.setDrawGridLines(false)
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setAvoidFirstLastClipping(true)
xAxis.setDrawAxisLine(false)
xAxis.labelRotationAngle = 335f
legend.textColor = colorRes(colorTextSecondaryResource)
legend.textSize = ViewUtils.spToPx(5, activity!!).toFloat()
legend.form = Legend.LegendForm.CIRCLE
legend.xEntrySpace = ViewUtils.dpToPx(4f, activity!!)
setDrawBorders(false)
}
}
private fun setupBarChart(chart: CombinedChart) {
with(chart) {
description = null
setExtraOffsets(0f, 0f, 0f, 0f)
isDoubleTapToZoomEnabled = false
setDrawValueAboveBar(true)
setTouchEnabled(true)
setPinchZoom(false)
extraTopOffset = 16f
extraBottomOffset = 16f
setDrawGridBackground(false)
axisRight.spaceTop = 0f
axisRight.granularity = 1f
axisRight.setDrawAxisLine(false)
axisRight.textSize = ViewUtils.spToPx(4, activity!!).toFloat()
axisRight.textColor = colorRes(colorTextSecondaryResource)
axisRight.setValueFormatter { value, _ -> " ${value.toInt()}" }
axisLeft.isEnabled = false
// xAxis.yOffset = ViewUtils.dpToPx(-2f, activity!!)
xAxis.isGranularityEnabled = true
xAxis.granularity = 1f
xAxis.textSize = ViewUtils.spToPx(4f, activity!!).toFloat()
xAxis.textColor = colorRes(colorTextSecondaryResource)
xAxis.setDrawGridLines(false)
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setAvoidFirstLastClipping(true)
xAxis.setDrawAxisLine(false)
xAxis.labelRotationAngle = 335f
legend.textColor = colorRes(colorTextSecondaryResource)
legend.textSize = ViewUtils.spToPx(5, activity!!).toFloat()
legend.form = Legend.LegendForm.CIRCLE
legend.xEntrySpace = ViewUtils.dpToPx(4f, activity!!)
setDrawBorders(false)
}
}
override fun onCreateLoadAction() = ChallengeAction.Load(challengeId)
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.challenge_menu, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.actionComplete).isVisible = showComplete
menu.findItem(R.id.actionEdit).isVisible = showEdit
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) =
when (item.itemId) {
android.R.id.home ->
router.handleBack()
R.id.actionComplete -> {
navigate().toConfirmation(
stringRes(R.string.dialog_confirmation_title),
stringRes(R.string.dialog_complete_challenge_message)
) {
dispatch(ChallengeAction.Complete(challengeId))
router.handleBack()
}
true
}
R.id.actionEdit -> {
showEdit()
true
}
R.id.actionDelete -> {
navigate().toConfirmation(
stringRes(R.string.dialog_confirmation_title),
stringRes(R.string.dialog_remove_challenge_message)
) {
dispatch(ChallengeAction.Remove(challengeId))
router.handleBack()
}
true
}
else -> super.onOptionsItemSelected(item)
}
private fun showEdit() {
navigateFromRoot().toEditChallenge(challengeId)
}
override fun onAttach(view: View) {
super.onAttach(view)
showBackButton()
val showTitle =
appBarOffsetListener.currentState != AppBarStateChangeListener.State.EXPANDED
(activity as MainActivity).supportActionBar?.setDisplayShowTitleEnabled(showTitle)
}
override fun onDetach(view: View) {
(activity as MainActivity).supportActionBar?.setDisplayShowTitleEnabled(true)
super.onDetach(view)
}
override fun onDestroyView(view: View) {
view.appbar.removeOnOffsetChangedListener(appBarOffsetListener)
super.onDestroyView(view)
}
override fun render(state: ChallengeViewState, view: View) {
when (state.type) {
ChallengeViewState.StateType.DATA_CHANGED -> {
showComplete = state.canComplete
showEdit = state.canEdit
activity!!.invalidateOptionsMenu()
if (state.canAdd) {
view.addQuests.visible()
} else {
view.addQuests.gone()
}
colorLayout(state, view)
renderName(state.name, view)
view.difficulty.text = state.difficulty
view.endDate.text = state.endText
view.nextDate.text = state.nextText
renderTags(state.tags, view)
renderTrackedValues(state.trackedValueViewModels, view)
renderMotivations(state, view)
renderNote(state, view)
renderQuests(state, view)
renderHabits(state, view)
}
else -> {
}
}
}
private fun renderTrackedValues(progress: List<TrackedValueViewModel>, view: View) {
(view.trackedValueList.adapter as TrackedValueAdapter).updateAll(progress)
}
private fun renderTags(
tags: List<Tag>,
view: View
) {
view.tagList.removeAllViews()
val inflater = LayoutInflater.from(activity!!)
tags.forEach { tag ->
val item = inflater.inflate(R.layout.item_quest_tag_list, view.tagList, false)
renderTag(item, tag)
view.tagList.addView(item)
}
}
private fun renderTag(view: View, tag: Tag) {
view.tagName.text = tag.name
val indicator = view.tagName.compoundDrawablesRelative[0] as GradientDrawable
indicator.setColor(colorRes(tag.color.androidColor.color500))
}
private fun renderNote(
state: ChallengeViewState,
view: View
) {
if (state.note != null && state.note.isNotBlank()) {
view.note.setMarkdown(state.note)
} else {
view.note.setText(R.string.tap_to_add_note)
view.note.setTextColor(colorRes(colorTextSecondaryResource))
}
view.note.onDebounceClick { showEdit() }
}
private fun renderMotivations(state: ChallengeViewState, view: View) {
val motivationsViews = listOf(view.motivation1, view.motivation2, view.motivation3)
motivationsViews.forEach { it.gone() }
state.motivations.forEachIndexed { index, text ->
val mView = motivationsViews[index]
mView.visible()
@SuppressLint("SetTextI18n")
mView.text = "${index + 1}. $text"
}
}
private fun renderQuests(state: ChallengeViewState, view: View) {
if (state.questViewModels.isEmpty()) {
view.emptyQuestList.visible()
view.questList.gone()
} else {
(view.questList.adapter as QuestAdapter).updateAll(state.questViewModels)
view.emptyQuestList.gone()
view.questList.visible()
}
}
private fun renderHabits(state: ChallengeViewState, view: View) {
if (state.habitViewModels.isEmpty()) {
view.emptyHabitList.visible()
view.habitList.gone()
} else {
(view.habitList.adapter as HabitAdapter).updateAll(state.habitViewModels)
view.emptyHabitList.gone()
view.habitList.visible()
}
}
private fun colorLayout(
state: ChallengeViewState,
view: View
) {
view.appbar.setBackgroundColor(colorRes(state.color500))
view.toolbar.setBackgroundColor(colorRes(state.color500))
view.collapsingToolbarContainer.setContentScrimColor(colorRes(state.color500))
activity?.window?.navigationBarColor = colorRes(state.color500)
activity?.window?.statusBarColor = colorRes(state.color700)
}
private fun renderName(
name: String,
view: View
) {
toolbarTitle = name
view.name.text = name
}
sealed class TrackedValueViewModel(
override val id: String
) : RecyclerViewViewModel {
data class Progress(
override val id: String,
val progressPercent: Int,
val progressText: String,
val currentDate: LocalDate,
val calendars: List<Calendar>,
val monthTitle: String
) : TrackedValueViewModel(id)
data class Target(
override val id: String,
val name: String,
val units: String,
val isCumulative: Boolean,
val currentValue: String,
val targetValue: Double,
val progressPercent: Int,
val remainingText: String,
val chartMin: Double,
val chartMax: Double,
val chartDates: List<LocalDate>,
val chartEntries: List<Entry>
) : TrackedValueViewModel(id)
data class Average(
override val id: String,
val name: String,
val units: String,
val averageValue: Double,
val targetValue: Double,
val deviationText: String,
val chartMax: Double,
val chartDates: List<LocalDate>,
val chartEntries: List<BarEntry>,
val chartEntryColors: List<Int>
) : TrackedValueViewModel(id)
}
enum class ViewType {
TARGET, AVERAGE, PROGRESS
}
inner class TrackedValueAdapter : MultiViewRecyclerViewAdapter<TrackedValueViewModel>() {
override fun onRegisterItemBinders() {
registerBinder<TrackedValueViewModel.Progress>(
ViewType.PROGRESS.ordinal,
R.layout.item_challenge_progress
) { vm, view, _ ->
@SuppressLint("SetTextI18n")
view.progressCompleteCurrent.text = "${vm.progressPercent}%"
view.progressCompleteProgress.progress = vm.progressPercent
view.progressCompleteRemaining.text = vm.progressText
view.calendarView.clearSchemeDate()
view.calendarView.setOnMonthChangeListener(null)
view.calendarView.post {
view.calendarView.setSchemeDate(vm.calendars.map { it.toString() to it }.toMap())
view.calendarMonth.text = vm.monthTitle
view.calendarView.scrollToCalendar(
vm.currentDate.year,
vm.currentDate.monthValue,
vm.currentDate.dayOfMonth
)
view.calendarView.setOnMonthChangeListener(SkipFirstChangeMonthListener { year, month ->
dispatch(
ChallengeAction.ChangeProgressMonth(
challengeId,
YearMonth.of(year, month)
)
)
})
}
}
registerBinder<TrackedValueViewModel.Target>(
ViewType.TARGET.ordinal,
R.layout.item_challenge_target_value
) { vm, view, _ ->
@SuppressLint("SetTextI18n")
view.targetTrackedValueLabel.text = "${vm.name} (${vm.units})"
view.targetTrackedValueProgress.progress = vm.progressPercent
view.targetTrackedValueCurrent.text = vm.currentValue
view.targetTrackedValueRemaining.text = vm.remainingText
view.targetTrackedValueLog.onDebounceClick {
navigate().toLogValue(
valueName = vm.name,
valueUnits = vm.units,
showAccumulateValueHint = vm.isCumulative,
logValueListener = { log ->
dispatch(
ChallengeAction.LogValue(
challengeId = challengeId,
trackValueId = vm.id,
log = log
)
)
})
}
setupLineChart(view.targetTrackedValueChart)
renderTargetValueChart(vm, view.targetTrackedValueChart)
}
registerBinder<TrackedValueViewModel.Average>(
ViewType.AVERAGE.ordinal,
R.layout.item_challenge_average_value
) { vm, view, _ ->
@SuppressLint("SetTextI18n")
view.averageValueLabel.text = "${vm.name} (${vm.units})"
view.logAverageValue.onDebounceClick {
navigate().toLogValue(
valueName = vm.name,
valueUnits = vm.units,
showAccumulateValueHint = false,
logValueListener = { log ->
dispatch(
ChallengeAction.LogValue(
challengeId = challengeId,
trackValueId = vm.id,
log = log
)
)
})
}
view.averageValue.text = DECIMAL_FORMATTER.format(vm.averageValue)
view.averageValueDeviation.text = vm.deviationText
setupBarChart(view.averageValueChart)
renderAverageValueChart(vm, view.averageValueChart)
}
}
inner class SkipFirstChangeMonthListener(private inline val onChange: (Int, Int) -> Unit) :
CalendarView.OnMonthChangeListener {
override fun onMonthChange(year: Int, month: Int) {
if (isFirstChange) {
isFirstChange = false
return
}
onChange(year, month)
}
private var isFirstChange = true
}
}
private fun renderAverageValueChart(
trackedValue: TrackedValueViewModel.Average,
chart: CombinedChart
) {
val barDataSet = BarDataSet(
trackedValue.chartEntries,
trackedValue.name
)
barDataSet.colors = trackedValue.chartEntryColors
barDataSet.axisDependency = YAxis.AxisDependency.RIGHT
val data = BarData(barDataSet)
data.setValueTextSize(ViewUtils.spToPx(4f, activity!!).toFloat())
data.setValueTextColor(colorRes(colorTextPrimaryResource))
data.setValueFormatter { value, _, _, _ ->
DECIMAL_FORMATTER.format(value)
}
data.barWidth = 0.5f
data.isHighlightEnabled = false
chart.xAxis.valueFormatter = IndexAxisValueFormatter(
trackedValue.chartDates.map { DateFormatter.formatWithoutYear(chart.context, it) }
)
val goalSet = LineDataSet(
listOf(
Entry(
-1f,
trackedValue.targetValue.toFloat()
)
) + trackedValue.chartDates.mapIndexed { index, _ ->
Entry(index.toFloat(), trackedValue.targetValue.toFloat())
} + listOf(
Entry(
trackedValue.chartDates.size.toFloat(),
trackedValue.targetValue.toFloat()
)
), "goal"
)
goalSet.isHighlightEnabled = false
goalSet.color = attrData(R.attr.colorAccent)
goalSet.lineWidth = ViewUtils.dpToPx(0.5f, chart.context)
goalSet.setDrawCircles(false)
goalSet.mode = LineDataSet.Mode.LINEAR
goalSet.setDrawValues(false)
goalSet.axisDependency = YAxis.AxisDependency.RIGHT
val combinedData = CombinedData()
combinedData.setData(LineData(goalSet))
combinedData.setData(data)
chart.data = combinedData
chart.xAxis.axisMinimum = -0.5f
chart.xAxis.axisMaximum = trackedValue.chartDates.size.toFloat() - 0.5f
chart.axisRight.axisMinimum = 0f
chart.axisRight.axisMaximum = trackedValue.chartMax.toFloat()
chart.setVisibleYRange(0f, trackedValue.chartMax.toFloat(), YAxis.AxisDependency.RIGHT)
chart.invalidate()
chart.animateY(longAnimTime.toInt(), AccelerateDecelerateEasingFunction)
}
private fun renderTargetValueChart(
trackedValue: TrackedValueViewModel.Target,
chart: LineChart
) {
chart.marker = AwesomenessScoreMarker(chart.context)
val logDataSet = LineDataSet(trackedValue.chartEntries, trackedValue.name)
logDataSet.color = attrData(R.attr.colorPrimary)
logDataSet.lineWidth = ViewUtils.dpToPx(1f, activity!!)
logDataSet.setDrawCircles(true)
logDataSet.circleRadius = 6f
logDataSet.setCircleColor(attrData(R.attr.colorPrimary))
logDataSet.setDrawCircleHole(false)
logDataSet.highLightColor = attrData(R.attr.colorAccent)
logDataSet.mode = LineDataSet.Mode.LINEAR
logDataSet.setDrawValues(false)
logDataSet.axisDependency = YAxis.AxisDependency.RIGHT
val goalSet = LineDataSet(
trackedValue.chartDates.mapIndexed { index, _ ->
Entry(index.toFloat(), trackedValue.targetValue.toFloat())
}, "goal"
)
goalSet.isHighlightEnabled = false
goalSet.color = attrData(R.attr.colorAccent)
goalSet.lineWidth = ViewUtils.dpToPx(0.5f, chart.context)
goalSet.setDrawCircles(false)
goalSet.mode = LineDataSet.Mode.LINEAR
goalSet.setDrawValues(false)
goalSet.axisDependency = YAxis.AxisDependency.RIGHT
chart.xAxis.valueFormatter = IndexAxisValueFormatter(
trackedValue.chartDates.map { DateFormatter.formatWithoutYear(chart.context, it) }
)
chart.data = LineData(goalSet, logDataSet)
chart.setVisibleYRange(
trackedValue.chartMin.toFloat(),
trackedValue.chartMax.toFloat(),
YAxis.AxisDependency.RIGHT
)
chart.axisRight.axisMinimum = trackedValue.chartMin.toFloat()
chart.axisRight.axisMaximum = trackedValue.chartMax.toFloat()
chart.invalidate()
chart.animateX(longAnimTime.toInt(), AccelerateDecelerateEasingFunction)
}
data class QuestViewModel(
override val id: String,
val name: String,
@ColorRes val color: Int,
@ColorRes val textColor: Int,
val icon: IIcon,
val isRepeating: Boolean,
val isCompleted: Boolean
) : RecyclerViewViewModel
inner class QuestAdapter :
BaseRecyclerViewAdapter<QuestViewModel>(R.layout.item_challenge_quest) {
override fun onBindViewModel(vm: QuestViewModel, view: View, holder: SimpleViewHolder) {
view.questName.text = vm.name
view.questName.setTextColor(colorRes(vm.textColor))
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(
IconicsDrawable(view.context)
.icon(vm.icon)
.colorRes(R.color.md_white)
.sizeDp(22)
)
view.questRepeatIndicator.visible = vm.isRepeating
view.onDebounceClick {
if (vm.isRepeating) {
navigateFromRoot().toRepeatingQuest(vm.id, HorizontalChangeHandler())
} else {
navigateFromRoot().toQuest(vm.id, HorizontalChangeHandler())
}
}
}
}
data class HabitViewModel(
override val id: String,
val name: String,
@ColorRes val color: Int,
val icon: IIcon
) : RecyclerViewViewModel
inner class HabitAdapter :
BaseRecyclerViewAdapter<HabitViewModel>(R.layout.item_challenge_quest) {
override fun onBindViewModel(vm: HabitViewModel, view: View, holder: SimpleViewHolder) {
view.questName.text = vm.name
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(
IconicsDrawable(view.context)
.icon(vm.icon)
.colorRes(R.color.md_white)
.sizeDp(22)
)
view.questRepeatIndicator.gone()
view.onDebounceClick {
navigateFromRoot().toEditHabit(vm.id)
}
}
}
private val ChallengeViewState.color500
get() = color.androidColor.color500
private val ChallengeViewState.color700
get() = color.androidColor.color700
private val ChallengeViewState.endText
get() = DateFormatter.formatWithoutYear(activity!!, endDate)
private val ChallengeViewState.nextText
get() = nextDate?.let { DateFormatter.formatWithoutYear(activity!!, it) }
?: stringRes(R.string.unscheduled)
private val ChallengeViewState.trackedValueViewModels
get() = trackedValues.sortedWith(Comparator { t1, t2 ->
when {
t1 is Challenge.TrackedValue.Progress -> -1
t2 is Challenge.TrackedValue.Progress -> 1
else -> 0
}
}).map {
when (it) {
is Challenge.TrackedValue.Progress -> {
val today = LocalDate.now()
TrackedValueViewModel.Progress(
id = it.id,
progressPercent = ((it.completedCount.toFloat() / it.allCount.toFloat()) * 100).toInt(),
progressText = if (it.allCount == 0)
"No Quests added"
else
"${it.completedCount}/${it.allCount} Quests done",
currentDate = currentDate,
calendars = progressItems!!.map { c ->
val itemDate = c.date
Calendar().apply {
day = itemDate.dayOfMonth
month = itemDate.monthValue
year = itemDate.year
isCurrentDay = itemDate == today
isCurrentMonth = itemDate.month == today.month
isLeapYear = itemDate.isLeapYear
scheme = "${c.state.name},${c.color.name},${c.progress}," +
"${c.shouldDoNothing}," +
"${c.isPreviousCompleted},${c.isNextCompleted}," +
"${c.isFirstDay},${c.isEndDay}"
}
},
monthTitle = "${
currentDate.month.getDisplayName(
TextStyle.FULL,
Locale.getDefault()
)}, ${currentDate.year}"
)
}
is Challenge.TrackedValue.Target -> {
val dates = LocalDate.now().minusDays(9).datesBetween(LocalDate.now())
val valueHistory = if (it.isCumulative) it.cumulativeHistory!! else it.history
val values = dates.map { d -> valueHistory[d]?.value }
val minVal =
if (it.isCumulative)
0.0
else
values.filterNotNull().min() ?: Math.min(
it.startValue,
it.targetValue
)
val maxVal =
if (it.isCumulative)
Math.max(it.targetValue, values.filterNotNull().max() ?: 0.0)
else
values.filterNotNull().max() ?: Math.max(
it.startValue,
it.targetValue
)
val chartEntries = dates.mapIndexed { index, localDate ->
valueHistory[localDate]?.let { log ->
Entry(
index.toFloat(),
log.value.toFloat(),
log.value.toFloat()
)
}
}.filterNotNull()
val total = Math.abs(it.targetValue - it.startValue)
val complete = Math.abs(it.currentValue - it.startValue)
val progressPercent = ((complete / total) * 100.0).toInt()
TrackedValueViewModel.Target(
id = it.id,
name = it.name,
units = it.units,
isCumulative = it.isCumulative,
currentValue = Constants.DECIMAL_FORMATTER.format(it.currentValue),
targetValue = it.targetValue,
progressPercent = progressPercent,
remainingText = "${DECIMAL_FORMATTER.format(it.remainingValue)} ${it.units} remaining",
chartMin = Math.max(Math.floor((minVal - minVal * 0.1) / 10) * 10, 0.0),
chartMax = Math.ceil((maxVal + maxVal * 0.1) / 10) * 10,
chartDates = dates,
chartEntries = if (chartEntries.isEmpty()) {
listOf(
Entry(
(dates.size - 1).toFloat(),
it.currentValue.toFloat(),
it.currentValue.toFloat()
)
)
} else {
chartEntries
}
)
}
is Challenge.TrackedValue.Average -> {
val dates = LocalDate.now().minusDays(6).datesBetween(LocalDate.now())
val values = dates.map { d -> it.history[d]?.value }
val nonNullValues = values.filterNotNull()
val valueSum = nonNullValues.sum()
val average =
if (nonNullValues.isEmpty()) it.targetValue else valueSum / nonNullValues.size
val deviation = Math.abs(it.targetValue - average)
val deviationText = if (average >= it.lowerBound && average <= it.upperBound) {
"You're doing great!"
} else if (average <= it.lowerBound) {
"${DECIMAL_FORMATTER.format(deviation)} below target"
} else {
"${DECIMAL_FORMATTER.format(deviation)} above target"
}
val maxVal = Math.max(nonNullValues.max() ?: 0.0, it.upperBound)
val chartEntries = values.asSequence().mapIndexed { index, v ->
if (v != null) {
BarEntry(index.toFloat(), v.toFloat())
} else null
}.filterNotNull().toMutableList()
val chartColors = nonNullValues.map { v ->
if (v >= it.lowerBound && v <= it.upperBound) {
colorRes(R.color.md_green_500)
} else
colorRes(R.color.md_red_500)
}
TrackedValueViewModel.Average(
id = it.id,
name = it.name,
units = it.units,
averageValue = average,
targetValue = it.targetValue,
deviationText = deviationText,
chartMax = Math.ceil((maxVal + maxVal * 0.1) / 10) * 10,
chartDates = dates,
chartEntries = chartEntries,
chartEntryColors = chartColors
)
}
}
}
private val ChallengeViewState.questViewModels
get() = quests.map {
when (it) {
is Quest -> QuestViewModel(
id = it.id,
name = it.name,
color = if (it.isCompleted) R.color.md_grey_300 else it.color.androidColor.color500,
textColor = if (it.isCompleted) colorTextHintResource else colorTextPrimaryResource,
icon = it.icon?.androidIcon?.icon ?: GoogleMaterial.Icon.gmd_local_florist,
isRepeating = false,
isCompleted = it.isCompleted
)
is RepeatingQuest -> QuestViewModel(
id = it.id,
name = it.name,
color = it.color.androidColor.color500,
textColor = if (it.isCompleted) colorTextHintResource else colorTextPrimaryResource,
icon = it.icon?.androidIcon?.icon ?: GoogleMaterial.Icon.gmd_local_florist,
isRepeating = true,
isCompleted = it.isCompleted
)
}
}
private val ChallengeViewState.habitViewModels
get() = habits.map {
HabitViewModel(
id = it.id,
name = it.name,
color = it.color.androidColor.color500,
icon = it.icon.androidIcon.icon
)
}
} | gpl-3.0 | 0302634e3befb3ca4cb0c5f87b46234c | 37.432161 | 112 | 0.563979 | 5.259112 | false | false | false | false |
hzsweers/CatchUp | services/producthunt/src/main/kotlin/io/sweers/catchup/service/producthunt/model/User.kt | 1 | 1124 | /*
* Copyright (C) 2019. Zac Sweers
*
* 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.sweers.catchup.service.producthunt.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Models a user on Product Hunt.
*/
@JsonClass(generateAdapter = true)
data class User(
@Json(name = "created_at") val createdAt: String,
val headline: String?,
val id: Long,
@Json(name = "image_url") val imageUrl: Map<String, String>,
val name: String,
@Json(name = "profile_url") val profileUrl: String,
val username: String,
@Json(name = "website_url") val websiteUrl: String?
)
| apache-2.0 | 99a6f20a9174e4d1f947df9471c88ead | 32.058824 | 75 | 0.72331 | 3.771812 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/attribute/BonusBooster.kt | 1 | 12741 | package io.ipoli.android.player.attribute
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.entity.SharingPreference
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.pet.Pet
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.data.Player.AttributeType.*
import io.ipoli.android.player.data.Player.Rank.*
import io.ipoli.android.quest.Quest
data class Booster(
val healthPointsPercentage: Int = 0,
val experiencePercentage: Int = 0,
val coinsPercentage: Int = 0,
val itemDropPercentage: Int = 0,
val strengthPercentage: Int = 0,
val intelligencePercentage: Int = 0,
val charismaPercentage: Int = 0,
val expertisePercentage: Int = 0,
val wellBeingPercentage: Int = 0,
val willpowerPercentage: Int = 0
) {
companion object {
fun ofAllAttributeBonus(bonus: Int) =
Booster(
strengthPercentage = bonus,
intelligencePercentage = bonus,
charismaPercentage = bonus,
expertisePercentage = bonus,
wellBeingPercentage = bonus,
willpowerPercentage = bonus
)
}
fun combineWith(other: Booster) =
Booster(
healthPointsPercentage = healthPointsPercentage + other.healthPointsPercentage,
experiencePercentage = experiencePercentage + other.experiencePercentage,
coinsPercentage = coinsPercentage + other.coinsPercentage,
itemDropPercentage = itemDropPercentage + other.itemDropPercentage,
strengthPercentage = strengthPercentage + other.strengthPercentage,
intelligencePercentage = intelligencePercentage + other.intelligencePercentage,
charismaPercentage = charismaPercentage + other.charismaPercentage,
expertisePercentage = expertisePercentage + other.expertisePercentage,
wellBeingPercentage = wellBeingPercentage + other.wellBeingPercentage,
willpowerPercentage = willpowerPercentage + other.willpowerPercentage
)
fun attributeBonus(attributeType: Player.AttributeType) =
when (attributeType) {
STRENGTH -> strengthPercentage
INTELLIGENCE -> intelligencePercentage
CHARISMA -> charismaPercentage
EXPERTISE -> expertisePercentage
WELL_BEING -> wellBeingPercentage
WILLPOWER -> willpowerPercentage
}
}
object TotalBonusBooster : BonusBooster {
private val bonusBoosters = listOf(
PetBooster(),
PetItemBooster(),
StrengthBooster(),
IntelligenceBooster(),
CharismaBooster(),
ExpertiseBooster(),
WellBeingBooster(),
WillpowerBooster()
)
override fun forQuest(quest: Quest, player: Player, rank: Player.Rank): Booster {
var booster = Booster()
bonusBoosters.forEach {
booster = booster.combineWith(it.forQuest(quest, player, rank))
}
return booster
}
override fun forHabit(habit: Habit, player: Player, rank: Player.Rank): Booster {
var booster = Booster()
bonusBoosters.forEach {
booster = booster.combineWith(it.forHabit(habit, player, rank))
}
return booster
}
override fun forChallenge(
challenge: Challenge,
player: Player,
rank: Player.Rank
): Booster {
var booster = Booster()
bonusBoosters.forEach {
booster = booster.combineWith(it.forChallenge(challenge, player, rank))
}
return booster
}
override fun forDailyChallenge(player: Player, rank: Player.Rank): Booster {
var booster = Booster()
bonusBoosters.forEach {
booster = booster.combineWith(it.forDailyChallenge(player, rank))
}
return booster
}
}
interface BonusBooster {
fun forQuest(quest: Quest, player: Player, rank: Player.Rank): Booster
fun forHabit(habit: Habit, player: Player, rank: Player.Rank): Booster
fun forChallenge(challenge: Challenge, player: Player, rank: Player.Rank): Booster
fun forDailyChallenge(player: Player, rank: Player.Rank): Booster
}
interface BoostStrategy {
fun specialistBooster(): Booster
fun adeptBooster(): Booster
fun apprenticeBooster(): Booster
}
open class NoBoostStrategy : BoostStrategy {
override fun specialistBooster() = Booster()
override fun adeptBooster() = Booster()
override fun apprenticeBooster() = Booster()
}
abstract class BaseAttributeBonusBooster(private val attributeType: Player.AttributeType) :
BonusBooster {
override fun forQuest(quest: Quest, player: Player, rank: Player.Rank) =
applyBoostStrategy(createQuestBoostStrategy(quest), player, rank)
override fun forHabit(habit: Habit, player: Player, rank: Player.Rank) =
applyBoostStrategy(createHabitBoostStrategy(habit), player, rank)
override fun forChallenge(
challenge: Challenge,
player: Player,
rank: Player.Rank
) =
applyBoostStrategy(createChallengeBoostStrategy(challenge), player, rank)
override fun forDailyChallenge(player: Player, rank: Player.Rank) =
applyBoostStrategy(createDailyChallengeBoostStrategy(), player, rank)
private fun applyBoostStrategy(strategy: BoostStrategy, player: Player, rank: Player.Rank) =
when (AttributeRank.of(player.attributeLevel(attributeType), rank)) {
SPECIALIST ->
strategy.apprenticeBooster()
.combineWith(strategy.adeptBooster())
.combineWith(strategy.specialistBooster())
ADEPT ->
strategy.apprenticeBooster()
.combineWith(strategy.adeptBooster())
APPRENTICE ->
strategy.apprenticeBooster()
else -> Booster()
}
protected open fun createQuestBoostStrategy(quest: Quest): BoostStrategy = NoBoostStrategy()
protected open fun createHabitBoostStrategy(habit: Habit): BoostStrategy = NoBoostStrategy()
protected open fun createChallengeBoostStrategy(challenge: Challenge): BoostStrategy =
NoBoostStrategy()
protected open fun createDailyChallengeBoostStrategy(): BoostStrategy = NoBoostStrategy()
}
class PetBooster : BonusBooster {
override fun forQuest(quest: Quest, player: Player, rank: Player.Rank) =
applyPetBonus(player)
override fun forHabit(habit: Habit, player: Player, rank: Player.Rank) =
applyPetBonus(player)
override fun forChallenge(
challenge: Challenge,
player: Player,
rank: Player.Rank
) = applyPetBonus(player)
private fun applyPetBonus(player: Player) =
player.pet.let {
Booster(
experiencePercentage = it.experienceBonus.toInt(),
coinsPercentage = it.coinBonus.toInt(),
itemDropPercentage = it.itemDropBonus.toInt()
)
}
override fun forDailyChallenge(player: Player, rank: Player.Rank) = Booster()
}
class PetItemBooster : BonusBooster {
override fun forQuest(quest: Quest, player: Player, rank: Player.Rank) =
applyPetItemBonus(player.pet)
override fun forHabit(habit: Habit, player: Player, rank: Player.Rank) =
applyPetItemBonus(player.pet)
override fun forChallenge(
challenge: Challenge,
player: Player,
rank: Player.Rank
) = applyPetItemBonus(player.pet)
private fun applyPetItemBonus(pet: Pet): Booster {
val eq = pet.equipment
var xp = 0
var coins = 0
var itemDrop = 0
eq.hat?.let {
xp += it.experienceBonus
coins += it.coinBonus
itemDrop += it.bountyBonus
}
eq.mask?.let {
xp += it.experienceBonus
coins += it.coinBonus
itemDrop += it.bountyBonus
}
eq.bodyArmor?.let {
xp += it.experienceBonus
coins += it.coinBonus
itemDrop += it.bountyBonus
}
return Booster(
experiencePercentage = xp,
coinsPercentage = coins,
itemDropPercentage = itemDrop
)
}
override fun forDailyChallenge(player: Player, rank: Player.Rank) = Booster()
}
class StrengthBooster : BaseAttributeBonusBooster(STRENGTH) {
override fun createQuestBoostStrategy(quest: Quest) =
object : NoBoostStrategy() {
override fun specialistBooster() =
Booster(healthPointsPercentage = 20)
}
}
class IntelligenceBooster : BaseAttributeBonusBooster(INTELLIGENCE) {
override fun createQuestBoostStrategy(quest: Quest) =
object : NoBoostStrategy() {
override fun adeptBooster() =
if (quest.hasTimer)
Booster(experiencePercentage = 100)
else
Booster()
override fun apprenticeBooster() =
if (quest.completedAtTime == null || quest.startTime == null || quest.endTime == null) {
Booster()
} else if (!quest.isScheduled || !quest.completedAtTime.isBetween(
quest.startTime,
quest.endTime!!.plus(120)
)
) {
Booster()
} else {
Booster(experiencePercentage = 20, coinsPercentage = 20)
}
}
}
class CharismaBooster : BaseAttributeBonusBooster(CHARISMA) {
override fun createChallengeBoostStrategy(challenge: Challenge) =
object : NoBoostStrategy() {
override fun specialistBooster() =
if (challenge.sharingPreference == SharingPreference.PRIVATE) {
Booster()
} else {
Booster.ofAllAttributeBonus(50)
}
}
}
class ExpertiseBooster : BaseAttributeBonusBooster(EXPERTISE) {
override fun createQuestBoostStrategy(quest: Quest) =
object : NoBoostStrategy() {
override fun adeptBooster() = Booster(intelligencePercentage = 5)
}
override fun createHabitBoostStrategy(habit: Habit) =
object : NoBoostStrategy() {
override fun adeptBooster() = Booster(intelligencePercentage = 5)
}
override fun createDailyChallengeBoostStrategy() =
object : NoBoostStrategy() {
override fun adeptBooster() = Booster(experiencePercentage = 20, coinsPercentage = 20)
override fun specialistBooster() =
Booster(experiencePercentage = 30, coinsPercentage = 30)
}
}
class WellBeingBooster : BaseAttributeBonusBooster(WELL_BEING) {
override fun createQuestBoostStrategy(quest: Quest) =
object : NoBoostStrategy() {
override fun adeptBooster() =
Booster.ofAllAttributeBonus(10)
override fun apprenticeBooster() =
Booster.ofAllAttributeBonus(5)
}
override fun createHabitBoostStrategy(habit: Habit) =
object : NoBoostStrategy() {
override fun adeptBooster() =
Booster.ofAllAttributeBonus(10)
override fun apprenticeBooster() =
Booster.ofAllAttributeBonus(5)
}
}
class WillpowerBooster : BaseAttributeBonusBooster(WILLPOWER) {
override fun createQuestBoostStrategy(quest: Quest) =
object : NoBoostStrategy() {
override fun specialistBooster() =
if (quest.isFromRepeatingQuest)
Booster(experiencePercentage = 5, coinsPercentage = 5)
else
Booster()
override fun apprenticeBooster() =
when {
quest.isFromChallenge -> Booster(
experiencePercentage = 10,
coinsPercentage = 10
)
quest.isFromRepeatingQuest -> Booster(
experiencePercentage = 5,
coinsPercentage = 5
)
else -> Booster()
}
}
override fun createHabitBoostStrategy(habit: Habit) =
object : NoBoostStrategy() {
override fun specialistBooster() =
Booster(Math.min(habit.streak.current, 20), Math.min(habit.streak.current, 20))
override fun apprenticeBooster() =
if (habit.isFromChallenge)
Booster(experiencePercentage = 10, coinsPercentage = 10)
else
Booster()
}
} | gpl-3.0 | 28174bf018a6ed578c9ff5a4c279578a | 32.531579 | 104 | 0.621066 | 4.612962 | false | false | false | false |
walleth/kethereum | erc831/src/main/kotlin/org/kethereum/erc831/ERC831Parser.kt | 1 | 1195 | package org.kethereum.erc831
import org.kethereum.erc831.ParseState.*
import org.kethereum.model.EthereumURI
// as defined in http://eips.ethereum.org/EIPS/eip-831
private enum class ParseState {
SCHEMA,
PREFIX,
PAYLOAD
}
fun EthereumURI.toERC831() = ERC831().apply {
var currentSegment = ""
var currentState = SCHEMA
fun stateTransition(newState: ParseState) {
when (currentState) {
SCHEMA -> scheme = currentSegment
PREFIX -> prefix = currentSegment
PAYLOAD -> payload = currentSegment
}
currentState = newState
currentSegment = ""
}
uri.forEach { char ->
when {
char == ':' && currentState == SCHEMA
-> stateTransition(if (uri.hasPrefix()) PREFIX else PAYLOAD)
char == '-' && currentState == PREFIX
-> stateTransition(PAYLOAD)
else -> currentSegment += char
}
}
if (!currentSegment.isBlank()) {
stateTransition(PAYLOAD)
}
}
private fun String.hasPrefix() = contains('-') && (!contains("0x") || indexOf('-') < indexOf("0x"))
fun parseERC831(url: String) = EthereumURI(url).toERC831() | mit | 04a90ad427d7bd7e3fce816a85b729bd | 22.92 | 99 | 0.599163 | 4.393382 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/compute/OpenCLContext.kt | 2 | 10817 | package graphics.scenery.compute
import graphics.scenery.Hub
import graphics.scenery.Hubable
import graphics.scenery.SceneryElement
import graphics.scenery.utils.LazyLogger
import org.jocl.*
import org.jocl.CL.*
import java.io.File
import java.net.URL
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import java.nio.IntBuffer
import java.nio.charset.StandardCharsets
import java.util.concurrent.ConcurrentHashMap
/**
* OpenCL context creation and handling.
*
* @author Ulrik Günther <[email protected]>
*/
class OpenCLContext(override var hub: Hub?, devicePreference: String = System.getProperty("scenery.OpenCLDevice", "0,0")) : Hubable, AutoCloseable {
private val logger by LazyLogger()
var device: cl_device_id
private var kernels = ConcurrentHashMap<String, cl_kernel>()
var context: cl_context
var queue: cl_command_queue
init {
hub?.add(SceneryElement.OpenCLContext, this)
val platformPref = devicePreference.substringBefore(",").toInt()
val devicePref = devicePreference.substringAfter(",").toInt()
val deviceType = CL_DEVICE_TYPE_ALL
// Enable exceptions and subsequently omit error checks in this sample
setExceptionsEnabled(true)
// Obtain a platform ID
val platforms = query<cl_platform_id> { l, a, n ->
clGetPlatformIDs(l, a, n)
}
val platform = platforms[platformPref]
// Initialize the context properties
val contextProperties = cl_context_properties()
contextProperties.addProperty(CL_CONTEXT_PLATFORM.toLong(), platform)
// Obtain a device ID
val devices = query({ l, a, n ->
clGetDeviceIDs(platform, deviceType, l, a, n)
}, { cl_device_id() })
device = devices[devicePref]
logger.info("Selected device: ${getString(device, CL_DEVICE_NAME)} running ${getString(device, CL_DEVICE_VERSION)}")
// Create a context for the selected device
context = clCreateContext(
contextProperties, 1, arrayOf(device),
null, null, null)
// Create a command-queue for the selected device
@Suppress("DEPRECATION")
queue = clCreateCommandQueue(context, device, 0, null)
}
/**
* Returns the device info for [device], specifically the parameter
* named [paramName].
*/
private fun getString(device: cl_device_id, paramName: Int): String
{
// Obtain the length of the string that will be queried
val size = LongArray(1)
clGetDeviceInfo(device, paramName, 0, null, size)
// Create a buffer of the appropriate size and fill it with the info
val buffer = ByteArray(size[0].toInt())
clGetDeviceInfo(device, paramName, buffer.size.toLong(), Pointer.to(buffer), null)
// Create a string from the buffer (excluding the trailing \0 byte)
return String(buffer, 0, buffer.size-1)
}
/**
* Loads an OpenCL kernel from a String [source], storing it under [name], and returning
* the compiled kernel.
*/
@Suppress("unused")
fun loadKernel(source: String, name: String): OpenCLContext {
if(!kernels.containsKey(name)) {
// Create the program from the source code
val program = clCreateProgramWithSource(context, 1, arrayOf(source), null, null)
// Build the program
clBuildProgram(program, 0, null, null, null, null)
// Create the kernel
val kernel = clCreateKernel(program, name, null)
kernels[name] = kernel
clReleaseProgram(program)
}
return this
}
/**
* Loads an OpenCL kernel from a file [source], storing it under [name], and returning
* the compiled kernel.
*/
@Suppress("unused")
fun loadKernel(source: File, name: String): OpenCLContext {
return loadKernel(source.readLines(charset = Charsets.UTF_8).joinToString("\n"), name)
}
/**
* Loads an OpenCL kernel from a URL [source], storing it under [name], and returning
* the compiled kernel.
*/
@Suppress("unused")
fun loadKernel(source: URL, name: String): OpenCLContext {
return loadKernel(String(source.readBytes(), StandardCharsets.UTF_8), name)
}
/**
* Returns the OpenCL size of different JVM objects as Long.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
private fun getSizeof(obj: Any): Long {
return when(obj) {
is Float -> Sizeof.cl_float
is Int -> Sizeof.cl_int
is Integer -> Sizeof.cl_int
is Byte -> Sizeof.cl_uchar
is cl_mem -> Sizeof.cl_mem
// buffers
is FloatBuffer -> Sizeof.cl_float
is ByteBuffer -> Sizeof.cl_uchar
is IntBuffer -> Sizeof.cl_int
else -> {
// these classes are package-local and can therefore not be matched for here directly
if(obj.javaClass.canonicalName.contains("DirectByteBuffer") || obj.javaClass.canonicalName.contains("HeapByteBuffer")) {
1
} else {
logger.error("Unrecognized class ${obj.javaClass.canonicalName}, returning 1 byte as size")
1
}
}
}.toLong()
}
/**
* Sets arguments for a specific OpenCL kernel.
*/
private fun cl_kernel.setArgs(vararg arguments: Any) {
arguments.forEachIndexed { i, arg ->
when (arg) {
is NativePointerObject -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arg))
is Buffer -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arg))
is cl_mem -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arg))
is Int -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arrayOf(arg).toIntArray()))
is Float -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arrayOf(arg).toFloatArray()))
is Byte -> clSetKernelArg(this,
i,
getSizeof(arg),
Pointer.to(arrayOf(arg).toByteArray()))
}
}
}
/**
* Runs the kernel specified by [name] with a number of [wavefronts], passing
* [arguments] to the kernel.
*/
fun runKernel(name: String, wavefronts: Int, vararg arguments: Any) {
val k = kernels[name]
if(k == null) {
logger.error("Kernel $name not found.")
return
}
k.setArgs(*arguments)
// Set the work-item dimensions
val global_work_size = arrayOf(1L * wavefronts).toLongArray()
val local_work_size = arrayOf(1L).toLongArray()
// Execute the kernel
clEnqueueNDRangeKernel(this.queue, k, 1, null,
global_work_size, local_work_size, 0, null, null)
}
/**
* Wraps a [buffer] for use with a kernel. The buffer can be defined as [readonly].
*/
fun wrapInput(buffer: Buffer, readonly: Boolean = false): cl_mem {
buffer.rewind()
val p = Pointer.to(buffer)
var flags = if(readonly) CL_MEM_READ_ONLY else CL_MEM_READ_WRITE
flags = flags or CL_MEM_COPY_HOST_PTR
val mem = clCreateBuffer(this.context, flags, getSizeof(buffer)*buffer.remaining(), p, null)
return mem
}
/**
* Wraps an output [buffer].
*/
fun wrapOutput(buffer: Buffer): cl_mem {
buffer.rewind()
val flags = CL_MEM_READ_WRITE
return clCreateBuffer(context, flags, getSizeof(buffer) *buffer.remaining(), null, null)
}
/**
* Reads from OpenCL memory specified by [memory] into the [Buffer] [target].
*/
fun readBuffer(memory: cl_mem, target: Buffer) {
val p = Pointer.to(target)
clEnqueueReadBuffer(queue, memory, CL_TRUE, 0, target.remaining() * getSizeof(target), p, 0, null, null)
}
/**
* Writes from [localData] to OpenCL memory specified by [memory].
*/
fun writeBuffer(localData: Buffer, memory: cl_mem) {
val p = Pointer.to(localData)
clEnqueueWriteBuffer(queue, memory, CL_TRUE, 0, localData.remaining() * getSizeof(localData), p, 0, null, null)
}
/**
* Closes the context.
*/
override fun close() {
kernels.forEach { clReleaseKernel(it.value) }
kernels.clear()
clReleaseDevice(device)
clReleaseContext(context)
}
/**
* Convenience utils for [OpenCLContext].
*/
companion object OpenCLUtils {
/**
* Convenience wrapper for OpenCL functions that query arrays and are usually
* called twice, once for finding the number of elements required for the array
* and a second time for filling the array with values. For example:
* ```
* val numDevicesArray = IntArray(1);
* clGetDeviceIDs(platform, deviceType, 0, null, numDevicesArray);
* val numDevices = numDevicesArray[0];
* val devices = Array<cl_device_id>(numDevices, {i -> cl_device_id() })
* clGetDeviceIDs(platform, deviceType, numDevices, devices, null);
* ```
*
* This can be replaced by
* ```
* val devices = query<cl_device_id>(
* { l, a, n -> clGetDeviceIDs(platform, deviceType, l, a, n) },
* { cl_device_id() })
* ```
* @param fn
* wraps the cl function to be called (twice),
* taking the parameters num_array_entries, array, num_available_entries.
* @param init
* T initializer for creating an Array<T>
*/
inline fun <reified T> query(fn: (Int, Array<T>?, IntArray?) -> Unit, noinline init: (Int) -> T): Array<T> {
val num = IntArray(1)
fn(0, null, num)
val things = Array<T>(num[0], init)
fn(num[0], things, null)
return things
}
/**
* Variant of [query] without array initializer. It creates arrays with nullable entries, and returns Array<T?> instead of Array<T>.
*/
inline fun <reified T> query(fn: (Int, Array<T?>?, IntArray?) -> Unit): Array<T?> {
val num = IntArray(1)
fn(0, null, num)
val things = arrayOfNulls<T>(num[0])
fn(num[0], things, null)
return things
}
}
}
| lgpl-3.0 | b028a504f740f8d6ad8c3930649bc06d | 33.555911 | 148 | 0.580159 | 4.281869 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/client/ClientSessionsManager.kt | 2 | 3861 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.client
import com.intellij.codeWithMe.ClientId
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectExImpl
import com.intellij.openapi.util.Disposer
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.ConcurrentHashMap
@ApiStatus.Experimental
@ApiStatus.Internal
sealed class ClientSessionsManager<T : ClientSession> {
companion object {
/**
* Returns a project-level session for a particular client.
* @see ClientSession
*/
@JvmStatic
@JvmOverloads
fun getProjectSession(project: Project, clientId: ClientId = ClientId.current): ClientProjectSession? {
return getInstance(project).getSession(clientId)
}
/**
* Returns an application-level session for a particular client.
* @see ClientSession
*/
@JvmStatic
@JvmOverloads
fun getAppSession(clientId: ClientId = ClientId.current): ClientAppSession? {
return getInstance().getSession(clientId)
}
/**
* Returns all project-level sessions.
* @param includeLocal specifies whether the local session should be included
* @see ClientSession
*/
@JvmStatic
fun getProjectSessions(project: Project, includeLocal: Boolean): List<ClientProjectSession> {
return getInstance(project).getSessions(includeLocal)
}
/**
* Returns all application-level sessions.
* @param includeLocal specifies whether the local session should be included
* @see ClientSession
*/
@JvmStatic
fun getAppSessions(includeLocal: Boolean): List<ClientAppSession> {
return getInstance().getSessions(includeLocal)
}
@ApiStatus.Internal
fun getInstance() = service<ClientSessionsManager<*>>() as ClientAppSessionsManager
@ApiStatus.Internal
fun getInstance(project: Project) = project.service<ClientSessionsManager<*>>() as ClientProjectSessionsManager
}
private val sessions = ConcurrentHashMap<ClientId, T>()
fun getSessions(includeLocal: Boolean): List<T> {
if (includeLocal) {
return java.util.List.copyOf(sessions.values)
}
else {
return sessions.values.filter { !it.isLocal }
}
}
fun getSession(clientId: ClientId): T? {
return sessions[clientId]
}
fun registerSession(disposable: Disposable, session: T) {
val clientId = session.clientId
if (sessions.putIfAbsent(clientId, session) != null) {
logger<ClientSessionsManager<*>>().error("Session with '$clientId' is already registered")
}
Disposer.register(disposable, session)
Disposer.register(disposable) {
sessions.remove(clientId)
}
}
}
open class ClientAppSessionsManager : ClientSessionsManager<ClientAppSession>() {
init {
val application = ApplicationManager.getApplication()
if (application is ApplicationImpl) {
@Suppress("LeakingThis")
registerSession(application, createLocalSession(application))
}
}
/**
* Used for [ClientId] overriding in JetBrains Client
*/
protected open fun createLocalSession(application: ApplicationImpl): ClientAppSessionImpl {
return ClientAppSessionImpl(ClientId.localId, application)
}
}
open class ClientProjectSessionsManager(project: Project) : ClientSessionsManager<ClientProjectSession>() {
init {
if (project is ProjectExImpl) {
registerSession(project, ClientProjectSessionImpl(ClientId.localId, project))
}
}
} | apache-2.0 | 79613824c46e8d1b894f2636dc31bf1f | 32.008547 | 158 | 0.73582 | 4.868852 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsExtractor.kt | 7 | 4794 | // 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.gradleTooling.arguments
import org.gradle.api.Task
import org.jetbrains.kotlin.idea.gradleTooling.get
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import java.io.File
import java.lang.reflect.Method
import kotlin.reflect.full.memberProperties
object CompilerArgumentsExtractor {
private const val ARGUMENT_ANNOTATION_CLASS = "org.jetbrains.kotlin.cli.common.arguments.Argument"
private const val LEGACY_ARGUMENT_ANNOTATION_CLASS = "org.jetbrains.kotlin.com.sampullara.cli.Argument"
private const val CREATE_COMPILER_ARGS = "createCompilerArgs"
private const val SETUP_COMPILER_ARGS = "setupCompilerArgs"
private val EXPLICIT_DEFAULT_OPTIONS: List<String> = listOf("jvmTarget")
private val ARGUMENT_ANNOTATION_CLASSES = setOf(LEGACY_ARGUMENT_ANNOTATION_CLASS, ARGUMENT_ANNOTATION_CLASS)
fun extractCompilerArgumentsFromTask(compileTask: Task, defaultsOnly: Boolean = false): ExtractedCompilerArgumentsBucket {
val compileTaskClass = compileTask.javaClass
val compilerArguments = compileTask[CREATE_COMPILER_ARGS]!!
compileTaskClass.getMethodOrNull(SETUP_COMPILER_ARGS, compilerArguments::class.java, Boolean::class.java, Boolean::class.java)
?.doSetupCompilerArgs(compileTask, compilerArguments, defaultsOnly, false)
?: compileTaskClass.getMethodOrNull(SETUP_COMPILER_ARGS, compilerArguments::class.java, Boolean::class.java)
?.doSetupCompilerArgs(compileTask, compilerArguments, defaultsOnly)
return prepareCompilerArgumentsBucket(compilerArguments)
}
private fun Method.doSetupCompilerArgs(
compileTask: Task,
compilerArgs: Any,
defaultsOnly: Boolean,
ignoreClasspathIssues: Boolean? = null
) {
try {
ignoreClasspathIssues?.also { invoke(compileTask, compilerArgs, defaultsOnly, it) }
?: invoke(compileTask, compilerArgs, defaultsOnly)
} catch (e: Exception) {
ignoreClasspathIssues?.also { if (!it) doSetupCompilerArgs(compileTask, compilerArgs, defaultsOnly, true) }
}
}
@Suppress("UNCHECKED_CAST")
fun prepareCompilerArgumentsBucket(compilerArguments: Any): ExtractedCompilerArgumentsBucket {
val compilerArgumentsClassName = compilerArguments::class.java.name
val defaultArgs = compilerArguments::class.java.getConstructor().newInstance()
val compilerArgumentsPropertiesToProcess = compilerArguments.javaClass.kotlin.memberProperties
.filter { prop ->
prop.name in EXPLICIT_DEFAULT_OPTIONS || prop.get(compilerArguments) != prop.get(defaultArgs) && prop.annotations.any {
(it.javaClass.getMethodOrNull("annotationType")?.invoke(it) as? Class<*>)?.name in ARGUMENT_ANNOTATION_CLASSES
}
}
val singleArguments: Map<String, String?>
val classpathParts: Array<String>
val allSingleArguments = compilerArgumentsPropertiesToProcess.filter { it.returnType.classifier == String::class }
.associate { (it.get(compilerArguments) as String?).let { value -> it.name to value } }
classpathParts = allSingleArguments["classpath"]?.split(File.pathSeparator)?.toTypedArray() ?: emptyArray()
singleArguments = allSingleArguments.filterKeys { it != "classpath" }
val multipleArguments = compilerArgumentsPropertiesToProcess.filter { it.returnType.classifier == Array<String>::class }
.associate { (it.get(compilerArguments) as Array<String>?).let { value -> it.name to value } }
val flagArguments = compilerArgumentsPropertiesToProcess.filter { it.returnType.classifier == Boolean::class }
.associate { it.name to it.get(compilerArguments) as Boolean }
val freeArgs = (compilerArguments.javaClass.kotlin.memberProperties.single { it.name == "freeArgs" }
.get(compilerArguments) as List<String>)
val internalArguments = (compilerArguments.javaClass.kotlin.memberProperties.single { it.name == "internalArguments" }
.get(compilerArguments) as List<*>).filterNotNull()
.map { internalArgument ->
internalArgument.javaClass.kotlin.memberProperties.single { prop -> prop.name == "stringRepresentation" }
.get(internalArgument) as String
}
return ExtractedCompilerArgumentsBucket(
compilerArgumentsClassName,
singleArguments,
classpathParts,
multipleArguments,
flagArguments,
internalArguments,
freeArgs
)
}
} | apache-2.0 | bdea3ddf24981eb9b71d8b9e4bed9632 | 51.119565 | 135 | 0.706091 | 5.07839 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/dialog/DlgOpenUrl.kt | 1 | 3597 | package jp.juggler.subwaytooter.dialog
import android.app.Activity
import android.app.Dialog
import android.content.ClipboardManager
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.core.view.postDelayed
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.databinding.DlgOpenUrlBinding
import jp.juggler.util.LogCategory
import jp.juggler.util.isEnabledAlpha
import jp.juggler.util.showToast
import jp.juggler.util.systemService
object DlgOpenUrl {
private val log = LogCategory("DlgOpenUrl")
fun show(
activity: Activity,
onEmptyError: () -> Unit = { activity.showToast(false, R.string.url_empty) },
onOK: (Dialog, String) -> Unit
) {
val allowEmpty = false
val clipboard: ClipboardManager? = systemService(activity)
val viewBinding = DlgOpenUrlBinding.inflate(activity.layoutInflater)
viewBinding.etInput.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
viewBinding.btnOk.performClick()
true
} else {
false
}
}
val dialog = Dialog(activity)
dialog.setContentView(viewBinding.root)
viewBinding.btnCancel.setOnClickListener { dialog.cancel() }
viewBinding.btnPaste.setOnClickListener { pasteTo(clipboard, viewBinding.etInput) }
viewBinding.btnOk.setOnClickListener {
val token = viewBinding.etInput.text.toString().trim { it <= ' ' }
if (token.isEmpty() && !allowEmpty) {
onEmptyError()
} else {
onOK(dialog, token)
}
}
dialog.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
val clipboardListener = ClipboardManager.OnPrimaryClipChangedListener {
showPasteButton(clipboard, viewBinding)
}
clipboard?.addPrimaryClipChangedListener(clipboardListener)
dialog.setOnDismissListener {
clipboard?.removePrimaryClipChangedListener(clipboardListener)
}
viewBinding.root.postDelayed(100L) {
showPasteButton(clipboard, viewBinding)
pasteTo(clipboard, viewBinding.etInput)
}
dialog.show()
}
private fun showPasteButton(clipboard: ClipboardManager?, viewBinding: DlgOpenUrlBinding) {
viewBinding.btnPaste.isEnabledAlpha = when {
clipboard == null -> false
!clipboard.hasPrimaryClip() -> false
clipboard.primaryClipDescription?.hasMimeType("text/plain") != true -> false
else -> true
}
}
private fun pasteTo(clipboard: ClipboardManager?, et: EditText) {
val text = clipboard?.getUrlFromClipboard()
?: return
val ss = et.selectionStart
val se = et.selectionEnd
et.text.replace(ss, se, text)
et.setSelection(ss, ss + text.length)
}
private fun ClipboardManager.getUrlFromClipboard(): String? {
try {
val item = primaryClip?.getItemAt(0)
item?.uri?.toString()?.let { return it }
item?.text?.toString()?.let { return it }
log.w("clip has nor uri or text.")
} catch (ex: Throwable) {
log.w(ex, "getUrlFromClipboard failed.")
}
return null
}
}
| apache-2.0 | b239288e4a937253be068dd3bdf4fadc | 33.613861 | 95 | 0.618849 | 4.841184 | false | false | false | false |
paplorinc/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/IconRobotsDataReader.kt | 2 | 1591 | // 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.intellij.build.images.sync
import com.intellij.openapi.application.PathManager
import org.jetbrains.intellij.build.images.ImageCollector
import org.jetbrains.intellij.build.images.ImageCollector.IconRobotsData
import org.jetbrains.intellij.build.images.ImageSyncFlags
import org.jetbrains.intellij.build.images.ROBOTS_FILE_NAME
import java.io.File
import java.nio.file.Paths
internal object IconRobotsDataReader {
@Volatile
private var iconRobotsData = emptyMap<File, IconRobotsData>()
private val root = ImageCollector(Paths.get(PathManager.getHomePath()), ignoreSkipTag = false).IconRobotsData()
private fun readIconRobotsData(file: File, block: ImageSyncFlags.() -> Boolean): Boolean {
val robotFile = findRobotsFileName(file) ?: return false
if (!iconRobotsData.containsKey(robotFile)) synchronized(this) {
if (!iconRobotsData.containsKey(robotFile)) {
iconRobotsData += robotFile to root.fork(robotFile.toPath(), robotFile.toPath())
}
}
return iconRobotsData.getValue(robotFile).getImageSyncFlags(file.toPath()).block()
}
private fun findRobotsFileName(file: File): File? =
if (file.isDirectory && File(file, ROBOTS_FILE_NAME).exists()) {
file
}
else file.parentFile?.let(::findRobotsFileName)
fun isSyncSkipped(file: File) = readIconRobotsData(file) {
skipSync
}
fun isSyncForced(file: File) = readIconRobotsData(file) {
forceSync
}
}
| apache-2.0 | 803adc5d899138b2eca62e358b7253b8 | 39.794872 | 140 | 0.756757 | 3.9775 | false | false | false | false |
paplorinc/intellij-community | plugins/git4idea/tests/git4idea/test/TestGit.kt | 2 | 6352 | // 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 git4idea.test
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import git4idea.branch.GitRebaseParams
import git4idea.commands.*
import git4idea.push.GitPushParams
import git4idea.rebase.GitInteractiveRebaseEditorHandler
import git4idea.repo.GitRepository
import java.io.File
/**
* Any unknown error that could be returned by Git.
*/
const val UNKNOWN_ERROR_TEXT: String = "unknown error"
class TestGitImpl : GitImpl() {
private val LOG = Logger.getInstance(TestGitImpl::class.java)
@Volatile var stashListener: ((GitRepository) -> Unit)? = null
@Volatile var mergeListener: ((GitRepository) -> Unit)? = null
@Volatile var pushListener: ((GitRepository) -> Unit)? = null
@Volatile private var rebaseShouldFail: (GitRepository) -> Boolean = { false }
@Volatile private var pushHandler: (GitRepository) -> GitCommandResult? = { null }
@Volatile private var branchDeleteHandler: (GitRepository) -> GitCommandResult? = { null }
@Volatile private var checkoutNewBranchHandler: (GitRepository) -> GitCommandResult? = { null }
@Volatile private var interactiveRebaseEditor: InteractiveRebaseEditor? = null
class InteractiveRebaseEditor(val entriesEditor: ((String) -> String)?,
val plainTextEditor: ((String) -> String)?)
override fun push(repository: GitRepository,
pushParams: GitPushParams,
vararg listeners: GitLineHandlerListener): GitCommandResult {
pushListener?.invoke(repository)
return pushHandler(repository) ?: super.push(repository, pushParams, *listeners)
}
override fun checkoutNewBranch(repository: GitRepository, branchName: String, listener: GitLineHandlerListener?): GitCommandResult {
return checkoutNewBranchHandler(repository) ?: super.checkoutNewBranch(repository, branchName, listener)
}
override fun branchDelete(repository: GitRepository,
branchName: String,
force: Boolean,
vararg listeners: GitLineHandlerListener?): GitCommandResult {
return branchDeleteHandler(repository) ?: super.branchDelete(repository, branchName, force, *listeners)
}
override fun rebase(repository: GitRepository, params: GitRebaseParams, vararg listeners: GitLineHandlerListener): GitRebaseCommandResult {
return failOrCallRebase(repository) {
super.rebase(repository, params, *listeners)
}
}
override fun rebaseAbort(repository: GitRepository, vararg listeners: GitLineHandlerListener?): GitRebaseCommandResult {
return failOrCallRebase(repository) {
super.rebaseAbort(repository, *listeners)
}
}
override fun rebaseContinue(repository: GitRepository, vararg listeners: GitLineHandlerListener?): GitRebaseCommandResult {
return failOrCallRebase(repository) {
super.rebaseContinue(repository, *listeners)
}
}
override fun rebaseSkip(repository: GitRepository, vararg listeners: GitLineHandlerListener?): GitRebaseCommandResult {
return failOrCallRebase(repository) {
super.rebaseSkip(repository, *listeners)
}
}
override fun createEditor(project: Project, root: VirtualFile, handler: GitLineHandler,
commitListAware: Boolean): GitInteractiveRebaseEditorHandler {
if (interactiveRebaseEditor == null) return super.createEditor(project, root, handler, commitListAware)
val editor = object : GitInteractiveRebaseEditorHandler(project, root) {
override fun handleUnstructuredEditor(path: String): Boolean {
val plainTextEditor = interactiveRebaseEditor!!.plainTextEditor
return if (plainTextEditor != null) handleEditor(path, plainTextEditor) else super.handleUnstructuredEditor(path)
}
override fun handleInteractiveEditor(path: String): Boolean {
val entriesEditor = interactiveRebaseEditor!!.entriesEditor
return if (entriesEditor != null) handleEditor(path, entriesEditor) else super.handleInteractiveEditor(path)
}
private fun handleEditor(path: String, editor: (String) -> String): Boolean {
try {
val file = File(path)
FileUtil.writeToFile(file, editor(FileUtil.loadFile(file)))
}
catch (e: Exception) {
LOG.error(e)
}
return true
}
}
return editor
}
override fun stashSave(repository: GitRepository, message: String): GitCommandResult {
stashListener?.invoke(repository)
return super.stashSave(repository, message)
}
override fun merge(repository: GitRepository,
branchToMerge: String,
additionalParams: MutableList<String>?,
vararg listeners: GitLineHandlerListener?): GitCommandResult {
mergeListener?.invoke(repository)
return super.merge(repository, branchToMerge, additionalParams, *listeners)
}
fun setShouldRebaseFail(shouldFail: (GitRepository) -> Boolean) {
rebaseShouldFail = shouldFail
}
fun onPush(handler: (GitRepository) -> GitCommandResult?) {
pushHandler = handler
}
fun onCheckoutNewBranch(handler: (GitRepository) -> GitCommandResult?) {
checkoutNewBranchHandler = handler
}
fun onBranchDelete(handler: (GitRepository) -> GitCommandResult?) {
branchDeleteHandler = handler
}
fun setInteractiveRebaseEditor(editor: InteractiveRebaseEditor) {
interactiveRebaseEditor = editor
}
fun reset() {
rebaseShouldFail = { false }
pushHandler = { null }
checkoutNewBranchHandler = { null }
branchDeleteHandler = { null }
interactiveRebaseEditor = null
pushListener = null
stashListener = null
mergeListener = null
}
private fun failOrCallRebase(repository: GitRepository, delegate: () -> GitRebaseCommandResult): GitRebaseCommandResult {
return if (rebaseShouldFail(repository)) {
GitRebaseCommandResult.normal(fatalResult())
}
else {
delegate()
}
}
private fun fatalResult() = GitCommandResult(false, 128, listOf("fatal: error: $UNKNOWN_ERROR_TEXT"), emptyList<String>())
}
| apache-2.0 | 69277e4bdc6973b7338c464163cef783 | 37.969325 | 141 | 0.718514 | 5.013418 | false | false | false | false |
zaviyalov/intellij-cleaner | src/main/kotlin/com/github/zaviyalov/intellijcleaner/controller/SettingsStageController.kt | 1 | 3483 | /*
* Copyright (c) 2016 Anton Zaviyalov
*/
package com.github.zaviyalov.intellijcleaner.controller
import com.github.zaviyalov.intellijcleaner.controller.companion.AbstractControllerCompanion
import com.github.zaviyalov.intellijcleaner.model.Edition
import com.github.zaviyalov.intellijcleaner.util.*
import javafx.beans.property.SimpleBooleanProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.ButtonBar
import javafx.scene.control.ComboBox
import javafx.stage.Stage
import javafx.stage.Window
import javafx.util.StringConverter
@Suppress("unused")
class SettingsStageController : AbstractController() {
@FXML private val editionData: ObservableList<Edition> = FXCollections.observableArrayList<Edition>({
arrayOf(it.nameProperty(), it.pathProperty())
})
@FXML lateinit private var ok: Button
@FXML lateinit private var cancel: Button
@FXML lateinit private var ideaEditionBox: ComboBox<Edition>
@FXML lateinit private var buttonBar: ButtonBar
@FXML private val changed = SimpleBooleanProperty(false)
private var parentController: StageController? = null
@FXML
override fun initialize() {
ideaEditionBox.converter = object : StringConverter<Edition>() {
override fun toString(`object`: Edition?): String {
return `object`?.name ?: "Error"
}
override fun fromString(string: String?): Edition {
throw UnsupportedOperationException("not implemented")
}
}
ideaEditionBox.items = editionData
editionData.addAll(
Edition("Ultimate Edition", ".IntelliJIdea"),
Edition("Community Edition", ".IdeaIC")
)
loadEdition()
ideaEditionBox.selectionModel.select(editionData.filter { it == ideaEdition }.getOrElse(0) { editionData.first() })
ideaEditionBox.valueProperty().addListener { ov, t0, t1 -> changed.set(true) }
cancel.disableProperty().bind(!changed)
if (isFirstLaunch()) {
buttonBar.buttons.remove(cancel)
}
}
@FXML
private fun handleOkButtonAction(event: ActionEvent) {
saveEdition(ideaEditionBox.value)
if (isFirstLaunch()) {
finishFirstLaunch()
}
parentController!!.updateData()
(event.source as Node).scene.window.hide()
}
@FXML
private fun handleCancelButtonAction(event: ActionEvent) {
(event.source as Node).scene.window.hide()
}
companion object : AbstractControllerCompanion<SettingsStageController>() {
override val FXML_PATH: String = "settingsStage.fxml"
override val WINDOW_TITLE = "Settings"
override fun <U> load(stage: Stage, owner: Window?, parentController: U?): SettingsStageController {
val result = super.load(stage, owner, parentController)
stage.isResizable = false
stage.width = 300.0
stage.height = 200.0
owner?.let {
stage.x = it.x + it.width / 2 - stage.width / 2
stage.y = it.y + it.height / 2 - stage.height / 2
}
if (parentController is StageController) {
result.parentController = parentController
}
return result
}
}
} | mit | 7a8ea16ea56c70f3b37ed77dd8372113 | 35.673684 | 123 | 0.667528 | 4.675168 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRCreatePullRequestAction.kt | 1 | 1931 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAwareAction
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.GHPRToolWindowController
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowInitialView
import java.util.function.Supplier
class GHPRCreatePullRequestAction : DumbAwareAction(GithubBundle.messagePointer("pull.request.create.show.form.action"),
Supplier { null },
AllIcons.General.Add) {
override fun update(e: AnActionEvent) {
with(e) {
val twController = project?.service<GHPRToolWindowController>()
val twAvailable = project != null && twController != null && twController.isAvailable()
val componentController = twController?.getTabController()?.componentController
val twInitialized = project != null && componentController != null
if (isFromActionToolbar) {
presentation.isEnabledAndVisible = twInitialized
presentation.icon = AllIcons.General.Add
}
else {
presentation.isEnabledAndVisible = twAvailable
presentation.icon = AllIcons.Vcs.Vendors.Github
}
}
}
override fun actionPerformed(e: AnActionEvent) {
val twController = e.getRequiredData(PlatformDataKeys.PROJECT).service<GHPRToolWindowController>()
twController.activate {
it.initialView = GHPRToolWindowInitialView.NEW
it.componentController?.createPullRequest()
}
}
} | apache-2.0 | cc7c874b35738b7706c392ade0f5c7ef | 43.930233 | 140 | 0.731227 | 4.938619 | false | false | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/SegmentedByteString.kt | 1 | 4426 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.internal.commonCopyInto
import okio.internal.commonEquals
import okio.internal.commonGetSize
import okio.internal.commonHashCode
import okio.internal.commonInternalGet
import okio.internal.commonRangeEquals
import okio.internal.commonSubstring
import okio.internal.commonToByteArray
import okio.internal.commonWrite
import okio.internal.forEachSegment
import java.io.IOException
import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.security.InvalidKeyException
import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
internal actual class SegmentedByteString internal actual constructor(
@Transient internal actual val segments: Array<ByteArray>,
@Transient internal actual val directory: IntArray
) : ByteString(EMPTY.data) {
override fun string(charset: Charset) = toByteString().string(charset)
override fun base64() = toByteString().base64()
override fun hex() = toByteString().hex()
override fun toAsciiLowercase() = toByteString().toAsciiLowercase()
override fun toAsciiUppercase() = toByteString().toAsciiUppercase()
override fun digest(algorithm: String): ByteString {
val digestBytes = MessageDigest.getInstance(algorithm).run {
forEachSegment { data, offset, byteCount ->
update(data, offset, byteCount)
}
digest()
}
return ByteString(digestBytes)
}
override fun hmac(algorithm: String, key: ByteString): ByteString {
try {
val mac = Mac.getInstance(algorithm)
mac.init(SecretKeySpec(key.toByteArray(), algorithm))
forEachSegment { data, offset, byteCount ->
mac.update(data, offset, byteCount)
}
return ByteString(mac.doFinal())
} catch (e: InvalidKeyException) {
throw IllegalArgumentException(e)
}
}
override fun base64Url() = toByteString().base64Url()
override fun substring(beginIndex: Int, endIndex: Int): ByteString =
commonSubstring(beginIndex, endIndex)
override fun internalGet(pos: Int): Byte = commonInternalGet(pos)
override fun getSize() = commonGetSize()
override fun toByteArray(): ByteArray = commonToByteArray()
override fun asByteBuffer(): ByteBuffer = ByteBuffer.wrap(toByteArray()).asReadOnlyBuffer()
@Throws(IOException::class)
override fun write(out: OutputStream) {
forEachSegment { data, offset, byteCount ->
out.write(data, offset, byteCount)
}
}
override fun write(buffer: Buffer, offset: Int, byteCount: Int): Unit =
commonWrite(buffer, offset, byteCount)
override fun rangeEquals(
offset: Int,
other: ByteString,
otherOffset: Int,
byteCount: Int
): Boolean = commonRangeEquals(offset, other, otherOffset, byteCount)
override fun rangeEquals(
offset: Int,
other: ByteArray,
otherOffset: Int,
byteCount: Int
): Boolean = commonRangeEquals(offset, other, otherOffset, byteCount)
override fun copyInto(
offset: Int,
target: ByteArray,
targetOffset: Int,
byteCount: Int
) = commonCopyInto(offset, target, targetOffset, byteCount)
override fun indexOf(other: ByteArray, fromIndex: Int) = toByteString().indexOf(other, fromIndex)
override fun lastIndexOf(other: ByteArray, fromIndex: Int) = toByteString().lastIndexOf(
other,
fromIndex
)
/** Returns a copy as a non-segmented byte string. */
private fun toByteString() = ByteString(toByteArray())
override fun internalArray() = toByteArray()
override fun equals(other: Any?): Boolean = commonEquals(other)
override fun hashCode(): Int = commonHashCode()
override fun toString() = toByteString().toString()
@Suppress("unused", "PLATFORM_CLASS_MAPPED_TO_KOTLIN") // For Java Serialization.
private fun writeReplace(): Object = toByteString() as Object
}
| apache-2.0 | 3160d1df7f1994f776f084a462bcde33 | 30.841727 | 99 | 0.736557 | 4.479757 | false | true | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypeDfaInstanceUtil.kt | 2 | 2213 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.dataFlow.types
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.getControlFlowOwner
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAType
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
fun getLeastUpperBoundByAllWrites(block: GrControlFlowOwner,
initialTypes: Map<VariableDescriptor, DFAType>,
descriptor: VariableDescriptor): PsiType {
val flow: Array<Instruction> = block.controlFlow
var resultType: PsiType = PsiType.NULL
val cache = TypeInferenceHelper.getInferenceCache(block)
for (instruction: Instruction in flow) {
val inferred: PsiType = if (instruction is ReadWriteVariableInstruction && instruction.isWrite && instruction.descriptor == descriptor) {
cache.getInferredType(instruction.descriptor, instruction, false, initialTypes) ?: PsiType.NULL
}
else if (instruction.element is GrFunctionalExpression) {
val nestedFlowOwner: GrControlFlowOwner? = (instruction.element as GrFunctionalExpression).getControlFlowOwner()
if (nestedFlowOwner != null && ControlFlowUtils.getOverwrittenForeignVariableDescriptors(nestedFlowOwner).contains(descriptor)) {
getLeastUpperBoundByAllWrites(nestedFlowOwner, initialTypes, descriptor)
}
else {
PsiType.NULL
}
}
else PsiType.NULL
if (inferred != PsiType.NULL) {
resultType = TypesUtil.getLeastUpperBound(resultType, inferred, block.manager) ?: PsiType.NULL
}
}
return resultType
}
| apache-2.0 | 7fffdf974f43777c22fc823d3589df27 | 54.325 | 141 | 0.772255 | 4.534836 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Model.kt | 1 | 4060 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.meta.models.*
//</doc:import_required>
//<doc:import_examples>
import slatekit.common.DateTime
import slatekit.results.Try
import slatekit.results.Success
import slatekit.common.auth.User
import slatekit.common.info.Host
import slatekit.orm.databases.vendors.MySqlBuilder
//</doc:import_examples>
class Example_Model : Command("model") {
override fun execute(request: CommandRequest) : Try<Any>
{
//<doc:examples>
// ABOUT:
// The Model component allows you to easily build up a model with fields
// This allows you to have a schema / structure representing a data model.
// With the structure in place, it helps facilitate code-generation.
// Also, the ORM / Mapper of Slate Kit internally builds a model for each
// Kotlin class that is mapped by the ORM.
// CASE 1: specify the api of the model e.g. "Resource"
// NOTE: The model is IMMUTABLE ( any additions of fields will result in a new model )
var model = Model("Resource", "slate.ext.resources.Resource")
// CASE 2. add a field for uniqueness / identity
val schema2 = Model.of<Long, Example_Mapper.Movie>(Long::class, Example_Mapper.Movie::class) {
field(Example_Mapper.Movie::id , category = FieldCategory.Id)
field(Example_Mapper.Movie::title , desc = "Title of movie", min = 5, max = 30)
field(Example_Mapper.Movie::category , desc = "Category (action|drama)", min = 1, max = 20)
field(Example_Mapper.Movie::playing , desc = "Whether its playing now")
field(Example_Mapper.Movie::rating , desc = "Rating from users")
field(Example_Mapper.Movie::released , desc = "Date of release")
field(Example_Mapper.Movie::createdAt, desc = "Who created record")
field(Example_Mapper.Movie::createdBy, desc = "When record was created")
field(Example_Mapper.Movie::updatedAt, desc = "Who updated record")
field(Example_Mapper.Movie::updatedBy, desc = "When record was updated")
}
// CASE 3: add fields for text, bool, int, date etc.
model = Model("Resource", "", dataType = User::class, desc = "", tableName = "users", modelFields = listOf(
ModelField(name = "key" , isRequired = true, maxLength = 30, dataCls = String::class),
ModelField(name = "api" , isRequired = true, maxLength = 30, dataCls = String::class),
ModelField(name = "recordState", isRequired = true, dataCls = Int::class),
ModelField(name = "hostInfo" , isRequired = true, dataCls = Host::class),
ModelField(name = "created" , isRequired = true, dataCls = DateTime::class),
ModelField(name = "updated" , isRequired = true, dataCls = DateTime::class)
))
// CASE 4. check for any fields
showResult( "any fields: " + model.any )
// CASE 5. total number of fields
showResult( "total fields: " + model.size )
// CASE 6. get the id field
showResult( "id field: " + model.hasId )
// CASE 7. get the id field
showResult( "id field: " + model.idField )
// CASE 8. string representation of field
showResult( "id field to string: " + model.idField.toString())
// CASE 8. access the fields
showResult ("access to fields : " + model.fields.size)
// CASE 9. get api + full api of model
showResult ("model api/fullName: " + model.name + ", " + model.fullName)
// CASE 10. build up the table sql for this model
showResult( "table sql : " + MySqlBuilder(null).createTable(model))
//</doc:examples>
return Success("")
}
fun showResult(content:String):Unit
{
println()
println( content )
}
}
| apache-2.0 | b9a3cfa413fbd72dad25609167b6a6f8 | 36.943925 | 111 | 0.657143 | 3.918919 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/properties/classFieldInsideLocalInSetter.kt | 3 | 315 | class My {
var my: String = "U"
get() = { field }()
set(arg) {
class Local {
fun foo() {
field = arg + "K"
}
}
Local().foo()
}
}
fun box(): String {
val m = My()
m.my = "O"
return m.my
} | apache-2.0 | 09a25aa951b57bee15d513c774eaed8f | 16.555556 | 37 | 0.307937 | 3.795181 | false | false | false | false |
hannesa2/owncloud-android | owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt | 2 | 6819 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.sharing.shares.repository
import androidx.lifecycle.LiveData
import com.owncloud.android.data.sharing.shares.datasources.LocalShareDataSource
import com.owncloud.android.data.sharing.shares.datasources.RemoteShareDataSource
import com.owncloud.android.domain.sharing.shares.ShareRepository
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.lib.resources.shares.RemoteShare
class OCShareRepository(
private val localShareDataSource: LocalShareDataSource,
private val remoteShareDataSource: RemoteShareDataSource
) : ShareRepository {
/******************************************************************************************************
******************************************* PRIVATE SHARES *******************************************
******************************************************************************************************/
override fun insertPrivateShare(
filePath: String,
shareType: ShareType,
shareeName: String, // User or group name of the target sharee.
permissions: Int, // See https://doc.owncloud.com/server/developer_manual/core/apis/ocs-share-api.html
accountName: String
) {
insertShare(
filePath = filePath,
shareType = shareType,
shareWith = shareeName,
permissions = permissions,
accountName = accountName
)
}
override fun updatePrivateShare(remoteId: String, permissions: Int, accountName: String) {
return updateShare(
remoteId = remoteId,
permissions = permissions,
accountName = accountName
)
}
/******************************************************************************************************
******************************************* PUBLIC SHARES ********************************************
******************************************************************************************************/
override fun insertPublicShare(
filePath: String,
permissions: Int,
name: String,
password: String,
expirationTimeInMillis: Long,
publicUpload: Boolean,
accountName: String
) {
insertShare(
filePath = filePath,
shareType = ShareType.PUBLIC_LINK,
permissions = permissions,
name = name,
password = password,
expirationTimeInMillis = expirationTimeInMillis,
publicUpload = publicUpload,
accountName = accountName
)
}
override fun updatePublicShare(
remoteId: String,
name: String,
password: String?,
expirationDateInMillis: Long,
permissions: Int,
publicUpload: Boolean,
accountName: String
) {
return updateShare(
remoteId,
permissions,
name,
password,
expirationDateInMillis,
publicUpload,
accountName
)
}
override fun deleteShare(remoteId: String) {
remoteShareDataSource.deleteShare(remoteId)
localShareDataSource.deleteShare(remoteId)
}
/******************************************************************************************************
*********************************************** COMMON ***********************************************
******************************************************************************************************/
override fun getSharesAsLiveData(filePath: String, accountName: String): LiveData<List<OCShare>> {
return localShareDataSource.getSharesAsLiveData(
filePath, accountName, listOf(
ShareType.PUBLIC_LINK,
ShareType.USER,
ShareType.GROUP,
ShareType.FEDERATED
)
)
}
override fun getShareAsLiveData(remoteId: String): LiveData<OCShare> =
localShareDataSource.getShareAsLiveData(remoteId)
override fun refreshSharesFromNetwork(
filePath: String,
accountName: String
) {
remoteShareDataSource.getShares(
filePath,
reshares = true,
subfiles = false,
accountName = accountName
).also { sharesFromNetwork ->
if (sharesFromNetwork.isEmpty()) {
localShareDataSource.deleteSharesForFile(filePath, accountName)
}
// Save shares
localShareDataSource.replaceShares(sharesFromNetwork)
}
}
private fun insertShare(
filePath: String,
shareType: ShareType,
shareWith: String = "",
permissions: Int,
name: String = "",
password: String = "",
expirationTimeInMillis: Long = RemoteShare.INIT_EXPIRATION_DATE_IN_MILLIS,
publicUpload: Boolean = false,
accountName: String
) {
remoteShareDataSource.insertShare(
filePath,
shareType,
shareWith,
permissions,
name,
password,
expirationTimeInMillis,
publicUpload,
accountName
).also { remotelyInsertedShare ->
localShareDataSource.insert(remotelyInsertedShare)
}
}
private fun updateShare(
remoteId: String,
permissions: Int,
name: String = "",
password: String? = "",
expirationDateInMillis: Long = RemoteShare.INIT_EXPIRATION_DATE_IN_MILLIS,
publicUpload: Boolean = false,
accountName: String
) {
remoteShareDataSource.updateShare(
remoteId,
name,
password,
expirationDateInMillis,
permissions,
publicUpload,
accountName
).also { remotelyUpdatedShare ->
localShareDataSource.update(remotelyUpdatedShare)
}
}
}
| gpl-2.0 | 0cef0c3e9c33db28321bbda7032303d9 | 33.785714 | 117 | 0.541068 | 5.923545 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt | 2 | 22998 | // 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.codeInsight
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastManager
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassQualifier
import org.jetbrains.kotlin.resolve.scopes.utils.collectAllFromMeAndParent
import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.synthetic.JavaSyntheticScopes
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.typeUtil.isUnit
import java.util.*
@OptIn(FrontendInternals::class)
class ReferenceVariantsHelper(
private val bindingContext: BindingContext,
private val resolutionFacade: ResolutionFacade,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val notProperties: Set<FqNameUnsafe> = setOf()
) {
fun getReferenceVariants(
expression: KtSimpleNameExpression,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> = getReferenceVariants(
expression, CallTypeAndReceiver.detect(expression),
kindFilter, nameFilter, filterOutJavaGettersAndSetters, filterOutShadowed, excludeNonInitializedVariable, useReceiverType
)
fun getReferenceVariants(
contextElement: PsiElement,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> {
var variants: Collection<DeclarationDescriptor> =
getReferenceVariantsNoVisibilityFilter(contextElement, kindFilter, nameFilter, callTypeAndReceiver, useReceiverType)
.filter { !resolutionFacade.frontendService<DeprecationResolver>().isHiddenInResolution(it) && visibilityFilter(it) }
if (filterOutShadowed) {
ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, contextElement, callTypeAndReceiver)?.let {
variants = it.filter(variants)
}
}
if (filterOutJavaGettersAndSetters && kindFilter.kindMask.and(DescriptorKindFilter.FUNCTIONS_MASK) != 0) {
variants = filterOutJavaGettersAndSetters(variants)
}
if (excludeNonInitializedVariable && kindFilter.kindMask.and(DescriptorKindFilter.VARIABLES_MASK) != 0) {
variants = excludeNonInitializedVariable(variants, contextElement)
}
return variants
}
fun <TDescriptor : DeclarationDescriptor> filterOutJavaGettersAndSetters(variants: Collection<TDescriptor>): Collection<TDescriptor> {
val accessorMethodsToRemove = HashSet<FunctionDescriptor>()
val filteredVariants = variants.filter { it !is SyntheticJavaPropertyDescriptor || !it.suppressedByNotPropertyList(notProperties) }
for (variant in filteredVariants) {
if (variant is SyntheticJavaPropertyDescriptor) {
accessorMethodsToRemove.add(variant.getMethod.original)
val setter = variant.setMethod
if (setter != null && setter.returnType?.isUnit() == true) { // we do not filter out non-Unit setters
accessorMethodsToRemove.add(setter.original)
}
}
}
return filteredVariants.filter { it !is FunctionDescriptor || it.original !in accessorMethodsToRemove }
}
// filters out variable inside its initializer
fun excludeNonInitializedVariable(
variants: Collection<DeclarationDescriptor>,
contextElement: PsiElement
): Collection<DeclarationDescriptor> {
for (element in contextElement.parentsWithSelf) {
val parent = element.parent
if (parent is KtVariableDeclaration && element == parent.initializer) {
return variants.filter { it.findPsi() != parent }
}
if (element is KtDeclaration) break // we can use variable inside lambda or anonymous object located in its initializer
}
return variants
}
private fun getReferenceVariantsNoVisibilityFilter(
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
useReceiverType: KotlinType?
): Collection<DeclarationDescriptor> {
val callType = callTypeAndReceiver.callType
@Suppress("NAME_SHADOWING")
val kindFilter = kindFilter.intersect(callType.descriptorKindFilter)
val receiverExpression: KtExpression?
when (callTypeAndReceiver) {
is CallTypeAndReceiver.IMPORT_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.PACKAGE_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.TYPE -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.ANNOTATION -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.CALLABLE_REFERENCE -> {
return getVariantsForCallableReference(callTypeAndReceiver, contextElement, useReceiverType, kindFilter, nameFilter)
}
is CallTypeAndReceiver.DEFAULT -> receiverExpression = null
is CallTypeAndReceiver.DOT -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SUPER_MEMBERS -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SAFE -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.INFIX -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.OPERATOR -> return emptyList()
is CallTypeAndReceiver.UNKNOWN -> return emptyList()
else -> throw RuntimeException() //TODO: see KT-9394
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextElement)
val containingDeclaration = resolutionScope.ownerDescriptor
val smartCastManager = resolutionFacade.frontendService<SmartCastManager>()
val languageVersionSettings = resolutionFacade.frontendService<LanguageVersionSettings>()
val implicitReceiverTypes = resolutionScope.getImplicitReceiversWithInstance(
languageVersionSettings.supportsFeature(LanguageFeature.DslMarkersSupport)
).flatMap {
smartCastManager.getSmartCastVariantsWithLessSpecificExcluded(
it.value,
bindingContext,
containingDeclaration,
dataFlowInfo,
languageVersionSettings,
resolutionFacade.frontendService<DataFlowValueFactory>()
)
}.toSet()
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val filterWithoutExtensions = kindFilter exclude DescriptorKindExclude.Extensions
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression]
if (qualifier != null) {
descriptors.addAll(qualifier.staticScope.collectStaticMembers(resolutionFacade, filterWithoutExtensions, nameFilter))
}
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
descriptors.processAll(implicitReceiverTypes, explicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
} else {
assert(useReceiverType == null) { "'useReceiverType' parameter is not supported for implicit receiver" }
descriptors.processAll(implicitReceiverTypes, implicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
// add non-instance members
descriptors.addAll(
resolutionScope.collectDescriptorsFiltered(
filterWithoutExtensions,
nameFilter,
changeNamesForAliased = true
)
)
descriptors.addAll(resolutionScope.collectAllFromMeAndParent { scope ->
scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, kindFilter, nameFilter)
})
}
if (callType == CallType.SUPER_MEMBERS) { // we need to unwrap fake overrides in case of "super." because ShadowedDeclarationsFilter does not work correctly
return descriptors.flatMapTo(LinkedHashSet<DeclarationDescriptor>()) {
if (it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE)
it.overriddenDescriptors
else
listOf(it)
}
}
return descriptors
}
private fun getVariantsForUserType(
receiverExpression: KtExpression?,
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
return qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
} else {
val scope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
return scope.collectDescriptorsFiltered(kindFilter, nameFilter, changeNamesForAliased = true)
}
}
private fun getVariantsForCallableReference(
callTypeAndReceiver: CallTypeAndReceiver.CALLABLE_REFERENCE,
contextElement: PsiElement,
useReceiverType: KotlinType?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val receiver = callTypeAndReceiver.receiver
if (receiver != null) {
val isStatic = bindingContext[BindingContext.DOUBLE_COLON_LHS, receiver] is DoubleColonLHS.Type
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
val constructorFilter = { descriptor: ClassDescriptor -> if (isStatic) true else descriptor.isInner }
descriptors.addNonExtensionMembers(explicitReceiverTypes, kindFilter, nameFilter, constructorFilter)
descriptors.addScopeAndSyntheticExtensions(
resolutionScope,
explicitReceiverTypes,
CallType.CALLABLE_REFERENCE,
kindFilter,
nameFilter
)
if (isStatic) {
explicitReceiverTypes
.mapNotNull { (it.constructor.declarationDescriptor as? ClassDescriptor)?.staticScope }
.flatMapTo(descriptors) { it.collectStaticMembers(resolutionFacade, kindFilter, nameFilter) }
}
} else {
// process non-instance members and class constructors
descriptors.addNonExtensionCallablesAndConstructors(
resolutionScope,
kindFilter, nameFilter, constructorFilter = { !it.isInner },
classesOnly = false
)
}
return descriptors
}
private fun getVariantsForImportOrPackageDirective(
receiverExpression: KtExpression?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
val staticDescriptors = qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
val objectDescriptor =
(qualifier as? ClassQualifier)?.descriptor?.takeIf { it.kind == ClassKind.OBJECT } ?: return staticDescriptors
return staticDescriptors + objectDescriptor.defaultType.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
} else {
val rootPackage = resolutionFacade.moduleDescriptor.getPackage(FqName.ROOT)
return rootPackage.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
}
}
private fun MutableSet<DeclarationDescriptor>.processAll(
implicitReceiverTypes: Collection<KotlinType>,
receiverTypes: Collection<KotlinType>,
resolutionScope: LexicalScope,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
addNonExtensionMembers(receiverTypes, kindFilter, nameFilter, constructorFilter = { it.isInner })
addMemberExtensions(implicitReceiverTypes, receiverTypes, callType, kindFilter, nameFilter)
addScopeAndSyntheticExtensions(resolutionScope, receiverTypes, callType, kindFilter, nameFilter)
}
private fun MutableSet<DeclarationDescriptor>.addMemberExtensions(
dispatchReceiverTypes: Collection<KotlinType>,
extensionReceiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
val memberFilter = kindFilter exclude DescriptorKindExclude.NonExtensions
for (dispatchReceiverType in dispatchReceiverTypes) {
for (member in dispatchReceiverType.memberScope.getDescriptorsFiltered(memberFilter, nameFilter)) {
addAll((member as CallableDescriptor).substituteExtensionIfCallable(extensionReceiverTypes, callType))
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionMembers(
receiverTypes: Collection<KotlinType>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean
) {
for (receiverType in receiverTypes) {
addNonExtensionCallablesAndConstructors(
receiverType.memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
false
)
receiverType.constructor.supertypes.forEach {
addNonExtensionCallablesAndConstructors(
it.memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
true
)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionCallablesAndConstructors(
scope: HierarchicalScope,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean,
classesOnly: Boolean
) {
var filterToUse =
DescriptorKindFilter(kindFilter.kindMask and DescriptorKindFilter.CALLABLES.kindMask).exclude(DescriptorKindExclude.Extensions)
// should process classes if we need constructors
if (filterToUse.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
filterToUse = filterToUse.withKinds(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS_MASK)
}
for (descriptor in scope.collectDescriptorsFiltered(filterToUse, nameFilter, changeNamesForAliased = true)) {
if (descriptor is ClassDescriptor) {
if (descriptor.modality == Modality.ABSTRACT || descriptor.modality == Modality.SEALED) continue
if (!constructorFilter(descriptor)) continue
descriptor.constructors.filterTo(this) { kindFilter.accepts(it) }
} else if (!classesOnly && kindFilter.accepts(descriptor)) {
this.add(descriptor)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addScopeAndSyntheticExtensions(
scope: LexicalScope,
receiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
if (kindFilter.excludes.contains(DescriptorKindExclude.Extensions)) return
if (receiverTypes.isEmpty()) return
fun process(extensionOrSyntheticMember: CallableDescriptor) {
if (kindFilter.accepts(extensionOrSyntheticMember) && nameFilter(extensionOrSyntheticMember.name)) {
if (extensionOrSyntheticMember.isExtension) {
addAll(extensionOrSyntheticMember.substituteExtensionIfCallable(receiverTypes, callType))
} else {
add(extensionOrSyntheticMember)
}
}
}
for (descriptor in scope.collectDescriptorsFiltered(
kindFilter exclude DescriptorKindExclude.NonExtensions,
nameFilter,
changeNamesForAliased = true
)) {
// todo: sometimes resolution scope here is LazyJavaClassMemberScope. see ea.jetbrains.com/browser/ea_problems/72572
process(descriptor as CallableDescriptor)
}
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java).forceEnableSamAdapters()
if (kindFilter.acceptsKinds(DescriptorKindFilter.VARIABLES_MASK)) {
val lookupLocation = (scope.ownerDescriptor.toSourceElement.getPsi() as? KtElement)?.let { KotlinLookupLocation(it) }
?: NoLookupLocation.FROM_IDE
for (extension in syntheticScopes.collectSyntheticExtensionProperties(receiverTypes, lookupLocation)) {
process(extension)
}
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
for (syntheticMember in syntheticScopes.collectSyntheticMemberFunctions(receiverTypes)) {
process(syntheticMember)
}
}
}
}
private fun MemberScope.collectStaticMembers(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return getDescriptorsFiltered(kindFilter, nameFilter) + collectSyntheticStaticMembersAndConstructors(
resolutionFacade,
kindFilter,
nameFilter
)
}
@OptIn(FrontendInternals::class)
fun ResolutionScope.collectSyntheticStaticMembersAndConstructors(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): List<FunctionDescriptor> {
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java)
val functionDescriptors = getContributedDescriptors(DescriptorKindFilter.FUNCTIONS)
val classifierDescriptors = getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS)
return (syntheticScopes.forceEnableSamAdapters().collectSyntheticStaticFunctions(functionDescriptors) +
syntheticScopes.collectSyntheticConstructors(classifierDescriptors))
.filter { kindFilter.accepts(it) && nameFilter(it.name) }
}
// New Inference disables scope with synthetic SAM-adapters because it uses conversions for resolution
// However, sometimes we need to pretend that we have those synthetic members, for example:
// - to show both option (with SAM-conversion signature, and without) in completion
// - for various intentions and checks (see RedundantSamConstructorInspection, ConflictingExtensionPropertyIntention and other)
// TODO(dsavvinov): review clients, rewrite them to not rely on synthetic adapetrs
fun SyntheticScopes.forceEnableSamAdapters(): SyntheticScopes {
return if (this !is JavaSyntheticScopes)
this
else
object : SyntheticScopes {
override val scopes: Collection<SyntheticScope> = [email protected]
}
}
| apache-2.0 | 4abab98b7f49fe147084e13e6341acac | 45.839104 | 164 | 0.69593 | 6.312929 | false | false | false | false |
smmribeiro/intellij-community | plugins/git-features-trainer/src/git4idea/ift/GitLearningCourse.kt | 1 | 2840 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ift
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowType
import com.intellij.openapi.wm.WindowInfo
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import git4idea.ift.lesson.*
import org.jetbrains.annotations.NonNls
import training.learn.course.IftModule
import training.learn.course.KLesson
import training.learn.course.LearningCourse
import training.learn.course.LessonType
class GitLearningCourse : LearningCourse {
override fun modules(): Collection<IftModule> {
return listOf(GitLearningModule("Git") {
listOf(GitQuickStartLesson(),
GitProjectHistoryLesson(),
GitCommitLesson(),
GitFeatureBranchWorkflowLesson(),
GitInteractiveRebaseLesson(),
GitChangelistsAndShelveLesson(),
GitAnnotateLesson())
})
}
private class GitLearningModule(@NonNls id: String, initLessons: () -> List<KLesson>)
: IftModule(id, GitLessonsBundle.message("git.module.name"), GitLessonsBundle.message("git.module.description"),
null, LessonType.PROJECT, initLessons) {
override val sanitizedName: String = ""
override fun preferredLearnWindowAnchor(project: Project): ToolWindowAnchor {
val toolWindowLayout = ToolWindowManagerEx.getInstanceEx(project).getLayout()
val commitWindowInfo = toolWindowLayout.getInfo(ToolWindowId.COMMIT)
val vcsWindowInfo = toolWindowLayout.getInfo(ToolWindowId.VCS)
return if (commitWindowInfo != null && vcsWindowInfo != null) {
if (commitWindowInfo.isDockedLeft() && vcsWindowInfo.isNotOnRightOrSeparated()
|| vcsWindowInfo.isDockedLeft() && commitWindowInfo.isNotOnRightOrSeparated()) {
ToolWindowAnchor.RIGHT
}
// There is only one case when we can't do something:
// Commit and VCS window docked at left and right
// In this case we will show Learn at default position - left
else ToolWindowAnchor.LEFT
}
else {
LOG.warn("Not found window info for tool windows: ${ToolWindowId.COMMIT}, ${ToolWindowId.VCS}")
ToolWindowAnchor.LEFT
}
}
private fun WindowInfo.isDockedLeft() = anchor == ToolWindowAnchor.LEFT && type == ToolWindowType.DOCKED
private fun WindowInfo.isNotOnRightOrSeparated() = anchor != ToolWindowAnchor.RIGHT || type == ToolWindowType.FLOATING
|| type == ToolWindowType.WINDOWED
companion object {
private val LOG = logger<GitLearningModule>()
}
}
} | apache-2.0 | 73484a7dcc091e4b413552f9d192a9f6 | 42.707692 | 122 | 0.710915 | 4.83816 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/services/apiresponses/commentresponse/CommentEnvelope.kt | 1 | 1393 | package com.kickstarter.services.apiresponses.commentresponse
import android.os.Parcelable
import com.kickstarter.models.ApolloEnvelope
import com.kickstarter.models.Comment
import kotlinx.android.parcel.Parcelize
@Parcelize
class CommentEnvelope(
val comments: List<Comment>?,
val commentableId: String?,
val pageInfoEnvelope: PageInfoEnvelope?,
val totalCount: Int?
) : Parcelable, ApolloEnvelope {
@Parcelize
data class Builder(
var comments: List<Comment>? = null,
var commentableId: String? = null,
var pageInfoEnvelope: PageInfoEnvelope? = null,
var totalCount: Int? = null
) : Parcelable {
fun comments(comments: List<Comment>?) = apply { this.comments = comments }
fun commentableId(commentableId: String?) = apply { this.commentableId = commentableId }
fun pageInfoEnvelope(pageInfoEnvelope: PageInfoEnvelope?) = apply { this.pageInfoEnvelope = pageInfoEnvelope }
fun totalCount(totalCount: Int?) = apply { this.totalCount = totalCount }
fun build() = CommentEnvelope(comments, commentableId, pageInfoEnvelope, totalCount)
}
companion object {
fun builder() = Builder()
}
fun toBuilder() = Builder(this.comments, this.commentableId, this.pageInfoEnvelope, this.totalCount)
override fun pageInfoEnvelope(): PageInfoEnvelope? = this.pageInfoEnvelope
}
| apache-2.0 | 706253ac1321923ecbf69640ea266bec | 36.648649 | 118 | 0.719311 | 4.522727 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/controller/StackOverflowSnippets.kt | 1 | 8133 | package com.cout970.modeler.controller
import java.io.File
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.JarURLConnection
import java.net.URL
import java.net.URLConnection
import java.net.URLDecoder
import java.util.*
import java.util.jar.JarEntry
/**
* Created by cout970 on 2017/07/19.
*/
object StackOverflowSnippets {
/**
* https://stackoverflow.com/a/22462785
* Private helper method
*
* @param directory
* * The directory to start with
* *
* @param pckgname
* * The package name to search for. Will be needed for getting the
* * Class object.
* *
* @param classes
* * if a file isn't loaded but still is in the directory
* *
* @throws ClassNotFoundException
*/
@Throws(ClassNotFoundException::class)
private fun checkDirectory(directory: File, pckgname: String, classes: ArrayList<Class<*>>) {
var tmpDirectory: File
if (directory.exists() && directory.isDirectory) {
val files = directory.list()
for (file in files!!) {
if (file.endsWith(".class")) {
try {
classes.add(Class.forName(pckgname + '.'
+ file.substring(0, file.length - 6)))
} catch (e: NoClassDefFoundError) {
// do nothing. this class hasn't been found by the
// loader, and we don't care.
}
} else {
tmpDirectory = File(directory, file)
if (tmpDirectory.isDirectory) {
checkDirectory(tmpDirectory, pckgname + "." + file, classes)
}
}
}
}
}
/**
* https://stackoverflow.com/a/22462785
* Private helper method.
* @param connection
* * the connection to the jar
* *
* @param pckgname
* * the package name to search for
* *
* @param classes
* * the current ArrayList of all classes. This method will simply
* * add new classes.
* *
* @throws ClassNotFoundException
* * if a file isn't loaded but still is in the jar file
* *
* @throws IOException
* * if it can't correctly read from the jar file.
*/
@Throws(ClassNotFoundException::class, IOException::class)
private fun checkJarFile(connection: JarURLConnection, pckgname: String, classes: ArrayList<Class<*>>) {
val jarFile = connection.jarFile
val entries = jarFile.entries()
var name: String
var jarEntry: JarEntry?
while (entries.hasMoreElements()) {
jarEntry = entries.nextElement()
if (jarEntry == null) break
name = jarEntry.name
if (name.contains(".class")) {
name = name.substring(0, name.length - 6).replace('/', '.')
if (name.contains(pckgname)) {
classes.add(Class.forName(name))
}
}
}
}
/**
* https://stackoverflow.com/a/22462785
* Attempts to list all the classes in the specified package as determined
* by the context class loader
* @param pckgname
* * the package name to search
* *
* @return a list of classes that exist within that package
* *
* @throws ClassNotFoundException
* * if something went wrong
*/
@Throws(ClassNotFoundException::class)
fun getClassesForPackage(pckgname: String): ArrayList<Class<*>> {
val classes = ArrayList<Class<*>>()
try {
val cld = Thread.currentThread().contextClassLoader
?: throw ClassNotFoundException("Can't get class loader.")
val resources = cld.getResources(pckgname.replace('.', '/'))
var connection: URLConnection
var url: URL?
while (resources.hasMoreElements()) {
url = resources.nextElement()
if (url == null) break
try {
connection = url.openConnection()
if (connection is JarURLConnection) {
checkJarFile(
connection, pckgname,
classes
)
} else if (connection::class.java.simpleName == "FileURLConnection") {
try {
checkDirectory(
File(URLDecoder.decode(url.path, "UTF-8")), pckgname, classes
)
} catch (ex: UnsupportedEncodingException) {
throw ClassNotFoundException(
pckgname + " does not appear to be a valid package (Unsupported encoding)",
ex
)
}
} else throw ClassNotFoundException(
pckgname + " (${url.path}) does not appear to be a valid package")
} catch (ioex: IOException) {
throw ClassNotFoundException(
"IOException was thrown when trying to get all resources for " + pckgname, ioex)
}
}
} catch (ex: NullPointerException) {
throw ClassNotFoundException(
pckgname + " does not appear to be a valid package (Null pointer exception)",
ex)
} catch (ioex: IOException) {
throw ClassNotFoundException(
"IOException was thrown when trying to get all resources for " + pckgname, ioex)
}
return classes
}
// https://stackoverflow.com/a/16018452
/**
* Calculates the similarity (a number within 0 and 1) between two strings.
*/
fun similarity(s1: String, s2: String): Double {
var longer = s1
var shorter = s2
if (s1.length < s2.length) { // longer should always have greater length
longer = s2
shorter = s1
}
val longerLength = longer.length
return if (longerLength == 0) {
1.0 /* both strings are zero length */
} else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble()
}
// Example implementation of the Levenshtein Edit Distance
// See http://rosettacode.org/wiki/Levenshtein_distance#Java
fun editDistance(s1: String, s2: String): Int {
val varS1 = s1.toLowerCase()
val varS2 = s2.toLowerCase()
val costs = IntArray(varS2.length + 1)
for (i in 0..varS1.length) {
var lastValue = i
for (j in 0..varS2.length) {
if (i == 0)
costs[j] = j
else {
if (j > 0) {
var newValue = costs[j - 1]
if (varS1[i - 1] != varS2[j - 1])
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1
costs[j - 1] = lastValue
lastValue = newValue
}
}
}
if (i > 0)
costs[varS2.length] = lastValue
}
return costs[varS2.length]
}
}
/** https://github.com/gazolla/Kotlin-Algorithm/blob/master/Shuffle/Shuffle.kt
*
*/
fun <T : Comparable<T>> shuffle(items: MutableList<T>): List<T> {
val rg = Random()
for (i in 0 until items.size) {
val randomPosition = rg.nextInt(items.size)
val tmp: T = items[i]
items[i] = items[randomPosition]
items[randomPosition] = tmp
}
return items
}
/* extension version */
fun <T> Iterable<T>.shuffle(): List<T> {
val list = this.toMutableList()
Collections.shuffle(list)
return list
}
| gpl-3.0 | f0cce4bd19e5845fb105457cf1f91c4e | 33.029289 | 108 | 0.51457 | 4.758923 | false | false | false | false |
ingokegel/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleManagerComponentBridge.kt | 1 | 17485 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module
import com.intellij.ProjectTopics
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.AutomaticModuleUnloader
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleEx
import com.intellij.openapi.module.impl.NonPersistentModuleStore
import com.intellij.openapi.module.impl.UnloadedModulesListStorage
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.InitProjectActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.ide.impl.executeOrQueueOnDispatchThread
import com.intellij.workspaceModel.ide.impl.jps.serialization.ErrorReporter
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectEntitiesLoader
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetEntityChangeListener
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootsChangeListener
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.VirtualFileUrlWatcher
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.nio.file.Path
class ModuleManagerComponentBridge(private val project: Project) : ModuleManagerBridgeImpl(project) {
private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
internal class ModuleManagerInitProjectActivity : InitProjectActivity {
override suspend fun run(project: Project) {
val moduleManager = ModuleManager.getInstance(project) as ModuleManagerComponentBridge
var activity = StartUpMeasurer.startActivity("firing modules_added event", ActivityCategory.DEFAULT)
val modules = moduleManager.modules().toList()
moduleManager.fireModulesAdded(modules)
activity = activity.endAndStart("deprecated module component moduleAdded calling")
@Suppress("removal", "DEPRECATION")
val deprecatedComponents = mutableListOf<com.intellij.openapi.module.ModuleComponent>()
for (module in modules) {
if (!module.isLoaded) {
module.moduleAdded(deprecatedComponents)
}
}
if (!deprecatedComponents.isEmpty()) {
withContext(Dispatchers.EDT) {
ApplicationManager.getApplication().runWriteAction {
for (deprecatedComponent in deprecatedComponents) {
@Suppress("DEPRECATION", "removal")
deprecatedComponent.moduleAdded()
}
}
}
}
activity.end()
}
}
init {
// default project doesn't have modules
if (!project.isDefault) {
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosed(eventProject: Project) {
if (project == eventProject) {
for (module in modules()) {
module.projectClosed()
}
}
}
})
val rootsChangeListener = ProjectRootsChangeListener(project)
WorkspaceModelTopics.getInstance(project).subscribeModuleBridgeInitializer(busConnection, object : WorkspaceModelChangeListener {
override fun beforeChanged(event: VersionedStorageChange) {
if (!VirtualFileUrlWatcher.getInstance(project).isInsideFilePointersUpdate) {
//the old implementation doesn't fire rootsChanged event when roots are moved or renamed, let's keep this behavior for now
rootsChangeListener.beforeChanged(event)
}
for (change in event.getChanges(FacetEntity::class.java)) {
LOG.debug { "Fire 'before' events for facet change $change" }
FacetEntityChangeListener.getInstance(project).processBeforeChange(change, event)
}
val moduleMap = event.storageBefore.moduleMap
for (change in event.getChanges(ModuleEntity::class.java)) {
if (change is EntityChange.Removed) {
val module = moduleMap.getDataByEntity(change.entity)
LOG.debug { "Fire 'beforeModuleRemoved' event for module ${change.entity.name}, module = $module" }
if (module != null) {
fireBeforeModuleRemoved(module)
}
}
}
}
override fun changed(event: VersionedStorageChange) {
val moduleLibraryChanges = event.getChanges(LibraryEntity::class.java).filterModuleLibraryChanges()
val changes = event.getChanges(ModuleEntity::class.java)
val facetChanges = event.getChanges(FacetEntity::class.java)
val addedModulesNames = changes.filterIsInstance<EntityChange.Added<ModuleEntity>>().mapTo(HashSet()) { it.entity.name }
if (changes.isNotEmpty() || moduleLibraryChanges.isNotEmpty() || facetChanges.isNotEmpty()) {
executeOrQueueOnDispatchThread {
LOG.debug("Process changed modules and facets")
incModificationCount()
for (change in moduleLibraryChanges) {
when (change) {
is EntityChange.Removed -> processModuleLibraryChange(change, event)
is EntityChange.Replaced -> processModuleLibraryChange(change, event)
is EntityChange.Added -> Unit
}
}
for (change in facetChanges) {
when (change) {
is EntityChange.Removed -> FacetEntityChangeListener.getInstance(project).processChange(change, event.storageBefore,
addedModulesNames)
is EntityChange.Replaced -> FacetEntityChangeListener.getInstance(project).processChange(change, event.storageBefore,
addedModulesNames)
is EntityChange.Added -> Unit
}
}
val oldModuleNames = mutableMapOf<Module, String>()
val unloadedModulesSet = UnloadedModulesListStorage.getInstance(project).unloadedModuleNames
for (change in changes) {
processModuleChange(change, unloadedModulesSet, oldModuleNames, event)
}
for (change in moduleLibraryChanges) {
if (change is EntityChange.Added) processModuleLibraryChange(change, event)
}
for (change in facetChanges) {
if (change is EntityChange.Added) {
FacetEntityChangeListener.getInstance(project).processChange(change, event.storageBefore, addedModulesNames)
}
}
// After every change processed
postProcessModules(oldModuleNames)
incModificationCount()
}
}
// Roots changed should be sent after syncing with legacy bridge
if (!VirtualFileUrlWatcher.getInstance(project).isInsideFilePointersUpdate) {
//the old implementation doesn't fire rootsChanged event when roots are moved or renamed, let's keep this behavior for now
rootsChangeListener.changed(event)
}
}
})
}
}
private fun postProcessModules(oldModuleNames: MutableMap<Module, String>) {
if (oldModuleNames.isNotEmpty()) {
project.messageBus
.syncPublisher(ProjectTopics.MODULES)
.modulesRenamed(project, oldModuleNames.keys.toList()) { module -> oldModuleNames[module] }
}
if (unloadedModules.isNotEmpty()) {
AutomaticModuleUnloader.getInstance(project).setLoadedModules(modules.map { it.name })
}
}
private fun addModule(moduleEntity: ModuleEntity): ModuleBridge {
val plugins = PluginManagerCore.getPluginSet().getEnabledModules()
val module = createModuleInstance(moduleEntity = moduleEntity,
versionedStorage = entityStore,
diff = null,
isNew = true,
precomputedExtensionModel = null,
plugins = plugins,
corePlugin = plugins.firstOrNull { it.pluginId == PluginManagerCore.CORE_ID })
WorkspaceModel.getInstance(project).updateProjectModelSilent {
it.mutableModuleMap.addMapping(moduleEntity, module)
}
return module
}
private fun processModuleChange(change: EntityChange<ModuleEntity>, unloadedModuleNames: Set<String>,
oldModuleNames: MutableMap<Module, String>, event: VersionedStorageChange) {
when (change) {
is EntityChange.Removed -> {
// It's possible case then idToModule doesn't contain element e.g. if unloaded module was removed
val module = event.storageBefore.findModuleByEntity(change.entity)
if (module != null) {
fireEventAndDisposeModule(module)
}
}
is EntityChange.Added -> {
val alreadyCreatedModule = event.storageAfter.findModuleByEntity(change.entity)
val module = if (alreadyCreatedModule != null) {
unloadedModules.remove(change.entity.name)
alreadyCreatedModule.entityStorage = entityStore
alreadyCreatedModule.diff = null
alreadyCreatedModule
}
else {
if (change.entity.name in unloadedModuleNames) {
unloadedModules[change.entity.name] = UnloadedModuleDescriptionBridge.createDescription(change.entity)
return
}
if (!areModulesLoaded()) return
addModule(change.entity)
}
if (project.isOpen) {
fireModuleAddedInWriteAction(module)
}
}
is EntityChange.Replaced -> {
val oldId = change.oldEntity.persistentId
val newId = change.newEntity.persistentId
if (oldId != newId) {
unloadedModules.remove(change.newEntity.name)
val module = event.storageBefore.findModuleByEntity(change.oldEntity)
if (module != null) {
module.rename(newId.name, getModuleVirtualFileUrl(change.newEntity), true)
oldModuleNames[module] = oldId.name
}
}
else if (getImlFileDirectory(change.oldEntity) != getImlFileDirectory(change.newEntity)) {
val module = event.storageBefore.findModuleByEntity(change.newEntity)
val imlFilePath = getModuleVirtualFileUrl(change.newEntity)
if (module != null && imlFilePath != null) {
module.onImlFileMoved(imlFilePath)
}
}
}
}
}
private fun processModuleLibraryChange(change: EntityChange<LibraryEntity>, event: VersionedStorageChange) {
when (change) {
is EntityChange.Removed -> {
val library = event.storageBefore.libraryMap.getDataByEntity(change.entity)
if (library != null) {
Disposer.dispose(library)
}
}
is EntityChange.Replaced -> {
val idBefore = change.oldEntity.persistentId
val idAfter = change.newEntity.persistentId
val newLibrary = event.storageAfter.libraryMap.getDataByEntity(change.newEntity) as LibraryBridgeImpl?
if (newLibrary != null) {
newLibrary.clearTargetBuilder()
if (idBefore != idAfter) {
newLibrary.entityId = idAfter
}
}
}
is EntityChange.Added -> {
val tableId = change.entity.tableId as LibraryTableId.ModuleLibraryTableId
val moduleEntity = entityStore.current.resolve(tableId.moduleId)
?: error("Could not find module for module library: ${change.entity.persistentId}")
if (moduleEntity.name !in unloadedModules) {
val library = event.storageAfter.libraryMap.getDataByEntity(change.entity)
if (library == null && areModulesLoaded()) {
val module = entityStore.current.findModuleByEntity(moduleEntity)
?: error("Could not find module bridge for module entity $moduleEntity")
val moduleRootComponent = ModuleRootComponentBridge.getInstance(module)
(moduleRootComponent.getModuleLibraryTable() as ModuleLibraryTableBridgeImpl).addLibrary(change.entity, null)
}
if (library != null) {
(library as LibraryBridgeImpl).entityStorage = entityStore
library.clearTargetBuilder()
}
}
}
}
}
private fun List<EntityChange<LibraryEntity>>.filterModuleLibraryChanges() = filter { it.isModuleLibrary() }
private fun fireModuleAddedInWriteAction(module: ModuleEx) {
ApplicationManager.getApplication().runWriteAction {
if (!module.isLoaded) {
@Suppress("removal", "DEPRECATION")
val oldComponents = mutableListOf<com.intellij.openapi.module.ModuleComponent>()
module.moduleAdded(oldComponents)
for (oldComponent in oldComponents) {
@Suppress("DEPRECATION", "removal")
oldComponent.moduleAdded()
}
fireModulesAdded(listOf(module))
}
}
}
private fun fireModulesAdded(modules: List<Module>) {
project.messageBus.syncPublisher(ProjectTopics.MODULES).modulesAdded(project, modules)
}
override fun registerNonPersistentModuleStore(module: ModuleBridge) {
(module as ModuleBridgeImpl).registerService(serviceInterface = IComponentStore::class.java,
implementation = NonPersistentModuleStore::class.java,
pluginDescriptor = ComponentManagerImpl.fakeCorePluginDescriptor,
override = true,
preloadMode = ServiceDescriptor.PreloadMode.FALSE)
}
override fun loadModuleToBuilder(moduleName: String, filePath: String, diff: MutableEntityStorage): ModuleEntity {
val builder = MutableEntityStorage.create()
var errorMessage: String? = null
JpsProjectEntitiesLoader.loadModule(Path.of(filePath), getJpsProjectConfigLocation(project)!!, builder, object : ErrorReporter {
override fun reportError(message: String, file: VirtualFileUrl) {
errorMessage = message
}
}, virtualFileManager)
if (errorMessage != null) {
throw IOException("Failed to load module from $filePath: $errorMessage")
}
diff.addDiff(builder)
val moduleEntity = diff.entities(ModuleEntity::class.java).firstOrNull { it.name == moduleName }
if (moduleEntity == null) {
throw IOException("Failed to load module from $filePath")
}
val moduleFileUrl = getModuleVirtualFileUrl(moduleEntity)!!
LocalFileSystem.getInstance().refreshAndFindFileByNioFile(moduleFileUrl.toPath())
return moduleEntity
}
override fun createModule(persistentId: ModuleId, name: String, virtualFileUrl: VirtualFileUrl?, entityStorage: VersionedEntityStorage,
diff: MutableEntityStorage?): ModuleBridge {
return ModuleBridgeImpl(persistentId, name, project, virtualFileUrl, entityStorage, diff)
}
companion object {
private val LOG = logger<ModuleManagerComponentBridge>()
private fun EntityChange<LibraryEntity>.isModuleLibrary(): Boolean {
return when (this) {
is EntityChange.Added -> entity.tableId is LibraryTableId.ModuleLibraryTableId
is EntityChange.Removed -> entity.tableId is LibraryTableId.ModuleLibraryTableId
is EntityChange.Replaced -> oldEntity.tableId is LibraryTableId.ModuleLibraryTableId
}
}
}
}
| apache-2.0 | 086a710df2b07814b8a706ce237c5279 | 45.876676 | 137 | 0.681098 | 5.477757 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.kt | 1 | 11367 | // 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.platform
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.lightEdit.LightEditUtil
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
private val LOG = logger<PlatformProjectOpenProcessor>()
private val EP_NAME = ExtensionPointName<DirectoryProjectConfigurator>("com.intellij.directoryProjectConfigurator")
class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectOpenProcessor {
enum class Option {
FORCE_NEW_FRAME,
@Suppress("unused")
TEMP_PROJECT
}
companion object {
@JvmField
val PROJECT_OPENED_BY_PLATFORM_PROCESSOR = Key.create<Boolean>("PROJECT_OPENED_BY_PLATFORM_PROCESSOR")
@JvmField
val PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR = Key.create<Boolean>("PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR")
@JvmField
val PROJECT_NEWLY_OPENED = Key.create<Boolean>("PROJECT_NEWLY_OPENED")
fun Project.isOpenedByPlatformProcessor(): Boolean {
return getUserData(PROJECT_OPENED_BY_PLATFORM_PROCESSOR) == true
}
fun Project.isConfiguredByPlatformProcessor(): Boolean {
return getUserData(PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR) == true
}
fun Project.isNewProject(): Boolean {
return getUserData(PROJECT_NEWLY_OPENED) == true
}
@JvmStatic
fun getInstance() = getInstanceIfItExists()!!
@JvmStatic
fun getInstanceIfItExists(): PlatformProjectOpenProcessor? {
for (processor in EXTENSION_POINT_NAME.extensionList) {
if (processor is PlatformProjectOpenProcessor) {
return processor
}
}
return null
}
@JvmStatic
@Suppress("UNUSED_PARAMETER")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
@Deprecated("Use {@link #doOpenProject(Path, OpenProjectTask)} ")
fun doOpenProject(virtualFile: VirtualFile,
projectToClose: Project?,
forceOpenInNewFrame: Boolean,
line: Int,
callback: ProjectOpenedCallback?,
isReopen: Boolean): Project? {
val options = OpenProjectTask(forceOpenInNewFrame = forceOpenInNewFrame, projectToClose = projectToClose, line = line)
return doOpenProject(Paths.get(virtualFile.path), options)
}
@JvmStatic
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
@Deprecated("Use {@link #doOpenProject(Path, OpenProjectTask)} ")
fun doOpenProject(virtualFile: VirtualFile,
projectToClose: Project?,
line: Int,
callback: ProjectOpenedCallback?,
options: EnumSet<Option>): Project? {
val openProjectOptions = OpenProjectTask(forceOpenInNewFrame = options.contains(Option.FORCE_NEW_FRAME),
projectToClose = projectToClose,
callback = callback,
runConfigurators = callback != null,
line = line)
return doOpenProject(Paths.get(virtualFile.path), openProjectOptions)
}
@ApiStatus.Internal
@JvmStatic
fun createTempProjectAndOpenFile(file: Path, options: OpenProjectTask): Project? {
val dummyProjectName = file.fileName.toString()
val baseDir = FileUtilRt.createTempDirectory(dummyProjectName, null, true).toPath()
val copy = options.copy(isNewProject = true, projectName = dummyProjectName, runConfigurators = true, preparedToOpen = { module ->
// add content root for chosen (single) file
ModuleRootModificationUtil.updateModel(module) { model ->
val entries = model.contentEntries
// remove custom content entry created for temp directory
if (entries.size == 1) {
model.removeContentEntry(entries[0])
}
model.addContentEntry(VfsUtilCore.pathToUrl(file.toString()))
}
})
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, copy) ?: return null
openFileFromCommandLine(project, file, copy.line, copy.column)
return project
}
@ApiStatus.Internal
@JvmStatic
fun doOpenProject(file: Path, originalOptions: OpenProjectTask): Project? {
LOG.info("Opening $file")
if (Files.isDirectory(file)) {
return ProjectManagerEx.getInstanceEx().openProject(file, createOptionsToOpenDotIdeaOrCreateNewIfNotExists(file, projectToClose = null))
}
var options = originalOptions
if (LightEditUtil.isForceOpenInLightEditMode()) {
val lightEditProject = LightEditUtil.openFile(file, false)
if (lightEditProject != null) {
return lightEditProject
}
}
var baseDirCandidate = file.parent
while (baseDirCandidate != null && !Files.exists(baseDirCandidate.resolve(Project.DIRECTORY_STORE_FOLDER))) {
baseDirCandidate = baseDirCandidate.parent
}
val baseDir: Path
// no reasonable directory -> create new temp one or use parent
if (baseDirCandidate == null) {
LOG.info("No project directory found")
if (LightEditUtil.isLightEditEnabled() && !LightEditService.getInstance().isPreferProjectMode) {
val lightEditProject = LightEditUtil.openFile(file, true)
if (lightEditProject != null) {
return lightEditProject
}
}
if (Registry.`is`("ide.open.file.in.temp.project.dir")) {
return createTempProjectAndOpenFile(file, options)
}
baseDir = file.parent
options = options.copy(isNewProject = !Files.isDirectory(baseDir.resolve(Project.DIRECTORY_STORE_FOLDER)))
}
else {
baseDir = baseDirCandidate
LOG.info("Project directory found: $baseDir")
}
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, if (baseDir == file) options else options.copy(projectName = file.fileName.toString()))
if (project != null && file != baseDir) {
openFileFromCommandLine(project, file, options.line, options.column)
}
return project
}
@JvmStatic
fun runDirectoryProjectConfigurators(baseDir: Path, project: Project, newProject: Boolean): Module {
project.putUserData(PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR, true)
val moduleRef = Ref<Module>()
val virtualFile = ProjectUtil.getFileAndRefresh(baseDir)!!
EP_NAME.forEachExtensionSafe { configurator ->
fun task() {
configurator.configureProject(project, virtualFile, moduleRef, newProject)
}
if (configurator.isEdtRequired) {
ApplicationManager.getApplication().invokeAndWait {
task()
}
}
else {
task()
}
}
val module = moduleRef.get()
if (module == null) {
LOG.error("No extension configured a module for $baseDir; extensions = ${EP_NAME.extensionList}")
}
return module
}
@JvmStatic
fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean {
return ProjectAttachProcessor.EP_NAME.findFirstSafe { processor ->
processor.attachToProject(project, projectDir, callback)
} != null
}
/**
* If project file in IDEA format (.idea directory or .ipr file) exists, open it and run configurators if no modules.
*
* If doesn't exists, create a new project using default project template and run configurators (something that creates module).
* (at the moment of creation project file in IDEA format will be removed if any).
*
* This method must be not used in tests.
*
* See OpenProjectTest.
*/
@ApiStatus.Internal
@JvmStatic
fun createOptionsToOpenDotIdeaOrCreateNewIfNotExists(projectDir: Path, projectToClose: Project?): OpenProjectTask {
// doesn't make sense to refresh
return OpenProjectTask(runConfigurators = true,
isNewProject = !ProjectUtil.isValidProjectPath(projectDir),
projectToClose = projectToClose,
isRefreshVfsNeeded = !ApplicationManager.getApplication().isUnitTestMode,
useDefaultProjectAsTemplate = true)
}
}
override fun canOpenProject(file: VirtualFile) = file.isDirectory
override fun isProjectFile(file: VirtualFile) = false
override fun lookForProjectsInDirectory() = false
override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
val baseDir = virtualFile.toNioPath()
return doOpenProject(baseDir, createOptionsToOpenDotIdeaOrCreateNewIfNotExists(baseDir, projectToClose).copy(forceOpenInNewFrame = forceOpenInNewFrame))
}
override fun openProjectAndFile(file: Path, line: Int, column: Int, tempProject: Boolean): Project? {
// force open in a new frame if temp project
if (tempProject) {
return createTempProjectAndOpenFile(file, OpenProjectTask(forceOpenInNewFrame = true, line = line, column = column))
}
else {
return doOpenProject(file, OpenProjectTask(line = line, column = column))
}
}
@Suppress("HardCodedStringLiteral")
override fun getName() = "text editor"
}
private fun openFileFromCommandLine(project: Project, file: Path, line: Int, column: Int) {
StartupManager.getInstance(project).runAfterOpened {
ApplicationManager.getApplication().invokeLater(Runnable {
if (project.isDisposed || !Files.exists(file)) {
return@Runnable
}
val virtualFile = ProjectUtil.getFileAndRefresh(file) ?: return@Runnable
val navigatable = if (line > 0) {
OpenFileDescriptor(project, virtualFile, line - 1, column.coerceAtLeast(0))
}
else {
PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, -1)
}
navigatable.navigate(true)
}, ModalityState.NON_MODAL, project.disposed)
}
} | apache-2.0 | 8f08744082727387b36b54eb5819a7c9 | 40.039711 | 161 | 0.690244 | 5.043035 | false | true | false | false |
kivensolo/UiUsingListView | module-Common/src/main/java/com/kingz/module/common/ext/CollectionExt.kt | 1 | 1231 | package com.kingz.module.common.ext
fun <T> Collection<T>.joinToString(
separator: String = ",",
prefix: String = "",
postfix: String = "",
transform: (T) -> String = { it.toString() }
// transform: 声明一个以lambda为默认值的函数类型的参数
): String {
val result = StringBuilder(prefix)
for ((index, element) in this.withIndex()) {
if (index > 0) result.append(separator)
result.append(transform(element))
}
result.append(postfix)
return result.toString()
}
fun <T> Collection<T>.joinToStringByInvoke(
separator: String = ",",
prefix: String = "",
postfix: String = "",
transform: ((T) -> String)? = null
// transform: 声明一个函数类型的可空参数
): String {
val result = StringBuilder(prefix)
for ((index, element) in this.withIndex()) {
if (index > 0) result.append(separator)
// 使用安全调用语法调用函数
val str = transform?.invoke(element)
?: element.toString() // 使用Elvis运算符处理回调没有被处理的情况
result.append(str)
}
result.append(postfix)
return result.toString()
} | gpl-2.0 | f6d5cc54f407dbebd181610327469715 | 26.75 | 63 | 0.591524 | 3.932624 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/generators/test/org/jetbrains/kotlin/testGenerator/generator/SuiteElement.kt | 1 | 4905 | // 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.testGenerator.generator
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.kotlin.testGenerator.generator.methods.RunTestMethod
import org.jetbrains.kotlin.testGenerator.generator.methods.TestCaseMethod
import org.jetbrains.kotlin.testGenerator.model.*
import org.junit.runner.RunWith
import java.io.File
import java.util.*
import javax.lang.model.element.Modifier
fun File.toRelativeStringSystemIndependent(base: File): String {
val path = this.toRelativeString(base)
return if (File.separatorChar == '\\') {
path.replace('\\', '/')
} else path
}
interface TestMethod: RenderElement {
val methodName: String
}
class SuiteElement private constructor(
private val group: TGroup, private val suite: TSuite, private val model: TModel,
private val className: String, private val isNested: Boolean,
methods: List<TestMethod>, nestedSuites: List<SuiteElement>
): RenderElement {
private val methods = methods.sortedBy { it.methodName }
private val nestedSuites = nestedSuites.sortedBy { it.className }
companion object {
fun create(group: TGroup, suite: TSuite, model: TModel, className: String, isNested: Boolean): SuiteElement {
return collect(group, suite, model, model.depth, className, isNested)
}
private fun collect(group: TGroup, suite: TSuite, model: TModel, depth: Int, className: String, isNested: Boolean): SuiteElement {
val rootFile = File(group.testDataRoot, model.path)
val methods = mutableListOf<TestMethod>()
val nestedSuites = mutableListOf<SuiteElement>()
for (file in rootFile.listFiles().orEmpty()) {
if (depth > 0 && file.isDirectory && file.name !in model.excludedDirectories) {
val nestedClassName = file.toJavaIdentifier().capitalize()
val nestedModel = model.copy(path = file.toRelativeStringSystemIndependent(group.testDataRoot), testClassName = nestedClassName)
val nestedElement = collect(group, suite, nestedModel, depth - 1, nestedClassName, isNested = true)
if (nestedElement.methods.isNotEmpty() || nestedElement.nestedSuites.isNotEmpty()) {
if (model.flatten) {
methods += flatten(nestedElement)
} else {
nestedSuites += nestedElement
}
continue
}
}
val match = model.pattern.matchEntire(file.name) ?: continue
assert(match.groupValues.size >= 2) { "Invalid pattern, test method name group should be defined" }
val methodNameBase = getTestMethodNameBase(match.groupValues[1])
val path = file.toRelativeStringSystemIndependent(group.moduleRoot)
methods += TestCaseMethod(methodNameBase, if (file.isDirectory) "$path/" else path, file.toRelativeStringSystemIndependent(rootFile))
}
if (methods.isNotEmpty()) {
methods += RunTestMethod(model)
}
return SuiteElement(group, suite, model, className, isNested, methods, nestedSuites)
}
private fun flatten(element: SuiteElement): List<TestMethod> {
val modelFileName = File(element.model.path).name
val ownMethods = element.methods.filterIsInstance<TestCaseMethod>().map { it.embed(modelFileName) }
val nestedMethods = element.nestedSuites.flatMap { flatten(it) }
return ownMethods + nestedMethods
}
private fun getTestMethodNameBase(path: String): String {
return path
.split(File.pathSeparator)
.joinToString(File.pathSeparator) { makeJavaIdentifier(it).capitalize() }
}
}
override fun Code.render() {
val testDataPath = File(group.testDataRoot, model.path).toRelativeStringSystemIndependent(group.moduleRoot)
appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java))
appendAnnotation(TAnnotation<TestMetadata>(testDataPath))
suite.annotations.forEach { appendAnnotation(it) }
val modifiers = EnumSet.of(Modifier.PUBLIC)
if (isNested) {
modifiers.add(Modifier.STATIC)
}
if (methods.isEmpty()) {
modifiers.add(Modifier.ABSTRACT)
}
appendModifiers(modifiers)
appendBlock("class $className extends ${suite.abstractTestClass.simpleName}") {
appendList(methods + nestedSuites, separator = "\n\n")
}
}
} | apache-2.0 | 18160edb29a83970b15901e83f6ee111 | 43.6 | 158 | 0.654638 | 5.109375 | false | true | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/benchmarks/bonnie/Bonnie.kt | 2 | 2299 | package com.github.kerubistan.kerub.utils.junix.benchmarks.bonnie
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import org.apache.sshd.client.session.ClientSession
object Bonnie : OsCommand {
override fun available(osVersion: SoftwarePackage, packages: List<SoftwarePackage>) =
packages.any { it.name == "bonnie++" || it.name == "bonnieplus" }
private val coma = ",".toRegex()
private fun String.kPerSec() = (this.toLong() * 1024).toBigInteger()
private fun String.time() = when {
this.endsWith("us") -> this.substringBefore("us").toLong()
this.endsWith("ms") -> this.substringBefore("ms").toLong() * 1000
else -> TODO("not handled: $this")
}
fun run(session: ClientSession, directory: String, user: String = "root", nrOfFiles: Int = 128): FsBenchmarkData =
session.executeOrDie("bonnie++ -n $nrOfFiles -u $user -d $directory", isError = { false })
.lines()
.last { it.isNotBlank() }
.split(coma).let { result ->
FsBenchmarkData(
sequentialOutputPerChr = IoBenchmarkItem(
throughput = result[7].kPerSec(),
latency = result[36].time(),
cpuUsagePercent = result[8].toShort()
),
sequentialOutputPerBlock = IoBenchmarkItem(
throughput = result[9].kPerSec(),
latency = result[37].time(),
cpuUsagePercent = result[10].toShort()
),
sequentialOutputRewrite = IoBenchmarkItem(
throughput = result[11].kPerSec(),
latency = result[38].time(),
cpuUsagePercent = result[12].toShort()
),
sequentialInputPerChr = IoBenchmarkItem(
throughput = result[13].kPerSec(),
latency = result[39].time(),
cpuUsagePercent = result[14].toShort()
),
sequentialInputPerBlock = IoBenchmarkItem(
throughput = result[15].kPerSec(),
latency = result[40].time(),
cpuUsagePercent = result[16].toShort()
),
random = IoBenchmarkItem(
throughput = result[17].toDouble().toBigDecimal().toBigInteger(),
latency = result[41].time(),
cpuUsagePercent = result[18].toShort()
)
)
}
} | apache-2.0 | 44c88e3a23a1440d6d42cffdcfb9af00 | 36.096774 | 115 | 0.635929 | 3.762684 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/checker/FunctionReturnTypes.fir.kt | 6 | 6899 | // COMPILER_ARGUMENTS: -XXLanguage:-NewInference
// RUNTIME
fun none() {}
fun unitEmptyInfer() {}
fun unitEmpty() : Unit {}
fun unitEmptyReturn() : Unit {return}
fun unitIntReturn() : Unit {return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Unit, actual kotlin/Int">1</error>}
fun unitUnitReturn() : Unit {return Unit}
fun test1() : Any = { <error descr="[RETURN_NOT_ALLOWED] 'return' is not allowed here">return</error> }
fun test2() : Any = a@ {return@a 1}
fun test3() : Any { return }
fun bbb() {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Unit, actual kotlin/Int">1</error>
}
fun foo(expr: StringBuilder): Int {
val c = 'a'
when(c) {
0.toChar() -> throw Exception("zero")
else -> throw Exception("nonzero" + c)
}
}
fun unitShort() : Unit = Unit
fun unitShortConv() : Unit = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Unit, actual kotlin/Int">1</error>
fun unitShortNull() : Unit = <error descr="[NULL_FOR_NONNULL_TYPE] ">null</error>
fun intEmpty() : Int {}
fun intShortInfer() = 1
fun intShort() : Int = 1
//fun intBlockInfer() {1}
fun intBlock() : Int {return 1}
fun intBlock1() : Int {1}
fun intString(): Int = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/String">"s"</error>
fun intFunctionLiteral(): Int = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Function0<kotlin/Int>">{ 10 }</error>
fun blockReturnUnitMismatch() : Int {<error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Unit">return</error>}
fun blockReturnValueTypeMismatch() : Int {return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">3.4</error>}
fun blockReturnValueTypeMatch() : Int {return 1}
fun blockReturnValueTypeMismatchUnit() : Int {return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Unit">Unit</error>}
fun blockAndAndMismatch() : Int {
true && false
}
fun blockAndAndMismatch1() : Int {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">true && false</error>
}
fun blockAndAndMismatch2() : Int {
(return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">true</error>) && (return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">false</error>)
}
fun blockAndAndMismatch3() : Int {
true || false
}
fun blockAndAndMismatch4() : Int {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">true || false</error>
}
fun blockAndAndMismatch5() : Int {
(return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">true</error>) || (return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Boolean">false</error>)
}
fun blockReturnValueTypeMatch1() : Int {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">if (1 > 2) 1.0 else 2.0</error>
}
fun blockReturnValueTypeMatch2() : Int {
return <error descr="[INVALID_IF_AS_EXPRESSION] 'if' must have both main and 'else' branches if used as an expression">if</error> (1 > 2) 1
}
fun blockReturnValueTypeMatch3() : Int {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Any">if (1 > 2) else 1</error>
}
fun blockReturnValueTypeMatch4() : Int {
if (1 > 2)
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">1.0</error>
else return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">2.0</error>
}
fun blockReturnValueTypeMatch5() : Int {
if (1 > 2)
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">1.0</error>
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">2.0</error>
}
fun blockReturnValueTypeMatch6() : Int {
if (1 > 2)
else return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">1.0</error>
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">2.0</error>
}
fun blockReturnValueTypeMatch7() : Int {
if (1 > 2)
1.0
else 2.0
}
fun blockReturnValueTypeMatch8() : Int {
if (1 > 2)
1.0
else 2.0
return 1
}
fun blockReturnValueTypeMatch9() : Int {
if (1 > 2)
1.0
}
fun blockReturnValueTypeMatch10() : Int {
return <error descr="[INVALID_IF_AS_EXPRESSION] 'if' must have both main and 'else' branches if used as an expression">if</error> (1 > 2) 1
}
fun blockReturnValueTypeMatch11() : Int {
if (1 > 2)
else 1.0
}
fun blockReturnValueTypeMatch12() : Int {
if (1 > 2)
return 1
else return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Double">1.0</error>
}
fun blockNoReturnIfValDeclaration(): Int {
val x = 1
}
fun blockNoReturnIfEmptyIf(): Int {
if (1 < 2) {} else {}
}
fun blockNoReturnIfUnitInOneBranch(): Int {
if (1 < 2) {
return 1
} else {
if (3 < 4) {
} else {
return 2
}
}
}
fun nonBlockReturnIfEmptyIf(): Int = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Unit">if (1 < 2) {} else {}</error>
fun nonBlockNoReturnIfUnitInOneBranch(): Int = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/Any">if (1 < 2) {} else 2</error>
val a = <error descr="[RETURN_NOT_ALLOWED] 'return' is not allowed here">return</error> 1
class A() {
}
fun illegalConstantBody(): Int = <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual kotlin/String">"s"</error>
fun illegalConstantBlock(): String {
return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/String, actual kotlin/Int">1</error>
}
fun illegalIfBody(): Int =
<error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Int, actual it(kotlin/Comparable<*> & java/io/Serializable)">if (1 < 2) 'a' else { 1.0 }</error>
fun illegalIfBlock(): Boolean {
if (1 < 2)
return false
else { return <error descr="[RETURN_TYPE_MISMATCH] Return type mismatch: expected kotlin/Boolean, actual kotlin/Int">1</error> }
}
fun illegalReturnIf(): Char {
return if (1 < 2) 'a' else { 1 }
}
fun returnNothing(): Nothing {
throw 1
}
fun f(): Int {
if (1 < 2) { return 1 } else returnNothing()
}
fun f1(): Int = if (1 < 2) 1 else returnNothing()
| apache-2.0 | 7cc713eccc880cbedadcdad2ca8ecb71 | 41.58642 | 255 | 0.706624 | 3.487867 | false | false | false | false |
bjansen/pebble-intellij | src/main/kotlin/com/github/bjansen/intellij/pebble/lang/PebbleFileViewProviderFactory.kt | 1 | 3542 | package com.github.bjansen.intellij.pebble.lang
import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition
import com.github.bjansen.pebble.parser.PebbleLexer
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.openapi.fileTypes.PlainTextLanguage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.templateLanguages.ConfigurableTemplateLanguageFileViewProvider
import com.intellij.psi.templateLanguages.TemplateDataElementType
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
import com.intellij.util.containers.ContainerUtil
import org.antlr.intellij.adaptor.lexer.TokenIElementType
class PebbleFileViewProviderFactory : FileViewProviderFactory {
override fun createFileViewProvider(file: VirtualFile, language: Language?, manager: PsiManager, eventSystemEnabled: Boolean): FileViewProvider {
return PebbleFileViewProvider(manager, file, eventSystemEnabled)
}
}
class PebbleFileViewProvider(manager: PsiManager, private val file: VirtualFile, eventSystemEnabled: Boolean,
private val myTemplateLanguage: Language = computeTemplateLanguage(manager, file))
: MultiplePsiFilesPerDocumentFileViewProvider(manager, file, eventSystemEnabled),
ConfigurableTemplateLanguageFileViewProvider {
override fun getBaseLanguage() = PebbleLanguage
override fun cloneInner(file: VirtualFile) = PebbleFileViewProvider(manager, file, false, myTemplateLanguage)
override fun getTemplateDataLanguage() = myTemplateLanguage
override fun getLanguages() = setOf(PebbleLanguage, templateDataLanguage)
override fun createFile(lang: Language): PsiFile? {
return when (lang) {
templateDataLanguage -> {
val file = LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this) as PsiFileImpl
file.contentElementType = getTemplateDataElementType(baseLanguage)
file
}
baseLanguage -> LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this)
else -> null
}
}
companion object {
private val templateDataToLang = ContainerUtil.newConcurrentMap<String, TemplateDataElementType>()
val pebbleFragment = TokenIElementType(0, "PEBBLE_FRAGMENT", PebbleLanguage)
private fun getTemplateDataElementType(lang: Language): TemplateDataElementType {
val result = templateDataToLang[lang.id]
if (result != null) return result
val content = PebbleParserDefinition.tokens[PebbleLexer.CONTENT]
val created = TemplateDataElementType("PEBBLE_TEMPLATE_DATA", lang, content, pebbleFragment)
val prevValue = templateDataToLang.putIfAbsent(lang.id, created)
return prevValue ?: created
}
private fun computeTemplateLanguage(manager: PsiManager, file: VirtualFile): Language {
val mappings = TemplateDataLanguageMappings.getInstance(manager.project)
val dataLang = mappings.getMapping(file)
?: PlainTextLanguage.INSTANCE
val substituteLang = LanguageSubstitutors.INSTANCE.substituteLanguage(dataLang, file, manager.project)
if (TemplateDataLanguageMappings.getTemplateableLanguages().contains(substituteLang)) {
return substituteLang
}
return dataLang
}
}
}
| mit | 2c1294055e5d09c5c9ae630edabb72ac | 46.226667 | 149 | 0.742518 | 5.334337 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewSharedSettings.kt | 5 | 1686 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.projectView.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.xmlb.XmlSerializerUtil
/**
* @author Konstantin Bulenkov
*/
@State(name = "ProjectViewSharedSettings", storages = [(Storage(value = "projectView.xml"))], category = SettingsCategory.UI)
class ProjectViewSharedSettings : PersistentStateComponent<ProjectViewSharedSettings> {
var flattenPackages: Boolean = false
var showMembers: Boolean = false
var sortByType: Boolean = false
var showModules: Boolean = true
var flattenModules: Boolean = false
var showExcludedFiles: Boolean = true
var showVisibilityIcons: Boolean = false
var showLibraryContents: Boolean = true
var hideEmptyPackages: Boolean = true
var compactDirectories: Boolean = false
var abbreviatePackages: Boolean = false
var autoscrollFromSource: Boolean = false
var autoscrollToSource: Boolean = false
var foldersAlwaysOnTop: Boolean = true
var manualOrder: Boolean = false
override fun getState(): ProjectViewSharedSettings {
return this
}
override fun loadState(state: ProjectViewSharedSettings) {
XmlSerializerUtil.copyBean(state, this)
}
companion object {
val instance: ProjectViewSharedSettings
get() = ApplicationManager.getApplication().getService(ProjectViewSharedSettings::class.java)
}
}
| apache-2.0 | 32600a841fb1f2b726249bba9a7141f0 | 37.318182 | 125 | 0.790629 | 4.789773 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/internal.kt | 3 | 2769 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Exposes Kotlin-internal APIs to Java test code and code in other modules. */
@file:JvmName("Internal")
package okhttp3.internal
import java.nio.charset.Charset
import javax.net.ssl.SSLSocket
import okhttp3.Cache
import okhttp3.CipherSuite
import okhttp3.ConnectionSpec
import okhttp3.Cookie
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.connection.RealConnection
fun parseCookie(currentTimeMillis: Long, url: HttpUrl, setCookie: String): Cookie? =
Cookie.parse(currentTimeMillis, url, setCookie)
fun cookieToString(cookie: Cookie, forObsoleteRfc2965: Boolean): String =
cookie.toString(forObsoleteRfc2965)
fun addHeaderLenient(builder: Headers.Builder, line: String): Headers.Builder =
builder.addLenient(line)
fun addHeaderLenient(builder: Headers.Builder, name: String, value: String): Headers.Builder =
builder.addLenient(name, value)
fun cacheGet(cache: Cache, request: Request): Response? = cache.get(request)
fun applyConnectionSpec(connectionSpec: ConnectionSpec, sslSocket: SSLSocket, isFallback: Boolean) =
connectionSpec.apply(sslSocket, isFallback)
fun ConnectionSpec.effectiveCipherSuites(socketEnabledCipherSuites: Array<String>): Array<String> {
return if (cipherSuitesAsString != null) {
socketEnabledCipherSuites.intersect(cipherSuitesAsString, CipherSuite.ORDER_BY_NAME)
} else {
socketEnabledCipherSuites
}
}
fun MediaType?.chooseCharset(): Pair<Charset, MediaType?> {
var charset: Charset = Charsets.UTF_8
var finalContentType: MediaType? = this
if (this != null) {
val resolvedCharset = this.charset()
if (resolvedCharset == null) {
charset = Charsets.UTF_8
finalContentType = "$this; charset=utf-8".toMediaTypeOrNull()
} else {
charset = resolvedCharset
}
}
return charset to finalContentType
}
fun MediaType?.charset(defaultValue: Charset = Charsets.UTF_8): Charset {
return this?.charset(defaultValue) ?: Charsets.UTF_8
}
val Response.connection: RealConnection
get() = this.exchange!!.connection
| apache-2.0 | 607c97a312b0dc42001286ed05839805 | 33.185185 | 100 | 0.76273 | 4.090103 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/SnackbarTokens.kt | 3 | 1797 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object SnackbarTokens {
val ActionFocusLabelTextColor = ColorSchemeKeyTokens.InversePrimary
val ActionHoverLabelTextColor = ColorSchemeKeyTokens.InversePrimary
val ActionLabelTextColor = ColorSchemeKeyTokens.InversePrimary
val ActionLabelTextFont = TypographyKeyTokens.LabelLarge
val ActionPressedLabelTextColor = ColorSchemeKeyTokens.InversePrimary
val ContainerColor = ColorSchemeKeyTokens.InverseSurface
val ContainerElevation = ElevationTokens.Level3
val ContainerShape = ShapeKeyTokens.CornerExtraSmall
val IconColor = ColorSchemeKeyTokens.InverseOnSurface
val FocusIconColor = ColorSchemeKeyTokens.InverseOnSurface
val HoverIconColor = ColorSchemeKeyTokens.InverseOnSurface
val PressedIconColor = ColorSchemeKeyTokens.InverseOnSurface
val IconSize = 24.0.dp
val SupportingTextColor = ColorSchemeKeyTokens.InverseOnSurface
val SupportingTextFont = TypographyKeyTokens.BodyMedium
val SingleLineContainerHeight = 48.0.dp
val TwoLinesContainerHeight = 68.0.dp
} | apache-2.0 | 0d989302b1a54d67760de1cfc6b64acd | 42.853659 | 75 | 0.792988 | 4.936813 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-remote-database/src/main/kotlin/com/onyx/application/impl/DatabaseServer.kt | 1 | 6204 | package com.onyx.application.impl
import com.onyx.application.OnyxServer
import com.onyx.network.auth.AuthenticationManager
import com.onyx.entity.SystemUser
import com.onyx.entity.SystemUserRole
import com.onyx.persistence.context.impl.ServerSchemaContext
import com.onyx.persistence.factory.PersistenceManagerFactory
import com.onyx.persistence.factory.impl.ServerPersistenceManagerFactory
import com.onyx.persistence.manager.PersistenceManager
import com.onyx.network.auth.impl.DefaultAuthenticationManager
import com.onyx.cli.CommandLineParser
import com.onyx.network.rmi.OnyxRMIServer
import com.onyx.interactors.encryption.impl.DefaultEncryptionInteractorInstance
import com.onyx.interactors.encryption.EncryptionInteractor
import com.onyx.network.ssl.SSLPeer
import com.onyx.persistence.IManagedEntity
import com.onyx.diskmap.store.StoreType
/**
* Base Database Server Application.
*
*
* All servers must inherit from this class in order to extend the Onyx Remote Database. This does not have
* any logic that is used within the Web Database.
*
*
*
* DatabaseServer server1 = new DatabaseServer();
* server1.setPort(8080);
* server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd");
* server1.start();
* server1.join();
*
*
* To invoke command line
* java -cp path_to_my_classes(.jar):onyx-remote-database-(0.0.1)-alpha.jar com.onyx.application.impl.DatabaseServer -l /path/to/database/databaseLocation -port=8080
*
* e.x
* java -cp /Users/Tim Osborn/Dropbox/OnyxSandbox/onyxdb-parent/OnyxDatabaseTests/target/classes/:onyx-remote-database-0.0.1-alpha.jar com.onyx.application.impl.DatabaseServer -l /Users/Tim Osborn/Desktop/database1 -port=8080
*
*
* @author Tim Osborn
* @since 1.0.0
*/
open class DatabaseServer(override val databaseLocation:String) : AbstractDatabaseServer(databaseLocation), OnyxServer, SSLPeer {
override var encryption: EncryptionInteractor = DefaultEncryptionInteractorInstance
override var protocol = "TLSv1.2"
override var sslStorePassword: String? = null
override var sslKeystoreFilePath: String? = null
override var sslKeystorePassword: String? = null
override var sslTrustStoreFilePath: String? = null
override var sslTrustStorePassword: String? = null
// RMI Server. This is the underlying network io server
@Suppress("MemberVisibilityCanPrivate")
protected lateinit var rmiServer: OnyxRMIServer
open var persistenceManagerFactory: PersistenceManagerFactory? = null
@Suppress("MemberVisibilityCanPrivate")
protected var authenticationManager: AuthenticationManager? = null
var storeType: StoreType = StoreType.FILE
/**
* Start the database socket server
*
* @since 1.0.0
*/
override fun start() {
if (!isRunning) {
this.persistenceManagerFactory = ServerPersistenceManagerFactory(this.databaseLocation)
this.persistenceManagerFactory?.setCredentials(this.user, this.password)
this.persistenceManagerFactory?.storeType = this.storeType
this.persistenceManagerFactory?.initialize()
// Create a default user
val user = SystemUser()
user.username = this.user
user.password = encryption.encrypt(this.password)
user.role = SystemUserRole.ROLE_ADMIN
user.firstName = "Admin"
user.lastName = "Admin"
// Default User and password
this.persistenceManagerFactory?.persistenceManager?.saveEntity<IManagedEntity>(user)
this.authenticationManager = DefaultAuthenticationManager(persistenceManagerFactory!!.persistenceManager, encryption)
// Create the RMI Server
this.rmiServer = OnyxRMIServer()
copySSLPeerTo(this.rmiServer)
this.rmiServer.port = port
this.registerServices()
this.rmiServer.start()
// Set the push publisher within the schema context so the query caching mechanism can
// tell what push clients to send updates to.
(this.persistenceManagerFactory?.schemaContext as ServerSchemaContext).setPushPublisher(rmiServer)
isRunning = true
}
}
/**
* Register services. This method registers all of the proxy objects and makes them public
*/
@Suppress("MemberVisibilityCanPrivate")
protected fun registerServices() {
// Register the Persistence Manager
rmiServer.register(PERSISTENCE_MANAGER_SERVICE, this.persistenceManagerFactory!!.persistenceManager, PersistenceManager::class.java)
rmiServer.register(AUTHENTICATION_MANAGER_SERVICE, this.authenticationManager!!, AuthenticationManager::class.java)
}
/**
* Stop the database server
*
* @since 1.0.0
*/
override fun stop() {
rmiServer.stop()
if (persistenceManagerFactory != null) {
persistenceManagerFactory!!.close()
}
}
/**
* Join Server. Have it suspend on a daemon thread
*
* @since 1.2.0
*/
override fun join() = rmiServer.join()
/**
* Get persistence manager
*
* @return the underlying persistence manager
* @since 1.2.3
*/
val persistenceManager: PersistenceManager
get() = this.persistenceManagerFactory!!.persistenceManager
companion object {
val PERSISTENCE_MANAGER_SERVICE = "1"
val AUTHENTICATION_MANAGER_SERVICE = "2"
/**
* Run Database Server Main Method
*
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args Command Line Arguments
* @throws Exception General Exception
* @since 1.0.0
*/
@Suppress("NON_FINAL_MEMBER_IN_OBJECT")
@Throws(Exception::class)
@JvmStatic
open fun main(args: Array<String>) {
val commandLineParser = CommandLineParser(args)
val instance = DatabaseServer(commandLineParser.databaseLocation)
commandLineParser.configureDatabaseWithCommandLineOptions(instance)
instance.start()
instance.join()
}
}
}
| agpl-3.0 | 0d0485984e6f007d5744476e22cefd52 | 34.451429 | 225 | 0.696486 | 4.598962 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/IntObjectCacheBase.kt | 1 | 2413 | /**
* 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.core.dataStructures
import java.io.Closeable
import kotlin.math.max
abstract class IntObjectCacheBase<V> protected constructor(size: Int) : CacheHitRateable() {
companion object {
const val DEFAULT_SIZE = 8192
const val MIN_SIZE = 4
}
private val size = max(MIN_SIZE, size)
private val criticalSection: Closeable = object : Closeable {
override fun close() {
unlock()
}
}
val isEmpty: Boolean get() = count() == 0
fun containsKey(key: Int) = isCached(key)
operator fun get(key: Int) = tryKey(key)
fun put(key: Int, value: V): V? {
val oldValue: V? = getObject(key)
if (oldValue != null) {
remove(key)
}
cacheObject(key, value)
return oldValue
}
open fun tryKeyLocked(key: Int) = newCriticalSection().use { tryKey(key) }
open fun getObjectLocked(key: Int) = newCriticalSection().use { getObject(key) }
open fun cacheObjectLocked(key: Int, x: V) = newCriticalSection().use {
if (getObject(key) == null) cacheObject(key, x) else null
}
open fun removeLocked(key: Int) = newCriticalSection().use { remove(key) }
fun isCached(key: Int) = getObjectLocked(key) != null
fun size() = size
override fun adjustHitRate() = newCriticalSection().use { super.adjustHitRate() }
abstract fun clear()
abstract fun lock()
abstract fun unlock()
abstract fun tryKey(key: Int): V?
abstract fun getObject(key: Int): V?
abstract fun cacheObject(key: Int, x: V): V?
// returns value pushed out of the cache
abstract fun remove(key: Int): V?
abstract fun count(): Int
private fun newCriticalSection(): Closeable {
lock()
return criticalSection
}
}
| apache-2.0 | d78f69eadd72170c7d02efdd7cf3e32f | 26.420455 | 92 | 0.65603 | 3.981848 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/base/adapter/EndlessProgressAdapter.kt | 1 | 3437 | package io.github.feelfreelinux.wykopmobilny.base.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.ui.helpers.EndlessScrollListener
abstract class EndlessProgressAdapter<T : androidx.recyclerview.widget.RecyclerView.ViewHolder, A : Any> :
androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
companion object {
const val ITEM_PROGRESS = 0
}
var loadNewDataListener: () -> Unit = {}
internal val dataset = arrayListOf<A?>()
private var isLoading = false
open val data: List<A>
get() = dataset.filterNotNull()
abstract fun constructViewHolder(parent: ViewGroup, viewType: Int): T
abstract fun bindHolder(holder: T, position: Int)
override fun getItemId(position: Int) = dataset[position]?.hashCode()?.toLong() ?: position.toLong()
// Attach EndlessScrollListener
override fun onAttachedToRecyclerView(recyclerView: androidx.recyclerview.widget.RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
if (recyclerView.layoutManager is androidx.recyclerview.widget.LinearLayoutManager) {
recyclerView.addOnScrollListener(EndlessScrollListener(recyclerView.layoutManager as androidx.recyclerview.widget.LinearLayoutManager) {
if (dataset.isNotEmpty() && dataset.last() == null) {
if (!isLoading) loadNewDataListener()
isLoading = true
}
})
}
}
fun disableLoading() {
if (dataset.isNotEmpty() && dataset.last() == null) {
val size = dataset.size - 1
dataset.removeAt(size)
notifyItemRemoved(size)
}
isLoading = true
}
open fun addData(items: List<A>, shouldClearAdapter: Boolean) {
if (shouldClearAdapter || dataset.isEmpty()) {
dataset.apply {
clear()
addAll(items)
add(null)
}
notifyDataSetChanged()
} else {
val filteredItems = items.filter { !dataset.contains(it) }
if (dataset.last() == null) {
dataset.removeAt(dataset.size - 1)
}
dataset.addAll(filteredItems)
dataset.add(null)
notifyItemRangeInserted(dataset.size - filteredItems.size, filteredItems.size + 1)
}
isLoading = false
}
override fun getItemCount() = dataset.size
abstract fun getViewType(position: Int): Int
override fun getItemViewType(position: Int): Int =
if (dataset[position] == null) ITEM_PROGRESS
else getViewType(position)
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
if (dataset[position] != null) bindHolder(holder as T, position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
when (viewType) {
ITEM_PROGRESS -> ProgressViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.progress_item, parent, false))
else -> constructViewHolder(parent, viewType)
}
class ProgressViewHolder(val view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view)
}
| mit | d3c30fbb361d1997f9c427c9145261b4 | 36.769231 | 148 | 0.658423 | 4.959596 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/attic/attic-1.kt | 1 | 2998 | fun attic__composeOrderBanner_LookingForWriters_forAdmin(juan: EntityPageTemplate.Juan<Order>): Renderable {
// 795f624b-c0af-464a-a311-02bb83a4bf11
val bord = "2px dashed ${Color.GRAY_500}"
return div().style("background: ${Color.GRAY_50}; border-top: $bord; border-bottom: $bord; padding-top: 8px; margin-bottom: 8px; position: relative;").with {
val bidding = juan.entity.data.bidding!!
if (bidding.closeBiddingReminderTime.time <= currentTime_ms()) {
oo(div().style("margin-bottom: 4px;").with {
val color = "color: ${Color.RED_700}"
oo(FA.infoCircle().appendStyle("$color;"))
oo(span("Пора закрывать эти сраные торги").style("/*font-weight: bold;*/ margin-left: 8px; $color;"))
})
}
oo(div().style("position: absolute; right: 4px; top: 4px;")
// c1f795fe-0be3-4eb1-855e-e4328d36da39
.add(button().classes("btn btn-default").style("border: none; background: transparent; padding-top: 0px; padding-bottom: 0px; padding-left: 6px; padding-right: 6px;")
.add(FA.pencil())
.attachOnClickWhenDomReady(jsBustOutModal(
biddingParamsModal(juan, submitButtonTitle = "Захуячить",
setInitialFields = {
/*it.accept(
minWriterMoney = {it.set(bidding.minWriterMoney.toString())},
maxWriterMoney = {it.set(bidding.maxWriterMoney.toString())},
closeBiddingAdviceNotificationTime = {it.set(bidding.closeBiddingReminderTime)})*/
},
performShit = {order, fs ->
/*doFuckOrderBidding(What1.UpdateBiddingParams, order, fs)*/
})))))
oo(div().style("position: absolute; right: 4px; top: 30px;")
.add(composeLittleDebugContextMenuButton {
it.item("Set reminder to current time").onClick(jsCallBackend(freakingServant {
/*doFuckOrderBidding(What1.UpdateBiddingParams, juan.entity, BiddingParamsFields().accept(
minWriterMoney = {it.set(bidding.minWriterMoney.toString())},
maxWriterMoney = {it.set(bidding.maxWriterMoney.toString())},
closeBiddingAdviceNotificationTime = {it.set(Timestamp(System.currentTimeMillis()))}))*/
btfEval(juan.jsReload())
}))
}))
oo(Row().with {
oo(col(3, t("TOTE", "Нижняя граница ставки"), displayMoney(bidding.minWriterMoney)))
oo(col(3, t("TOTE", "Верхняя граница ставки"), displayMoney(bidding.maxWriterMoney)))
oo(composeTimestampCol(3, t("TOTE", "Напомнить закрыть торги"), bidding.closeBiddingReminderTime))
})
}
}
| apache-2.0 | e32f135ec8638591fa99b34091090828 | 62.086957 | 178 | 0.575465 | 3.975342 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveLabeledReturnInLambdaIntention.kt | 5 | 1570 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class RemoveLabeledReturnInLambdaIntention : SelfTargetingIntention<KtReturnExpression>(
KtReturnExpression::class.java,
KotlinBundle.lazyMessage("remove.labeled.return.from.last.expression.in.a.lambda")
), LowPriorityAction {
override fun isApplicableTo(element: KtReturnExpression, caretOffset: Int): Boolean {
val labelName = element.getLabelName() ?: return false
val block = element.getStrictParentOfType<KtBlockExpression>() ?: return false
if (block.statements.lastOrNull() != element) return false
val callName = block.getParentLambdaLabelName() ?: return false
if (labelName != callName) return false
setTextGetter { KotlinBundle.message("remove.return.0", labelName) }
return true
}
override fun applyTo(element: KtReturnExpression, editor: Editor?) {
val returnedExpression = element.returnedExpression
if (returnedExpression == null) {
element.delete()
} else {
element.replace(returnedExpression)
}
}
} | apache-2.0 | 9997826cf77b100780cab143222c99a7 | 45.205882 | 158 | 0.74586 | 5.015974 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/harmony_regex/ModeTest.kt | 4 | 4159 | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.text.harmony_regex
import kotlin.text.*
import kotlin.test.*
class ModeTest {
/**
* Tests Pattern compilation modes and modes triggered in pattern strings
*/
@Test fun testCase() {
var regex: Regex
var result: MatchResult?
regex = Regex("([a-z]+)[0-9]+")
result = regex.find("cAT123#dog345")
assertNotNull(result)
assertEquals("dog", result!!.groupValues[1])
assertNull(result.next())
regex = Regex("([a-z]+)[0-9]+", RegexOption.IGNORE_CASE)
result = regex.find("cAt123#doG345")
assertNotNull(result)
assertEquals("cAt", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("doG", result!!.groupValues[1])
assertNull(result.next())
regex = Regex("(?i)([a-z]+)[0-9]+")
result = regex.find("cAt123#doG345")
assertNotNull(result)
assertEquals("cAt", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("doG", result!!.groupValues[1])
assertNull(result.next())
}
@Test fun testMultiline() {
var regex: Regex
var result: MatchResult?
regex = Regex("^foo")
result = regex.find("foobar")
assertNotNull(result)
assertTrue(result!!.range.start == 0 && result.range.endInclusive == 2)
assertTrue(result.groups[0]!!.range.start == 0 && result.groups[0]!!.range.endInclusive == 2)
assertNull(result.next())
result = regex.find("barfoo")
assertNull(result)
regex = Regex("foo$")
result = regex.find("foobar")
assertNull(result)
result = regex.find("barfoo")
assertNotNull(result)
assertTrue(result!!.range.start == 3 && result.range.endInclusive == 5)
assertTrue(result.groups[0]!!.range.start == 3 && result.groups[0]!!.range.endInclusive == 5)
assertNull(result.next())
regex = Regex("^foo([0-9]*)", RegexOption.MULTILINE)
result = regex.find("foo1bar\nfoo2foo3\nbarfoo4")
assertNotNull(result)
assertEquals("1", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("2", result!!.groupValues[1])
assertNull(result.next())
regex = Regex("foo([0-9]*)$", RegexOption.MULTILINE)
result = regex.find("foo1bar\nfoo2foo3\nbarfoo4")
assertNotNull(result)
assertEquals("3", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("4", result!!.groupValues[1])
assertNull(result.next())
regex = Regex("(?m)^foo([0-9]*)")
result = regex.find("foo1bar\nfoo2foo3\nbarfoo4")
assertNotNull(result)
assertEquals("1", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("2", result!!.groupValues[1])
assertNull(result.next())
regex = Regex("(?m)foo([0-9]*)$")
result = regex.find("foo1bar\nfoo2foo3\nbarfoo4")
assertNotNull(result)
assertEquals("3", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("4", result!!.groupValues[1])
assertNull(result.next())
}
}
| apache-2.0 | 1469f57eae9e82c8840a1410b63b60da | 34.547009 | 101 | 0.623227 | 4.226626 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ControlFlowWithEmptyBodyInspection.kt | 3 | 4600 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.util.hasComments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ControlFlowWithEmptyBodyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitIfExpression(expression: KtIfExpression) {
val thenBranch = expression.then
val elseBranch = expression.`else`
val thenIsEmpty = thenBranch.isEmptyBodyOrNull()
val elseIsEmpty = elseBranch.isEmptyBodyOrNull()
val isUsedAsExpression by lazy { expression.isUsedAsExpression(expression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)) }
expression.ifKeyword
.takeIf { thenIsEmpty && (elseIsEmpty || thenBranch.hasNoComments()) && !isUsedAsExpression }
?.let { holder.registerProblem(expression, it) }
expression.elseKeyword
?.takeIf { elseIsEmpty && (thenIsEmpty || elseBranch.hasNoComments()) && !isUsedAsExpression }
?.let { holder.registerProblem(expression, it) }
}
override fun visitWhenExpression(expression: KtWhenExpression) {
if (expression.entries.isNotEmpty()) return
holder.registerProblem(expression, expression.whenKeyword)
}
override fun visitForExpression(expression: KtForExpression) {
if (expression.body.isEmptyBodyOrNull()) {
holder.registerProblem(expression, expression.forKeyword)
}
}
override fun visitWhileExpression(expression: KtWhileExpression) {
val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.WHILE_KEYWORD } ?: return
val body = expression.body
if (body.hasNoComments() && body.isEmptyBodyOrNull()) {
holder.registerProblem(expression, keyword)
}
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.DO_KEYWORD } ?: return
val body = expression.body
if (body.hasNoComments() && body.isEmptyBodyOrNull()) {
holder.registerProblem(expression, keyword)
}
}
override fun visitCallExpression(expression: KtCallExpression) {
val callee = expression.calleeExpression ?: return
val body = when (val argument = expression.valueArguments.singleOrNull()?.getArgumentExpression()) {
is KtLambdaExpression -> argument.bodyExpression
is KtNamedFunction -> argument.bodyBlockExpression
else -> return
}
if (body.isEmptyBodyOrNull() && expression.isCalling(controlFlowFunctions)) {
holder.registerProblem(expression, callee)
}
}
}
private fun KtExpression?.isEmptyBodyOrNull(): Boolean = this?.isEmptyBody() ?: true
private fun KtExpression.isEmptyBody(): Boolean = this is KtBlockExpression && statements.isEmpty()
private fun KtExpression?.hasNoComments(): Boolean = this?.hasComments() != true
private fun ProblemsHolder.registerProblem(expression: KtExpression, keyword: PsiElement) {
val keywordText = if (expression is KtDoWhileExpression) "do while" else keyword.text
registerProblem(
expression,
keyword.textRange.shiftLeft(expression.startOffset),
KotlinBundle.message("0.has.empty.body", keywordText)
)
}
companion object {
private val controlFlowFunctions = listOf("kotlin.also").map { FqName(it) }
}
} | apache-2.0 | 059906672a58c0560f5b2e1598458cd3 | 45.01 | 158 | 0.692826 | 5.330243 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/ArrayLiteralsInAnnotationItems.kt | 6 | 2724 | // 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.completion.smart
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.fuzzyType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
object ArrayLiteralsInAnnotationItems {
private fun MutableCollection<LookupElement>.addForUsage(
expectedInfos: Collection<ExpectedInfo>,
position: PsiElement
) {
if (position.getParentOfType<KtAnnotationEntry>(false) != null) {
expectedInfos.asSequence()
.filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true }
.filterNot { it.itemOptions.starPrefix }
.mapTo(this) { createLookupElement() }
}
}
private fun MutableCollection<LookupElement>.addForDefaultArguments(
expectedInfos: Collection<ExpectedInfo>,
position: PsiElement
) {
// CLASS [MODIFIER_LIST, PRIMARY_CONSTRUCTOR [VALUE_PARAMETER_LIST [VALUE_PARAMETER [..., REFERENCE_EXPRESSION=position]]]]
val valueParameter = position.parent as? KtParameter ?: return
val klass = position.getParentOfType<KtClass>(true) ?: return
if (!klass.hasModifier(KtTokens.ANNOTATION_KEYWORD)) return
val primaryConstructor = klass.primaryConstructor ?: return
if (primaryConstructor.valueParameterList == valueParameter.parent) {
expectedInfos.filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true }
.mapTo(this) { createLookupElement() }
}
}
private fun createLookupElement(): LookupElement = LookupElementBuilder.create("[]")
.withInsertHandler { context, _ ->
context.editor.caretModel.moveToOffset(context.tailOffset - 1)
}
.apply { putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, SmartCompletionItemPriority.ARRAY_LITERAL_IN_ANNOTATION) }
fun collect(expectedInfos: Collection<ExpectedInfo>, position: PsiElement): Collection<LookupElement> =
mutableListOf<LookupElement>().apply {
addForUsage(expectedInfos, position)
addForDefaultArguments(expectedInfos, position)
}
} | apache-2.0 | 3ff57af68b11162dd5bfe95537868706 | 45.186441 | 158 | 0.718796 | 4.934783 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt | 2 | 2593 | // 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 org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.ArrayFqNames
class SurroundWithArrayOfWithSpreadOperatorInFunctionFix(
val wrapper: Name,
argument: KtExpression
) : KotlinQuickFixAction<KtExpression>(argument) {
override fun getText() = KotlinBundle.message("surround.with.star.0", wrapper)
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val argument = element?.getParentOfType<KtValueArgument>(false) ?: return
val argumentName = argument.getArgumentName()?.asName ?: return
val argumentExpression = argument.getArgumentExpression() ?: return
val factory = KtPsiFactory(argumentExpression)
val surroundedWithArrayOf = factory.createExpressionByPattern("$wrapper($0)", argumentExpression)
val newArgument = factory.createArgument(surroundedWithArrayOf, argumentName, isSpread = true)
argument.replace(newArgument)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? {
val actualDiagnostic = when (diagnostic.factory) {
Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION ->
Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.cast(diagnostic)
Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION_ERROR ->
Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION_ERROR.cast(diagnostic)
else -> error("Non expected diagnostic: $diagnostic")
}
val parameterType = actualDiagnostic.a
val wrapper = ArrayFqNames.PRIMITIVE_TYPE_TO_ARRAY[KotlinBuiltIns.getPrimitiveArrayElementType(parameterType)] ?: ArrayFqNames.ARRAY_OF_FUNCTION
return SurroundWithArrayOfWithSpreadOperatorInFunctionFix(wrapper, actualDiagnostic.psiElement)
}
}
}
| apache-2.0 | 7b36b3951c3008b0fe42c6263498c0e8 | 46.145455 | 158 | 0.743926 | 4.828678 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/db/dao/PlayerDao.kt | 1 | 2144 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.db.dao
import android.arch.lifecycle.LiveData
import android.arch.paging.DataSource
import android.arch.persistence.room.*
import android.arch.persistence.room.OnConflictStrategy.REPLACE
import com.sinyuk.fanfou.domain.DO.Player
/**
* Created by sinyuk on 2017/11/27.
*
*/
@Dao
interface PlayerDao {
@Delete
fun delete(player: Player): Int
@Query("SELECT * FROM players WHERE uniqueId = :uniqueId")
fun queryAsLive(uniqueId: String?): LiveData<Player?>
@Query("SELECT * FROM players WHERE uniqueId = :uniqueId")
fun query(uniqueId: String?): Player?
@Insert(onConflict = REPLACE)
fun insert(player: Player?): Long?
@Insert(onConflict = REPLACE)
fun inserts(items: MutableList<Player>): List<Long>
@Update(onConflict = REPLACE)
fun update(player: Player)
@Query("SELECT * FROM players WHERE pathFlag & :path = :path ORDER BY screenName ASC")
fun players(path: Int): DataSource.Factory<Int, Player>
@Query("SELECT * FROM players WHERE screenName LIKE '%' || :query || '%' ORDER BY mentionedAt DESC")
fun filterAsLive(query: String): LiveData<MutableList<Player>>
@Query("SELECT * FROM players WHERE screenName LIKE '%' || :query || '%' ORDER BY mentionedAt DESC")
fun filter(query: String): MutableList<Player>
@Query("SELECT * FROM players WHERE pathFlag & :path = :path ORDER BY updatedAt DESC")
fun byPath(path: Int): LiveData<MutableList<Player>>
} | mit | e9744c023407caa269db8fedf65177c5 | 31.5 | 104 | 0.696362 | 3.912409 | false | false | false | false |
sky-map-team/stardroid | app/src/main/java/com/google/android/stardroid/layers/GridLayer.kt | 1 | 5993 | // Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.layers
import android.content.res.Resources
import android.graphics.Color
import com.google.android.stardroid.R
import com.google.android.stardroid.math.RaDec
import com.google.android.stardroid.math.getGeocentricCoords
import com.google.android.stardroid.renderables.AbstractAstronomicalRenderable
import com.google.android.stardroid.renderables.AstronomicalRenderable
import com.google.android.stardroid.renderables.LinePrimitive
import com.google.android.stardroid.renderables.TextPrimitive
import java.util.*
/**
* Creates a Layer containing a Renderable which correspond to grid lines parallel
* to the celestial equator and the hour angle. That is, returns a set of lines
* with constant right ascension, and another set with constant declination.
*
* @author Brent Bryan
* @author John Taylor
*/
class GridLayer
/**
*
* @param resources
* @param numRightAscensionLines
* @param numDeclinationLines The number of declination lines to show including the poles
* on each side of the equator. 9 is a good number for 10 degree intervals.
*/(
resources: Resources,
private val numRightAscensionLines: Int,
private val numDeclinationLines: Int
) : AbstractRenderablesLayer(resources, false) {
override fun initializeAstroSources(sources: ArrayList<AstronomicalRenderable>) {
sources.add(GridRenderable(resources, numRightAscensionLines, numDeclinationLines))
}
override val layerDepthOrder = 0
override val layerNameId = R.string.show_grid_pref // TODO(johntaylor): rename this string Id.
// TODO(brent): Remove this.
override val preferenceId = "source_provider.4"
/** Implementation of the grid elements as an [AstronomicalRenderable] */
internal class GridRenderable(resources: Resources, numRaSources: Int, numDecSources: Int) :
AbstractAstronomicalRenderable() {
override val labels: MutableList<TextPrimitive> = ArrayList()
override val lines: MutableList<LinePrimitive> = ArrayList()
/**
* Constructs a single longitude line. These lines run from the north pole to
* the south pole at fixed Right Ascensions.
*/
private fun createRaLine(index: Int, numRaSources: Int): LinePrimitive {
val line = LinePrimitive(LINE_COLOR)
val ra = index * 360.0f / numRaSources
for (i in 0 until NUM_DEC_VERTICES - 1) {
val dec = 90.0f - i * 180.0f / (NUM_DEC_VERTICES - 1)
val raDec = RaDec(ra, dec)
line.raDecs.add(raDec)
line.vertices.add(getGeocentricCoords(raDec))
}
val raDec = RaDec(0.0f, -90.0f)
line.raDecs.add(raDec)
line.vertices.add(getGeocentricCoords(raDec))
return line
}
private fun createDecLine(dec: Float): LinePrimitive {
val line = LinePrimitive(LINE_COLOR)
for (i in 0 until NUM_RA_VERTICES) {
val ra = i * 360.0f / NUM_RA_VERTICES
val raDec = RaDec(ra, dec)
line.raDecs.add(raDec)
line.vertices.add(getGeocentricCoords(raDec))
}
val raDec = RaDec(0.0f, dec)
line.raDecs.add(raDec)
line.vertices.add(getGeocentricCoords(raDec))
return line
}
companion object {
private val LINE_COLOR = Color.argb(20, 248, 239, 188)
/** These are great (semi)circles, so only need 3 points. */
private const val NUM_DEC_VERTICES = 3
/** every 10 degrees */
private const val NUM_RA_VERTICES = 36
}
init {
for (r in 0 until numRaSources) {
lines.add(createRaLine(r, numRaSources))
}
/** North & South pole, hour markers every 2hrs. */
labels.add(
TextPrimitive(
0f,
90f,
resources.getString(R.string.north_pole),
LINE_COLOR
)
)
labels.add(
TextPrimitive(
0f,
-90f,
resources.getString(R.string.south_pole),
LINE_COLOR
)
)
for (index in 0..11) {
val ra = index * 30.0f
val title = String.format("%dh", 2 * index)
labels.add(TextPrimitive(ra, 0.0f, title, LINE_COLOR))
}
lines.add(createDecLine(0f)) // Equator
// Note that we don't create lines at the poles.
for (d in 1 until numDecSources) {
val dec = d * 90.0f / numDecSources
lines.add(createDecLine(dec))
labels.add(
TextPrimitive(
0f,
dec,
String.format("%d°", dec.toInt()),
LINE_COLOR
)
)
lines.add(createDecLine(-dec))
labels.add(
TextPrimitive(
0f,
-dec,
String.format("%d°", -dec.toInt()),
LINE_COLOR
)
)
}
}
}
} | apache-2.0 | 5ad157ec8781087e947f81746462213e | 36.685535 | 98 | 0.584543 | 4.257996 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer/src/main/java/com/mikepenz/materialdrawer/widget/MaterialDrawerSliderView.kt | 1 | 34222 | package com.mikepenz.materialdrawer.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.IAdapter
import com.mikepenz.fastadapter.adapters.ItemAdapter
import com.mikepenz.fastadapter.adapters.ModelAdapter
import com.mikepenz.fastadapter.expandable.ExpandableExtension
import com.mikepenz.fastadapter.expandable.ExpandableExtensionFactory
import com.mikepenz.fastadapter.extensions.ExtensionsFactories
import com.mikepenz.fastadapter.select.SelectExtension
import com.mikepenz.fastadapter.select.SelectExtensionFactory
import com.mikepenz.fastadapter.select.getSelectExtension
import com.mikepenz.fastadapter.utils.DefaultIdDistributor
import com.mikepenz.fastadapter.utils.DefaultIdDistributorImpl
import com.mikepenz.materialdrawer.R
import com.mikepenz.materialdrawer.holder.DimenHolder
import com.mikepenz.materialdrawer.model.AbstractDrawerItem
import com.mikepenz.materialdrawer.model.ContainerDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
import com.mikepenz.materialdrawer.util.*
/**
* This view is a simple drop in view for the [DrawerLayout] offering a convenient API to provide a nice and flexible slider view following
* the material design guidelines v2.
*/
open class MaterialDrawerSliderView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.materialDrawerStyle) : RelativeLayout(context, attrs, defStyleAttr) {
/** Temporarily disable invalidation for optimizations */
private var invalidationEnabled: Boolean = true
private var invalidateContent: Boolean = false
private var invalidateHeader: Boolean = false
private var invalidateFooter: Boolean = false
private var invalidateStickyFooter: Boolean = false
/** Specify the foreground color for the insets */
var insetForeground: Drawable? = null
set(value) {
field = value
invalidateThis()
}
private var insets: Rect? = null
private val tempRect = Rect()
/** Fires when the insets get set */
var onInsetsCallback: ((WindowInsetsCompat) -> Unit)? = null
/** Specify if the statusbar should be tinted. */
var tintStatusBar = false
set(value) {
field = value
invalidateThis()
}
/** Specify if the navigationbar should be tinted. */
var tintNavigationBar = true
set(value) {
field = value
invalidateThis()
}
/** Specify if the systemUI should be visible. */
var systemUIVisible = true
set(value) {
field = value
invalidateThis()
}
/** Defines the current sticky footer selection */
internal var currentStickyFooterSelection = -1
/** Allow to specify a custom string key postfix for the savedInstanceKey (for multiple sliders). */
var savedInstanceKey: String = ""
/** Specify if the layoutManager for the recyclerView. */
var layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(context)
set(value) {
field = value
createContent()
}
/** Specify if the [com.mikepenz.fastadapter.IIdDistributor] for the [FastAdapter] */
val idDistributor: DefaultIdDistributor<IDrawerItem<*>> = DefaultIdDistributorImpl()
/** Defines if we want an inner shadow (used in with the MiniDrawer). */
var innerShadow = false
set(value) {
field = value
createContent()
}
/** Defines the [AccountHeaderView] bound to this slider */
var accountHeader: AccountHeaderView? = null
set(value) {
field = value
if (field?.sliderView != this) {
field?.attachToSliderView(this)
}
}
/** Defines if the account header shall be displayed as a sticky header. */
var accountHeaderSticky = false
set(value) {
field = value
handleHeaderView()
}
/** Defines the [MiniDrawerSliderView] bound to this [MaterialDrawerSliderView] */
var miniDrawer: MiniDrawerSliderView? = null
set(value) {
field = value
if (field?.drawer != this) {
field?.drawer = this
}
}
/** Defines if the drawer should scroll to top after click. */
var scrollToTopAfterClick = false
/** Defines the header view to display in this [MaterialDrawerSliderView]. Note this is not possible when a [AccountHeaderView] is used. */
var headerView: View? = null
set(value) {
field = value
headerAdapter.clear()
if (value != null) {
if (headerPadding) {
headerAdapter.add(ContainerDrawerItem().withView(value).withDivider(headerDivider).withHeight(headerHeight).withViewPosition(ContainerDrawerItem.Position.TOP))
} else {
headerAdapter.add(ContainerDrawerItem().withView(value).withDivider(headerDivider).withHeight(headerHeight).withViewPosition(ContainerDrawerItem.Position.NONE))
}
//we need to set the padding so the header starts on top
recyclerView.setPadding(recyclerView.paddingLeft, 0, recyclerView.paddingRight, recyclerView.paddingBottom)
}
}
internal var _headerDivider = true
/** Defines if there should be a divider below the header. */
var headerDivider: Boolean
get() = _headerDivider
set(value) {
_headerDivider = value
headerView = headerView // udpate the header view
}
internal var _headerPadding = true
/** Defines the apdding for the header divider. */
var headerPadding: Boolean
get() = _headerPadding
set(value) {
_headerPadding = value
headerView = headerView // udpate the header view
}
/** Defines the height of the header. */
var headerHeight: DimenHolder? = null
set(value) {
field = value
handleHeaderView()
}
/** Defines the [View] to be displayed as sticky header. Note this is not possible if a sticky [AccountHeaderView] is uesed. */
var stickyHeaderView: View? = null
set(value) {
field = value
handleHeaderView()
}
/** Defines if a shadow shown on the top of the sticky header. */
var stickyHeaderShadow = true
set(value) {
field = value
handleHeaderView()
}
/** Defines the footer we want to display with the [MaterialDrawerSliderView]. */
var footerView: View? = null
set(value) {
field = value
// set the footer (do this before the setAdapter because some devices will crash else
if (value != null) {
if (footerDivider) {
footerAdapter.add(ContainerDrawerItem().apply { view = value; viewPosition = ContainerDrawerItem.Position.BOTTOM })
} else {
footerAdapter.add(ContainerDrawerItem().apply { view = value; viewPosition = ContainerDrawerItem.Position.NONE })
}
}
}
/** Defines if the footer should show with a divider. */
var footerDivider = true
set(value) {
field = value
footerView = footerView // udpate the footer view
}
private val footerClickListener = OnClickListener { v ->
val drawerItem = v.getTag(R.id.material_drawer_item) as IDrawerItem<*>
onFooterDrawerItemClick(this, drawerItem, v, true)
}
internal var _stickyFooterView: ViewGroup? = null
/** Defines the [ViewGroup] to display as sticky footer. */
val stickyFooterView: ViewGroup?
get() = _stickyFooterView
/** Defines if the sticky footer should be displayed with a divider. */
var stickyFooterDivider = false
set(value) {
field = value
handleStickyFooterView()
}
/** Defines the shadow [View] to provide for the sticky footer. */
var stickyFooterShadowView: View? = null
set(value) {
field = value
handleStickyFooterView()
}
/** Defines if the sticky footer should display a shadow above. */
var stickyFooterShadow = true
set(value) {
field = value
handleFooterView()
}
/** Defines if multi select is enabled in this drawer. */
var multiSelect
set(value) {
this.selectExtension.multiSelect = value
this.selectExtension.allowDeselection = value
}
get() = this.selectExtension.multiSelect
// item to select
private var _selectedItemPosition: Int = 0
/** Defines the currently selected item position. */
var selectedItemPosition: Int
get() = _selectedItemPosition
set(value) {
_selectedItemPosition = if (value == 0 && headerView != null) 1 else value
this.selectExtension.deselect()
this.selectExtension.select(_selectedItemPosition)
}
/** Defines the currently selected item identifier. Note this will not be updated if there are new items selected. */
var selectedItemIdentifier: Long = 0
set(value) {
field = value
selectedItemPosition = this.getPosition(selectedItemIdentifier)
}
// the _drawerLayout owning this slider
internal var _drawerLayout: DrawerLayout? = null
/** Defines the [DrawerLayout] bound to this [MaterialDrawerSliderView]. */
val drawerLayout: DrawerLayout?
get() = _drawerLayout
/** Defines if we want to use a custom width with this [MaterialDrawerSliderView]. */
var customWidth: Int? = null
set(value) {
field = value
onAttachedToWindow()
}
/** Defines the [RecyclerView] used in this [MaterialDrawerSliderView]. */
lateinit var recyclerView: RecyclerView
/** Defines if the adapter should enable hasStableIds to improve performance and allow animations. */
var hasStableIds = true
set(value) {
field = value
recyclerView.adapter = null // disconnect the RV
adapter.setHasStableIds(hasStableIds)
attachAdapter() // reattach the RV
}
// an adapter to use for the list
internal lateinit var _adapter: FastAdapter<IDrawerItem<*>>
/** Defines the adapter for the header items */
var headerAdapter: ModelAdapter<IDrawerItem<*>, IDrawerItem<*>> = ItemAdapter()
internal set
/** Defines the adapter for the normal items */
var itemAdapter: ModelAdapter<IDrawerItem<*>, IDrawerItem<*>> = ItemAdapter()
internal set
/** Defines the adapter for the account items (if we switch the set of elements) */
var secondaryItemAdapter: ModelAdapter<IDrawerItem<*>, IDrawerItem<*>> = ItemAdapter()
internal set
/** Defines the adapter for the footer items */
var footerAdapter: ModelAdapter<IDrawerItem<*>, IDrawerItem<*>> = ItemAdapter()
internal set
lateinit var expandableExtension: ExpandableExtension<IDrawerItem<*>>
lateinit var selectExtension: SelectExtension<IDrawerItem<*>>
/**
* Defines the [FastAdapter] used to display elements in the [MaterialDrawerSliderView]
*/
var adapter: FastAdapter<IDrawerItem<*>>
get() {
if (!::_adapter.isInitialized) {
secondaryItemAdapter.active = false
_adapter = FastAdapter.with(listOf(headerAdapter, itemAdapter, secondaryItemAdapter, footerAdapter))
_adapter.setHasStableIds(hasStableIds)
initAdapter()
this.selectExtension.isSelectable = true
this.selectExtension.multiSelect = false
this.selectExtension.allowDeselection = false
}
return _adapter
}
set(value) {
secondaryItemAdapter.active = false
_adapter = value
this.selectExtension = _adapter.getOrCreateExtension(SelectExtension::class.java)!! // is definitely not null
//we have to rewrap as a different FastAdapter was provided
_adapter.addAdapter(0, headerAdapter)
_adapter.addAdapter(1, itemAdapter)
_adapter.addAdapter(2, secondaryItemAdapter)
_adapter.addAdapter(3, footerAdapter)
initAdapter()
}
/** Defines an Adapter which wraps the main Adapter used in the RecyclerView to allow extended navigation and other stuff */
var adapterWrapper: RecyclerView.Adapter<*>? = null
set(value) {
if (!::_adapter.isInitialized) {
throw RuntimeException("this adapter has to be set in conjunction to a normal adapter which is used inside this wrapper adapter")
}
field = value
createContent()
}
/** defines the itemAnimator to be used in conjunction with the RecyclerView */
var itemAnimator: RecyclerView.ItemAnimator = DefaultItemAnimator()
set(value) {
field = value
createContent()
}
/** Defines if the drawer should be closed on a click */
var closeOnClick = true
/** Defines the delay before the drawer gets closed after a click. This is meant to prevent lag */
var delayOnDrawerClose = 50
/** delay drawer click event to prevent lag (you should either choose DelayOnDrawerClose or this) */
var delayDrawerClickEvent = 0
/** defines if we want to keep the sticky items visible, upon switching to the profiles */
var keepStickyItemsVisible = false
/** Defines the set of stickyDrawerItems to show */
var stickyDrawerItems: MutableList<IDrawerItem<*>> = ArrayList()
/** Defines the click listener to listen for clicks on drawer items */
var onDrawerItemClickListener: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
/** Defines the long click listener to listen for long clicks on drawer items */
var onDrawerItemLongClickListener: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
//variables to store and remember the original list of the drawer
private var originalOnDrawerItemClickListener: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
private var originalOnDrawerItemLongClickListener: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
private var originalDrawerState: Bundle? = null
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.MaterialDrawerSliderView, defStyleAttr, R.style.Widget_MaterialDrawerStyle)
insetForeground = a.getDrawable(R.styleable.MaterialDrawerSliderView_materialDrawerInsetForeground)
background = a.getDrawable(R.styleable.MaterialDrawerSliderView_materialDrawerBackground)
a.recycle()
setWillNotDraw(true) // No need to draw until the insets are adjusted
adapter // call getter to setup
createContent()
ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
if (null == this.insets) {
this.insets = Rect()
}
this.insets?.set(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, insets.systemWindowInsetBottom)
if (headerView == null && accountHeader == null) {
if (stickyHeaderView == null) {
recyclerView.updatePadding(top = insets.systemWindowInsetTop + context.resources.getDimensionPixelSize(R.dimen.material_drawer_padding_top_bottom))
}
if (stickyFooterView == null) {
recyclerView.updatePadding(bottom = insets.systemWindowInsetBottom + context.resources.getDimensionPixelSize(R.dimen.material_drawer_padding_top_bottom))
}
}
setWillNotDraw(insetForeground == null)
ViewCompat.postInvalidateOnAnimation(this@MaterialDrawerSliderView)
onInsetsCallback?.invoke(insets)
insets
}
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
val width = width
val height = height
val insets = insets
val insetForeground = insetForeground
if (insets != null && insetForeground != null) {
val sc = canvas.save()
canvas.translate(scrollX.toFloat(), scrollY.toFloat())
if (!systemUIVisible) {
insets.top = 0
insets.right = 0
insets.bottom = 0
insets.left = 0
}
// Top
if (tintStatusBar) {
tempRect.set(0, 0, width, insets.top)
insetForeground.bounds = tempRect
insetForeground.draw(canvas)
}
// Bottom
if (tintNavigationBar) {
tempRect.set(0, height - insets.bottom, width, height)
insetForeground.bounds = tempRect
insetForeground.draw(canvas)
}
// Left
if (tintNavigationBar) {
tempRect.set(0, insets.top, insets.left, height - insets.bottom)
insetForeground.bounds = tempRect
insetForeground.draw(canvas)
}
// Right
if (tintNavigationBar) {
tempRect.set(width - insets.right, insets.top, width, height - insets.bottom)
insetForeground.bounds = tempRect
insetForeground.draw(canvas)
}
canvas.restoreToCount(sc)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
insetForeground?.callback = this
if (parent != null) {
_drawerLayout = parent as? DrawerLayout ?: parent.parent as? DrawerLayout
?: parent.parent.parent as? DrawerLayout // give it 3 parents chance to find the parent
layoutParams?.also {
// if this is a drawer from the right, change the margins :D & set the new params
it.width = customWidth ?: getOptimalDrawerWidth(context)
layoutParams = it
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
insetForeground?.callback = null
}
/**
* Set the Bundle (savedInstance) which is passed by the activity.
* No need to null-check everything is handled automatically
*/
@Deprecated("Replaced with setSavedInstance", ReplaceWith("setSavedInstance(savedInstance)"))
fun withSavedInstance(savedInstance: Bundle?) {
setSavedInstance(savedInstance)
}
/**
* Set the Bundle (savedInstance) which is passed by the activity.
* No need to null-check everything is handled automatically
*/
fun setSavedInstance(savedInstance: Bundle?) {
savedInstance ?: return
// try to restore all saved values again
this.selectExtension.deselect()
adapter.withSavedInstanceState(savedInstance, BUNDLE_SELECTION + savedInstanceKey)
this.setStickyFooterSelection(savedInstance.getInt(BUNDLE_STICKY_FOOTER_SELECTION + savedInstanceKey, -1), null)
//toggle selection list if we were previously on the account list
if (savedInstance.getBoolean(BUNDLE_DRAWER_CONTENT_SWITCHED + savedInstanceKey, false)) {
accountHeader?.toggleSelectionList()
}
}
private fun initAdapter() {
ExtensionsFactories.register(SelectExtensionFactory())
ExtensionsFactories.register(ExpandableExtensionFactory())
this.selectExtension = adapter.getOrCreateExtension(SelectExtension::class.java)!! // is definitely not null
headerAdapter.idDistributor = idDistributor
itemAdapter.idDistributor = idDistributor
footerAdapter.idDistributor = idDistributor
expandableExtension = adapter.getOrCreateExtension(ExpandableExtension::class.java)!! // is definitely not null
}
/**
* the helper method to create the content for the drawer
*/
private fun createContent() {
if (!invalidationEnabled) {
invalidateContent = true
return
}
invalidateContent = false
// if we have an adapter (either by defining a custom one or the included one add a list :D
val contentView: View
if (!::recyclerView.isInitialized) {
contentView = LayoutInflater.from(context).inflate(R.layout.material_drawer_recycler_view, this, false)
recyclerView = contentView.findViewById(R.id.material_drawer_recycler_view)
//some style improvements on older devices
recyclerView.setFadingEdgeLength(0)
recyclerView.clipToPadding = false
} else {
contentView = recyclerView
}
//set the itemAnimator
recyclerView.itemAnimator = itemAnimator
//additional stuff
recyclerView.layoutManager = layoutManager
val params = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
params.weight = 1f
this.removeView(contentView) // ensure the view is not already part
this.addView(contentView, params)
if (innerShadow) {
var innerShadow = this.findViewById<View?>(R.id.material_drawer_inner_shadow)
if (innerShadow == null) {
innerShadow = LayoutInflater.from(context).inflate(R.layout.material_drawer_inner_shadow, this, false)!!
this.addView(innerShadow)
}
innerShadow.visibility = View.VISIBLE
innerShadow.bringToFront()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && gravity == GravityCompat.END) {
innerShadow.setBackgroundResource(R.drawable.material_drawer_shadow_right)
} else {
innerShadow.setBackgroundResource(R.drawable.material_drawer_shadow_left)
}
} else {
removeView(this.findViewById(R.id.material_drawer_inner_shadow))
}
//handle the header
handleHeaderView()
//handle the footer
handleFooterView()
//set the adapter on the listView
attachAdapter()
//predefine selection (should be the first element)
selectedItemPosition = _selectedItemPosition
// add the onDrawerItemClickListener if set
adapter.onClickListener = { v: View?, _: IAdapter<IDrawerItem<*>>, item: IDrawerItem<*>, position: Int ->
if (item.isSelectable) {
resetStickyFooterSelection()
currentStickyFooterSelection = -1
}
//call the listener
var consumed = false
//call the item specific listener
if (item is AbstractDrawerItem<*, *>) {
consumed = item.onDrawerItemClickListener?.invoke(v, item, position) ?: false
}
//we have to notify the miniDrawer if existing, and if the event was not consumed yet
if (!consumed) {
consumed = miniDrawer?.onItemClick(item) ?: false
}
//call the drawer listener
onDrawerItemClickListener?.let { mOnDrawerItemClickListener ->
if (delayDrawerClickEvent > 0) {
Handler().postDelayed({ mOnDrawerItemClickListener.invoke(v, item, position) }, delayDrawerClickEvent.toLong())
} else {
consumed = mOnDrawerItemClickListener.invoke(v, item, position)
}
}
//if we were a expandable item we consume the event closing makes no sense
if (item.subItems.isNotEmpty()) {
//we consume the event and want no further handling
true
} else {
if (!consumed) {
//close the drawer after click
closeDrawerDelayed()
}
consumed
}
}
// add the onDrawerItemLongClickListener if set
adapter.onLongClickListener = { v: View, _: IAdapter<IDrawerItem<*>>, item: IDrawerItem<*>, position: Int ->
onDrawerItemLongClickListener?.invoke(v, item, position) ?: false
}
recyclerView.scrollToPosition(0)
}
/**
* Attaches the adapter to the recyclerView
*/
private fun attachAdapter() {
//set the adapter on the listView
if (adapterWrapper == null) {
recyclerView.adapter = adapter
} else {
recyclerView.adapter = adapterWrapper
}
}
/**
* simple helper method to reset the selection of the sticky footer
*/
internal fun resetStickyFooterSelection() {
val stickyFooterView = stickyFooterView ?: return
if (stickyFooterView is LinearLayout) {
for (i in 0 until stickyFooterView.childCount) {
stickyFooterView.getChildAt(i).isActivated = false
stickyFooterView.getChildAt(i).isSelected = false
}
}
}
/**
* helper method to close the drawer delayed
*/
internal fun closeDrawerDelayed() {
if (closeOnClick && _drawerLayout != null) {
if (delayOnDrawerClose > -1) {
Handler().postDelayed({
_drawerLayout?.closeDrawers()
if (scrollToTopAfterClick) {
recyclerView.smoothScrollToPosition(0)
}
}, delayOnDrawerClose.toLong())
} else {
_drawerLayout?.closeDrawers()
}
}
}
/**
* information if the current drawer content is switched by alternative content (profileItems)
*/
fun switchedDrawerContent(): Boolean {
return !(originalOnDrawerItemClickListener == null && originalDrawerState == null)
}
/**
* method to switch the drawer content to new elements
*/
fun switchDrawerContent(onDrawerItemClickListenerInner: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)?, onDrawerItemLongClickListenerInner: ((v: View?, item: IDrawerItem<*>, position: Int) -> Boolean)?, drawerItemsInner: List<IDrawerItem<*>>, drawerSelection: Int) {
//just allow a single switched drawer
if (!switchedDrawerContent()) {
//save out previous values
originalOnDrawerItemClickListener = onDrawerItemClickListener
originalOnDrawerItemLongClickListener = onDrawerItemLongClickListener
originalDrawerState = adapter.saveInstanceState(Bundle())
expandableExtension.collapse(false)
secondaryItemAdapter.active = true
itemAdapter.active = false
}
//set the new items
onDrawerItemClickListener = onDrawerItemClickListenerInner
onDrawerItemLongClickListener = onDrawerItemLongClickListenerInner
secondaryItemAdapter.set(drawerItemsInner)
setSelectionAtPosition(drawerSelection, false)
if (!keepStickyItemsVisible) {
//hide stickyFooter and it's shadow
stickyFooterView?.visibility = View.GONE
stickyFooterShadowView?.visibility = View.GONE
}
}
/**
* helper method to reset to the original drawerContent
*/
fun resetDrawerContent() {
if (switchedDrawerContent()) {
//set the new items
onDrawerItemClickListener = originalOnDrawerItemClickListener
onDrawerItemLongClickListener = originalOnDrawerItemLongClickListener
adapter.withSavedInstanceState(originalDrawerState)
//remove the references
originalOnDrawerItemClickListener = null
originalOnDrawerItemLongClickListener = null
originalDrawerState = null
secondaryItemAdapter.active = false
itemAdapter.active = true
//if we switch back scroll back to the top
recyclerView.smoothScrollToPosition(0)
//show the stickyFooter and it's shadow again
stickyFooterView?.visibility = View.VISIBLE
stickyFooterShadowView?.visibility = View.VISIBLE
//if we currently show the accountHeader selection list make sure to reset this attr
accountHeader?._selectionListShown = false
}
}
/**
* set the current selection in the drawer
* NOTE: this also deselects all other selections. if you do not want this. use the direct api of the adater .getAdapter().select(position, fireOnClick)
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*/
@JvmOverloads
fun setSelectionAtPosition(position: Int, fireOnClick: Boolean = true): Boolean {
selectExtension.deselect()
if (position >= 0) {
selectExtension.select(position, false)
notifySelect(position, fireOnClick)
}
return false
}
private fun notifySelect(position: Int, fireOnClick: Boolean) {
_selectedItemPosition = position
if (fireOnClick && position >= 0) {
adapter.getItem(position)?.let { item ->
if (item is AbstractDrawerItem<*, *>) {
item.onDrawerItemClickListener?.invoke(null, item, position)
}
onDrawerItemClickListener?.invoke(null, item, position)
}
}
//we set the selection on a normal item in the drawer so we have to deselect the items in the StickyDrawer
resetStickyFooterSelection()
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param identifier the identifier to search for
* @param fireOnClick true if the click listener should be called
*/
@JvmOverloads
fun setSelection(identifier: Long, fireOnClick: Boolean = true) {
val select = adapter.getSelectExtension()
select.selectByIdentifier(identifier, false, true)
//we also have to call the general notify
val res = adapter.getItemById(identifier)
if (res != null) {
val position = res.second
notifySelect(position ?: -1, fireOnClick)
}
}
/**
* add the values to the bundle for saveInstanceState
*/
fun saveInstanceState(_savedInstanceState: Bundle): Bundle {
adapter.saveInstanceState(_savedInstanceState, BUNDLE_SELECTION + savedInstanceKey).apply {
putInt(BUNDLE_STICKY_FOOTER_SELECTION + savedInstanceKey, currentStickyFooterSelection)
putBoolean(BUNDLE_DRAWER_CONTENT_SWITCHED + savedInstanceKey, switchedDrawerContent())
}
return _savedInstanceState
}
/**
* Invalidates the `IconicsDrawable` if invalidation is currently enabled
*/
private fun invalidateThis() {
if (invalidationEnabled) {
invalidate()
}
}
/**
* Invalidates the header view in an optimized form
*/
private fun handleHeaderView() {
if (!invalidationEnabled) {
invalidateHeader = true
return
}
invalidateHeader = false
handleHeaderView(this)
}
/**
* Invalidates the footer view in an optimized form
*/
private fun handleFooterView() {
if (!invalidationEnabled) {
invalidateFooter = true
return
}
invalidateFooter = false
handleFooterView(this, footerClickListener)
}
/**
* Invalidates the sticky footer view in an optimized form
*/
internal fun handleStickyFooterView() {
if (!invalidationEnabled) {
invalidateStickyFooter = true
return
}
invalidateStickyFooter = false
rebuildStickyFooterView(this)
}
/** Applies properties in an optimized form. Will disable invalidation of the MaterialDrawerSliderView for the inner property set operations */
fun apply(block: MaterialDrawerSliderView.() -> Unit): MaterialDrawerSliderView {
invalidationEnabled = false
block()
invalidationEnabled = true
if (invalidateContent) {
createContent()
}
if (invalidateHeader) {
handleHeaderView()
}
if (invalidateFooter) {
handleFooterView()
}
if (invalidateStickyFooter) {
handleStickyFooterView()
}
invalidate()
return this
}
companion object {
/**
* BUNDLE param to store the selection
*/
const val BUNDLE_SELECTION = "_selection"
const val BUNDLE_STICKY_FOOTER_SELECTION = "bundle_sticky_footer_selection"
const val BUNDLE_DRAWER_CONTENT_SWITCHED = "bundle_drawer_content_switched"
/**
* Defines globally if we should animat selection state changes of the background
*/
var DEFAULT_SELECTED_BACKGROUND_ANIMATED = true
}
}
| apache-2.0 | 8905bfba86e561a2354395bb72462513 | 37.066741 | 285 | 0.635731 | 5.299985 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/importwallet/Import.kt | 1 | 8708 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 12/3/19.
* Copyright (c) 2019 breadwallet LLC
*
* 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.breadwallet.ui.importwallet
import com.breadwallet.R
import com.breadwallet.crypto.Amount
import com.breadwallet.tools.util.BRConstants.FAQ_IMPORT_WALLET
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.util.CurrencyCode
import dev.zacsweers.redacted.annotations.Redacted
import java.math.BigDecimal
object Import {
const val CONFIRM_IMPORT_DIALOG = "confirm_import"
const val IMPORT_SUCCESS_DIALOG = "import_success"
data class M(
@Redacted val privateKey: String? = null,
@Redacted val keyPassword: String? = null,
val keyRequiresPassword: Boolean = false,
val isKeyValid: Boolean = false,
val loadingState: LoadingState = LoadingState.IDLE,
val currencyCode: CurrencyCode? = null,
val reclaimGiftHash: String? = null,
val scanned: Boolean = false,
val gift: Boolean = false
) {
enum class LoadingState {
IDLE, VALIDATING, ESTIMATING, SUBMITTING
}
val isLoading: Boolean =
loadingState != LoadingState.IDLE
fun reset(): M = copy(
privateKey = null,
keyPassword = null,
keyRequiresPassword = false,
isKeyValid = false,
loadingState = LoadingState.IDLE
)
companion object {
fun createDefault(
privateKey: String? = null,
isPasswordProtected: Boolean = false,
reclaimGiftHash: String? = null,
scanned: Boolean = false,
gift: Boolean = false
): M = M(
privateKey = privateKey,
keyRequiresPassword = isPasswordProtected,
reclaimGiftHash = reclaimGiftHash,
scanned = scanned,
gift = gift,
loadingState = if (privateKey == null) {
LoadingState.IDLE
} else {
LoadingState.VALIDATING
}
)
}
}
sealed class E {
object OnFaqClicked : E()
object OnScanClicked : E()
object OnCloseClicked : E()
object OnImportConfirm : E()
object OnImportCancel : E()
data class OnPasswordEntered(
@Redacted val password: String
) : E()
data class RetryImport(
@Redacted val privateKey: String,
@Redacted val password: String?
) : E()
data class OnKeyScanned(
@Redacted val privateKey: String,
val isPasswordProtected: Boolean
) : E()
sealed class Key : E() {
object NoWallets : Key()
object OnInvalid : Key()
object OnPasswordInvalid : Key()
data class OnValid(
val isPasswordProtected: Boolean = false
) : Key()
}
sealed class Estimate : E() {
data class Success(
val balance: Amount,
val feeAmount: Amount,
val currencyCode: CurrencyCode
) : Estimate()
data class FeeError(
val balance: BigDecimal
) : Estimate()
object NoBalance : Estimate()
data class BalanceTooLow(
val balance: BigDecimal
) : Estimate()
}
sealed class Transfer : E() {
data class OnSuccess(
@Redacted val transferHash: String,
val currencyCode: CurrencyCode
) : Transfer()
object OnFailed : Transfer()
}
}
sealed class F {
object ShowPasswordInput : F(), ViewEffect
object ShowKeyInvalid : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
messageResId = R.string.Import_Error_notValid,
positiveButtonResId = R.string.Button_ok
)
}
object ShowPasswordInvalid : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
messageResId = R.string.Import_wrongPassword,
positiveButtonResId = R.string.Button_ok
)
}
object ShowBalanceTooLow : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.Import_title,
messageResId = R.string.Import_Error_highFees,
positiveButtonResId = R.string.Button_ok
)
}
object ShowNoBalance : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.Import_title,
messageResId = R.string.Import_Error_empty,
positiveButtonResId = R.string.Button_ok
)
}
object ShowImportFailed : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.Import_title,
messageResId = R.string.Import_Error_signing,
positiveButtonResId = R.string.Button_ok
)
}
object ShowImportSuccess : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.Import_success,
messageResId = R.string.Import_SuccessBody,
positiveButtonResId = R.string.Button_ok,
dialogId = IMPORT_SUCCESS_DIALOG
)
}
data class ShowConfirmImport(
val receiveAmount: String,
val feeAmount: String
) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.Import_title,
messageResId = R.string.Import_confirm,
messageArgs = listOf(receiveAmount, feeAmount),
positiveButtonResId = R.string.Import_importButton,
negativeButtonResId = R.string.Button_cancel,
dialogId = CONFIRM_IMPORT_DIALOG
)
}
data class ValidateKey(
@Redacted val privateKey: String,
@Redacted val password: String?
) : F()
data class SubmitImport(
@Redacted val privateKey: String,
@Redacted val password: String?,
val currencyCode: CurrencyCode,
val reclaimGiftHash: String?,
) : F()
data class TrackEvent(
val eventString: String,
) : F()
sealed class Nav(
override val navigationTarget: NavigationTarget
) : F(), NavigationEffect {
object GoBack : Nav(NavigationTarget.Back)
object GoToFaq : Nav(NavigationTarget.SupportPage(FAQ_IMPORT_WALLET))
object GoToScan : Nav(NavigationTarget.QRScanner)
}
sealed class EstimateImport : F() {
abstract val privateKey: String
data class Key(
@Redacted override val privateKey: String
) : EstimateImport()
data class KeyWithPassword(
@Redacted override val privateKey: String,
@Redacted val password: String
) : EstimateImport()
}
}
}
| mit | 7ad0f188f537420ba085a9fb2909e9f6 | 34.542857 | 81 | 0.593133 | 5.248945 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/Spinner.kt | 1 | 1720 | package com.bixlabs.bkotlin
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.SpinnerAdapter
/**
* Callback executed when a spinner item is selected
* @return Am implemented `OnItemSelectedListener` interface in case the same is needed for any other operation.
*/
fun Spinner.onItemSelected(
onNothingSelect: (parent: AdapterView<*>?) -> Unit = { _ -> },
onItemSelect: (parent: AdapterView<*>?, view: View?, position: Int?, id: Long?) -> Unit = { _, _, _, _ -> }):
AdapterView.OnItemSelectedListener {
val itemSelected = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {
onNothingSelect(p0)
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
onItemSelect(p0, p1, p2, p3)
}
}
onItemSelectedListener = itemSelected
return itemSelected
}
/**
* Sets an ArrayList of objects with an additional (but optional and which defaults to `object.toString()`)
* string conversion method for the same.
* @return A new `ArrayAdapter` already containing the items received by this method
*/
fun <T> Spinner.setItems(
items: ArrayList<T>?,
layoutResource: Int = android.R.layout.simple_spinner_dropdown_item,
getTitle: (item: T) -> String = { a -> a.toString() }): SpinnerAdapter? {
val finalList: ArrayList<String> = ArrayList<String>()
items?.forEach {
finalList.add(getTitle(it))
}
val myAdapter = ArrayAdapter(this.context, layoutResource, finalList)
adapter = myAdapter
return adapter
} | apache-2.0 | 132b2be2c34c2334cfc9691f26efad60 | 32.096154 | 117 | 0.677907 | 4.37659 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/database/table/RPKBankTable.kt | 1 | 7325 | /*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.banks.bukkit.database.table
import com.rpkit.banks.bukkit.RPKBanksBukkit
import com.rpkit.banks.bukkit.bank.RPKBank
import com.rpkit.banks.bukkit.database.jooq.rpkit.Tables.RPKIT_BANK
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.economy.bukkit.currency.RPKCurrency
import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
/**
* Represents the bank table.
*/
class RPKBankTable(database: Database, private val plugin: RPKBanksBukkit): Table<RPKBank>(database, RPKBank::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_bank.id.enabled")) {
database.cacheManager.createCache("rpk-banks-bukkit.rpkit_bank.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKBank::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_bank.id.size"))).build())
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_BANK)
.column(RPKIT_BANK.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_BANK.CHARACTER_ID, SQLDataType.INTEGER)
.column(RPKIT_BANK.CURRENCY_ID, SQLDataType.INTEGER)
.column(RPKIT_BANK.BALANCE, SQLDataType.INTEGER)
.constraints(
constraint("pk_rpkit_bank").primaryKey(RPKIT_BANK.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "0.2.0")
}
}
override fun insert(entity: RPKBank): Int {
database.create
.insertInto(
RPKIT_BANK,
RPKIT_BANK.CHARACTER_ID,
RPKIT_BANK.CURRENCY_ID,
RPKIT_BANK.BALANCE
)
.values(
entity.character.id,
entity.currency.id,
entity.balance
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKBank) {
database.create
.update(RPKIT_BANK)
.set(RPKIT_BANK.CHARACTER_ID, entity.character.id)
.set(RPKIT_BANK.CURRENCY_ID, entity.currency.id)
.set(RPKIT_BANK.BALANCE, entity.balance)
.where(RPKIT_BANK.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKBank? {
if (cache?.containsKey(id) == true) {
return cache.get(id)
} else {
val result = database.create
.select(
RPKIT_BANK.CHARACTER_ID,
RPKIT_BANK.CURRENCY_ID,
RPKIT_BANK.BALANCE
)
.from(RPKIT_BANK)
.where(RPKIT_BANK.ID.eq(id))
.fetchOne() ?: return null
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val characterId = result.get(RPKIT_BANK.CHARACTER_ID)
val character = characterProvider.getCharacter(characterId)
val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class)
val currencyId = result.get(RPKIT_BANK.CURRENCY_ID)
val currency = currencyProvider.getCurrency(currencyId)
if (character != null && currency != null) {
val bank = RPKBank(
id,
character,
currency,
result.get(RPKIT_BANK.BALANCE)
)
cache?.put(id, bank)
return bank
} else {
database.create
.deleteFrom(RPKIT_BANK)
.where(RPKIT_BANK.ID.eq(id))
.execute()
return null
}
}
}
/**
* Gets the bank account for the given character in the given currency.
* If no account exists, one will be created.
*
* @param character The character to get the account for
* @param currency The currency which the account should be in
* @return The account of the character in the currency
*/
fun get(character: RPKCharacter, currency: RPKCurrency): RPKBank {
val result = database.create
.select(RPKIT_BANK.ID)
.from(RPKIT_BANK)
.where(RPKIT_BANK.CHARACTER_ID.eq(character.id))
.and(RPKIT_BANK.CURRENCY_ID.eq(currency.id))
.fetchOne()
var bank = if (result == null) null else get(result.get(RPKIT_BANK.ID))
if (bank == null) {
bank = RPKBank(
character = character,
currency = currency,
balance = 0
)
insert(bank)
}
return bank
}
/**
* Gets the characters with the highest balance in the given currency.
*
* @param amount The amount of characters to retrieve
* @param currency The currency to
* @return A list of characters with the highest balance in the given currency
*/
fun getTop(amount: Int = 5, currency: RPKCurrency): List<RPKCharacter> {
val results = database.create
.select(RPKIT_BANK.ID)
.from(RPKIT_BANK)
.where(RPKIT_BANK.CURRENCY_ID.eq(currency.id))
.orderBy(RPKIT_BANK.BALANCE.desc())
.limit(amount)
.fetch()
return results
.map { result ->
get(result.get(RPKIT_BANK.ID))
}
.filterNotNull()
.map { bank ->
bank.character
}
}
override fun delete(entity: RPKBank) {
database.create
.deleteFrom(RPKIT_BANK)
.where(RPKIT_BANK.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | apache-2.0 | 48c126dec1834a591eeab3fe5164b2af | 36.762887 | 118 | 0.568055 | 4.698525 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/main/java/com/piticlistudio/playednext/ui/PlatformUIUtils.kt | 1 | 2878 | package com.piticlistudio.playednext.ui
import android.graphics.Color
import org.json.JSONObject
import java.io.InputStream
import java.nio.charset.Charset
import javax.inject.Inject
class PlatformUIUtils @Inject constructor(val colorsMap: HashMap<String, Int>, val acronymsMap: HashMap<String, String>) {
fun getAcronym(platformName: String): String {
return acronymsMap.get(platformName.toUpperCase()).takeIf { it != null } ?: acronymsMap.get(platformName).takeIf { it != null } ?: platformName
}
fun getColor(platformName: String): Int {
return colorsMap.get(platformName.toUpperCase()).takeIf { it != null } ?: colorsMap.get(platformName).takeIf { it != null } ?: Color.BLACK
}
class Builder {
private var colorsMap: HashMap<String, Int>? = null
private var acronymsMap: HashMap<String, String>? = null
private var inputStream: InputStream? = null
fun inputstream(input: InputStream) = apply { this.inputStream = input }
fun colorsmap(colors: HashMap<String, Int>) = apply { this.colorsMap = colors }
fun acronymsmap(acronyms: HashMap<String, String>) = apply { this.acronymsMap = acronyms }
fun build(): PlatformUIUtils {
if (colorsMap != null && acronymsMap != null) {
return PlatformUIUtils(colorsMap!!, acronymsMap!!)
}
inputStream?.let {
if (colorsMap == null) {
colorsMap = HashMap<String, Int>()
}
if (acronymsMap == null) {
acronymsMap = HashMap<String, String>()
}
parseJSON(loadJSON(inputStream!!))
return PlatformUIUtils(colorsMap!!, acronymsMap!!)
}
throw RuntimeException("No input specified")
}
private fun loadJSON(input: InputStream): String {
val size = input.available()
val buffer = ByteArray(size)
input.read(buffer)
input.close()
return String(buffer, Charset.forName("UTF-8"))
}
private fun parseJSON(json: String) {
val values = JSONObject(json)
val keys = values.keys()
while (keys.hasNext()) {
val key = keys.next()
val value = values.getJSONObject(key)
val color = value.getString("color")
val acronym = value.getString("acronym")
colorsMap?.let {
if (!it.containsKey(key)) {
it.put(key.toUpperCase(), Color.parseColor(color))
}
}
acronymsMap?.let {
if (!it.containsKey(key)) {
it.put(key.toUpperCase(), acronym)
}
}
}
}
}
} | mit | 58474f08b4ed97f3852060c0e82298cf | 36.38961 | 151 | 0.555942 | 4.553797 | false | false | false | false |
CyroPCJr/Kotlin-Koans | src/test/kotlin/builders/TheFunctionApply.kt | 1 | 646 | package builders
import org.junit.Assert
import org.junit.Test
class TheFunctionApplyTest {
@Test
fun testCreateString() {
val s = createString()
val sb = StringBuilder()
sb.append("Numbers: ")
for (i in 1..10) {
sb.append(i)
}
Assert.assertEquals("String should be built", sb.toString(), s)
}
@Test
fun testCreateMap() {
val map = createMap()
val expected = HashMap<Int, String>()
for (i in 0..10) {
expected[i] = "$i"
}
Assert.assertEquals("Map should be filled with the right values", expected, map)
}
} | apache-2.0 | 5fd47126a66296d33f2dec7c22d7888b | 22.107143 | 88 | 0.558824 | 4.0375 | false | true | false | false |
addonovan/ftc-ext | FtcRobotController/src/main/java/com/addonovan/ftcext/testing/OpModes.kt | 1 | 1161 | package com.addonovan.ftcext.testing
import com.addonovan.ftcext.control.*
import com.qualcomm.robotcore.hardware.DcMotor
@Register( "OpMode1" )
class OpMode1 : OpMode()
{
val motorSpeed = get( "motor_speed", 1.0 );
val timeLength = get( "time_length", 1 );
val redTeam = get( "red_team", false );
val motor_back = getDevice< DcMotor >( "motor_back" );
val motor_front: DcMotor = getDevice( "motor_front" );
val motor_left = motor( "motor_left" );
val motor_right = motor( "motor_right" );
val blueTeam = get( "blue_team", true );
val stuff = get( "stuff", 100000 );
override fun init(){}
override fun loop(){}
}
@Register( "OpMode2" )
class OpMode2 : OpMode()
{
val motorSpeed = get( "motor_speed", 0.5 );
val duration = get( "duration", 500000 );
override fun init(){}
override fun loop(){}
}
@Register( "OpMode3" )
class OpMode3 : OpMode()
{
override fun init(){}
override fun loop(){}
}
//
// Invisible Ones
//
@Register( "IOM 1" )
abstract class OpMode4 : OpMode();
@Register( "IOM 2" )
private class OpMode5 : OpMode()
{
override fun init(){}
override fun loop(){}
} | mit | 7f5e20c1f7532af10276c5a93d16de19 | 19.75 | 58 | 0.624462 | 3.326648 | false | false | false | false |
bubelov/coins-android | app/src/main/java/com/bubelov/coins/editplace/EditPlaceFragment.kt | 1 | 6790 | package com.bubelov.coins.editplace
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.bubelov.coins.R
import com.bubelov.coins.model.Location
import com.bubelov.coins.picklocation.PickLocationResultViewModel
import kotlinx.android.synthetic.main.fragment_edit_place.*
import org.koin.android.viewmodel.ext.android.sharedViewModel
import org.koin.android.viewmodel.ext.android.viewModel
class EditPlaceFragment : Fragment() {
private val model: EditPlaceViewModel by viewModel()
private val locationResultModel: PickLocationResultViewModel by sharedViewModel()
private val placeId by lazy {
EditPlaceFragmentArgs.fromBundle(requireArguments()).placeId
}
private val passedLocation by lazy {
EditPlaceFragmentArgs.fromBundle(requireArguments()).mapLocation
}
// private var map: GoogleMap? = null
//
// private var placeLocationMarker: Marker? = null
private var pickedLocation: Location? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_edit_place, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
toolbar.apply {
setNavigationOnClickListener { findNavController().popBackStack() }
inflateMenu(R.menu.edit_place)
setOnMenuItemClickListener { item ->
if (item.itemId == R.id.action_send) {
submit()
}
true
}
}
// val place = place
//
// if (place == null) {
// toolbar.setTitle(R.string.action_add_place)
// closedSwitch.isVisible = false
// } else {
// name.setText(place.name)
// phone.setText(place.phone)
// website.setText(place.website)
// description.setText(place.description)
// openingHours.setText(place.openingHours)
// }
// (childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment).getMapAsync(this)
closedSwitch.setOnCheckedChangeListener { _, checked ->
name.isEnabled = !checked
editLocationButton.isVisible = !checked
phone.isEnabled = !checked
website.isEnabled = !checked
description.isEnabled = !checked
openingHours.isEnabled = !checked
}
// editLocationButton.setOnClickListener {
// val action = EditPlaceFragmentDirections.actionEditPlaceFragmentToPickLocationFragment(
// map.getLocation()
// )
//
// findNavController().navigate(action)
// }
// model.showProgress.observe(viewLifecycleOwner, Observer { showProgress ->
// content.isVisible = !showProgress
// progress.isVisible = showProgress
// })
//
// model.changesSubmitted.observe(viewLifecycleOwner, Observer {
// findNavController().popBackStack()
// })
//
// model.error.observe(viewLifecycleOwner, Observer {
// AlertDialog.Builder(requireContext())
// .setMessage(it)
// .setPositiveButton(android.R.string.ok, null)
// .show()
// })
// locationResultModel.pickedLocation.observe(viewLifecycleOwner, Observer {
// it.let { location ->
// pickedLocation = location
//
// map?.moveCamera(
// CameraUpdateFactory.newLatLngZoom(
// LatLng(location.latitude, location.longitude),
// MAP_ZOOM
// )
// )
// }
// })
}
// override fun onMapReady(map: GoogleMap) {
// this.map = map
//
// map.uiSettings.setAllGesturesEnabled(false)
//
// val pickedLocation = pickedLocation
//
// if (pickedLocation != null) {
// setMarker(map, pickedLocation)
//
// map.moveCamera(
// CameraUpdateFactory.newLatLngZoom(
// LatLng(pickedLocation.latitude, pickedLocation.longitude),
// MAP_ZOOM
// )
// )
// } else {
// val place = place
//
// val initialLocation = if (place == null) {
// passedLocation
// } else {
// LatLng(place.latitude, place.longitude).toLocation()
// }
//
// setMarker(map, initialLocation)
//
// map.moveCamera(
// CameraUpdateFactory.newLatLngZoom(
// LatLng(initialLocation.latitude, initialLocation.longitude),
// MAP_ZOOM
// )
// )
//
// this.pickedLocation = initialLocation
// }
// }
// private fun setMarker(map: GoogleMap, location: Location) {
// placeLocationMarker?.remove()
//
// placeLocationMarker = map.addMarker(
// MarkerOptions()
// .position(location.toLatLng())
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker_empty))
// .anchor(BuildConfig.MAP_MARKER_ANCHOR_U, BuildConfig.MAP_MARKER_ANCHOR_V)
// )
// }
private fun submit() {
if (name.length() == 0) {
AlertDialog.Builder(requireContext())
.setMessage(R.string.name_is_not_specified)
.setPositiveButton(android.R.string.ok, null)
.show()
return
}
// model.submitChanges(place, getUpdatedPlace())
}
// private fun getUpdatedPlace(): Place {
// val map = map ?: throw IllegalStateException("Map is not initialized")
//
// return Place(
// id = place?.id ?: UUID.randomUUID().toString(),
// name = name.text.toString(),
// latitude = map.cameraPosition.target.latitude,
// longitude = map.cameraPosition.target.longitude,
// phone = phone.text.toString(),
// website = website.text.toString(),
// categoryId = place?.categoryId ?: "",
// description = description.text.toString(),
// openingHours = openingHours.text.toString(),
// visible = !closedSwitch.isChecked,
// createdAt = DateTime.now(),
// updatedAt = DateTime.now()
// )
// }
companion object {
const val MAP_ZOOM = 15f
}
} | unlicense | 7b04679c4baa84c2e463e2843e69ab4f | 31.966019 | 101 | 0.583505 | 4.587838 | false | false | false | false |
tommyettinger/SquidSetup | src/main/kotlin/com/github/czyzby/setup/data/libs/unofficial/squidLib.kt | 1 | 2807 | package com.github.czyzby.setup.data.libs.unofficial
import com.github.czyzby.setup.data.platforms.Core
import com.github.czyzby.setup.data.platforms.GWT
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.views.Extension
import com.jcabi.github.Coordinates
import com.jcabi.github.RtGithub
import java.util.*
/**
* Version of SquidLib libraries.
* @author Eben Howard
* @author Tommy Ettinger
*/
val SQUID_LIB_VERSION = //"3.0.4"
RtGithub().repos().get(Coordinates.Simple("yellowstonegames", "SquidLib"))
.commits().iterate(Collections.emptyMap()).first().sha().substring(0, 10)
/**
* URL of SquidLib libraries.
* @author Eben Howard
* @author Tommy Ettinger
*/
const val SQUID_LIB_URL = "https://github.com/yellowstonegames/SquidLib"
const val REPO_PATH = "com.github.yellowstonegames.SquidLib" //// used with JitPack
//const val REPO_PATH = "com.squidpony" //// used with stable versions
/**
* Utilities for grid-based games.
* @author Eben Howard
* @author Tommy Ettinger
*/
@Extension()
class SquidLibUtil : ThirdPartyExtension() {
override val id = "squidLibUtil"
override var defaultVersion = SQUID_LIB_VERSION
override val url = SQUID_LIB_URL
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "$REPO_PATH:squidlib-util")
addDependency(project, GWT.ID, "$REPO_PATH:squidlib-util:sources")
addGwtInherit(project, "squidlib-util")
RegExodus().initiate(project)
}
}
/**
* Text-based display for roguelike games.
* @author Eben Howard
* @author Tommy Ettinger
*/
@Extension()
class SquidLib : ThirdPartyExtension() {
override val id = "squidLib"
override var defaultVersion = SQUID_LIB_VERSION
override val url = SQUID_LIB_URL
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "$REPO_PATH:squidlib")
addDependency(project, GWT.ID, "$REPO_PATH:squidlib:sources")
addGwtInherit(project, "squidlib")
SquidLibUtil().initiate(project)
Anim8().initiate(project)
defaultVersion = SQUID_LIB_VERSION
}
}
/**
* Extra save/load support for SquidLib objects.
* @author Eben Howard
* @author Tommy Ettinger
*/
@Extension()
class SquidLibExtra : ThirdPartyExtension() {
override val id = "squidLibExtra"
override var defaultVersion = SQUID_LIB_VERSION
override val url = SQUID_LIB_URL
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "$REPO_PATH:squidlib-extra")
addDependency(project, GWT.ID, "$REPO_PATH:squidlib-extra:sources")
addGwtInherit(project, "squidlib-extra")
SquidLibUtil().initiate(project)
defaultVersion = SQUID_LIB_VERSION
}
}
| apache-2.0 | 224e6aca12d31eb5d88c2a9878a4b9af | 28.239583 | 83 | 0.705379 | 3.562183 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/FactBinding.kt | 1 | 1090 | package org.klips.engine
import org.klips.dsl.Facet
import org.klips.dsl.Facet.FacetRef
import org.klips.dsl.Fact
import org.klips.engine.util.ListSet
import org.klips.engine.util.SimpleEntry
import kotlin.collections.Map.Entry
class FactBinding(val fact: Fact, val refIndex:Map<FacetRef<*>, Int>) : Binding() {
override val entries : Set<Entry<Facet<*>, Facet<*>>> = ListSet {
refIndex.entries.map { SimpleEntry(it.key, fact.facets[it.value]) }
}
override val keys: Set<FacetRef<*>>
get(){ return refIndex.keys }
override val size: Int
get(){ return refIndex.size }
override val values: Collection<Facet<*>> = ListSet{refIndex.values.map { fact.facets[it] }}
override fun containsKey(key: Facet<*>) = refs.contains(key)
override fun containsValue(value: Facet<*>) = values.contains(value)
override fun get(key: Facet<*>) = refIndex[key]?.let{fact.facets[it]}
override fun isEmpty() = fact.facets.isEmpty()
override fun toString() =
refs.joinToString (prefix = "{",postfix = "}"){ "$it = ${get(it)}" }
} | apache-2.0 | c046a51d612afeed483ee4e2c76d735a | 42.64 | 96 | 0.673394 | 3.670034 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/model/StocksProvider.kt | 1 | 12844 | package com.github.premnirmal.ticker.model
import android.content.Context
import android.content.SharedPreferences
import com.github.premnirmal.ticker.AppPreferences
import com.github.premnirmal.ticker.components.AppClock
import com.github.premnirmal.ticker.createTimeString
import com.github.premnirmal.ticker.network.StocksApi
import com.github.premnirmal.ticker.network.data.Holding
import com.github.premnirmal.ticker.network.data.Position
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.repo.StocksStorage
import com.github.premnirmal.ticker.widget.WidgetDataProvider
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by premnirmal on 2/28/16.
*/
@Singleton
class StocksProvider @Inject constructor(
@ApplicationContext private val context: Context,
private val api: StocksApi,
private val preferences: SharedPreferences,
private val appPreferences: AppPreferences,
private val widgetDataProvider: WidgetDataProvider,
private val alarmScheduler: AlarmScheduler,
private val clock: AppClock,
private val storage: StocksStorage,
private val coroutineScope: CoroutineScope,
private val exponentialBackoff: ExponentialBackoff
) {
companion object {
private const val LAST_FETCHED = "LAST_FETCHED"
private const val NEXT_FETCH = "NEXT_FETCH"
private val DEFAULT_STOCKS = arrayOf("^GSPC", "^DJI", "GOOG", "AAPL", "MSFT")
const val DEFAULT_INTERVAL_MS: Long = 15_000L
}
private val tickerSet: MutableSet<String> = HashSet()
private val quoteMap: MutableMap<String, Quote> = HashMap()
private val _fetchState = MutableStateFlow<FetchState>(FetchState.NotFetched)
private val _nextFetch = MutableStateFlow<Long>(0)
private val _lastFetched = MutableStateFlow<Long>(0)
private val _tickers = MutableStateFlow<List<String>>(emptyList())
private val _portfolio = MutableStateFlow<List<Quote>>(emptyList())
init {
val tickers = storage.readTickers()
this.tickerSet.addAll(tickers)
if (this.tickerSet.isEmpty()) {
this.tickerSet.addAll(DEFAULT_STOCKS)
}
_tickers.tryEmit(tickerSet.toList())
val lastFetched = preferences.getLong(LAST_FETCHED, 0L)
_lastFetched.tryEmit(lastFetched)
val nextFetch = preferences.getLong(NEXT_FETCH, 0L)
_nextFetch.tryEmit(nextFetch)
coroutineScope.launch {
alarmScheduler.enqueuePeriodicRefresh(context)
}
runBlocking { fetchLocal() }
if (lastFetched == 0L) {
coroutineScope.launch {
fetch()
}
} else {
_fetchState.tryEmit(FetchState.Success(lastFetched))
}
}
private suspend fun fetchLocal() = withContext(Dispatchers.IO) {
try {
val quotes = storage.readQuotes()
synchronized(quoteMap) {
quotes.forEach { quoteMap[it.symbol] = it }
}
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
} catch (e: Exception) {
Timber.w(e)
}
}
private fun saveLastFetched() {
preferences.edit()
.putLong(LAST_FETCHED, _lastFetched.value)
.apply()
}
private fun saveTickers() {
storage.saveTickers(tickerSet)
}
private fun scheduleUpdate() {
scheduleUpdateWithMs(alarmScheduler.msToNextAlarm(_lastFetched.value))
}
private fun scheduleUpdateWithMs(
msToNextAlarm: Long
) {
val updateTime = alarmScheduler.scheduleUpdate(msToNextAlarm, context)
_nextFetch.tryEmit(updateTime.toInstant().toEpochMilli())
preferences.edit()
.putLong(NEXT_FETCH, _nextFetch.value)
.apply()
appPreferences.setRefreshing(false)
widgetDataProvider.broadcastUpdateAllWidgets()
}
private suspend fun fetchStockInternal(ticker: String, allowCache: Boolean): FetchResult<Quote> = withContext(Dispatchers.IO){
val quote = if (allowCache) quoteMap[ticker] else null
return@withContext quote?.let { FetchResult.success(quote) } ?: run {
try {
val res = api.getStock(ticker)
if (res.wasSuccessful) {
val data = res.data
val quoteFromStorage = storage.readQuote(ticker)
val quote = quoteFromStorage?.let {
it.copyValues(data)
quoteFromStorage
} ?: data
quoteMap[ticker] = quote
FetchResult.success(quote)
} else {
FetchResult.failure<Quote>(FetchException("Failed to fetch", res.error))
}
} catch (ex: CancellationException) {
// ignore
FetchResult.failure<Quote>(FetchException("Failed to fetch", ex))
} catch (ex: Exception) {
Timber.w(ex)
FetchResult.failure<Quote>(FetchException("Failed to fetch", ex))
}
}
}
/////////////////////
// public api
/////////////////////
fun hasTicker(ticker: String): Boolean {
return tickerSet.contains(ticker)
}
suspend fun fetch(allowScheduling: Boolean = true): FetchResult<List<Quote>> = withContext(Dispatchers.IO) {
if (tickerSet.isEmpty()) {
if (allowScheduling) {
_fetchState.emit(FetchState.Failure(FetchException("No symbols in portfolio")))
}
FetchResult.failure<List<Quote>>(FetchException("No symbols in portfolio"))
} else {
return@withContext try {
if (allowScheduling) {
appPreferences.setRefreshing(true)
}
widgetDataProvider.broadcastUpdateAllWidgets()
val fr = api.getStocks(tickerSet.toList())
if (fr.hasError) {
throw fr.error
}
val fetchedStocks = fr.data
if (fetchedStocks.isEmpty()) {
return@withContext FetchResult.failure<List<Quote>>(FetchException("Refresh failed"))
} else {
synchronized(tickerSet) {
tickerSet.addAll(fetchedStocks.map { it.symbol })
}
_tickers.emit(tickerSet.toList())
// clean up existing tickers
ArrayList(tickerSet).forEach { ticker ->
if (!widgetDataProvider.containsTicker(ticker)) {
removeStock(ticker)
}
}
storage.saveQuotes(fetchedStocks)
fetchLocal()
if (allowScheduling) {
_lastFetched.emit(api.lastFetched)
_fetchState.emit(FetchState.Success(api.lastFetched))
saveLastFetched()
exponentialBackoff.reset()
scheduleUpdate()
}
FetchResult.success(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
}
} catch(ex: CancellationException) {
if (allowScheduling) {
val backOffTimeMs = exponentialBackoff.getBackoffDurationMs()
scheduleUpdateWithMs(backOffTimeMs)
}
FetchResult.failure<List<Quote>>(FetchException("Failed to fetch", ex))
} catch (ex: Throwable) {
Timber.w(ex)
if (allowScheduling) {
_fetchState.emit(FetchState.Failure(ex))
val backOffTimeMs = exponentialBackoff.getBackoffDurationMs()
scheduleUpdateWithMs(backOffTimeMs)
}
FetchResult.failure<List<Quote>>(FetchException("Failed to fetch", ex))
} finally {
if (allowScheduling) {
appPreferences.setRefreshing(false)
}
}
}
}
fun schedule() {
scheduleUpdate()
coroutineScope.launch {
alarmScheduler.enqueuePeriodicRefresh(context, force = true)
}
}
fun addStock(ticker: String): Collection<String> {
synchronized(quoteMap) {
if (!tickerSet.contains(ticker)) {
tickerSet.add(ticker)
val quote = Quote(symbol = ticker)
quoteMap[ticker] = quote
saveTickers()
}
}
_tickers.tryEmit(tickerSet.toList())
_portfolio.tryEmit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
coroutineScope.launch {
val result = fetchStockInternal(ticker, false)
if (result.wasSuccessful) {
val data = result.data
quoteMap[ticker] = data
storage.saveQuote(result.data)
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
}
}
return tickerSet
}
fun hasPositions(): Boolean = quoteMap.filter { it.value.hasPositions() }.isNotEmpty()
fun hasPosition(ticker: String): Boolean = quoteMap[ticker]?.hasPositions() ?: false
fun getPosition(ticker: String): Position? = quoteMap[ticker]?.position
suspend fun addHolding(
ticker: String,
shares: Float,
price: Float
): Holding {
val quote: Quote?
var position: Position
synchronized(quoteMap) {
quote = quoteMap[ticker]
position = getPosition(ticker) ?: Position(ticker)
if (!tickerSet.contains(ticker)) {
tickerSet.add(ticker)
}
}
_tickers.emit(tickerSet.toList())
saveTickers()
val holding = Holding(ticker, shares, price)
position.add(holding)
quote?.position = position
val id = storage.addHolding(holding)
holding.id = id
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
return holding
}
suspend fun removePosition(
ticker: String,
holding: Holding
) {
synchronized(quoteMap) {
val position = getPosition(ticker)
val quote = quoteMap[ticker]
position?.remove(holding)
quote?.position = position
}
storage.removeHolding(ticker, holding)
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
}
fun addStocks(symbols: Collection<String>): Collection<String> {
synchronized(this.tickerSet) {
val filterNot = symbols.filterNot { this.tickerSet.contains(it) }
filterNot.forEach { this.tickerSet.add(it) }
saveTickers()
if (filterNot.isNotEmpty()) {
coroutineScope.launch {
fetch()
}
}
}
_tickers.tryEmit(tickerSet.toList())
_portfolio.tryEmit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
return this.tickerSet
}
suspend fun removeStock(ticker: String): Collection<String> {
synchronized(quoteMap) {
tickerSet.remove(ticker)
saveTickers()
quoteMap.remove(ticker)
}
storage.removeQuoteBySymbol(ticker)
_tickers.emit(tickerSet.toList())
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
return tickerSet
}
suspend fun removeStocks(symbols: Collection<String>) {
synchronized(quoteMap) {
symbols.forEach {
tickerSet.remove(it)
quoteMap.remove(it)
}
}
storage.removeQuotesBySymbol(symbols.toList())
_tickers.emit(tickerSet.toList())
_portfolio.emit(quoteMap.values.filter { tickerSet.contains(it.symbol) }.toList())
saveTickers()
}
suspend fun fetchStock(ticker: String, allowCache: Boolean = true): FetchResult<Quote> {
return fetchStockInternal(ticker, allowCache)
}
fun getStock(ticker: String): Quote? = quoteMap[ticker]
val tickers: StateFlow<List<String>>
get() = _tickers
val portfolio: StateFlow<List<Quote>>
get() = _portfolio//quoteMap.filter { widgetDataProvider.containsTicker(it.key) }.map { it.value }
fun addPortfolio(portfolio: List<Quote>) {
synchronized(quoteMap) {
portfolio.forEach {
val symbol = it.symbol
if (!tickerSet.contains(symbol)) tickerSet.add(symbol)
quoteMap[symbol] = it
}
}
saveTickers()
widgetDataProvider.updateWidgets(tickerSet.toList())
coroutineScope.launch {
storage.saveQuotes(portfolio)
fetchLocal()
fetch()
}
}
val fetchState: StateFlow<FetchState>
get() = _fetchState
val nextFetchMs: StateFlow<Long>
get() = _nextFetch
sealed class FetchState {
abstract val displayString: String
object NotFetched : FetchState() {
override val displayString: String = "--"
}
class Success(val fetchTime: Long) : FetchState() {
override val displayString: String by lazy {
val instant = Instant.ofEpochMilli(fetchTime)
val time = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
time.createTimeString()
}
}
class Failure(val exception: Throwable) : FetchState() {
override val displayString: String by lazy {
exception.message.orEmpty()
}
}
}
}
| gpl-3.0 | 2ae7b7e2a72af2e63da951b2f5a039f3 | 31.598985 | 128 | 0.670741 | 4.227781 | false | false | false | false |
kamgurgul/cpu-info | app/src/main/java/com/kgurgul/cpuinfo/features/information/base/BaseRvFragment.kt | 1 | 3036 | /*
* Copyright 2017 KG Soft
*
* 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.kgurgul.cpuinfo.features.information.base
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.snackbar.Snackbar
import com.kgurgul.cpuinfo.R
import dagger.hilt.android.AndroidEntryPoint
/**
* Simple base for all info fragments which displays data on [RecyclerView]
*
* @author kgurgul
*/
@AndroidEntryPoint
abstract class BaseRvFragment : Fragment(), InfoItemsAdapter.OnClickListener {
protected lateinit var mainContainer: View
protected lateinit var recyclerView: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.fragment_rv, container, false)
mainContainer = view.findViewById(R.id.main_container)
recyclerView = view.findViewById(R.id.recycler_view)
setupRecyclerView()
setupRecyclerViewAdapter()
return view
}
override fun onDestroyView() {
recyclerView.adapter = null
super.onDestroyView()
}
/**
* Basic [RecyclerView] configuration with [LinearLayoutManager] and disabled animations
*/
private fun setupRecyclerView() {
val layoutManager = LinearLayoutManager(requireContext())
recyclerView.layoutManager = layoutManager
// Remove change animation
(recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
}
/**
* Setup adapter for [RecyclerView]. Use this method to set adapter and refreshing logic.
*/
abstract fun setupRecyclerViewAdapter()
override fun onItemLongPressed(item: Pair<String, String>) {
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE)
as ClipboardManager
val clip = ClipData.newPlainText(requireContext().getString(R.string.app_name),
item.second)
clipboard.setPrimaryClip(clip)
Snackbar.make(mainContainer, R.string.text_copied, Snackbar.LENGTH_SHORT).show()
}
} | apache-2.0 | 232289704eeab0bbaae8b53886f0ea8d | 34.729412 | 93 | 0.73419 | 4.968903 | false | false | false | false |
libktx/ktx | actors/src/test/kotlin/ktx/actors/EventsTest.kt | 1 | 12935 | package ktx.actors
import com.badlogic.gdx.Input.Keys
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type.keyDown
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type.keyTyped
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type.keyUp
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type.touchDown
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type.touchUp
import com.badlogic.gdx.scenes.scene2d.ui.Tree
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent.Type.keyboard
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent.Type.scroll
import io.kotlintest.mock.mock
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
/**
* Tests events and listeners utilities.
*/
@Suppress("UNUSED_PARAMETER", "UNUSED_ANONYMOUS_PARAMETER") // Unused lambda parameters showcase the listeners API.
class EventsTest {
@Test
fun `should attach ChangeListener`() {
val actor = Actor()
var changed = false
val listener = actor.onChange { changed = true }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
actor.fire(ChangeEvent())
assertTrue(changed)
}
@Test
fun `should attach ChangeListener consuming ChangeEvent`() {
val actor = Actor()
var changed = false
val listener = actor.onChangeEvent { event -> changed = true }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
actor.fire(ChangeEvent())
assertTrue(changed)
}
@Test
fun `should attach ClickListener`() {
val actor = Actor()
val listener = actor.onClick { }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach ClickListener consuming InputEvent`() {
val actor = Actor()
val listener = actor.onClickEvent { event -> }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach ClickListener consuming InputEvent with local coordinates`() {
val actor = Actor()
val listener = actor.onClickEvent { event, x, y -> }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach ClickListener triggered on enter events`() {
val actor = Actor()
val listener = actor.onEnter { }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener triggered on exit events`() {
val actor = Actor()
val listener = actor.onExit { }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach ClickListener consuming onEnter events with local coordinates`() {
val actor = Actor()
val listener = actor.onEnterEvent { event, x, y -> }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach ClickListener consuming onExit events with local coordinates`() {
val actor = Actor()
val listener = actor.onExitEvent { event, x, y -> }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
class SampleNode : Tree.Node<SampleNode, Any, Actor>(mock())
@Test
fun `should attach ChangeListener to a Tree consuming Selection with the selected Nodes`() {
val style = mock<Tree.TreeStyle>()
style.plus = mock()
style.minus = mock()
val tree = Tree<SampleNode, Any>(style)
val listener = tree.onSelectionChange {}
assertNotNull(listener)
assertTrue(listener in tree.listeners)
}
@Test
fun `should invoke attached ChangeListener when tree Selection changes`() {
val style = mock<Tree.TreeStyle>()
style.plus = mock()
style.minus = mock()
val tree = Tree<SampleNode, Any>(style)
tree.selection.setProgrammaticChangeEvents(true)
val nodes = Array(3) { SampleNode() }
val selected = SampleNode()
nodes.forEach(tree::add)
tree.add(selected)
val executions = AtomicInteger()
val selectedNodes = mutableListOf<SampleNode>()
tree.selection.clear()
tree.onSelectionChange { selection ->
executions.incrementAndGet()
selectedNodes.clear()
selectedNodes.addAll(selection.items())
}
tree.selection.add(selected)
assertEquals(1, executions.get())
assertEquals(1, selectedNodes.size)
assertSame(selected, selectedNodes.first())
}
@Test
fun `should attach InputListener for touchDown`() {
val actor = Actor()
val listener = actor.onTouchDown { }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener for touchUp`() {
val actor = Actor()
val listener = actor.onTouchUp { }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener consuming InputEvent for touch events`() {
val actor = Actor()
val listener = actor.onTouchEvent(
onDown = { event -> },
onUp = { event -> }
)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener consuming InputEvent for touch events with local coordinates`() {
val actor = Actor()
val listener = actor.onTouchEvent(
onDown = { event, x, y -> },
onUp = { event, x, y -> }
)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener consuming InputEvent for touch events with local coordinates, pointer and button`() {
val actor = Actor()
val listener = actor.onTouchEvent(
onDown = { event, x, y, pointer, button -> },
onUp = { event, x, y, pointer, button -> }
)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
}
@Test
fun `should attach InputListener and trigger touchDown event`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event -> result = event.type == touchDown }
listener.touchDown(InputEvent().apply { type = touchDown }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach InputListener and trigger touchUp event`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event -> result = event.type == touchUp }
listener.touchDown(InputEvent().apply { type = touchUp }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach InputListener and trigger touchDown event with local coordinates, pointer and button`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event, x, y, pointer, button -> result = event.type == touchDown }
listener.touchDown(InputEvent().apply { type = touchDown }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach InputListener and trigger touchUp event with local coordinates, pointer and button`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event, x, y, pointer, button -> result = event.type == touchUp }
listener.touchDown(InputEvent().apply { type = touchUp }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach InputListener and trigger touchDown event with local coordinates`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event, x, y -> result = event.type == touchDown }
listener.touchDown(InputEvent().apply { type = touchDown }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach InputListener and trigger touchUp event with local coordinates`() {
val actor = Actor()
var result = false
val listener = actor.onTouchEvent { event, x, y -> result = event.type == touchUp }
listener.touchDown(InputEvent().apply { type = touchUp }, 0f, 0f, 0, 0)
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertTrue(result)
}
@Test
fun `should attach key listener`() {
val actor = Actor()
var typed: Char? = null
val listener = actor.onKey { key -> typed = key }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(typed)
val event = InputEvent()
event.character = 'a'
event.type = keyTyped
actor.fire(event)
assertEquals('a', typed)
}
@Test
fun `should attach key listener consuming InputEvent`() {
val actor = Actor()
var typed: Char? = null
val listener = actor.onKeyEvent { event, key -> typed = key }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(typed)
val event = InputEvent()
event.character = 'a'
event.type = keyTyped
actor.fire(event)
assertEquals('a', typed)
}
@Test
fun `should attach key down listener`() {
val actor = Actor()
var pressed: Int? = null
val listener = actor.onKeyDown { keyCode -> pressed = keyCode }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(pressed)
val event = InputEvent()
event.keyCode = Keys.A
event.type = keyDown
actor.fire(event)
assertEquals(Keys.A, pressed)
}
@Test
fun `should attach key down listener consuming InputEvent`() {
val actor = Actor()
var pressed: Int? = null
val listener = actor.onKeyDownEvent { event, keyCode -> pressed = keyCode }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(pressed)
val event = InputEvent()
event.keyCode = Keys.A
event.type = keyDown
actor.fire(event)
assertEquals(Keys.A, pressed)
}
@Test
fun `should attach key up listener`() {
val actor = Actor()
var released: Int? = null
val listener = actor.onKeyUp { keyCode -> released = keyCode }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(released)
val event = InputEvent()
event.keyCode = Keys.A
event.type = keyUp
actor.fire(event)
assertEquals(Keys.A, released)
}
@Test
fun `should attach key up listener consuming InputEvent`() {
val actor = Actor()
var released: Int? = null
val listener = actor.onKeyUpEvent { event, keyCode -> released = keyCode }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
assertNull(released)
val event = InputEvent()
event.keyCode = Keys.A
event.type = keyUp
actor.fire(event)
assertEquals(Keys.A, released)
}
@Test
fun `should attach scroll focus listener`() {
val actor = Actor()
var focused = false
val listener = actor.onScrollFocus { focused = it }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
val event = FocusEvent()
event.type = scroll
event.isFocused = true
actor.fire(event)
assertTrue(focused)
}
@Test
fun `should attach scroll focus listener consuming FocusEvent`() {
val actor = Actor()
var focused = false
val listener = actor.onScrollFocusEvent { event -> focused = event.isFocused }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
val event = FocusEvent()
event.type = scroll
event.isFocused = true
actor.fire(event)
assertTrue(focused)
}
@Test
fun `should attach keyboard focus listener`() {
val actor = Actor()
var focused = false
val listener = actor.onKeyboardFocus { focused = it }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
val event = FocusEvent()
event.type = keyboard
event.isFocused = true
actor.fire(event)
assertTrue(focused)
}
@Test
fun `should attach keyboard focus listener consuming FocusEvent`() {
val actor = Actor()
var focused = false
val listener = actor.onKeyboardFocusEvent { event -> focused = event.isFocused }
assertNotNull(listener)
assertTrue(listener in actor.listeners)
val event = FocusEvent()
event.type = keyboard
event.isFocused = true
actor.fire(event)
assertTrue(focused)
}
@Suppress("unused", "ClassName")
class `should extend KtxInputListener with no methods overridden` : KtxInputListener() {
// Guarantees all KtxInputListener methods are optional to implement.
}
}
| cc0-1.0 | daf0fc8d7973628a48fcf41ec9f40c8b | 26.1174 | 120 | 0.689215 | 4.290216 | false | true | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut09/basicLighting.kt | 2 | 7120 | package main.tut09
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import glNext.*
import glm.L
import glm.f
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.destroy
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.mousePole.*
/**
* Created by elect on 20/03/17.
*/
fun main(args: Array<String>) {
BasicLighting_().setup("Tutorial 09 - Basic Lighting")
}
class BasicLighting_ : Framework() {
lateinit var whiteDiffuseColor: ProgramData
lateinit var vertexDiffuseColor: ProgramData
lateinit var cylinderMesh: Mesh
lateinit var planeMesh: Mesh
var mat: Mat4? = null
val projectionUniformBuffer = intBufferBig(1)
val cameraToClipMatrix = Mat4(0.0f)
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
val lightDirection = Vec4(0.866f, 0.5f, 0.0f, 0.0f)
var drawColoredCyl = true
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
cylinderMesh = Mesh(gl, javaClass, "tut09/UnitCylinder.xml")
planeMesh = Mesh(gl, javaClass, "tut09/LargePlane.xml")
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(0.0f, 1.0f)
glEnable(GL_DEPTH_CLAMP)
glGenBuffer(projectionUniformBuffer)
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer[0])
glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE.L, null, GL_DYNAMIC_DRAW)
//Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, projectionUniformBuffer, 0, Mat4.SIZE)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
}
fun initializeProgram(gl: GL3) {
whiteDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PN.vert", "color-passthrough.frag")
vertexDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PCN.vert", "color-passthrough.frag")
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
val modelMatrix = MatrixStack(viewPole.calcMatrix())
val lightDirCameraSpace = modelMatrix.top() * lightDirection
glUseProgram(whiteDiffuseColor.theProgram)
glUniform3f(whiteDiffuseColor.dirToLightUnif, lightDirCameraSpace)
glUseProgram(vertexDiffuseColor.theProgram)
glUniform3f(vertexDiffuseColor.dirToLightUnif, lightDirCameraSpace)
glUseProgram()
modelMatrix run {
// Render the ground plane
run {
glUseProgram(whiteDiffuseColor.theProgram)
glUniformMatrix4f(whiteDiffuseColor.modelToCameraMatrixUnif, top())
val normalMatrix = top().toMat3()
glUniformMatrix3f(whiteDiffuseColor.normalModelToCameraMatrixUnif, normalMatrix)
glUniform4f(whiteDiffuseColor.lightIntensityUnif, 1.0f)
planeMesh.render(gl)
glUseProgram()
}
// Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (drawColoredCyl) {
glUseProgram(vertexDiffuseColor.theProgram)
glUniformMatrix4f(vertexDiffuseColor.modelToCameraMatrixUnif, top())
val normalMatrix = top().toMat3()
glUniformMatrix3f(vertexDiffuseColor.normalModelToCameraMatrixUnif, normalMatrix)
glUniform4f(vertexDiffuseColor.lightIntensityUnif, 1.0f)
cylinderMesh.render(gl, "lit-color")
} else {
glUseProgram(whiteDiffuseColor.theProgram)
glUniformMatrix4f(whiteDiffuseColor.modelToCameraMatrixUnif, top())
val normalMatrix = top().toMat3()
glUniformMatrix3f(whiteDiffuseColor.normalModelToCameraMatrixUnif, normalMatrix)
glUniform4f(whiteDiffuseColor.lightIntensityUnif, 1.0f)
cylinderMesh.render(gl, "lit")
}
glUseProgram()
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
perspMatrix.perspective(45.0f, w.f / h, zNear, zFar)
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer)
glBufferSubData(GL_UNIFORM_BUFFER, perspMatrix.top())
glBindBuffer(GL_UNIFORM_BUFFER)
glViewport(w, h)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl
}
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(vertexDiffuseColor.theProgram, whiteDiffuseColor.theProgram)
glDeleteBuffer(projectionUniformBuffer)
cylinderMesh.dispose(gl)
planeMesh.dispose(gl)
projectionUniformBuffer.destroy()
}
class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut09", vertex, fragment)
val dirToLightUnif = gl.glGetUniformLocation(theProgram, "dirToLight")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
} | mit | bd3af5c435ff438c39b77df8ef5309a2 | 29.693966 | 112 | 0.642978 | 4.132327 | false | false | false | false |
BracketCove/PosTrainer | androiddata/src/main/java/com/wiseassblog/androiddata/data/movementdatabase/MovementDatabaseImpl.kt | 1 | 2023 | package com.wiseassblog.androiddata.data.movementdatabase
import android.content.res.AssetManager
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.wiseassblog.common.MovementRepositoryException
import com.wiseassblog.common.ResultWrapper
import com.wiseassblog.domain.domainmodel.Movement
import com.wiseassblog.domain.repository.IMovementRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class MovementDatabaseImpl(private val assets: AssetManager) : IMovementRepository {
override suspend fun getMovements(): ResultWrapper<Exception, List<Movement>> = withContext(Dispatchers.IO) {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonString = assets.open("movements.json")
.bufferedReader()
.use {
it.readText()
}
val type = Types.newParameterizedType(List::class.java, Movement::class.java)
val adapter = moshi.adapter<List<Movement>>(type)
ResultWrapper.build { adapter.fromJson(jsonString) ?: throw MovementRepositoryException }
}
override suspend fun getMovementById(movementId: String): ResultWrapper<Exception, Movement> =
withContext(Dispatchers.IO) {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonString = assets.open("movements.json")
.bufferedReader()
.use {
it.readText()
}
val type = Types.newParameterizedType(List::class.java, Movement::class.java)
val adapter = moshi.adapter<List<Movement>>(type)
var movement: Movement? = null
adapter.fromJson(jsonString)
?.forEach {
if (it.name == movementId) movement = it
}
ResultWrapper.build { movement ?: throw MovementRepositoryException }
}
} | apache-2.0 | 5ff01278554d46f6f91011b177a092c3 | 36.481481 | 113 | 0.676718 | 5.019851 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/GangueCommand.kt | 1 | 3218 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.utils.LorittaImage
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.makeRoundedCorners
import net.perfectdreams.loritta.morenitta.utils.toBufferedImage
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
class GangueCommand(loritta: LorittaBot) : AbstractCommand(loritta, "gang", listOf("gangue"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
companion object {
val TEMPLATE_OVERLAY by lazy { ImageIO.read(File(Constants.ASSETS_FOLDER, "cocielo/overlay.png")) }
}
override fun getDescriptionKey() = LocaleKeyData("commands.command.gang.description")
override fun getExamplesKey() = LocaleKeyData("commands.command.gang.examples")
// TODO: Fix Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val contextImage2 = context.getImageAt(1) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val contextImage3 = context.getImageAt(2) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val contextImage4 = context.getImageAt(3) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val contextImage5 = context.getImageAt(4) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val template = readImage(File(LorittaBot.ASSETS + "cocielo/cocielo.png"))
val scaled = contextImage.getScaledInstance(59, 59, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.makeRoundedCorners(20)
val scaled2 = contextImage2.getScaledInstance(47, 57, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.makeRoundedCorners(20)
val scaled3 = contextImage3.getScaledInstance(50, 50, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.makeRoundedCorners(20)
val scaled4 = contextImage4.getScaledInstance(53, 58, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.makeRoundedCorners(20)
val scaled5 = contextImage5.getScaledInstance(43, 43, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.makeRoundedCorners(20)
// Porque nós precisamos rotacionar
val rotated = LorittaImage(scaled5)
rotated.rotate(335.0)
template.graphics.drawImage(scaled, 216, 80, null)
template.graphics.drawImage(scaled2, 142, 87, null)
template.graphics.drawImage(scaled3, 345, 80, null)
template.graphics.drawImage(scaled4, 28, 141, null)
template.graphics.drawImage(rotated.bufferedImage, 290, -5, null)
template.graphics.drawImage(TEMPLATE_OVERLAY, 0, 0, null)
context.sendFile(template, "gangue.png", context.getAsMention(true))
}
} | agpl-3.0 | 01c394292cd6945976f774306c2ed32f | 47.029851 | 161 | 0.788623 | 3.793632 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/DailyRoute.kt | 1 | 17893 | package net.perfectdreams.spicymorenitta.routes
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import jq
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.dom.addClass
import kotlinx.dom.clear
import kotlinx.dom.removeClass
import kotlinx.html.*
import kotlinx.html.dom.prepend
import kotlinx.serialization.Serializable
import loriUrl
import net.perfectdreams.loritta.common.utils.daily.DailyGuildMissingRequirement
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.http
import net.perfectdreams.spicymorenitta.locale
import net.perfectdreams.spicymorenitta.utils.GoogleRecaptchaUtils
import net.perfectdreams.spicymorenitta.utils.LoriWebCode
import net.perfectdreams.spicymorenitta.utils.locale.buildAsHtml
import net.perfectdreams.spicymorenitta.utils.onClick
import net.perfectdreams.spicymorenitta.utils.select
import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig
import org.w3c.dom.Audio
import org.w3c.dom.Element
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.url.URLSearchParams
import utils.CountUp
import utils.CountUpOptions
import utils.Moment
import utils.RecaptchaOptions
import kotlin.collections.set
import kotlin.js.Date
import kotlin.js.Json
import kotlin.js.json
import kotlin.random.Random
class DailyRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/daily") {
override val keepLoadingScreen: Boolean
get() = true
val dailyNotification: Element
get() = document.select<HTMLElement>(".daily-notification")
val dailyRewardButton: Element
get() = document.select<HTMLElement>(".daily-reward-button")
val dailyPrewrapper: Element
get() = document.select<HTMLDivElement>("#daily-prewrapper")
val dailyWrapper: Element
get() = document.select<HTMLDivElement>("#daily-wrapper")
companion object {
const val USER_PADDING = 2
@JsName("recaptchaCallback")
fun recaptchaCallback(response: String) {
val currentRoute = SpicyMorenitta.INSTANCE.currentRoute
if (currentRoute is DailyRoute)
currentRoute.recaptchaCallback(response)
}
private val randomEmotes = listOf(
"/assets/img/daily/here_comes_the_money.gif",
"/assets/img/daily/lori_rica.png",
"/assets/img/daily/lori_woop.gif",
"/assets/img/daily/lori_ehissoai.gif",
"/assets/img/daily/lori_confetti.gif",
"/assets/img/daily/lori_yay_wobbly.gif",
"/assets/img/daily/ferret.gif"
)
}
override fun onRender(call: ApplicationCall) {
super.onRender(call)
m.launch {
val response = http.get {
url("${window.location.origin}/api/v1/economy/daily-reward-status")
}
val dailyRewardStatusAsString = response.bodyAsText()
debug("Daily Reward Status: $dailyRewardStatusAsString")
val data = JSON.parse<Json>(dailyRewardStatusAsString)
if (checkIfThereAreErrors(response, data))
return@launch
val receivedDailyWithSameIp = data["receivedDailyWithSameIp"] as Int
dailyNotification.textContent = if (receivedDailyWithSameIp == 0) {
locale["website.daily.pleaseCompleteReCaptcha"]
} else {
locale["website.daily.alreadyReceivedPrizesWithTheSameIp"]
}
GoogleRecaptchaUtils.render(jq("#daily-captcha").get()[0], RecaptchaOptions(
"6LfRyUkUAAAAAASo0YM4IZBqvkzxyRWJ1Ydw5weC",
"recaptchaCallback",
"normal"
))
m.hideLoadingScreen()
}
}
fun checkIfThereAreErrors(response: HttpResponse, data: Json): Boolean {
if (response.status != HttpStatusCode.OK) {
// oof, parece ser um erro!
val error = data["error"] as Json?
if (error == null) {
dailyNotification.textContent = locale["website.daily.thisShouldNeverHappen", response.status.value]
return true
}
val code = error["code"] as Int
val webCode = LoriWebCode.fromErrorId(code)
dailyNotification.textContent = when (webCode) {
LoriWebCode.UNAUTHORIZED -> {
dailyRewardButton.addClass("button-discord-success")
dailyRewardButton.removeClass("button-discord-disabled")
dailyRewardButton.onClick {
val json = json()
json["redirectUrl"] = "${loriUrl}daily"
window.location.href = "https://discordapp.com/oauth2/authorize?redirect_uri=${loriUrl}dashboard&scope=identify%20guilds%20email&response_type=code&client_id=297153970613387264&state=${window.btoa(JSON.stringify(json))}"
}
locale["website.daily.notLoggedIn"]
}
LoriWebCode.ALREADY_GOT_THE_DAILY_REWARD_SAME_ACCOUNT_TODAY -> {
val moment = Moment(data["canPayoutAgain"].unsafeCast<Long>())
locale["website.daily.alreadyReceivedDailyReward", moment.fromNow()]
}
LoriWebCode.ALREADY_GOT_THE_DAILY_REWARD_SAME_IP_TODAY -> {
val moment = Moment(data["canPayoutAgain"].unsafeCast<Long>())
locale["website.daily.alreadyReceivedDailyReward", moment.fromNow()]
}
LoriWebCode.BLACKLISTED_EMAIL -> locale["website.daily.blacklistedEmail"]
LoriWebCode.BLACKLISTED_IP -> locale["website.daily.blacklistedIp"]
LoriWebCode.UNVERIFIED_ACCOUNT -> locale["website.daily.unverifiedAccount"]
LoriWebCode.INVALID_RECAPTCHA -> locale["website.daily.invalidReCaptcha"]
LoriWebCode.MFA_DISABLED -> locale["website.daily.pleaseActivate2FA"]
else -> locale["website.daily.thisShouldNeverHappen", webCode.name]
}
return true
} else return false
}
@JsName("recaptchaCallback")
fun recaptchaCallback(response: String) {
val ts1Promotion2 = Audio("${loriUrl}assets/snd/ts1_promotion2.mp3")
val cash = Audio("${loriUrl}assets/snd/css1_cash.wav")
dailyNotification.clear()
debug("reCAPTCHA Token: $response")
dailyRewardButton.addClass("button-discord-success")
dailyRewardButton.removeClass("button-discord-disabled")
dailyRewardButton.onClick {
dailyRewardButton.addClass("button-discord-disabled")
dailyRewardButton.removeClass("button-discord-success")
m.launch {
val searchParams = URLSearchParams(window.location.search)
val guild = searchParams.get("guild")
val url = if (guild != null)
"${window.location.origin}/api/v1/economy/daily-reward?guild=$guild"
else
"${window.location.origin}/api/v1/economy/daily-reward"
val response = http.get {
url(url)
parameter("recaptcha", response)
}
val dailyRewardStatusAsString = response.bodyAsText()
debug("Daily Reward: $dailyRewardStatusAsString")
val data = JSON.parse<Json>(dailyRewardStatusAsString)
if (checkIfThereAreErrors(response, data))
return@launch
val payload = kotlinx.serialization.json.JSON.nonstrict.decodeFromString(DailyResponse.serializer(), JSON.stringify(data))
jq("#daily-wrapper").fadeTo(500, 0, {
dailyWrapper.asDynamic().style.position = "absolute"
dailyPrewrapper.prepend {
div {
id = "daily-info"
style = "opacity: 0;"
h2 {
+ locale["website.daily.congratulations"]
}
img(src = "https://assets.perfectdreams.media/loritta/sonhos/[email protected]") {
width = "200"
}
h1 {
+ "0"
id = "dailyPayout"
}
h2 {
+ "Sonhos!"
}
p {
locale.buildAsHtml(locale["website.daily.wantMoreSonhos"], { control ->
if (control == 0) {
a(href = "/user/@me/dashboard/bundles") {
+ locale["website.daily.clickingHere"]
}
}
}, { str ->
+ str
})
}
div {
style = "display: flex; justify-content: center; flex-wrap: wrap; gap: 0.5em;"
a(href = "https://twitter.com/LorittaBot", classes = "button primary", target = "_blank") {
i(classes = "fab fa-twitter")
+" Siga no Twitter"
}
a(href = "https://www.youtube.com/c/Loritta", classes = "button red", target = "_blank") {
i(classes = "fab fa-youtube")
+" Inscreva-se no YouTube"
}
a(href = "https://www.instagram.com/lorittabot/", classes = "button pink", target = "_blank") {
i(classes = "fab fa-instagram")
+" Siga no Instagram"
}
a(href = "https://tiktok.com/@lorittamorenittabot", classes = "button purple", target = "_blank") {
i(classes = "fab fa-tiktok")
+" Siga no TikTok"
}
}
if (payload.sponsoredBy != null) {
h1 {
+ locale["website.daily.youEarnedMoreSonhos", payload.sponsoredBy.multipliedBy]
}
// https://discord.com/developers/docs/reference#image-formatting
val guildIconUrl = "https://cdn.discordapp.com/icons/${payload.sponsoredBy.guild.id}/${payload.sponsoredBy.guild.iconUrl}" +
if (payload.sponsoredBy.guild.iconUrl.startsWith("a_"))
".gif"
else
".png"
img(src = guildIconUrl) {
attributes["width"] = "128"
attributes["height"] = "128"
attributes["style"] = "border-radius: 99999px;"
}
h2 {
+payload.sponsoredBy.guild.name
}
p {
+ locale["website.daily.sponsoredStatus", payload.sponsoredBy.originalPayout, payload.sponsoredBy.guild.name, payload.dailyPayout]
}
if (payload.sponsoredBy.user != null) {
p {
+ locale["website.daily.thankTheSponsor", "${payload.sponsoredBy.user.name}#${payload.sponsoredBy.user.discriminator}", payload.dailyPayout - payload.sponsoredBy.originalPayout]
}
}
}
p {
+"Agora você possui ${payload.currentBalance} sonhos, que tal gastar os seus sonhos "
val random = Random(Date().getTime().toInt()).nextInt(0, 9)
when (random) {
0 -> {
+"na rifa (+rifa)"
}
1 -> {
a(href = "${loriUrl}user/@me/dashboard/ship-effects") {
+"alterando o valor do ship entre você e a sua namoradx"
}
}
2 -> {
a(href = "${loriUrl}user/@me/dashboard/profiles") {
+"alterando o look do seu perfil"
}
}
3 -> {
a(href = "${loriUrl}user/@me/dashboard/daily-shop") {
+"comprando novas bugigangas na loja"
}
}
4 -> {
+"doando eles para a sua pessoa favorita (/sonhos pay)"
}
5 -> {
+"apostando com seus amigos (+coinflip bet)"
}
6 -> {
+"apostando com outros usuários (/bet coinflip global)"
}
7 -> {
+"apostando em rinhas de emojis (+emojifight bet)"
}
8 -> {
+"jogando no SparklyPower, o servidor de Minecraft da Loritta (mc.sparklypower.net)"
}
}
+"?"
}
if (payload.failedGuilds.isNotEmpty()) {
for (failedGuild in payload.failedGuilds) {
p {
+"Você poderia ganhar x${failedGuild.multiplier} sonhos "
when (failedGuild.type) {
DailyGuildMissingRequirement.REQUIRES_MORE_TIME -> {
+"após ficar por mais de 15 dias em "
}
DailyGuildMissingRequirement.REQUIRES_MORE_XP -> {
+"se você conseguir ser mais ativo ao ponto de ter 500 XP em "
}
}
+failedGuild.guild.name
+"!"
}
}
}
img {
width = "128"
height = "128"
src = randomEmotes.random()
}
p {
+ locale["website.daily.comeBackLater"]
}
}
}
jq("#daily-wrapper").css("position", "absolute")
val prepended = jq("#daily-info")
prepended.fadeTo(500, 1)
val countUp = CountUp("dailyPayout", 0.0, payload.dailyPayout.toDouble(), 0, 7.5, CountUpOptions(
true,
true,
"",
""
))
ts1Promotion2.play()
countUp.start {
println("Finished!!!")
cash.play()
}
})
}
}
}
@Serializable
class DailyResponse(
val receivedDailyAt: String,
val dailyPayout: Int,
val sponsoredBy: Sponsored? = null,
val currentBalance: Double,
val failedGuilds: Array<FailedGuildDailyStats>
)
@Serializable
class Guild(
// É deserializado para String pois JavaScript é burro e não funciona direito com Longs
val name: String,
val iconUrl: String,
val id: String
)
@Serializable
class Sponsored(
val guild: Guild,
val user: ServerConfig.SelfMember? = null,
val multipliedBy: Double,
val originalPayout: Double
)
@Serializable
class FailedGuildDailyStats(
val guild: Guild,
val type: DailyGuildMissingRequirement,
val data: Long,
val multiplier: Double
)
} | agpl-3.0 | 51a268c5cc6cc846315fcef103aecf99 | 41.684964 | 244 | 0.464885 | 5.368958 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/psi/impl/ElementChangeUtil.kt | 1 | 2290 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.psi.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.impl.source.SourceTreeToPsiMap
import com.intellij.psi.impl.source.tree.Factory
import com.intellij.psi.tree.IElementType
import com.intellij.util.IncorrectOperationException
object ElementChangeUtil {
@Throws(IncorrectOperationException::class)
internal fun doNameReplacement(elementDecl: PsiNameIdentifierOwner, identifier: PsiElement, name: String, elementType: IElementType) {
if (!elementDecl.isWritable) {
throw IncorrectOperationException("Cannot rename ${elementDecl.javaClass.name}: element non-writable")
} else if (!isInProjectContent(elementDecl.project, elementDecl.containingFile.virtualFile)) {
throw IncorrectOperationException("Cannot rename ${elementDecl.javaClass.name}: element not in project content")
} else {
if (identifier is HCLStringLiteralMixin) {
identifier.setName(name)
return
} else if (identifier is HCLIdentifierMixin) {
identifier.setName(name)
return
}
val replacement = SourceTreeToPsiMap.treeElementToPsi(Factory.createSingleLeafElement(elementType, name, null, elementDecl.manager))
if (replacement != null) {
identifier.replace(replacement)
}
}
}
internal fun isInProjectContent(project: Project, vfile: VirtualFile?): Boolean {
return vfile == null || ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(vfile) != null
}
}
| apache-2.0 | c5076a902e07e49b7570ef2d33dac3a5 | 41.407407 | 138 | 0.761572 | 4.516765 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/formatter/HCLFormattingBuilderModel.kt | 1 | 2840 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.formatter
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.lang.Language
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.intellij.plugins.hcl.HCLElementTypes.*
import org.intellij.plugins.hcl.HCLLanguage
open class HCLFormattingBuilderModel(val language: Language = HCLLanguage) : FormattingModelBuilder {
override fun createModel(element: PsiElement, settings: CodeStyleSettings): FormattingModel {
val builder = createSpacingBuilder(settings)
val block = HCLBlock(null, element.node, null, null, builder, Indent.getNoneIndent(), settings.getCustomSettings(HCLCodeStyleSettings::class.java))
return FormattingModelProvider.createFormattingModelForPsiFile(element.containingFile, block, settings)
}
private fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder {
val commonSettings = settings.getCommonSettings(language)
val spacesBeforeComma = if (commonSettings.SPACE_BEFORE_COMMA) 1 else 0
val spacesAroundAssignment = if (commonSettings.SPACE_AROUND_ASSIGNMENT_OPERATORS) 1 else 0
return SpacingBuilder(settings, language)
.after(HEREDOC_LITERAL).lineBreakInCode()
.before(EQUALS).spacing(spacesAroundAssignment, spacesAroundAssignment, 0, false, 0)
.after(EQUALS).spacing(spacesAroundAssignment, spacesAroundAssignment, 0, false, 0)
.afterInside(IDENTIFIER, BLOCK).spaces(1)
.afterInside(STRING_LITERAL, BLOCK).spaces(1)
.between(L_CURLY, R_CURLY).none()
.withinPairInside(L_CURLY, R_CURLY, OBJECT).lineBreakInCode()
.withinPair(L_BRACKET, R_BRACKET).spaceIf(commonSettings.SPACE_WITHIN_BRACKETS) //, true
.withinPair(L_CURLY, R_CURLY).spaceIf(commonSettings.SPACE_WITHIN_BRACES) //, true
.before(COMMA).spacing(spacesBeforeComma, spacesBeforeComma, 0, false, 0)
.after(COMMA).spaceIf(commonSettings.SPACE_AFTER_COMMA)
.after(BLOCK).lineBreakInCode()
}
override fun getRangeAffectingIndent(file: PsiFile?, offset: Int, elementAtOffset: ASTNode?): TextRange? {
return null
}
}
| apache-2.0 | 3fa2e1941b47bc842ae9e0c66e8724a3 | 46.333333 | 151 | 0.762324 | 4.21365 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/utils/network/HttpClient.kt | 1 | 3344 | package be.digitalia.fosdem.utils.network
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Headers
import okhttp3.Request
import okhttp3.ResponseBody
import java.io.IOException
import java.net.HttpURLConnection
import javax.inject.Inject
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* High-level coroutines-based HTTP client.
*
* @author Christophe Beyls
*/
class HttpClient @Inject constructor(private val deferredCallFactory: @JvmSuppressWildcards Deferred<Call.Factory>) {
suspend fun <T> get(url: String, bodyParser: (body: ResponseBody, headers: Headers) -> T): Response.Success<T> {
return when (val response = get(url, null, bodyParser)) {
// Can only receive NotModified if lastModified argument is non-null
is Response.NotModified -> throw IllegalStateException()
is Response.Success -> response
}
}
/**
* @param lastModified header value matching a previous "Last-Modified" response header.
*/
suspend fun <T> get(url: String, lastModified: String?, bodyParser: (body: ResponseBody, headers: Headers) -> T): Response<T> {
val requestBuilder = Request.Builder()
if (lastModified != null) {
requestBuilder.header("If-Modified-Since", lastModified)
}
val request = requestBuilder
.url(url)
.build()
val call = deferredCallFactory.await().newCall(request)
return suspendCancellableCoroutine { continuation ->
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
override fun onResponse(call: Call, response: okhttp3.Response) {
// This block is invoked on OkHttp's network thread
val body = response.body()
if (!response.isSuccessful) {
body?.close()
if (lastModified != null && response.code() == HttpURLConnection.HTTP_NOT_MODIFIED) {
// Cached result is still valid; return an empty response
continuation.resume(Response.NotModified)
} else {
continuation.resumeWithException(IOException("Server returned response code: " + response.code()))
}
} else {
try {
val parsedBody = checkNotNull(body).use { bodyParser(it, response.headers()) }
continuation.resume(Response.Success(parsedBody, response))
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
}
})
continuation.invokeOnCancellation { call.cancel() }
}
}
sealed class Response<out T> {
object NotModified : Response<Nothing>()
class Success<T>(val body: T, val raw: okhttp3.Response) : Response<T>()
}
companion object {
const val LAST_MODIFIED_HEADER_NAME = "Last-Modified"
}
} | apache-2.0 | e3a63b952b253d86de6edc9bda6ba899 | 39.301205 | 131 | 0.594498 | 5.208723 | false | false | false | false |
EmmanuelMess/Simple-Accounting | SimpleAccounting/app/src/main/java/com/emmanuelmess/simpleaccounting/dataloading/LoadMonthAsyncTask.kt | 1 | 1822 | package com.emmanuelmess.simpleaccounting.dataloading
import android.os.AsyncTask
import com.emmanuelmess.simpleaccounting.data.MonthData
import com.emmanuelmess.simpleaccounting.data.Session
import com.emmanuelmess.simpleaccounting.db.legacy.TableGeneral
import com.emmanuelmess.simpleaccounting.db.legacy.TableMonthlyBalance
import java.util.ArrayList
/**
* @author Emmanuel
* on 27/11/2016, at 15:03.
*/
class LoadMonthAsyncTask(
private val session: Session,
private val tableMonthlyBalance: TableMonthlyBalance?,
private val tableGeneral: TableGeneral,
private val listener: AsyncFinishedListener<MonthData>
) : AsyncTask<Void, Void, MonthData>() {
@Suppress("UsePropertyAccessSyntax")
override fun onPreExecute() {
tableMonthlyBalance?.getReadableDatabase()//updates the database, calls onUpgrade()
tableGeneral.getReadableDatabase()//triggers onUpdate()
}
override fun doInBackground(vararg p: Void): MonthData? {
if (!isAlreadyLoading)
isAlreadyLoading = true
else
throw IllegalStateException("Already loading month: ${session.year}-${session.month + 1}");
val data = tableGeneral.getIndexesForMonth(session)
val rowToDBRowConversion = ArrayList<Int>()
if (isCancelled) return null
for (m in data)
rowToDBRowConversion.add(m)
return (
if (isCancelled) null
else MonthData(
session,
tableMonthlyBalance?.getBalanceLastMonthWithData(session),
tableGeneral.getAllForMonth(session),
rowToDBRowConversion)
)
}
override fun onPostExecute(dbRowsPairedRowToDBConversion: MonthData) {
if (!isCancelled)
listener.onAsyncFinished(dbRowsPairedRowToDBConversion)
isAlreadyLoading = false
}
override fun onCancelled(result: MonthData) {
isAlreadyLoading = false
}
companion object {
var isAlreadyLoading = false
private set
}
}
| gpl-3.0 | 4d93a20307ee62c74a3fab7e1ea39540 | 24.661972 | 94 | 0.776619 | 3.935205 | false | false | false | false |
chRyNaN/GuitarChords | android/src/main/java/com/chrynan/chords/span/TouchableSpan.kt | 1 | 3756 | package com.chrynan.chords.span
import android.graphics.Typeface
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.UpdateAppearance
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import com.chrynan.colors.ColorInt
/*
* Copyright 2016 chRyNaN
*
* 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.
*/
/**
* References: http://stackoverflow.com/a/7292485/1478764,
* http://stackoverflow.com/a/20905824/1478764
*
* If an object of this type is attached to the text of a [TextView] with a movement method of
* [LinkTouchMovementMethod], the affected spans of the text can be selected. If touched, the
* [onTouch] method will be called.
*
* @author chRyNaN
*/
abstract class TouchableSpan : CharacterStyle(),
UpdateAppearance,
TouchableSpanView {
/**
* Indicates whether this [TouchableSpan] is selected or not. A value of true means that this
* [TouchableSpan] is selected, a value of false means that it is not selected.
*
* @author chRyNaN
*/
var isSelected = false
internal set
var viewModel: TouchableSpanViewModel = TouchableSpanViewModel()
set(value) {
field = value
backgroundColor = value.backgroundColor
selectedBackgroundColor = value.selectedBackgroundColor
textColor = value.textColor
selectedTextColor = value.selectedTextColor
isUnderlined = value.isUnderlined
isUnderlinedWhenSelected = value.isUnderlinedWhenSelected
textTypeface = value.textTypeface
selectedTextTypeface = value.selectedTextTypeface
}
override var backgroundColor: ColorInt = viewModel.backgroundColor
internal set
override var selectedBackgroundColor: ColorInt = viewModel.selectedBackgroundColor
internal set
override var textColor: ColorInt = viewModel.textColor
internal set
override var selectedTextColor: ColorInt = viewModel.selectedTextColor
internal set
override var isUnderlined: Boolean = viewModel.isUnderlined
internal set
override var isUnderlinedWhenSelected: Boolean = viewModel.isUnderlinedWhenSelected
internal set
override var textTypeface: Typeface = viewModel.textTypeface
internal set
override var selectedTextTypeface: Typeface = viewModel.selectedTextTypeface
internal set
/**
* Performs the touch action associated with this span.
*
* @return A [Boolean] value indicating whether the touch event was handled or not.
*
* @author chRyNaN
*/
abstract fun onTouch(widget: View, m: MotionEvent): Boolean
/**
* Updates the draw state of the underlying text in this span.
*
* @author chRyNaN
*/
override fun updateDrawState(textPaint: TextPaint) {
textPaint.apply {
color = if (isSelected) selectedTextColor else textColor
bgColor = if (isSelected) selectedBackgroundColor else backgroundColor
isUnderlineText = if (isSelected) isUnderlinedWhenSelected else isUnderlined
typeface = if (isSelected) selectedTextTypeface else textTypeface
}
}
}
| apache-2.0 | c859e368c439f91e26687035c0bec34a | 35.115385 | 97 | 0.713259 | 4.988048 | false | false | false | false |
jiangkang/KTools | widget/src/main/java/com/jiangkang/widget/ui/TouchLogicActivity.kt | 1 | 1227 | package com.jiangkang.widget.ui
import android.graphics.Rect
import android.os.Bundle
import android.view.MotionEvent
import android.view.TouchDelegate
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.jiangkang.tools.utils.ToastUtils
import com.jiangkang.widget.databinding.ActivityTouchLogicBinding
class TouchLogicActivity : AppCompatActivity() {
private val binding by lazy { ActivityTouchLogicBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.ivCenter.apply {
post {
val gap = 500
val bounds = Rect()
getHitRect(bounds)
bounds.left -= gap
bounds.top -= gap
bounds.right += gap
bounds.bottom += gap
setOnClickListener { ToastUtils.showShortToast("Click") }
(binding.ivCenter.parent as View).touchDelegate = TouchDelegate(bounds, binding.ivCenter)
}
}
binding.btnRight.setOnClickListener {
ToastUtils.showShortToast("Btn Click")
}
}
} | mit | 16bfca763c9b8e3744bee2aecf2353dd | 30.487179 | 105 | 0.654442 | 5.028689 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/model/theme/Theme.kt | 1 | 1211 | package com.github.emulio.model.theme
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.github.emulio.model.Platform
class Theme {
var formatVersion: String? = null
var includeTheme: Theme? = null
var platform: Platform? = null
var views: List<View>? = null
override fun toString(): String {
return "Theme(formatVersion=$formatVersion, includeTheme=$includeTheme, views=$views)"
}
fun getDrawableFromPlatformTheme(): Drawable {
val systemView = checkNotNull(this.findView("system"), {
"System tag of theme ${this.platform?.platformName} not found. please check your theme files." })
val logo = systemView.findViewItem("logo")!! as ViewImage
val texture = Texture(FileHandle(logo.path), true)
texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap)
return TextureRegionDrawable(TextureRegion(texture))
}
fun findView(name: String): View? {
views?.forEach { view ->
if (view.name == name) {
return view
}
}
return null
}
}
| gpl-3.0 | e700a54fc4c1534d4c5299f62d45f2e3 | 26.522727 | 100 | 0.753097 | 3.64759 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/RtpParser.kt | 1 | 2273 | /*
* Copyright @ 2019 - present 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.format.PayloadTypeEncoding.RED
import org.jitsi.nlj.rtp.AudioRtpPacket
import org.jitsi.nlj.rtp.RedAudioRtpPacket
import org.jitsi.nlj.rtp.VideoRtpPacket
import org.jitsi.nlj.util.ReadOnlyStreamInformationStore
import org.jitsi.rtp.rtp.RtpHeader
import org.jitsi.utils.MediaType
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.cdebug
import org.jitsi.utils.logging2.createChildLogger
class RtpParser(
private val streamInformationStore: ReadOnlyStreamInformationStore,
parentLogger: Logger
) : TransformerNode("RTP Parser") {
private val logger = createChildLogger(parentLogger)
override fun transform(packetInfo: PacketInfo): PacketInfo? {
val packet = packetInfo.packet
val payloadTypeNumber = RtpHeader.getPayloadType(packet.buffer, packet.offset).toByte()
val payloadType = streamInformationStore.rtpPayloadTypes[payloadTypeNumber] ?: run {
logger.cdebug { "Unknown payload type: $payloadTypeNumber" }
return null
}
packetInfo.packet = when (payloadType.mediaType) {
MediaType.AUDIO -> when (payloadType.encoding) {
RED -> packet.toOtherType(::RedAudioRtpPacket)
else -> packet.toOtherType(::AudioRtpPacket)
}
MediaType.VIDEO -> packet.toOtherType(::VideoRtpPacket)
else -> throw Exception("Unrecognized media type: '${payloadType.mediaType}'")
}
packetInfo.resetPayloadVerification()
return packetInfo
}
override fun trace(f: () -> Unit) = f.invoke()
}
| apache-2.0 | 898f6828ac2628965f465c864c7041c4 | 37.525424 | 95 | 0.720634 | 4.396518 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/toolWindow/log/UnityLogTokenizer.kt | 1 | 7861 | package com.jetbrains.rider.plugins.unity.toolWindow.log
import com.intellij.openapi.util.NlsSafe
import java.awt.Color
import java.util.*
class UnityLogTokenizer {
private val validTokens = mapOf("<b>" to UnityLogTokenType.Bold,
"</b>" to UnityLogTokenType.BoldEnd,
"<i>" to UnityLogTokenType.Italic,
"</i>" to UnityLogTokenType.ItalicEnd,
"<color=*>" to UnityLogTokenType.Color,
"</color>" to UnityLogTokenType.ColorEnd,
"<size=*>" to UnityLogTokenType.Size,
"</size>" to UnityLogTokenType.SizeEnd,
"<material=*>" to UnityLogTokenType.Material,
"</material>" to UnityLogTokenType.MaterialEnd,
"<quad=*>" to UnityLogTokenType.Quad)
private val startToEndMapping = mapOf(UnityLogTokenType.Bold to UnityLogTokenType.BoldEnd,
UnityLogTokenType.Italic to UnityLogTokenType.ItalicEnd,
UnityLogTokenType.Color to UnityLogTokenType.ColorEnd,
UnityLogTokenType.Size to UnityLogTokenType.SizeEnd,
UnityLogTokenType.Material to UnityLogTokenType.MaterialEnd)
fun tokenize(fullString: String): List<Token> {
val tokens: MutableList<Token> = mutableListOf()
var lastTokenIndex = 0
for ((i) in fullString.withIndex()) {
for (validToken in validTokens) {
val lastIndex = checkToken(fullString, validToken.key, i)
if (lastIndex != -1) {
addTokens(i, lastTokenIndex, tokens, fullString, fullString.substring(i, lastIndex + 1), validToken.value)
lastTokenIndex = lastIndex + 1
continue
}
}
}
tokens.add(Token(fullString.substring(lastTokenIndex), UnityLogTokenType.String))
generateStyles(tokens)
return tokens
}
private fun generateStyles(tokens: MutableList<Token>) {
for ((i, token) in tokens.withIndex()) {
if (token.type == UnityLogTokenType.Bold) {
for (x in i until tokens.count()) {
if (tokens[x].type == UnityLogTokenType.BoldEnd && !tokens[x].used) {
token.used = true
tokens[x].used = true
for (y in i until x) {
tokens[y].bold = true
}
break
}
}
}
else if (token.type == UnityLogTokenType.Italic) {
for (x in i until tokens.count()) {
if (tokens[x].type == UnityLogTokenType.ItalicEnd && !tokens[x].used) {
token.used = true
tokens[x].used = true
for (y in i until x) {
tokens[y].italic = true
}
break
}
}
}
else if (token.type == UnityLogTokenType.Color) {
colorizeTokens(i, tokens, token)
}
else if (token.type == UnityLogTokenType.Quad) {
token.used = true
}
else if (validTokens.containsValue(token.type)) {
if (!startToEndMapping.containsKey(token.type))
continue
val endToken = startToEndMapping[token.type]
for (x in i until tokens.count()) {
if (tokens[x].type == endToken && !tokens[x].used) {
token.used = true
tokens[x].used = true
}
}
}
}
}
private fun colorizeTokens(i: Int,
tokens: MutableList<Token>,
token: Token) {
for (x in i+1 until tokens.count()) {
if (tokens[x].type == UnityLogTokenType.Color && !tokens[x].used) {
colorizeTokens(x, tokens, tokens[x])
}
if (tokens[x].type == UnityLogTokenType.ColorEnd && !tokens[x].used) {
token.used = true
tokens[x].used = true
val color = this.parseColor(getTokenValue(token.token))
for (y in i until x) {
if (tokens[y].color == null)
tokens[y].color = color
}
break
}
}
}
private fun addTokens(i: Int, lastTokenIndex: Int, tokens: MutableList<Token>, fullString: String, tokenString: String, type: UnityLogTokenType) {
if (i > lastTokenIndex)
tokens.add(Token(fullString.substring(lastTokenIndex, i), UnityLogTokenType.String))
tokens.add(Token(tokenString, type))
}
private fun getTokenValue(tokenString: String) : String
{
if(!tokenString.contains('='))
return ""
val cleanedToken = tokenString.replace(">", "")
return cleanedToken.substring(cleanedToken.indexOf('=') + 1).trim('"')
}
private fun checkToken(fullString: String, expectedToken: String, startIndex: Int): Int {
var expectedTokenIndex = 0
for (i in startIndex until fullString.length) {
val currentChar = fullString[i].lowercaseChar()
val expectedChar = expectedToken[expectedTokenIndex].lowercaseChar()
if (expectedChar == '*') {
if (currentChar == expectedToken[expectedTokenIndex + 1].lowercaseChar()) {
expectedTokenIndex++
} else {
continue
}
} else if (currentChar != expectedChar) {
return -1
}
if (expectedTokenIndex == expectedToken.length - 1) {
return i
}
expectedTokenIndex++
}
return -1
}
private fun parseColor(color: String): Color? {
try {
when (color.lowercase(Locale.getDefault())) {
"aqua" -> return Color.decode("#00ffff")
"black" -> return Color.decode("#000000")
"blue" -> return Color.decode("#0000ff")
"brown" -> return Color.decode("#a52a2a")
"cyan" -> return Color.decode("#00ffff")
"darkblue" -> return Color.decode("#0000a0")
"fuchsia" -> return Color.decode("#ff00ff")
"green" -> return Color.decode("#008000")
"grey" -> return Color.decode("#808080")
"lightblue" -> return Color.decode("#add8e6")
"lime" -> return Color.decode("#00ff00")
"magenta" -> return Color.decode("#ff00ff")
"maroon" -> return Color.decode("#800000")
"navy" -> return Color.decode("#000080")
"olive" -> return Color.decode("#808000")
"orange" -> return Color.decode("#ffa500")
"purple" -> return Color.decode("#800080")
"red" -> return Color.decode("#ff0000")
"silver" -> return Color.decode("#c0c0c0")
"teal" -> return Color.decode("#008080")
"white" -> return Color.decode("#ffffff")
"yellow" -> return Color.decode("#ffff00")
else -> return when {
color.length == 8 -> Color.decode(color.substring(0..7))
color.length == 7 -> Color.decode(color)
else -> null
}
}
} catch (t: Throwable) {
return null
}
}
data class Token(
@NlsSafe
val token: String,
val type: UnityLogTokenType,
var bold: Boolean = false,
var italic: Boolean = false,
var used: Boolean = false,
var color: Color? = null
)
}
| apache-2.0 | 4ced9c2801519e0bb1a56a8151e6bc7b | 36.433333 | 150 | 0.51164 | 4.624118 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/tileentity/heat/TileIcebox.kt | 2 | 10243 | package tileentity.heat
import com.cout970.magneticraft.api.internal.heat.HeatContainer
import com.cout970.magneticraft.api.internal.registries.machines.heatrecipes.IceboxRecipeManager
import com.cout970.magneticraft.api.registries.machines.heatrecipes.IIceboxRecipe
import com.cout970.magneticraft.config.Config
import com.cout970.magneticraft.gui.common.DATA_ID_MACHINE_HEAT
import com.cout970.magneticraft.gui.common.DATA_ID_MACHINE_WORKING
import com.cout970.magneticraft.misc.fluid.Tank
import com.cout970.magneticraft.misc.inventory.consumeItem
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitHeat
import com.cout970.magneticraft.registry.ITEM_HANDLER
import com.cout970.magneticraft.tileentity.TileBase
import com.cout970.magneticraft.util.*
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.items.ItemStackHandler
/**
* Created by cout970 on 04/07/2016.
*/
@TileRegister("icebox")
class TileIcebox : TileBase() {
val tank: Tank = object : Tank(4000) {
override fun canFillFluidType(fluid: FluidStack?): Boolean = fluid?.fluid?.name == "water"
}
val heat = HeatContainer(dissipation = 0.0,
specificHeat = IRON_HEAT_CAPACITY * 7,
maxHeat = IRON_HEAT_CAPACITY * 3 * IRON_MELTING_POINT,
conductivity = DEFAULT_CONDUCTIVITY,
worldGetter = { this.world },
posGetter = { this.getPos() })
val traitHeat: TraitHeat = TraitHeat(this, listOf(heat))
override val traits: List<ITileTrait> = listOf(traitHeat)
val inventory = ItemStackHandler(1)
var maxMeltingTime = 0f
var meltingTime = 0f
var maxFreezingTime = 0f
var freezingTime = 0f
private var lastInput: ItemStack? = null
private var lastOutput: FluidStack? = null
override fun update() {
if (worldObj.isServer) {
//consumes fuel
if (meltingTime <= 0) {
if (inventory[0] != null) {
lastInput = getRecipe()?.input
if (lastInput != null) {
val time = lastRecipe()?.getTotalHeat(guessAmbientTemp(world, pos)) ?: 0
if (time > 0) {
maxMeltingTime = time.toFloat()
meltingTime = time.toFloat()
inventory.setStackInSlot(0, inventory[0]!!.consumeItem())
markDirty()
}
}
} else {
lastInput = null
}
}
if (freezingTime <= 0) {
if (tank.fluid != null) {
lastOutput = getRecipeReverse()?.output
if (lastOutput != null) {
val time = lastRecipe()?.getTotalHeat(guessAmbientTemp(world, pos)) ?: 0
if (time > 0) {
maxFreezingTime = time.toFloat()
freezingTime = time.toFloat()
markDirty()
}
}
}
}
//burns fuel
if (canMelt()) {
//Melting rate depends on difference between current temperature and recipe's temperature range
val meltingSpeed = Math.ceil(
(Config.iceboxMaxConsumption * interpolate(heat.temperature, lastRecipe()!!.minTemp,
lastRecipe()!!.maxTemp)) / 10.0).toInt()
val outFluidInc = FluidStack(lastRecipe()!!.output.fluid,
(lastRecipe()!!.output.amount * meltingSpeed / maxMeltingTime).toInt())
if (tank.fillInternal(outFluidInc,
false) != 0) { //This is lossy, but the fluid is considered a byproduct, so whatever
meltingTime -= meltingSpeed
tank.fillInternal(outFluidInc, true)
heat.applyHeat(-meltingSpeed.toDouble(), false)
markDirty()
}
} else if (canFreeze()) {
val freezingSpeed = Math.ceil(Config.iceboxMaxConsumption / 10.0).toInt()
val outFluidInc = FluidStack(lastRecipeReverse()!!.output.fluid,
(lastRecipe()!!.output.amount * freezingSpeed / maxMeltingTime).toInt())
if (tank.drainInternal(outFluidInc,
false) != null) { //This is lossy, but the fluid is considered a byproduct, so whatever
if (freezingTime - freezingSpeed > 0 || inventory.insertItem(0, lastRecipeReverse()!!.input,
true) == null) //If we would need to insert output, check to see if possible
freezingTime -= freezingSpeed
if (freezingTime <= 0) {
inventory.insertItem(0, lastRecipeReverse()!!.input, false)
if (tank.fluid == null) {
lastOutput = null
}
}
tank.drainInternal(outFluidInc, true)
heat.applyHeat(freezingSpeed.toDouble(), false)
markDirty()
}
}
//sends an update to the client to start/stop the fan animation
if (shouldTick(200)) {
val data = IBD()
data.setBoolean(DATA_ID_MACHINE_WORKING, heat.temperature > guessAmbientTemp(world, pos) + 1)
data.setDouble(DATA_ID_MACHINE_HEAT, heat.heat)
//tileSendSyncData(data, Side.CLIENT)
}
super.update()
}
}
private var recipeCache: IIceboxRecipe? = null
private var inputCache: ItemStack? = null
private var recipeCacheOut: IIceboxRecipe? = null
private var outputCache: FluidStack? = null
fun canMelt(): Boolean
= lastRecipe() != null
&& meltingTime > 0
&& heat.temperature > Math.ceil(
lastRecipe()!!.minTemp) //Ensure min melting temp is strictly greater than max freezing temp
&& heat.heat < heat.maxHeat
&& heat.temperature < lastRecipe()!!.maxTemp
fun canFreeze(): Boolean {
return lastRecipeReverse() != null
&& freezingTime > 0
&& lastRecipeReverse()!!.reverse
&& heat.temperature < Math.floor(
lastRecipeReverse()!!.minTemp) //Ensure min melting temp is strictly greater than max freezing temp
&& heat.heat < heat.maxHeat
}
fun lastRecipe(): IIceboxRecipe? {
if (lastInput == null) return null
return getRecipe(lastInput!!)
}
fun lastRecipeReverse(): IIceboxRecipe? {
if (lastOutput == null) return null
return getRecipe(lastOutput!!)
}
fun getRecipe(input: ItemStack): IIceboxRecipe? {
if (input === inputCache) return recipeCache
val recipe = IceboxRecipeManager.findRecipe(input)
if (recipe != null) {
recipeCache = recipe
inputCache = input
}
return recipe
}
fun getRecipe(output: FluidStack): IIceboxRecipe? {
if (output.isFluidEqual(outputCache)) return recipeCacheOut
val recipe = IceboxRecipeManager.findRecipeReverse(output)
if (recipe != null) {
recipeCacheOut = recipe
outputCache = output
}
return recipe
}
fun getRecipe(): IIceboxRecipe? = if (inventory[0] != null) getRecipe(inventory[0]!!) else null
fun getRecipeReverse(): IIceboxRecipe? = if (tank.fluid != null) getRecipe(tank.fluid!!) else null
override fun receiveSyncData(data: IBD, side: Side) {
super.receiveSyncData(data, side)
if (side == Side.SERVER) {
data.getDouble(DATA_ID_MACHINE_WORKING, { heat.heat = it })
}
}
override fun save(): NBTTagCompound {
val nbt = newNbt {
add("inventory", inventory.serializeNBT())
if (lastInput != null)
add("recipe_cache", lastInput!!.serializeNBT())
add("maxMeltingTime", maxMeltingTime)
add("meltingTime", meltingTime)
add("tank", NBTTagCompound().apply { tank.writeToNBT(this) })
if (lastOutput != null)
add("reverse_cache", NBTTagCompound().apply { lastOutput!!.writeToNBT(this) })
}
return super.save().also { it.merge(nbt) }
}
override fun load(nbt: NBTTagCompound) {
inventory.deserializeNBT(nbt.getCompoundTag("inventory"))
if (nbt.hasKey("recipe_cache")) lastInput!!.deserializeNBT(nbt.getCompoundTag("recipe_cache"))
else lastInput = null
maxMeltingTime = nbt.getFloat("maxMeltingTime")
meltingTime = nbt.getFloat("meltingTime")
tank.readFromNBT(nbt.getCompoundTag("tank"))
if (nbt.hasKey("reverse_cache"))
lastOutput = FluidStack.loadFluidStackFromNBT(nbt.getCompoundTag("reverse_cache"))
else lastOutput = null
super.load(nbt)
}
override fun onBreak() {
super.onBreak()
if (worldObj.isServer) {
if (inventory[0] != null) {
dropItem(inventory[0]!!, pos)
}
}
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? {
if (capability == ITEM_HANDLER) return inventory as T
return super.getCapability(capability, facing)
}
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean {
if (capability == ITEM_HANDLER) return true
return super.hasCapability(capability, facing)
}
} | gpl-2.0 | 255430a61bea2ed4c58b126006bf9645 | 40.473684 | 115 | 0.586547 | 4.582998 | false | false | false | false |
curiosityio/AndroidBoilerplate | androidboilerplate/src/main/java/com/curiosityio/androidboilerplate/util/InternetConnectionUtil.kt | 1 | 3305 | package com.curiosityio.androidboilerplate.util
import android.content.Context
import android.net.ConnectivityManager
import android.provider.Settings
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
open class InternetConnectionUtil() {
companion object {
fun isAnyInternetConnected(context: Context): Boolean {
val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
fun isRotationEnabled(context: Context): Boolean {
return Settings.System.getInt(context.contentResolver, Settings.System.ACCELEROMETER_ROTATION, 0) == 1
}
fun isNetworkConnectedAnyType(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
fun isConnectedToWifi(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = connectivityManager.activeNetworkInfo
return info != null && info.type == ConnectivityManager.TYPE_WIFI
}
fun isConnectedToWifiAndInternetConnected(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = connectivityManager.activeNetworkInfo
return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_WIFI
}
fun isConnectedToMobile(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = connectivityManager.activeNetworkInfo
return info != null && info.type == ConnectivityManager.TYPE_MOBILE
}
fun isConnectedToMobileAndInternetConnected(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = connectivityManager.activeNetworkInfo
return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE
}
@Throws(IOException::class)
fun pingServer(context: Context): Boolean {
if (!isAnyInternetConnected(context)) return false
try {
val urlConnection = URL("http://clients3.google.com/generate_204").openConnection() as HttpURLConnection
urlConnection.setRequestProperty("User-Agent", "Android")
urlConnection.setRequestProperty("Connection", "close")
urlConnection.connectTimeout = 1500
urlConnection.connect()
return urlConnection.responseCode === 204 && urlConnection.contentLength === 0
} catch (e: IOException) {
throw e
}
}
}
}
| mit | 4eda46e83d48ae169dca098cbe9c1f12 | 42.486842 | 136 | 0.691679 | 6.06422 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/core/extension/Activity.kt | 1 | 1326 | package com.waz.zclient.core.extension
import android.app.Activity
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
fun AppCompatActivity.addFragment(frameId: Int, fragment: Fragment) =
supportFragmentManager.doTransaction { add(frameId, fragment) }
fun AppCompatActivity.replaceFragment(frameId: Int, fragment: Fragment, addToBackStack: Boolean = true) =
supportFragmentManager.doTransaction {
replace(frameId, fragment).apply {
if (addToBackStack) {
addToBackStack(fragment.tag)
}
}
}
fun AppCompatActivity.removeFragment(fragment: Fragment) =
supportFragmentManager.doTransaction { remove(fragment) }
fun Activity.getDeviceLocale() =
resources.configuration.locales.get(0)
fun Activity.hideKeyboard() = currentFocus?.let {
val inputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0)
} ?: false
fun Activity.showKeyboard() {
val inputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
| gpl-3.0 | fa10a8419291d56a6d4fd6831dadf802 | 38 | 111 | 0.775264 | 4.875 | false | false | false | false |
facebook/litho | codelabs/group-section-lifecycle/app/src/main/java/com/facebook/litho/codelab/MainActivity.kt | 1 | 1894 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.codelab
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.facebook.litho.ComponentContext
import com.facebook.litho.LithoView
import com.facebook.litho.codelab.auxiliary.TimelineRootComponent
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val componentContext = ComponentContext(this)
val lifecycleEvents = mutableListOf<LifecycleEvent>()
val timelineView = findViewById<LithoView>(R.id.timeline)
val lifecycleListener =
object : LifecycleListener {
override fun onLifecycleMethodCalled(type: LifecycleEventType, endTime: Long) {
lifecycleEvents.add(LifecycleEvent(type, endTime))
timelineView.setComponentAsync(
TimelineRootComponent.create(componentContext)
.lifecycleEvents(lifecycleEvents.toList())
.build())
}
}
val sectionView = findViewById<LithoView>(R.id.section)
sectionView.setComponent(
LifecycleRootComponent.create(componentContext)
.lifecycleListener(lifecycleListener)
.build())
}
}
| apache-2.0 | a62d55bc59c72266335e44876ce1983a | 34.735849 | 89 | 0.721225 | 4.758794 | false | false | false | false |
google/horologist | base-ui/src/debug/java/com/google/android/horologist/base/ui/components/StandardChipIconWithProgressPreview.kt | 1 | 3733 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistBaseUiApi::class)
package com.google.android.horologist.base.ui.components
import androidx.compose.material.icons.materialPath
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi
@Preview(
name = "Standard",
group = "Variants",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun StandardChipIconWithProgressPreview() {
StandardChipIconWithProgress()
}
@Preview(
name = "With 75 percent download complete",
group = "Variants",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun StandardChipIconWithProgressInProgressPreview() {
StandardChipIconWithProgress(progress = 75f)
}
@Preview(
name = "With 75 percent download complete with large icon",
group = "Variants",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun StandardChipIconWithProgressInProgressLargeIconPreview() {
StandardChipIconWithProgress(
progress = 75f,
icon = Icon48dp,
largeIcon = true
)
}
@Preview(
name = "With 75 percent download complete with medium icon",
group = "Variants",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun StandardChipIconWithProgressInProgressMediumIconPreview() {
StandardChipIconWithProgress(progress = 75f, icon = Icon32dp)
}
@Preview(
name = "With 75 percent download complete with small icon",
group = "Variants",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun StandardChipIconWithProgressInProgressSmallIconPreview() {
StandardChipIconWithProgress(progress = 75f, icon = Icon12dp)
}
private val Icon12dp: ImageVector
get() = ImageVector.Builder(
name = "Icon Small",
defaultWidth = 12f.dp,
defaultHeight = 12f.dp,
viewportWidth = 12f,
viewportHeight = 12f
)
.materialPath {
horizontalLineToRelative(12.0f)
verticalLineToRelative(12.0f)
horizontalLineTo(0.0f)
close()
}
.build()
private val Icon32dp: ImageVector
get() = ImageVector.Builder(
name = "Icon Large",
defaultWidth = 32f.dp,
defaultHeight = 32f.dp,
viewportWidth = 32f,
viewportHeight = 32f
)
.materialPath {
horizontalLineToRelative(32.0f)
verticalLineToRelative(32.0f)
horizontalLineTo(0.0f)
close()
}
.build()
private val Icon48dp: ImageVector
get() = ImageVector.Builder(
name = "Icon Extra Large",
defaultWidth = 48f.dp,
defaultHeight = 48f.dp,
viewportWidth = 48f,
viewportHeight = 48f
)
.materialPath {
horizontalLineToRelative(48.0f)
verticalLineToRelative(48.0f)
horizontalLineTo(0.0f)
close()
}
.build()
| apache-2.0 | 0ed4357d91f8496e6c28cf0e50b1560c | 27.067669 | 76 | 0.682561 | 4.428233 | false | false | false | false |
ScienceYuan/WidgetNote | app/src/main/java/com/rousci/androidapp/widgetnote/model/NotesDatabaseHelper.kt | 1 | 1511 | package com.rousci.androidapp.widgetnote.model
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*
/**
* Created by rousci on 17-10-11.
* a standard anko databaseHelper
* anko is simple to use
* I do not want to dear with complex api of tools
* so I choose it
*/
class NotesDatabaseHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, databaseName, null, 1) {
/*
* A static synchronized method for thread safe access
* which returns a single instance of NotesDatabaseHelper
*/
companion object {
private var instance: NotesDatabaseHelper? = null
@Synchronized
fun getInstance(ctx: Context): NotesDatabaseHelper {
return if (instance == null) {
instance = NotesDatabaseHelper(ctx.applicationContext)
instance!!
} else {
instance!!
}
}
}
override fun onCreate(dataBase: SQLiteDatabase) {
dataBase.createTable(
noteTableName,
true,
idName to INTEGER + PRIMARY_KEY + AUTOINCREMENT + UNIQUE,
contentName to TEXT + NOT_NULL
)
}
override fun onUpgrade(dataBase: SQLiteDatabase, p1: Int, p2: Int) {
dataBase.dropTable(noteTableName, true)
onCreate(dataBase)
}
}
val Context.database: NotesDatabaseHelper
get() = NotesDatabaseHelper.getInstance(this)
data class Note(val id: Int, val content: String)
| mit | ff867bb819b82941074628176d6517e4 | 26.981481 | 95 | 0.644606 | 4.564955 | false | false | false | false |
zensum/franz | src/main/kotlin/producer/kafka_one/KProduceResult.kt | 1 | 495 | package franz.producer.kafka_one
import franz.producer.ProduceResult
import org.apache.kafka.clients.producer.RecordMetadata
class KProduceResult private constructor(private val md: RecordMetadata) : ProduceResult {
override fun offset() = md.offset()
override fun partition() = md.partition()
override fun timestamp() = md.timestamp()
override fun topic() = md.topic()!!
companion object {
fun create(md: RecordMetadata): ProduceResult = KProduceResult(md)
}
} | mit | f9f76e3f8c05348136111003eb636de4 | 34.428571 | 90 | 0.735354 | 4.230769 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/utils/FileDataStore.kt | 1 | 1403 | package me.mrkirby153.KirBot.utils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import me.mrkirby153.kcutils.utils.DataStore
import java.io.File
class FileDataStore<K, V>(private val file: File) : DataStore<K, V> {
private var map = mutableMapOf<K, V>()
private val gson = Gson()
init {
if (!file.exists()) {
file.createNewFile()
file.writeText("{}")
}
load()
}
override fun clear() {
map.clear()
save()
}
override fun containsKey(key: K) = map.containsKey(key)
override fun containsValue(value: V) = map.containsValue(value)
override fun get(key: K): V? = map[key]
override fun remove(key: K): V? {
val v = map.remove(key)
save()
return v
}
override fun set(key: K, value: V): V? {
val v = map.put(key, value)
save()
return v
}
override fun size() = map.size
fun save() {
val json = gson.toJson(map)
file.writer().use {
it.write(json)
it.flush()
}
}
fun values() = map.values.toList()
fun keys() = map.keys.toList()
fun entries() = map.entries.toList()
fun load() {
val typeToken = object : TypeToken<Map<K, V>>() {}.type
file.reader().use {
map = gson.fromJson(it, typeToken)
}
}
}
| mit | 1b4f4ce6214ebef26ab8787b77001d9c | 20.584615 | 69 | 0.548111 | 3.741333 | false | false | false | false |
canou/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/adapters/FilepickerItemsAdapter.kt | 2 | 3424 | package com.simplemobiletools.commons.adapters
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.formatSize
import com.simplemobiletools.commons.extensions.getColoredDrawableWithColor
import com.simplemobiletools.commons.models.FileDirItem
import kotlinx.android.synthetic.main.filepicker_list_item.view.*
class FilepickerItemsAdapter(val context: Context, private val mItems: List<FileDirItem>, val itemClick: (FileDirItem) -> Unit) :
RecyclerView.Adapter<FilepickerItemsAdapter.ViewHolder>() {
companion object {
lateinit var folderDrawable: Drawable
lateinit var fileDrawable: Drawable
var textColor = 0
}
init {
textColor = context.baseConfig.textColor
folderDrawable = context.resources.getColoredDrawableWithColor(R.drawable.ic_folder, textColor)
folderDrawable.alpha = 180
fileDrawable = context.resources.getColoredDrawableWithColor(R.drawable.ic_file, textColor)
fileDrawable.alpha = 180
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.filepicker_list_item, parent, false)
return ViewHolder(context, view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindView(mItems[position])
}
override fun onViewRecycled(holder: ViewHolder?) {
super.onViewRecycled(holder)
holder?.stopLoad()
}
override fun getItemCount() = mItems.size
class ViewHolder(val context: Context, val view: View, val itemClick: (FileDirItem) -> (Unit)) : RecyclerView.ViewHolder(view) {
fun bindView(fileDirItem: FileDirItem) {
itemView.apply {
list_item_name.text = fileDirItem.name
list_item_name.setTextColor(textColor)
if (fileDirItem.isDirectory) {
list_item_icon.setImageDrawable(folderDrawable)
list_item_details.text = getChildrenCnt(fileDirItem)
} else {
val path = fileDirItem.path
val options = RequestOptions().centerCrop().error(fileDrawable)
Glide.with(context).load(path).transition(withCrossFade()).apply(options).into(list_item_icon)
list_item_details.text = fileDirItem.size.formatSize()
}
list_item_details.setTextColor(textColor)
setOnClickListener { itemClick(fileDirItem) }
}
}
private fun getChildrenCnt(item: FileDirItem): String {
val children = item.children
return context.resources.getQuantityString(R.plurals.items, children, children)
}
fun stopLoad() {
try {
Glide.with(context).clear(view.list_item_icon)
} catch (ignored: Exception) {
}
}
}
}
| apache-2.0 | 320869cd0a671cef3188ee63d7f7a5ad | 39.282353 | 132 | 0.685748 | 4.976744 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/logViewer/LogViewerToolbar.kt | 1 | 1087 | package com.garpr.android.features.logViewer
import android.content.Context
import android.util.AttributeSet
import android.view.View.OnClickListener
import com.garpr.android.R
import com.garpr.android.extensions.layoutInflater
import com.garpr.android.features.common.views.GarToolbar
import kotlinx.android.synthetic.main.gar_toolbar.view.*
import kotlinx.android.synthetic.main.log_viewer_toolbar_items.view.*
class LogViewerToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : GarToolbar(context, attrs) {
var isClearEnabled: Boolean
get() = clearButton.isEnabled
set(value) {
clearButton.isEnabled = value
}
var listener: Listener? = null
private val clearClickListener = OnClickListener {
listener?.onClearClick(this)
}
interface Listener {
fun onClearClick(v: LogViewerToolbar)
}
init {
layoutInflater.inflate(R.layout.log_viewer_toolbar_items, menuExpansionContainer)
clearButton.setOnClickListener(clearClickListener)
}
}
| unlicense | 9028f1774a03f43193f8215efa08c6f1 | 27.605263 | 89 | 0.731371 | 4.348 | false | false | false | false |
MaisonWan/AppFileExplorer | FileExplorer/src/main/java/com/domker/app/explorer/fragment/SettingsFragment.kt | 1 | 2150 | package com.domker.app.explorer.fragment
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.preference.ListPreference
import android.preference.Preference
import android.preference.PreferenceFragment
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import com.domker.app.explorer.R
import com.domker.app.explorer.helper.SettingsHelper.Companion.KEY_FILE_SORT
import com.domker.app.explorer.util.hideMenu
/**
* 设置
* Created by wanlipeng on 2017/9/3.
*/
class SettingsFragment : PreferenceFragment(), IActionFragment {
private lateinit var mListPreference: ListPreference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.fe_settings_layout)
mListPreference = findPreference(KEY_FILE_SORT) as ListPreference
mListPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
loadFileSortType()
false
}
setHasOptionsMenu(true)
}
override fun onResume() {
super.onResume()
loadFileSortType()
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
menu?.hideMenu()
}
private fun loadFileSortType() {
val defaultValue = getString(R.string.fe_settings_sort_default_value)
val value = preferenceManager.sharedPreferences.getString(KEY_FILE_SORT, defaultValue)
val names = resources.getStringArray(R.array.file_sort_name)
val index = Math.max(mListPreference.findIndexOfValue(value), 0) // 防止找不到-1越界
mListPreference.summary = names[index]
}
override fun init(context: Context, view: View) {
}
override fun initAssistButtonDrawable(context: Context): Drawable? = null
override fun onAssistButtonClick(view: View) {
// ignore
}
override fun onShown(context: Context) {
}
override fun initLayoutId(): Int = 0
override fun onBackPressed(): Boolean = false
} | apache-2.0 | cf25ca1e54670cdf5a37cf96865a8b0f | 29.042254 | 94 | 0.724203 | 4.56531 | false | false | false | false |
JanYoStudio/WhatAnime | app/src/main/java/pw/janyo/whatanime/ui/activity/HistoryActivity.kt | 1 | 9297 | package pw.janyo.whatanime.ui.activity
import androidx.activity.viewModels
import androidx.compose.animation.*
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FractionalThreshold
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.DeleteSweep
import androidx.compose.material.icons.outlined.TipsAndUpdates
import androidx.compose.material.rememberSwipeableState
import androidx.compose.material.swipeable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.SubcomposeAsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import pw.janyo.whatanime.R
import pw.janyo.whatanime.base.BaseComposeActivity
import pw.janyo.whatanime.model.AnimationHistory
import pw.janyo.whatanime.ui.theme.Icons
import pw.janyo.whatanime.utils.getCalendarFromLong
import pw.janyo.whatanime.utils.toDateTimeString
import pw.janyo.whatanime.viewModel.HistoryViewModel
import java.io.File
import java.text.DecimalFormat
import kotlin.math.roundToInt
class HistoryActivity : BaseComposeActivity() {
private val viewModel: HistoryViewModel by viewModels()
@OptIn(ExperimentalMaterial3Api::class)
@Composable
override fun BuildContent() {
val listState by viewModel.historyListState.collectAsState()
val selectedList = remember { mutableStateListOf<Int>() }
val selectedMode by remember { derivedStateOf { selectedList.isNotEmpty() } }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text(text = title.toString()) },
navigationIcon = {
IconButton(onClick = {
finish()
}) {
Icons(Icons.Filled.ArrowBack)
}
},
actions = {
IconButton(onClick = {
R.string.hint_swipe_to_delete.toast()
}) {
Icons(Icons.Outlined.TipsAndUpdates)
}
}
)
},
floatingActionButton = {
AnimatedVisibility(
visible = selectedMode,
enter = slideInVertically(initialOffsetY = { it }),
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut()
) {
FloatingActionButton(onClick = {
viewModel.deleteHistory(selectedList)
}) {
Icons(Icons.Outlined.DeleteSweep)
}
}
},
) { innerPadding ->
SwipeRefresh(
state = rememberSwipeRefreshState(listState.loading),
onRefresh = { viewModel.refresh() },
modifier = Modifier
.fillMaxHeight()
.padding(innerPadding)
) {
BuildList(listState.list, selectedList)
}
}
}
@Composable
fun BuildList(
list: List<AnimationHistory>,
selectedList: SnapshotStateList<Int>
) {
LazyColumn(
modifier = Modifier
.fillMaxHeight()
.padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(list) { item: AnimationHistory ->
BuildResultItem(
history = item,
selectedList = selectedList,
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun BuildResultItem(
history: AnimationHistory,
selectedList: SnapshotStateList<Int>,
) {
val similarity = "${DecimalFormat("#.0000").format(history.similarity * 100)}%"
val isOldData =
history.episode == "old" || history.similarity == 0.0
fun reverseState() {
if (selectedList.contains(history.id)) {
selectedList.remove(history.id)
} else {
selectedList.add(history.id)
}
}
val cardBorder = if (selectedList.contains(history.id))
BorderStroke(
4.dp,
MaterialTheme.colorScheme.primary
)
else
null
val swipeState = rememberSwipeableState(0,
confirmStateChange = {
if (it != 0) {
reverseState()
}
false
})
val sizePx = with(LocalDensity.current) { 48.dp.toPx() }
val anchors = mapOf(-sizePx to -1, 0f to 0, sizePx to 1)
Card(
modifier = Modifier
.padding(horizontal = 8.dp)
.pointerInput(Unit) {
detectTapGestures(
onLongPress = { reverseState() },
onTap = {
when {
selectedList.isNotEmpty() ->
reverseState()
isOldData ->
R.string.hint_data_convert_no_detail_in_history.toast(true)
else ->
intentTo(
DetailActivity::class,
DetailActivity.showDetail(history)
)
}
},
)
}
.swipeable(
state = swipeState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
),
border = cardBorder,
shape = RoundedCornerShape(8.dp),
) {
Row(
modifier = Modifier
.padding(8.dp)
.offset { IntOffset(swipeState.offset.value.roundToInt(), 0) }
) {
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(File(history.cachePath))
.memoryCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.DISABLED)
.build(),
contentDescription = null,
modifier = Modifier
.height(90.dp)
.width(160.dp),
)
Column(modifier = Modifier.padding(horizontal = 8.dp)) {
BuildText(stringResource(R.string.history_hint_save_time))
BuildText(stringResource(R.string.history_hint_native_title), FontWeight.Bold)
if (!isOldData) {
BuildText(stringResource(R.string.history_hint_ani_list_id))
}
if (!isOldData) {
BuildText(stringResource(R.string.history_hint_similarity), FontWeight.Bold)
}
}
Column(
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxWidth()
) {
BuildText(history.time.getCalendarFromLong().toDateTimeString())
BuildText(history.title, FontWeight.Bold)
if (!isOldData) {
BuildText(history.anilistId.toString())
}
if (!isOldData) {
BuildText(similarity, FontWeight.Bold)
}
}
}
}
}
@Composable
fun BuildText(text: String, fontWeight: FontWeight? = null) {
Text(
text = text,
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontWeight = fontWeight
)
}
}
| apache-2.0 | 69ad6a69792eaf463099b99577805fe9 | 36.639676 | 100 | 0.534796 | 5.530637 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.