repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dragbone/slacking-pizzabot | src/main/kotlin/com/dragbone/pizzabot/PizzaVoteParser.kt | 1 | 2237 | package com.dragbone.pizzabot
import java.text.ParseException
class PizzaVoteParser {
companion object {
private val dayMap: Map<String, DayOfWeek> = mapOf(
"mo" to DayOfWeek.MONDAY,
"di" to DayOfWeek.TUESDAY,
"tu" to DayOfWeek.TUESDAY,
"mi" to DayOfWeek.WEDNESDAY,
"we" to DayOfWeek.WEDNESDAY,
"do" to DayOfWeek.THURSDAY,
"th" to DayOfWeek.THURSDAY,
"fr" to DayOfWeek.FRIDAY,
"sa" to DayOfWeek.SATURDAY,
"so" to DayOfWeek.SUNDAY,
"su" to DayOfWeek.SUNDAY
)
val noneList: Set<String> = setOf("none", "null", "{}", "()", "[]", "nada", "never", "nope", ":-(", ":'-(")
}
fun mapToDay(day: String): DayOfWeek = dayMap[day.toLowerCase().substring(0, 2)]!!
fun parsePizzaVote(input: String): Set<Vote> {
if (noneList.contains(input.trim()))
return emptySet()
//remove all superfluous whitespace
val cleanInput = input.replace(Regex("\\s*-\\s*"), "-").replace(Regex("\\(\\s*"), "(").replace(Regex("\\s*\\)"), ")")
// Split on whitespaces and comma and remove all empty sections
val sections = cleanInput.split(Regex("[\\s,]")).filter { it.length > 0 }
// Map sections to votes
val votes = sections.flatMap { parsePizzaVoteSection(it) }
if (votes.groupBy { it.day }.any { it.value.count() > 1 })
throw IllegalArgumentException("You can't fool me with your double votes!")
return votes.toSet()
}
private fun parsePizzaVoteSection(input: String): Iterable<Vote> {
val strength = if (input.matches(Regex("\\(.+\\)"))) 0.5f else 1f
val trimmed = input.trim('(', ')')
if (trimmed.contains('-')) {
val startEnd = trimmed.split('-')
val start = mapToDay(startEnd[0])
val end = mapToDay(startEnd[1])
if (start >= end)
throw ParseException("End before start in '$input'", 0)
return (start.ordinal..end.ordinal).map { Vote(DayOfWeek.of(it), strength) }
}
return listOf(Vote(mapToDay(trimmed), strength))
}
}
| apache-2.0 | 785c0a0e669e0709a392583e34acac17 | 40.425926 | 125 | 0.554761 | 4.181308 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckbuild/DeckRepository.kt | 1 | 9765 | package com.bachhuberdesign.deckbuildergwent.features.deckbuild
import android.content.ContentValues
import com.bachhuberdesign.deckbuildergwent.features.shared.exception.CardException
import com.bachhuberdesign.deckbuildergwent.features.shared.exception.DeckException
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card
import com.bachhuberdesign.deckbuildergwent.features.shared.model.CardType
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction
import com.bachhuberdesign.deckbuildergwent.features.stattrack.Match
import com.bachhuberdesign.deckbuildergwent.inject.annotation.PersistedScope
import com.squareup.sqlbrite.BriteDatabase
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.text.Normalizer
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
/**
* Helper class which contains functions that pertain to SQLite [Deck] queries and persistence.
*
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
@PersistedScope
class DeckRepository
@Inject constructor(val database: BriteDatabase) {
companion object {
@JvmStatic val TAG: String = DeckRepository::class.java.name
}
/**
* Checks if a given [deckName] has been persisted in the database.
*
* @return True if a deck with [deckName] is persisted. False if no deck with [deckName] is persisted.
*/
fun deckNameExists(deckName: String): Boolean {
var normalizedDeckName = Normalizer.normalize(deckName, Normalizer.Form.NFD).replace("[^\\p{ASCII}]", "")
normalizedDeckName = normalizedDeckName.replace("'", "''")
val count = database.readableDatabase.compileStatement("SELECT COUNT(*) FROM ${Deck.TABLE} WHERE ${Deck.NAME} = '$normalizedDeckName';")
return count.simpleQueryForLong() > 0
}
/**
* @return [Deck]
*/
fun getDeckById(deckId: Int): Deck? {
if (deckId <= 0) {
throw DeckException("Expected a valid deck id but received $deckId.")
}
val deckCursor = database.query("SELECT * FROM ${Deck.TABLE} WHERE ${Deck.ID} = $deckId")
var deck: Deck? = null
deckCursor.use {
while (deckCursor.moveToNext()) {
deck = Deck.MAPPER.apply(deckCursor)
}
}
if (deck == null) {
throw DeckException("Unable to load deck $deckId")
} else {
deck!!.leader = getLeaderCardForDeck(deck!!.leaderId)
deck!!.cards = getCardsForDeck(deckId)
}
return deck
}
/**
*
* @return [Deck]
*/
fun getMostRecentDeck(): Deck? {
val cursor = database.query("SELECT * FROM ${Deck.TABLE} " +
"ORDER BY last_update DESC " +
"LIMIT 1")
cursor.use { cursor ->
if (cursor.moveToNext()) {
return Deck.MAPPER.apply(cursor)
} else {
return null
}
}
}
/**
*
*/
fun observeRecentlyUpdatedDecks(): Observable<MutableList<Deck>> {
val query = "SELECT * FROM ${Deck.TABLE} " +
"ORDER BY last_update DESC " +
"LIMIT 5"
return database.createQuery(Deck.TABLE, query)
.mapToList(Deck.MAP1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
/**
*
*/
fun observeCardUpdates(deckId: Int): Observable<MutableList<Card>> {
val tables: MutableList<String> = arrayListOf(Card.TABLE, "user_decks_cards")
val query: String = "SELECT * FROM ${Card.TABLE} " +
"JOIN user_decks_cards as t2 " +
"ON ${Card.ID} = t2.card_id " +
"WHERE t2.deck_id = $deckId"
return database.createQuery(tables, query)
.mapToList(Card.MAP1)
.skip(1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
/**
*
*/
fun getCardsForDeck(deckId: Int): MutableList<Card> {
val cursor = database.query("SELECT * FROM ${Card.TABLE} " +
"JOIN user_decks_cards as t2 " +
"ON ${Card.ID} = t2.card_id " +
"WHERE t2.deck_id = $deckId")
val cards: MutableList<Card> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
cards.add(Card.MAPPER.apply(cursor))
}
}
return cards
}
/**
* @return [Card]
*/
private fun getLeaderCardForDeck(leaderCardId: Int): Card {
val cursor = database.query("SELECT * FROM ${Card.TABLE} WHERE ${Card.ID} = $leaderCardId")
cursor.use { cursor ->
while (cursor.moveToNext()) {
return Card.MAPPER.apply(cursor)
}
}
throw CardException("Leader $leaderCardId not found.")
}
/**
* @return
*/
fun getAllUserCreatedDecks(): List<Deck> {
val cursor = database.query("SELECT * FROM ${Deck.TABLE}")
val decks: MutableList<Deck> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
decks.add(Deck.MAPPER.apply(cursor))
}
}
decks.forEach { deck ->
deck.leader = getLeaderCardForDeck(deck.id)
}
return decks
}
/**
* @return [Int]
*/
fun countUserDecksWithLeader(leaderCardId: Int): Int {
val cursor = database.query("SELECT * FROM ${Deck.TABLE} " +
"WHERE ${Deck.LEADER_ID} = $leaderCardId")
cursor.use { cursor ->
return cursor.count
}
}
/**
*
*/
fun getFactions(): List<Faction> {
val factions: MutableList<Faction> = ArrayList()
val factionsCursor = database.query("SELECT * FROM ${Faction.TABLE}")
factionsCursor.use {
while (factionsCursor.moveToNext()) {
factions.add(Faction.MAPPER.apply(factionsCursor))
}
}
factions.forEach { faction ->
faction.leaders = getLeadersForFaction(faction.id) as MutableList<Card>
}
return factions
}
/**
*
*/
fun getLeadersForFaction(factionId: Int): List<Card> {
val cursor = database.query("SELECT * FROM ${Card.TABLE} " +
"WHERE ${Card.TYPE} = ${CardType.LEADER} " +
"AND ${Card.FACTION} = $factionId")
val leaders: MutableList<Card> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
leaders.add(Card.MAPPER.apply(cursor))
}
}
return leaders
}
/**
*
*/
fun saveDeck(deck: Deck): Int {
val currentTime = Date().time
val deckValues = ContentValues()
deckValues.put(Deck.NAME, deck.name)
deckValues.put(Deck.FACTION, deck.faction)
deckValues.put(Deck.LEADER_ID, deck.leader!!.cardId)
deckValues.put(Deck.FAVORITED, deck.isFavorited)
deckValues.put(Deck.LAST_UPDATE, currentTime)
if (deck.id == 0) {
deckValues.put(Deck.CREATED_DATE, currentTime)
deck.id = database.insert(Deck.TABLE, deckValues).toInt()
} else {
database.update(Deck.TABLE, deckValues, "${Deck.ID} = ${deck.id}")
}
return deck.id
}
/**
*
*/
fun updateLeaderForDeck(deckId: Int, leaderId: Int) {
val deckValues = ContentValues()
deckValues.put(Deck.LEADER_ID, leaderId)
database.update(Deck.TABLE, deckValues, "${Deck.ID} = $deckId")
}
/**
*
*/
fun addCardToDeck(card: Card, deckId: Int) {
val values = ContentValues()
values.put("card_id", card.cardId)
values.put("deck_id", deckId)
if (card.selectedLane > 0) {
values.put(Card.SELECTED_LANE, card.selectedLane)
} else {
values.put(Card.SELECTED_LANE, card.lane)
}
database.insert(Deck.JOIN_CARD_TABLE, values)
saveDeckLastUpdateTime(deckId)
}
/**
*
*/
fun renameDeck(newDeckName: String, deckId: Int) {
val values = ContentValues()
values.put(Deck.NAME, newDeckName)
database.update(Deck.TABLE, values, "${Deck.ID} = $deckId")
}
/**
*
*/
fun removeCardFromDeck(card: Card, deckId: Int) {
val query: String
if (card.selectedLane == 0) {
query = "join_id = " +
"(SELECT MIN(join_id) " +
"FROM user_decks_cards " +
"WHERE deck_id = $deckId " +
"AND card_id = ${card.cardId})"
} else {
query = "join_id = " +
"(SELECT MIN(join_id) " +
"FROM user_decks_cards " +
"WHERE deck_id = $deckId " +
"AND card_id = ${card.cardId} " +
"AND ${Card.SELECTED_LANE} = ${card.selectedLane})"
}
database.delete(Deck.JOIN_CARD_TABLE, query)
saveDeckLastUpdateTime(deckId)
}
/**
*
*/
fun deleteDeck(deckId: Int) {
database.delete(Deck.JOIN_CARD_TABLE, "deck_id = $deckId")
database.delete(Deck.TABLE, "${Deck.ID} = $deckId")
database.delete(Match.TABLE, "${Match.DECK_ID} = $deckId")
}
private fun saveDeckLastUpdateTime(deckId: Int) {
val deckValues = ContentValues()
deckValues.put(Deck.LAST_UPDATE, Date().time)
database.update(Deck.TABLE, deckValues, "${Deck.ID} = $deckId")
}
} | apache-2.0 | 624941485735d399c931515136a4a607 | 28.239521 | 144 | 0.56682 | 4.277267 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/widget/ProjectFeedWidgetConfigureProjectActivity.kt | 2 | 2034 | package com.commit451.gitlab.widget
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.BaseActivity
import com.commit451.gitlab.adapter.ProjectsPagerAdapter
import com.commit451.gitlab.api.GitLab
import com.commit451.gitlab.api.GitLabFactory
import com.commit451.gitlab.api.GitLabService
import com.commit451.gitlab.api.OkHttpClientFactory
import com.commit451.gitlab.fragment.ProjectsFragment
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.model.api.Project
import kotlinx.android.synthetic.main.activity_project_feed_widget_configure.*
/**
* You chose your account, now choose your project!
*/
class ProjectFeedWidgetConfigureProjectActivity : BaseActivity(), ProjectsFragment.Listener {
companion object {
const val EXTRA_PROJECT = "project"
const val EXTRA_ACCOUNT = "account"
fun newIntent(context: Context, account: Account): Intent {
val intent = Intent(context, ProjectFeedWidgetConfigureProjectActivity::class.java)
intent.putExtra(EXTRA_ACCOUNT, account)
return intent
}
}
private lateinit var gitLabInstance: GitLab
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_project_feed_widget_configure)
val account = intent.getParcelableExtra<Account>(EXTRA_ACCOUNT)!!
gitLabInstance = GitLabFactory.createGitLab(account, OkHttpClientFactory.create(account, false))
viewPager.adapter = ProjectsPagerAdapter(this, supportFragmentManager)
tabLayout.setupWithViewPager(viewPager)
}
override fun onProjectClicked(project: Project) {
val data = Intent()
data.putExtra(EXTRA_PROJECT, project)
setResult(Activity.RESULT_OK, data)
finish()
}
override fun providedGitLab(): GitLab {
return gitLabInstance
}
}
| apache-2.0 | d1a64f3cb09997af1ae5cc4671361eab | 33.474576 | 104 | 0.748771 | 4.560538 | false | true | false | false |
GaryMcGowan/Moviepedia | app/src/main/java/com/garymcgowan/moviepedia/view/search/MovieListAdapter.kt | 1 | 2550 | package com.garymcgowan.moviepedia.view.search
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.navigation.Navigation
import com.garymcgowan.moviepedia.R
import com.garymcgowan.moviepedia.model.Movie
import com.garymcgowan.moviepedia.view.details.MovieDetailsFragment
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_movie.view.*
class MovieListAdapter(private val movieList: List<Movie>?, private val favCallback: (Movie) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie, parent, false)
// RxView.clicks(view)
// .map(v -> vh.getAdapterPosition())
// .subscribe(onClickSubject);
return ViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMovie = movieList!![position]
when (holder) {
is ViewHolder -> {
//set movie title
holder.titleTextView.text = currentMovie.titleYear()
//load image with Picasso
Picasso.with(holder.parentView.context).load(currentMovie.posterURL).placeholder(R.color.imagePlaceholder).error(R.color.imagePlaceholder).into(holder.posterImageView)
holder.parentView.setOnClickListener { v ->
Navigation.findNavController(v)
.navigate(
R.id.navigation_details,
MovieDetailsFragment.safeArgs(currentMovie.imdbID, currentMovie.title)
)
}
holder.favouriteButton.setOnClickListener {
favCallback.invoke(currentMovie)
}
}
}
}
override fun getItemCount(): Int {
return movieList?.size ?: 0
}
internal class ViewHolder(val parentView: View) : RecyclerView.ViewHolder(parentView) {
var titleTextView: TextView = parentView.titleTextView
var posterImageView: ImageView = parentView.posterImageView
var favouriteButton: View = parentView.favourite_button
}
}
| apache-2.0 | 92a5ce0e01094ccd7bcf001d94149a38 | 38.230769 | 183 | 0.661569 | 5.1 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/swing/SwingHtmlPanelProvider.kt | 1 | 1656 | // Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.swing
import com.intellij.openapi.project.Project
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.HtmlPanelHost
import com.vladsch.md.nav.editor.resources.SwingHtmlGeneratorProvider
import com.vladsch.md.nav.editor.util.HtmlCompatibility
import com.vladsch.md.nav.editor.util.HtmlPanel
import com.vladsch.md.nav.editor.util.HtmlPanelProvider
import com.vladsch.md.nav.settings.MdPreviewSettings
object SwingHtmlPanelProvider : HtmlPanelProvider() {
val NAME = MdBundle.message("editor.swing.html.panel.provider.name")
val ID = "com.vladsch.md.nav.editor.swing.html.panel"
override val INFO = HtmlPanelProvider.Info(ID, NAME)
override val COMPATIBILITY = HtmlCompatibility(ID, 3f, 1f, 0f, arrayOf(SwingHtmlGeneratorProvider.ID), arrayOf<String>())
override fun isSupportedSetting(settingName: String): Boolean {
return when (settingName) {
MdPreviewSettings.MAX_IMAGE_WIDTH -> true
MdPreviewSettings.ZOOM_FACTOR -> true
// FIX: sync preview work for swing browser
MdPreviewSettings.SYNCHRONIZE_PREVIEW_POSITION -> false
else -> false
}
}
override fun createHtmlPanel(project: Project, htmlPanelHost: HtmlPanelHost): HtmlPanel {
return SwingHtmlPanel(project, htmlPanelHost)
}
override val isAvailable: HtmlPanelProvider.AvailabilityInfo
get() = HtmlPanelProvider.AvailabilityInfo.AVAILABLE
}
| apache-2.0 | ab3080f69835b56de6e8c713526d190f | 46.314286 | 177 | 0.751812 | 4.3125 | false | false | false | false |
toastkidjp/Yobidashi_kt | loan/src/main/java/jp/toastkid/loan/usecase/DebouncedCalculatorUseCase.kt | 1 | 1773 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.loan.usecase
import jp.toastkid.loan.Calculator
import jp.toastkid.loan.model.Factor
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
class DebouncedCalculatorUseCase(
private val inputChannel: Channel<String>,
private val currentFactorProvider: () -> Factor,
private val onResult: (Long) -> Unit,
private val calculator: Calculator = Calculator(),
private val debounceMillis: Long = 1000,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
@FlowPreview
operator fun invoke() {
CoroutineScope(ioDispatcher).launch {
inputChannel
.receiveAsFlow()
.distinctUntilChanged()
.debounce(debounceMillis)
.flowOn(mainDispatcher)
.collect {
val factor = currentFactorProvider()
val payment = calculator(factor)
onResult(payment)
}
}
}
} | epl-1.0 | 72a11e8352c970ed9055ba8312fa600e | 33.115385 | 88 | 0.712916 | 5.051282 | false | false | false | false |
rei-m/android_hyakuninisshu | state/src/main/java/me/rei_m/hyakuninisshu/state/question/action/AnswerQuestionAction.kt | 1 | 1216 | /*
* Copyright (c) 2020. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hyakuninisshu.state.question.action
import me.rei_m.hyakuninisshu.state.core.Action
import me.rei_m.hyakuninisshu.state.question.model.QuestionState
/**
* 問題に回答したアクション.
*/
sealed class AnswerQuestionAction(override val error: Throwable? = null) : Action {
class Success(val state: QuestionState.Answered) : AnswerQuestionAction() {
override fun toString() = "$name(state=$state)"
}
class Failure(error: Throwable) : AnswerQuestionAction(error) {
override fun toString() = "$name(error=$error)"
}
override val name = "AnswerQuestionAction"
}
| apache-2.0 | 6c639b831854f51ce48f35afea06938c | 35.121212 | 112 | 0.73406 | 4.09622 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/json/Entities.kt | 1 | 3239 | package cs.ut.json
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import cs.ut.configuration.ConfigurationReader
import cs.ut.engine.item.ModelParameter
import cs.ut.util.Algorithm
import cs.ut.util.Node
enum class JSONKeys(val value: String) {
UI_DATA("ui_data"),
EVALUATION("evaluation"),
OWNER("job_owner"),
LOG_FILE("log_file"),
START("start_time"),
METRIC("metric"),
VALUE("value")
}
data class TrainingConfiguration(
@get:JsonIgnore val encoding: ModelParameter,
@get:JsonIgnore val bucketing: ModelParameter,
@get:JsonIgnore val learner: ModelParameter,
@get:JsonIgnore val outcome: ModelParameter
) {
lateinit var info: JobInformation
@JsonIgnore get
lateinit var evaluation: Report
@JsonIgnore get
@JsonAnyGetter
fun getProperties(): Map<String, Any> {
fun String.safeConvert(): Number = this.toIntOrNull() ?: this.toFloat()
val map = mutableMapOf<String, Any>()
val learnerMap = mutableMapOf<String, Any>()
if (bucketing.id == Algorithm.PREFIX.value) {
val propMap = mutableMapOf<String, Any>()
learner.properties.forEach { propMap[it.id] = it.property.safeConvert() }
val node = ConfigurationReader.findNode("models/parameters/prefix_length_based").
valueWithIdentifier(Node.EVENT_NUMBER.value).value<Int>()
for (i in 1..node) {
learnerMap[i.toString()] = propMap
}
} else {
learner.properties.forEach { learnerMap[it.id] = it.property.safeConvert() }
}
val encodingMap = mapOf<String, Any>(learner.parameter to learnerMap)
val bucketingMap = mapOf<String, Any>(encoding.parameter to encodingMap)
val targetMap = mapOf<String, Any>(bucketing.parameter to bucketingMap)
map[outcome.parameter] = targetMap
map[JSONKeys.UI_DATA.value] = JSONHandler().toMap(info)
return map
}
}
data class JobInformation(
@field:JsonProperty(value = "job_owner") var owner: String,
@field:JsonProperty(value = "log_file") var logFile: String,
@field:JsonProperty(value = "start_time") var startTime: String
) {
constructor() : this("", "", "")
}
class Report {
var metric: String = ""
var value: Double = 0.0
}
class TrainingData {
@JsonProperty(value = "static_cat_cols")
var staticCategorical = listOf<String>()
@JsonProperty(value = "dynamic_cat_cols")
var dynamicCategorical = listOf<String>()
@JsonProperty(value = "static_num_cols")
var staticNumeric = listOf<String>()
@JsonProperty(value = "dynamic_num_cols")
var dynamicNumeric = listOf<String>()
@JsonProperty(value = "case_id_col")
var caseId = ""
@JsonProperty(value = "activity_col")
var activity = ""
@JsonProperty(value = "timestamp_col")
var timestamp = ""
@JsonProperty(value = "future_values")
var futureValues = listOf<String>()
fun getAllColumns(): List<String> = ((staticCategorical + staticNumeric + futureValues).toList() - activity)
} | lgpl-3.0 | ce8a2bfcfa6f5503f697e98ec813beea | 29.566038 | 112 | 0.658537 | 4.115629 | false | false | false | false |
squins/ooverkommelig | main/src/commonMain/kotlin/org/ooverkommelig/graph/UninitializedObjectGraphState.kt | 1 | 1577 | package org.ooverkommelig.graph
import org.ooverkommelig.definition.ObjectCreatingDefinition
internal class UninitializedObjectGraphState : FollowingObjectGraphState {
private lateinit var graph: ObjectGraphImpl
override fun enter(graph: ObjectGraphImpl) {
this.graph = graph
try {
runSetUpOfObjectlessLifecycles()
graph.transition(InitializedObjectGraphState())
} catch (exception: Exception) {
graph.transition(DisposingObjectGraphState())
throw exception
}
}
private fun runSetUpOfObjectlessLifecycles() {
graph.objectlessLifecycles.forEach { lifecycle ->
lifecycle.init()
graph.objectlessLifecyclesOfWhichSetUpHasRun += lifecycle
}
}
override fun creationStarted(definition: ObjectCreatingDefinition<*>, argument: Any?) = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun <TObject> creationEnded(definition: ObjectCreatingDefinition<TObject>, argument: Any?, createdObject: TObject?) = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun creationFailed() = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun logCleanUpError(sourceObject: Any, operation: String, exception: Exception) = throw UnsupportedOperationException("Cannot clean up sub graphs and objects while uninitialized.")
override fun dispose() {
graph.transition(DisposedObjectGraphState())
}
}
| mit | bd75a61886fc0ad236934aa605edecb8 | 40.5 | 212 | 0.73811 | 5.840741 | false | false | false | false |
jeffcharles/visitor-detector | app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/AlarmSchedulingHelperImpl.kt | 1 | 1549 | package com.beyondtechnicallycorrect.visitordetector
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import com.beyondtechnicallycorrect.visitordetector.broadcastreceivers.AlarmReceiver
import org.joda.time.DateTime
import org.joda.time.LocalTime
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class AlarmSchedulingHelperImpl @Inject constructor(
val alarmManager: AlarmManager,
@Named("applicationContext") val applicationContext: Context
) : AlarmSchedulingHelper {
override fun setupAlarm() {
Timber.v("Setting up alarm")
val intent = Intent(applicationContext, AlarmReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val now = DateTime()
val timeToExecute = LocalTime(23, 0)
val isCloseToOrAfterTimeToExecute = now.isAfter(now.withTime(timeToExecute).minusSeconds(15))
val nextTimeToExecute =
if (isCloseToOrAfterTimeToExecute)
now.plusDays(1).withTime(timeToExecute)
else
now.withTime(timeToExecute)
Timber.d("Setting alarm for %s", nextTimeToExecute)
val nextTimeToExecuteMillis = nextTimeToExecute.millis
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTimeToExecuteMillis,
pendingIntent
)
}
}
| mit | f2d7549e1f16bf3b170a23767a9f0e74 | 37.725 | 104 | 0.730148 | 5.112211 | false | false | false | false |
premisedata/cameraview | demo/src/main/kotlin/com/otaliastudios/cameraview/demo/VideoPreviewActivity.kt | 1 | 4323 | package com.otaliastudios.cameraview.demo
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.MediaController
import android.widget.Toast
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.otaliastudios.cameraview.VideoResult
import com.otaliastudios.cameraview.size.AspectRatio
class VideoPreviewActivity : AppCompatActivity() {
companion object {
var videoResult: VideoResult? = null
}
private val videoView: VideoView by lazy { findViewById<VideoView>(R.id.video) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video_preview)
val result = videoResult ?: run {
finish()
return
}
videoView.setOnClickListener { playVideo() }
val actualResolution = findViewById<MessageView>(R.id.actualResolution)
val isSnapshot = findViewById<MessageView>(R.id.isSnapshot)
val rotation = findViewById<MessageView>(R.id.rotation)
val audio = findViewById<MessageView>(R.id.audio)
val audioBitRate = findViewById<MessageView>(R.id.audioBitRate)
val videoCodec = findViewById<MessageView>(R.id.videoCodec)
val audioCodec = findViewById<MessageView>(R.id.audioCodec)
val videoBitRate = findViewById<MessageView>(R.id.videoBitRate)
val videoFrameRate = findViewById<MessageView>(R.id.videoFrameRate)
val ratio = AspectRatio.of(result.size)
actualResolution.setTitleAndMessage("Size", "${result.size} ($ratio)")
isSnapshot.setTitleAndMessage("Snapshot", result.isSnapshot.toString())
rotation.setTitleAndMessage("Rotation", result.rotation.toString())
audio.setTitleAndMessage("Audio", result.audio.name)
audioBitRate.setTitleAndMessage("Audio bit rate", "${result.audioBitRate} bits per sec.")
videoCodec.setTitleAndMessage("VideoCodec", result.videoCodec.name)
audioCodec.setTitleAndMessage("AudioCodec", result.audioCodec.name)
videoBitRate.setTitleAndMessage("Video bit rate", "${result.videoBitRate} bits per sec.")
videoFrameRate.setTitleAndMessage("Video frame rate", "${result.videoFrameRate} fps")
val controller = MediaController(this)
controller.setAnchorView(videoView)
controller.setMediaPlayer(videoView)
videoView.setMediaController(controller)
videoView.setVideoURI(Uri.fromFile(result.file))
videoView.setOnPreparedListener { mp ->
val lp = videoView.layoutParams
val videoWidth = mp.videoWidth.toFloat()
val videoHeight = mp.videoHeight.toFloat()
val viewWidth = videoView.width.toFloat()
lp.height = (viewWidth * (videoHeight / videoWidth)).toInt()
videoView.layoutParams = lp
playVideo()
if (result.isSnapshot) {
// Log the real size for debugging reason.
Log.e("VideoPreview", "The video full size is " + videoWidth + "x" + videoHeight)
}
}
}
fun playVideo() {
if (!videoView.isPlaying) {
videoView.start()
}
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
videoResult = null
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.share, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.share) {
Toast.makeText(this, "Sharing...", Toast.LENGTH_SHORT).show()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "video/*"
val uri = FileProvider.getUriForFile(this,
this.packageName + ".provider",
videoResult!!.file)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | 7d25e5a3055001312ad502086b715fe0 | 39.411215 | 97 | 0.667129 | 4.929304 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/extension/PlayerExtensions.kt | 1 | 1679 | package me.sweetll.tucao.extension
import com.shuyu.gsyvideoplayer.video.PreviewGSYVideoPlayer
import me.sweetll.tucao.AppApplication
import me.sweetll.tucao.model.xml.Durl
import java.io.File
import java.io.FileOutputStream
fun PreviewGSYVideoPlayer.setUp(durls: MutableList<Durl>, cache: Boolean, vararg objects: Any) {
/*
* 使用concat协议拼接多段视频
*/
try {
val outputFile = File.createTempFile("tucao", ".concat", AppApplication.get().cacheDir)
val outputStream = FileOutputStream(outputFile)
val concatContent = buildString {
appendln("ffconcat version 1.0")
for (durl in durls) {
appendln("file '${if (cache) durl.getCacheAbsolutePath() else durl.url}'")
appendln("duration ${durl.length / 1000f}")
}
}
// val concatContent = buildString {
// appendln("ffconcat version 1.0")
// appendln("file 'http://58.216.103.180/youku/697354F8AE94983EA216016D28/0300010900553A4D76DD1718581209B15F3A81-E563-D647-2FC4-06C5A8F05A9A.flv?sid=048412648117712c2f3d3_00&ctype=12'")
// appendln("duration 200.992")
// appendln("file 'http://222.73.245.134/youku/6772EA596B8368109D3AE55035/0300010901553A4D76DD1718581209B15F3A81-E563-D647-2FC4-06C5A8F05A9A.flv?sid=048412648117712c2f3d3_00&ctype=12'")
// appendln("duration 181.765")
// }
outputStream.write(concatContent.toByteArray())
outputStream.flush()
outputStream.close()
this.setUp(outputFile.absolutePath)
} catch (e: Exception) {
e.message?.toast()
e.printStackTrace()
}
}
| mit | 2404ea90330b39071ade76234e8551f1 | 37.581395 | 196 | 0.667269 | 3.318 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/ui/ImageFragment.kt | 1 | 30157 | package me.panpf.sketch.sample.ui
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.text.format.Formatter
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_image.*
import me.panpf.androidxkt.app.bindBooleanArgOr
import me.panpf.androidxkt.app.bindParcelableArg
import me.panpf.androidxkt.app.bindStringArgOrNull
import me.panpf.sketch.Sketch
import me.panpf.sketch.datasource.DataSource
import me.panpf.sketch.decode.ImageAttrs
import me.panpf.sketch.display.FadeInImageDisplayer
import me.panpf.sketch.drawable.SketchDrawable
import me.panpf.sketch.drawable.SketchGifDrawable
import me.panpf.sketch.drawable.SketchRefBitmap
import me.panpf.sketch.request.*
import me.panpf.sketch.sample.AppConfig
import me.panpf.sketch.sample.R
import me.panpf.sketch.sample.base.BaseFragment
import me.panpf.sketch.sample.base.BindContentView
import me.panpf.sketch.sample.bean.Image
import me.panpf.sketch.sample.event.AppConfigChangedEvent
import me.panpf.sketch.sample.event.RegisterEvent
import me.panpf.sketch.sample.util.ApplyWallpaperAsyncTask
import me.panpf.sketch.sample.util.FixedThreeLevelScales
import me.panpf.sketch.sample.util.SaveImageAsyncTask
import me.panpf.sketch.sample.widget.MappingView
import me.panpf.sketch.sample.widget.SampleImageView
import me.panpf.sketch.state.MemoryCacheStateImage
import me.panpf.sketch.uri.FileUriModel
import me.panpf.sketch.uri.GetDataSourceException
import me.panpf.sketch.uri.UriModel
import me.panpf.sketch.util.SketchUtils
import me.panpf.sketch.zoom.AdaptiveTwoLevelScales
import me.panpf.sketch.zoom.ImageZoomer
import me.panpf.sketch.zoom.Size
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.io.IOException
import java.util.*
@RegisterEvent
@BindContentView(R.layout.fragment_image)
class ImageFragment : BaseFragment() {
private val image by bindParcelableArg<Image>(PARAM_REQUIRED_STRING_IMAGE_URI)
private val loadingImageOptionsKey: String? by bindStringArgOrNull(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY)
private val showTools: Boolean by bindBooleanArgOr(PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS)
private lateinit var finalShowImageUrl: String
private val showHelper = ShowHelper()
private val zoomHelper = ZoomHelper()
private var mappingHelper = MappingHelper()
private val clickHelper = ClickHelper()
private val setWindowBackgroundHelper = SetWindowBackgroundHelper()
private val gifPlayFollowPageVisibleHelper = GifPlayFollowPageVisibleHelper()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activity = activity ?: return
setWindowBackgroundHelper.onCreate(activity)
val showHighDefinitionImage = AppConfig.getBoolean(activity, AppConfig.Key.SHOW_UNSPLASH_RAW_IMAGE)
finalShowImageUrl = if (showHighDefinitionImage) image.rawQualityUrl else image.normalQualityUrl
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
zoomHelper.onViewCreated()
mappingHelper.onViewCreated()
clickHelper.onViewCreated()
showHelper.onViewCreated()
EventBus.getDefault().register(this)
}
override fun onUserVisibleChanged(isVisibleToUser: Boolean) {
zoomHelper.onUserVisibleChanged()
setWindowBackgroundHelper.onUserVisibleChanged()
gifPlayFollowPageVisibleHelper.onUserVisibleChanged()
}
@Suppress("unused")
@Subscribe
fun onEvent(event: AppConfigChangedEvent) {
if (AppConfig.Key.SUPPORT_ZOOM == event.key) {
zoomHelper.onConfigChanged()
mappingHelper.onViewCreated()
} else if (AppConfig.Key.READ_MODE == event.key) {
zoomHelper.onReadModeConfigChanged()
}
}
override fun onDestroyView() {
EventBus.getDefault().unregister(this)
super.onDestroyView()
}
class PlayImageEvent
private inner class ShowHelper {
fun onViewCreated() {
image_imageFragment_image.displayListener = ImageDisplayListener()
image_imageFragment_image.downloadProgressListener = ImageDownloadProgressListener()
initOptions()
image_imageFragment_image.displayImage(finalShowImageUrl)
}
private fun initOptions() {
val activity = activity ?: return
image_imageFragment_image.page = SampleImageView.Page.DETAIL
val options = image_imageFragment_image.options
// 允许播放 GIF
options.isDecodeGifImage = true
// 有占位图选项信息的话就使用内存缓存占位图但不使用任何显示器,否则就是用渐入显示器
if (!TextUtils.isEmpty(loadingImageOptionsKey)) {
val uriModel = UriModel.match(activity, finalShowImageUrl)
var cachedRefBitmap: SketchRefBitmap? = null
var memoryCacheKey: String? = null
if (uriModel != null) {
memoryCacheKey = SketchUtils.makeRequestKey(image.normalQualityUrl, uriModel, loadingImageOptionsKey!!)
cachedRefBitmap = Sketch.with(activity).configuration.memoryCache.get(memoryCacheKey)
}
if (cachedRefBitmap != null && memoryCacheKey != null) {
options.loadingImage = MemoryCacheStateImage(memoryCacheKey, null)
} else {
options.displayer = FadeInImageDisplayer()
}
} else {
options.displayer = FadeInImageDisplayer()
}
}
inner class ImageDisplayListener : DisplayListener {
override fun onStarted() {
if (view == null) {
return
}
hint_imageFragment_hint.loading(null)
}
override fun onCompleted(drawable: Drawable, imageFrom: ImageFrom, imageAttrs: ImageAttrs) {
if (view == null) {
return
}
hint_imageFragment_hint.hidden()
setWindowBackgroundHelper.onDisplayCompleted()
gifPlayFollowPageVisibleHelper.onDisplayCompleted()
}
override fun onError(cause: ErrorCause) {
if (view == null) {
return
}
hint_imageFragment_hint.hint(R.drawable.ic_error, "Image display failed", "Again", View.OnClickListener { image_imageFragment_image.displayImage(finalShowImageUrl) })
}
override fun onCanceled(cause: CancelCause) {
if (view == null) {
return
}
@Suppress("NON_EXHAUSTIVE_WHEN")
when (cause) {
CancelCause.PAUSE_DOWNLOAD -> hint_imageFragment_hint.hint(R.drawable.ic_error, "Pause to download new image for saving traffic", "I do not care", View.OnClickListener {
val requestLevel = image_imageFragment_image.options.requestLevel
image_imageFragment_image.options.requestLevel = RequestLevel.NET
image_imageFragment_image.displayImage(finalShowImageUrl)
image_imageFragment_image.options.requestLevel = requestLevel
})
CancelCause.PAUSE_LOAD -> hint_imageFragment_hint.hint(R.drawable.ic_error, "Paused to load new image", "Forced to load", View.OnClickListener {
val requestLevel = image_imageFragment_image.options.requestLevel
image_imageFragment_image.options.requestLevel = RequestLevel.NET
image_imageFragment_image.displayImage(finalShowImageUrl)
image_imageFragment_image.options.requestLevel = requestLevel
})
}
}
}
inner class ImageDownloadProgressListener : DownloadProgressListener {
override fun onUpdateDownloadProgress(totalLength: Int, completedLength: Int) {
if (view == null) {
return
}
hint_imageFragment_hint.setProgress(totalLength, completedLength)
}
}
}
private inner class ZoomHelper {
fun onViewCreated() {
image_imageFragment_image.isZoomEnabled = AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.SUPPORT_ZOOM)
if (AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.FIXED_THREE_LEVEL_ZOOM_MODE)) {
image_imageFragment_image.zoomer?.setZoomScales(FixedThreeLevelScales())
} else {
image_imageFragment_image.zoomer?.setZoomScales(AdaptiveTwoLevelScales())
}
onReadModeConfigChanged() // 初始化阅读模式
onUserVisibleChanged() // 初始化超大图查看器的暂停状态,这一步很重要
}
fun onConfigChanged() {
onViewCreated()
}
fun onUserVisibleChanged() {
val activity = activity ?: return
image_imageFragment_image.zoomer?.let {
if (AppConfig.getBoolean(activity, AppConfig.Key.PAUSE_BLOCK_DISPLAY_WHEN_PAGE_NOT_VISIBLE)) {
it.blockDisplayer.setPause(!isVisibleToUser) // 不可见的时候暂停超大图查看器,节省内存
} else if (isVisibleToUser && it.blockDisplayer.isPaused) {
it.blockDisplayer.setPause(false) // 因为有 PAUSE_BLOCK_DISPLAY_WHEN_PAGE_NOT_VISIBLE 开关的存在,可能会出现关闭开关后依然处于暂停状态的情况,因此这里恢复一下,加个保险
}
}
}
fun onReadModeConfigChanged() {
val activity = activity ?: return
image_imageFragment_image.zoomer?.let {
it.isReadMode = AppConfig.getBoolean(activity, AppConfig.Key.READ_MODE)
}
}
}
private inner class MappingHelper {
val zoomMatrixChangedListener = ZoomMatrixChangedListener()
fun onViewCreated() {
if (!showTools) {
mapping_imageFragment.visibility = View.GONE
return
}
if (image_imageFragment_image.zoomer != null) {
// MappingView 跟随 Matrix 变化刷新显示区域
image_imageFragment_image.zoomer?.addOnMatrixChangeListener(zoomMatrixChangedListener)
// MappingView 跟随碎片变化刷新碎片区域
image_imageFragment_image.zoomer?.blockDisplayer?.setOnBlockChangedListener { mapping_imageFragment.blockChanged(it) }
// 点击 MappingView 定位到指定位置
mapping_imageFragment.setOnSingleClickListener(object : MappingView.OnSingleClickListener {
override fun onSingleClick(x: Float, y: Float): Boolean {
val drawable = image_imageFragment_image.drawable ?: return false
if (drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) {
return false
}
if (mapping_imageFragment.width == 0 || mapping_imageFragment.height == 0) {
return false
}
val widthScale = drawable.intrinsicWidth.toFloat() / mapping_imageFragment.width
val heightScale = drawable.intrinsicHeight.toFloat() / mapping_imageFragment.height
val realX = x * widthScale
val realY = y * heightScale
val showLocationAnimation = AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.LOCATION_ANIMATE)
location(realX, realY, showLocationAnimation)
return true
}
})
} else {
mapping_imageFragment.setOnSingleClickListener(null)
mapping_imageFragment.update(Size(0, 0), Rect())
}
mapping_imageFragment.options.displayer = FadeInImageDisplayer()
mapping_imageFragment.options.setMaxSize(600, 600)
mapping_imageFragment.displayImage(finalShowImageUrl)
}
fun location(x: Float, y: Float, animate: Boolean): Boolean {
image_imageFragment_image.zoomer?.location(x, y, animate)
return true
}
private inner class ZoomMatrixChangedListener : ImageZoomer.OnMatrixChangeListener {
internal var visibleRect = Rect()
override fun onMatrixChanged(imageZoomer: ImageZoomer) {
imageZoomer.getVisibleRect(visibleRect)
mapping_imageFragment.update(imageZoomer.drawableSize, visibleRect)
}
}
}
private inner class SetWindowBackgroundHelper {
private var pageBackgApplyCallback: PageBackgApplyCallback? = null
fun onCreate(activity: Activity) {
if (activity is PageBackgApplyCallback) {
setWindowBackgroundHelper.pageBackgApplyCallback = activity
}
}
fun onUserVisibleChanged() {
if (pageBackgApplyCallback != null && isVisibleToUser) {
pageBackgApplyCallback!!.onApplyBackground(finalShowImageUrl)
}
}
fun onDisplayCompleted() {
onUserVisibleChanged()
}
}
private inner class GifPlayFollowPageVisibleHelper {
fun onUserVisibleChanged() {
val drawable = image_imageFragment_image.drawable
val lastDrawable = SketchUtils.getLastDrawable(drawable)
if (lastDrawable != null && lastDrawable is SketchGifDrawable) {
(lastDrawable as SketchGifDrawable).followPageVisible(isVisibleToUser, false)
}
}
fun onDisplayCompleted() {
val drawable = image_imageFragment_image.drawable
val lastDrawable = SketchUtils.getLastDrawable(drawable)
if (lastDrawable != null && lastDrawable is SketchGifDrawable) {
(lastDrawable as SketchGifDrawable).followPageVisible(isVisibleToUser, true)
}
}
}
private inner class ClickHelper {
fun onViewCreated() {
// 将单击事件传递给上层 Activity
val zoomer = image_imageFragment_image.zoomer
zoomer?.setOnViewTapListener { view, x, y ->
val parentFragment = parentFragment
if (parentFragment != null && parentFragment is ImageZoomer.OnViewTapListener) {
(parentFragment as ImageZoomer.OnViewTapListener).onViewTap(view, x, y)
} else {
val drawablePoint = zoomer.touchPointToDrawablePoint(x.toInt(), y.toInt())
val block = if(drawablePoint != null) zoomer.getBlockByDrawablePoint(drawablePoint.x, drawablePoint.y) else null
if (block?.bitmap != null) {
val imageView = ImageView(activity).apply {
setImageBitmap(block.bitmap)
}
AlertDialog.Builder(activity).setView(imageView).setPositiveButton("取消", null).show()
}
}
}
image_imageFragment_image.setOnLongClickListener {
val menuItemList = LinkedList<MenuItem>()
menuItemList.add(MenuItem(
"Image Info",
DialogInterface.OnClickListener { _, _ -> activity?.let { it1 -> image_imageFragment_image.showInfo(it1) } }
))
menuItemList.add(MenuItem(
"Zoom/Rotate/Block Display",
DialogInterface.OnClickListener { _, _ -> showZoomMenu() }
))
menuItemList.add(MenuItem(
String.format("Toggle ScaleType (%s)", image_imageFragment_image.zoomer?.scaleType
?: image_imageFragment_image.scaleType),
DialogInterface.OnClickListener { _, _ -> showScaleTypeMenu() }
))
menuItemList.add(MenuItem(
"Auto Play",
DialogInterface.OnClickListener { _, _ -> play() }
))
menuItemList.add(MenuItem(
"Set as wallpaper",
DialogInterface.OnClickListener { _, _ -> setWallpaper() }
))
menuItemList.add(MenuItem(
"Share Image",
DialogInterface.OnClickListener { _, _ -> share() }
))
menuItemList.add(MenuItem(
"Save Image",
DialogInterface.OnClickListener { _, _ -> save() }
))
val items = arrayOfNulls<String>(menuItemList.size)
var w = 0
val size = menuItemList.size
while (w < size) {
items[w] = menuItemList[w].title
w++
}
val itemClickListener = DialogInterface.OnClickListener { dialog, which ->
dialog.dismiss()
menuItemList[which].clickListener?.onClick(dialog, which)
}
AlertDialog.Builder(activity)
.setItems(items, itemClickListener)
.show()
true
}
}
fun showZoomMenu() {
val menuItemList = LinkedList<MenuItem>()
// 缩放信息
val zoomer = image_imageFragment_image.zoomer
if (zoomer != null) {
val zoomInfoBuilder = StringBuilder()
val zoomScale = SketchUtils.formatFloat(zoomer.zoomScale, 2)
val visibleRect = Rect()
zoomer.getVisibleRect(visibleRect)
val visibleRectString = visibleRect.toShortString()
zoomInfoBuilder.append("Zoom: ").append(zoomScale).append(" / ").append(visibleRectString)
menuItemList.add(MenuItem(zoomInfoBuilder.toString(), null))
menuItemList.add(MenuItem("canScrollHorizontally: ${zoomer.canScrollHorizontally().toString()}", null))
menuItemList.add(MenuItem("canScrollVertically: ${zoomer.canScrollVertically().toString()}", null))
} else {
menuItemList.add(MenuItem("Zoom (Disabled)", null))
}
// 分块显示信息
if (zoomer != null) {
val blockDisplayer = zoomer.blockDisplayer
val blockInfoBuilder = StringBuilder()
when {
blockDisplayer.isReady -> {
blockInfoBuilder.append("Blocks:")
.append(blockDisplayer.blockBaseNumber)
.append("/")
.append(blockDisplayer.blockSize)
.append("/")
.append(Formatter.formatFileSize(context, blockDisplayer.allocationByteCount))
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks Area:").append(blockDisplayer.decodeRect.toShortString())
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks Area (SRC):").append(blockDisplayer.decodeSrcRect.toShortString())
}
blockDisplayer.isInitializing -> {
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks initializing...")
}
else -> blockInfoBuilder.append("Blocks (No need)")
}
menuItemList.add(MenuItem(blockInfoBuilder.toString(), null))
} else {
menuItemList.add(MenuItem("Blocks (Disabled)", null))
}
// 分块边界开关
if (zoomer != null) {
val blockDisplayer = zoomer.blockDisplayer
if (blockDisplayer.isReady || blockDisplayer.isInitializing) {
menuItemList.add(MenuItem(if (blockDisplayer.isShowBlockBounds) "Hide block bounds" else "Show block bounds",
DialogInterface.OnClickListener { _, _ -> image_imageFragment_image.zoomer?.blockDisplayer?.let { it.isShowBlockBounds = !it.isShowBlockBounds } }))
} else {
menuItemList.add(MenuItem("Block bounds (No need)", null))
}
} else {
menuItemList.add(MenuItem("Block bounds (Disabled)", null))
}
// 阅读模式开关
if (zoomer != null) {
menuItemList.add(MenuItem(if (zoomer.isReadMode) "Close read mode" else "Open read mode",
DialogInterface.OnClickListener { _, _ -> image_imageFragment_image.zoomer?.let { it.isReadMode = !it.isReadMode } }))
} else {
menuItemList.add(MenuItem("Read mode (Zoom disabled)", null))
}
// 旋转菜单
if (zoomer != null) {
menuItemList.add(MenuItem(String.format("Clockwise rotation 90°(%d)", zoomer.rotateDegrees),
DialogInterface.OnClickListener { _, _ ->
image_imageFragment_image.zoomer?.let {
if (!it.rotateBy(90)) {
Toast.makeText(context, "The rotation angle must be a multiple of 90", Toast.LENGTH_LONG).show()
}
}
}))
} else {
menuItemList.add(MenuItem("Clockwise rotation 90° (Zoom disabled)", null))
}
val items = arrayOfNulls<String>(menuItemList.size)
var w = 0
val size = menuItemList.size
while (w < size) {
items[w] = menuItemList[w].title
w++
}
val itemClickListener = DialogInterface.OnClickListener { dialog, which ->
dialog.dismiss()
menuItemList[which].clickListener?.onClick(dialog, which)
}
AlertDialog.Builder(activity)
.setItems(items, itemClickListener)
.show()
}
fun showScaleTypeMenu() {
val builder = AlertDialog.Builder(activity)
builder.setTitle("Toggle ScaleType")
val items = arrayOfNulls<String>(7)
items[0] = "CENTER"
items[1] = "CENTER_CROP"
items[2] = "CENTER_INSIDE"
items[3] = "FIT_START"
items[4] = "FIT_CENTER"
items[5] = "FIT_END"
items[6] = "FIT_XY"
builder.setItems(items) { dialog, which ->
dialog.dismiss()
when (which) {
0 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER
1 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER_CROP
2 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER_INSIDE
3 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_START
4 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_CENTER
5 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_END
6 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_XY
}
}
builder.setNegativeButton("Cancel", null)
builder.show()
}
fun getImageFile(imageUri: String?): File? {
val context = context ?: return null
if (TextUtils.isEmpty(imageUri)) {
return null
}
val uriModel = UriModel.match(context, imageUri!!)
if (uriModel == null) {
Toast.makeText(activity, "Unknown format uri: $imageUri", Toast.LENGTH_LONG).show()
return null
}
val dataSource: DataSource
try {
dataSource = uriModel.getDataSource(context, imageUri, null)
} catch (e: GetDataSourceException) {
e.printStackTrace()
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return null
}
return try {
dataSource.getFile(context.externalCacheDir, null)
} catch (e: IOException) {
e.printStackTrace()
null
}
}
fun share() {
val activity = activity ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val imageFile = getImageFile(imageUri)
if (imageFile == null) {
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile))
intent.type = "image/" + parseFileType(imageFile.name)!!
val infoList = activity.packageManager.queryIntentActivities(intent, 0)
if (infoList == null || infoList.isEmpty()) {
Toast.makeText(activity, "There is no APP on your device to share the picture", Toast.LENGTH_LONG).show()
return
}
startActivity(intent)
}
fun setWallpaper() {
val activity = activity ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val imageFile = getImageFile(imageUri)
if (imageFile == null) {
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
ApplyWallpaperAsyncTask(activity, imageFile).execute(0)
}
fun play() {
EventBus.getDefault().post(PlayImageEvent())
}
fun save() {
val context = context ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val uriModel = UriModel.match(context, imageUri!!)
if (uriModel == null) {
Toast.makeText(activity, "Unknown format uri: $imageUri", Toast.LENGTH_LONG).show()
return
}
if (uriModel is FileUriModel) {
Toast.makeText(activity, "This image is the local no need to save", Toast.LENGTH_LONG).show()
return
}
val dataSource: DataSource
try {
dataSource = uriModel.getDataSource(context, imageUri, null)
} catch (e: GetDataSourceException) {
e.printStackTrace()
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
SaveImageAsyncTask(activity, dataSource, imageUri).execute("")
}
fun parseFileType(fileName: String): String? {
val lastIndexOf = fileName.lastIndexOf("")
if (lastIndexOf < 0) {
return null
}
val fileType = fileName.substring(lastIndexOf + 1)
if ("" == fileType.trim { it <= ' ' }) {
return null
}
return fileType
}
private inner class MenuItem(val title: String, var clickListener: DialogInterface.OnClickListener?)
}
companion object {
const val PARAM_REQUIRED_STRING_IMAGE_URI = "PARAM_REQUIRED_STRING_IMAGE_URI"
const val PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY = "PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY"
const val PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS = "PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS"
fun build(image: Image, loadingImageOptionsId: String?, showTools: Boolean): ImageFragment {
val bundle = Bundle()
bundle.putParcelable(PARAM_REQUIRED_STRING_IMAGE_URI, image)
bundle.putString(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY, loadingImageOptionsId)
bundle.putBoolean(PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS, showTools)
val fragment = ImageFragment()
fragment.arguments = bundle
return fragment
}
}
} | apache-2.0 | f2730488f018ae2d5ce6167943fc4ad4 | 41.241477 | 189 | 0.584356 | 5.341656 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/headers/HeaderAdapter.kt | 1 | 1570 | package com.infinum.dbinspector.ui.shared.headers
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.infinum.dbinspector.databinding.DbinspectorItemHeaderBinding
internal class HeaderAdapter : RecyclerView.Adapter<HeaderViewHolder>() {
private var headerItems: List<Header> = listOf()
var isClickable: Boolean = false
var onClick: ((Header) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder =
HeaderViewHolder(
DbinspectorItemHeaderBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) =
holder.bind(
headerItems[position % headerItems.size],
isClickable,
onClick
)
override fun onViewRecycled(holder: HeaderViewHolder) =
with(holder) {
holder.unbind()
super.onViewRecycled(this)
}
override fun getItemCount(): Int =
headerItems.size
fun setItems(headers: List<Header>) {
headerItems = headers
notifyDataSetChanged()
}
fun updateHeader(header: Header) {
headerItems = headerItems.map {
if (it.name == header.name) {
header.copy(active = true)
} else {
it.copy(active = false)
}
}
notifyDataSetChanged()
}
}
| apache-2.0 | 7fd1968c08c97322db464f87869c18bd | 28.074074 | 89 | 0.620382 | 5.304054 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/web/HttpFetcher.kt | 1 | 7032 | /****************************************************************************************
* Copyright (c) 2013 Bibek Shrestha <bibekshrestha@gmail.com> *
* Copyright (c) 2013 Zaur Molotnikov <qutorial@gmail.com> *
* Copyright (c) 2013 Nicolas Raoul <nicolas.raoul@gmail.com> *
* Copyright (c) 2013 Flavio Lerda <flerda@gmail.com> *
* Copyright (c) 2020 Mike Hardy <github@mikehardy.net> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.web
import android.content.Context
import com.ichi2.async.Connection
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.sync.Tls12SocketFactory
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.VersionUtils.pkgVersionName
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import timber.log.Timber
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.URL
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
/**
* Helper class to download from web.
* <p>
* Used in AsyncTasks in Translation and Pronunciation activities, and more...
*/
object HttpFetcher {
/**
* Get an OkHttpClient configured with correct timeouts and headers
*
* @param fakeUserAgent true if we should issue "fake" User-Agent header 'Mozilla/5.0' for compatibility
* @return OkHttpClient.Builder ready for use or further configuration
*/
fun getOkHttpBuilder(fakeUserAgent: Boolean): OkHttpClient.Builder {
val clientBuilder = OkHttpClient.Builder()
Tls12SocketFactory.enableTls12OnPreLollipop(clientBuilder)
.connectTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
if (fakeUserAgent) {
clientBuilder.addNetworkInterceptor(
Interceptor { chain: Interceptor.Chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("Referer", "com.ichi2.anki")
.header("User-Agent", "Mozilla/5.0 ( compatible ) ")
.header("Accept", "*/*")
.build()
)
}
)
} else {
clientBuilder.addNetworkInterceptor(
Interceptor { chain: Interceptor.Chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "AnkiDroid-$pkgVersionName")
.build()
)
}
)
}
return clientBuilder
}
fun fetchThroughHttp(address: String?, encoding: String? = "utf-8"): String {
Timber.d("fetching %s", address)
var response: Response? = null
return try {
val requestBuilder = Request.Builder()
requestBuilder.url(address!!).get()
val httpGet: Request = requestBuilder.build()
val client: OkHttpClient = getOkHttpBuilder(true).build()
response = client.newCall(httpGet).execute()
if (response.code != 200) {
Timber.d("Response code was %s, returning failure", response.code)
return "FAILED"
}
val reader = BufferedReader(
InputStreamReader(
response.body!!.byteStream(),
Charset.forName(encoding)
)
)
val stringBuilder = StringBuilder()
var line: String?
@KotlinCleanup("it's strange")
while (reader.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
stringBuilder.toString()
} catch (e: Exception) {
Timber.d(e, "Failed with an exception")
"FAILED with exception: " + e.message
} finally {
response?.body?.close()
}
}
fun downloadFileToSdCard(UrlToFile: String, context: Context, prefix: String?): String {
var str = downloadFileToSdCardMethod(UrlToFile, context, prefix, "GET")
if (str.startsWith("FAIL")) {
str = downloadFileToSdCardMethod(UrlToFile, context, prefix, "POST")
}
return str
}
private fun downloadFileToSdCardMethod(UrlToFile: String, context: Context, prefix: String?, method: String): String {
var response: Response? = null
return try {
val url = URL(UrlToFile)
val extension = UrlToFile.substring(UrlToFile.length - 4)
val requestBuilder = Request.Builder()
requestBuilder.url(url)
if ("GET" == method) {
requestBuilder.get()
} else {
requestBuilder.post(ByteArray(0).toRequestBody(null, 0, 0))
}
val request: Request = requestBuilder.build()
val client: OkHttpClient = getOkHttpBuilder(true).build()
response = client.newCall(request).execute()
val file = File.createTempFile(prefix!!, extension, context.cacheDir)
val inputStream = response.body!!.byteStream()
CompatHelper.compat.copyFile(inputStream, file.canonicalPath)
inputStream.close()
file.absolutePath
} catch (e: Exception) {
Timber.w(e)
"FAILED " + e.message
} finally {
response?.body?.close()
}
}
}
| gpl-3.0 | 9d88539f0cd8ee073ed389c6a68588f1 | 44.076923 | 122 | 0.537685 | 5.201183 | false | false | false | false |
Aunmag/a-zombie-shooter-game | src/main/java/aunmag/shooter/data/Sounds.kt | 1 | 843 | package aunmag.shooter.data
import aunmag.nightingale.audio.AudioSource
import aunmag.nightingale.utilities.UtilsAudio
val soundAmbiance = initializeSoundAmbiance()
val soundAtmosphere = initializeSoundAtmosphere()
val soundGameOver = initializeSoundGameOver()
private fun initializeSoundAmbiance(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/ambiance/birds")
sound.setVolume(0.4f)
sound.setIsLooped(true)
return sound
}
private fun initializeSoundAtmosphere(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/music/gameplay_atmosphere")
sound.setVolume(0.06f)
sound.setIsLooped(true)
return sound
}
private fun initializeSoundGameOver(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/music/death")
sound.setVolume(0.6f)
return sound
}
| apache-2.0 | abbd804477712a18dd6406591ffd5e87 | 29.107143 | 82 | 0.782918 | 4.152709 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/construction/MarkCompletedConstructionMinorOrGeneric.kt | 1 | 2268 | package de.westnordost.streetcomplete.quests.construction
import de.westnordost.streetcomplete.data.meta.ALL_ROADS
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.SURVEY_MARK_KEY
import de.westnordost.streetcomplete.data.meta.toCheckDateString
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
import java.time.LocalDate
import java.util.*
class MarkCompletedConstructionMinorOrGeneric() : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
ways with construction = yes or construction = minor
and (!opening_date or opening_date < today)
and older today -1 months
"""
override val commitMessage = "Determine whether construction is now completed"
override val wikiLink = "Tag:construction=yes"
override val icon = R.drawable.ic_quest_building_construction
override fun getTitle(tags: Map<String, String>): Int {
val isRoad = ALL_ROADS.contains(tags["construction"])
val isCycleway = tags["construction"] == "cycleway"
val isFootway = tags["construction"] == "footway"
val isBridge = tags["man_made"] == "bridge"
return when {
isRoad -> R.string.quest_construction_road_title
isCycleway -> R.string.quest_construction_cycleway_title
isFootway -> R.string.quest_construction_footway_title
isBridge -> R.string.quest_construction_bridge_title
else -> R.string.quest_construction_even_more_generic_title
}
}
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
if (answer) {
deleteTagsDescribingConstruction(changes) //includes deletion of construction=yes/minor
} else {
changes.addOrModify(SURVEY_MARK_KEY, LocalDate.now().toCheckDateString())
}
}
override val questTypeAchievements: List<QuestTypeAchievement>
get() = listOf()
}
| gpl-3.0 | 0d46a7cc5a28dcb25cebafdedfb843eb | 41.792453 | 99 | 0.72575 | 4.695652 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/fs/fat32/ShortNameGenerator.kt | 2 | 6616 | /*
* (C) Copyright 2014 mjahnen <github@mgns.tech>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.core.fs.fat32
import java.util.*
/**
* This class is responsible for generating valid 8.3 short names for any given
* long file name.
*
* @author mjahnen
* @see FatLfnDirectoryEntry
*
* @see FatDirectoryEntry
*/
internal object ShortNameGenerator {
/**
* See fatgen103.pdf from Microsoft for allowed characters.
*
* @param c
* The character to test.
* @return True if the character is allowed in an 8.3 short name.
*/
private fun isValidChar(c: Char): Boolean {
if (c in '0'..'9')
return true
return if (c in 'A'..'Z') true else c == '$' || c == '%' || c == '\'' || c == '-' || c == '_' || c == '@' || c == '~'
|| c == '`' || c == '!' || c == '(' || c == ')' || c == '{' || c == '}' || c == '^'
|| c == '#' || c == '&'
}
/**
*
* @param str
* The String to test.
* @return True if the String contains any invalid chars which are not
* allowed on 8.3 short names.
*/
private fun containsInvalidChars(str: String): Boolean {
val length = str.length
for (i in 0 until length) {
val c = str[i]
if (!isValidChar(c))
return true
}
return false
}
/**
* Replaces all invalid characters in an string with an underscore (_).
*
* @param str
* The string where invalid chars shall be replaced.
* @return The new string only containing valid chars.
*/
private fun replaceInvalidChars(str: String): String {
val length = str.length
val builder = StringBuilder(length)
for (i in 0 until length) {
val c = str[i]
if (isValidChar(c)) {
builder.append(c)
} else {
builder.append("_")
}
}
return builder.toString()
}
/**
* Generate the next possible hex part for using in SFN. We are using a
* similar approach as what Windows 2000 did.
*/
private fun getNextHexPart(hexPart: String, limit: Int): String? {
var hexValue = java.lang.Long.parseLong(hexPart, 16)
hexValue += 1
val tempHexString = java.lang.Long.toHexString(hexValue)
if (tempHexString.length <= limit) {
val sb = StringBuilder()
for (i in 0 until limit - tempHexString.length) {
sb.append("0")
}
return sb.toString() + tempHexString
}
return null
}
/**
* Generates an 8.3 short name for a given long file name. It creates a
* suffix at the end of the short name if there is already a existing entry
* in the directory with an equal short name.
*
* @param lfnName
* Long file name.
* @param existingShortNames
* The short names already existing in the directory.
* @return The generated short name.
*/
fun generateShortName(lfnName: String,
existingShortNames: Collection<ShortName>): ShortName {
var lfnName = lfnName
lfnName = lfnName.toUpperCase(Locale.ROOT).trim { it <= ' ' }
// remove leading periods
var i = 0
while (i < lfnName.length) {
if (lfnName[i] != '.')
break
i++
}
lfnName = lfnName.substring(i)
lfnName = lfnName.replace(" ", "")
var filenamePart: String
var extensionPart: String
val indexOfDot = lfnName.lastIndexOf(".")
if (indexOfDot == -1) {
// no extension
filenamePart = lfnName
extensionPart = ""
} else {
// has extension
filenamePart = lfnName.substring(0, indexOfDot)
extensionPart = lfnName.substring(indexOfDot + 1)
if (extensionPart.length > 3) {
extensionPart = extensionPart.substring(0, 3)
}
}
// remove invalid chars
if (containsInvalidChars(filenamePart)) {
filenamePart = replaceInvalidChars(filenamePart)
}
// remove invalid chars
if (containsInvalidChars(extensionPart)) {
extensionPart = replaceInvalidChars(extensionPart)
}
var filePrefix = filenamePart
when {
filenamePart.isEmpty() -> filePrefix = "__"
filenamePart.length == 1 -> filePrefix += "_"
filenamePart.length == 2 -> {
// Do nothing
}
filenamePart.length > 2 -> filePrefix = filenamePart.substring(0, 2)
}
var extSuffix = extensionPart
when {
extensionPart.isEmpty() -> extSuffix = "000"
extensionPart.length == 1 -> extSuffix = extensionPart + "00"
extensionPart.length == 2 -> extSuffix = extensionPart + "0"
}
var hexPart = "0000"
var tildeDigit = 0
var result = ShortName("$filePrefix$hexPart~$tildeDigit", extSuffix)
while (containShortName(existingShortNames, result)) {
val hexPartNullable = getNextHexPart(hexPart, 4)
if (hexPartNullable != null) {
hexPart = hexPartNullable
} else {
if (tildeDigit + 1 < 10) {
tildeDigit += 1
hexPart = "0000"
} else {
// This should not happen
break
}
}
result = ShortName("$filePrefix$hexPart~$tildeDigit", extSuffix)
}
return result
}
private fun containShortName(shortNames: Collection<ShortName>, shortName: ShortName): Boolean {
var contain = false
for (temp in shortNames) {
if (temp.string.equals(shortName.string, ignoreCase = true)) {
contain = true
break
}
}
return contain
}
}
| apache-2.0 | 5ed0fd55bbecf791f3d5deb67f53da8c | 30.207547 | 125 | 0.545949 | 4.665726 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/query/QueryHandler.kt | 1 | 9719 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
/*
* Copyright (c) 2011-2014 Glowstone - Tad Hardesty
* Copyright (c) 2010-2011 Lightstone - Graham Edgecombe
*
* 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 org.lanternpowered.server.network.query
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.socket.DatagramPacket
import org.lanternpowered.api.cause.causeOf
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.api.plugin.name
import org.lanternpowered.api.plugin.version
import org.lanternpowered.api.text.toPlain
import org.lanternpowered.api.world.WorldManager
import org.lanternpowered.server.network.SimpleRemoteConnection
import org.lanternpowered.server.util.future.thenAsync
import org.spongepowered.api.Platform
import org.spongepowered.api.event.server.query.QueryServerEvent
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
import java.util.LinkedHashMap
/**
* Class for handling UDP packets according to the minecraft server query protocol.
*
* @see QueryServer
* @see [Protocol Specifications](http://wiki.vg/Query)
*/
internal class QueryHandler(
private val queryServer: QueryServer,
private val showPlugins: Boolean
) : SimpleChannelInboundHandler<DatagramPacket>() {
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
this.queryServer.server.logger.error("Error in query handling", cause)
}
override fun channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
}
override fun channelRead0(ctx: ChannelHandlerContext, msg: DatagramPacket) {
val buf = msg.content()
if (buf.readableBytes() < 7) {
return
}
val magic = buf.readUnsignedShort()
val type = buf.readByte()
val sessionId = buf.readInt()
if (magic != 0xFEFD) {
return
}
if (type == ACTION_HANDSHAKE) {
handleHandshake(ctx, msg, sessionId)
} else if (type == ACTION_STATS) {
if (buf.readableBytes() < 4) {
return
}
val token = buf.readInt()
if (this.queryServer.verifyChallengeToken(msg.sender(), token)) {
if (buf.readableBytes() == 4) {
handleFullStats(ctx, msg, sessionId)
} else {
handleBasicStats(ctx, msg, sessionId)
}
}
}
}
private fun handleHandshake(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val challengeToken = this.queryServer.generateChallengeToken(packet.sender())
val out = ctx.alloc().buffer()
out.writeByte(ACTION_HANDSHAKE.toInt())
out.writeInt(sessionId)
out.writeString(challengeToken.toString())
ctx.write(DatagramPacket(out, packet.sender()))
}
private fun handleBasicStats(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val sender = packet.sender()
this.queryServer.server.syncExecutor.submit {
val event = createBasicEvent(ctx.channel())
EventManager.post(event)
event
}.thenAsync(ctx.channel().eventLoop()) { event ->
val buf = ctx.alloc().buffer()
buf.write(event, sessionId)
ctx.write(DatagramPacket(buf, sender))
}
}
private fun createBasicEvent(channel: Channel): QueryServerEvent.Basic {
val server = this.queryServer.server
val connection = SimpleRemoteConnection.of(channel)
val cause = causeOf(connection)
val address = channel.localAddress() as InetSocketAddress
return LanternEventFactory.createQueryServerEventBasic(cause,
address, "SMP", worldName, server.motd.toPlain(),
server.maxPlayers, Int.MAX_VALUE, server.onlinePlayers.size, 0)
}
private fun ByteBuf.write(event: QueryServerEvent.Basic, sessionId: Int) {
writeByte(ACTION_STATS.toInt())
writeInt(sessionId)
writeString(event.motd)
writeString(event.gameType)
writeString(event.map)
writeString(event.playerCount.toString())
writeString(event.maxPlayerCount.toString())
writeShortLE(event.address.port)
writeString(event.address.hostString)
}
private fun handleFullStats(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val sender = packet.sender()
this.queryServer.server.syncExecutor.submit {
val event = createFullEvent(ctx.channel())
EventManager.post(event)
event
}.thenAsync(ctx.channel().eventLoop()) { event ->
val buf = ctx.alloc().buffer()
buf.write(event, sessionId)
ctx.write(DatagramPacket(buf, sender))
}
}
private fun createFullEvent(channel: Channel): QueryServerEvent.Full {
val game = this.queryServer.server.game
val server = game.server
val platform: Platform = game.platform
val api = platform.getContainer(Platform.Component.API)
val impl = platform.getContainer(Platform.Component.IMPLEMENTATION)
val mc = platform.getContainer(Platform.Component.GAME)
val plugins = StringBuilder()
.append(impl.name)
.append(" ")
.append(impl.version)
.append(" on ")
.append(api.name)
.append(" ")
.append(api.version)
if (this.showPlugins) {
val containers = game.pluginManager.plugins.toMutableList()
containers.remove(api)
containers.remove(impl)
containers.remove(mc)
var delim = ':'
for (plugin in containers) {
plugins.append(delim).append(' ').append(plugin.name)
delim = ';'
}
}
val playerNames = server.onlinePlayers.map { it.name }
val connection = SimpleRemoteConnection.of(channel)
val cause = causeOf(connection)
val address = channel.localAddress() as InetSocketAddress
return LanternEventFactory.createQueryServerEventFull(cause, address, mutableMapOf<String, String>(), "MINECRAFT", "SMP",
worldName, server.motd.toPlain(), playerNames, plugins.toString(), mc.version, server.maxPlayers, Int.MAX_VALUE, playerNames.size, 0)
}
private fun ByteBuf.write(event: QueryServerEvent.Full, sessionId: Int) {
val data: MutableMap<String, String> = LinkedHashMap()
data["hostname"] = event.motd
data["gametype"] = event.gameType
data["game_id"] = event.gameId
data["version"] = event.version
data["plugins"] = event.plugins
data["map"] = event.map
data["numplayers"] = event.playerCount.toString()
data["maxplayers"] = event.maxPlayerCount.toString()
data["hostport"] = event.address.port.toString()
data["hostip"] = event.address.hostString
event.customValuesMap.entries.stream()
.filter { entry -> !data.containsKey(entry.key) }
.forEach { entry -> data[entry.key] = entry.value }
writeByte(ACTION_STATS.toInt())
writeInt(sessionId)
// constant: splitnum\x00\x80\x00
writeBytes(byteArrayOf(0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, 0x80.toByte(), 0x00))
for ((key, value) in data) {
writeString(key)
writeString(value)
}
writeByte(0)
// constant: \x01player_\x00\x00
writeBytes(byteArrayOf(0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00))
for (player in event.players) {
writeString(player)
}
writeByte(0)
}
private val worldName: String
get() = WorldManager.worlds.firstOrNull()?.properties?.key?.formatted ?: "none"
companion object {
private const val ACTION_HANDSHAKE: Byte = 9
private const val ACTION_STATS: Byte = 0
private fun ByteBuf.writeString(str: String) {
writeBytes(str.toByteArray(StandardCharsets.UTF_8)).writeByte(0)
}
}
}
| mit | d86a7c4e0b08b75b07a284617b6b77bf | 39.665272 | 149 | 0.656343 | 4.431829 | false | false | false | false |
ageery/kwicket | kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/wicket/core/ajax/markup/html/bootstrap/form/KBootstrapForm.kt | 1 | 1741 | package org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.form
import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm
import de.agilecoders.wicket.core.markup.html.bootstrap.form.FormType
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.markup.html.form.validation.IFormValidator
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.component.q
@Deprecated(replaceWith = ReplaceWith("org.kwicket.agilecoders.queued.bootstrapForm"), message = "Use in different package")
fun <T> WebMarkupContainer.bootstrapForm(
id: String,
model: IModel<T>? = null,
type: FormType? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
behaviors: List<Behavior>? = null,
validators: List<IFormValidator>? = null
) = q(
KBootstrapForm(
id = id,
model = model,
type = type,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
behaviors = behaviors,
validators = validators
)
)
open class KBootstrapForm<T>(
id: String,
model: IModel<T>? = null,
type: FormType? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
behaviors: List<Behavior>? = null,
validators: List<IFormValidator>? = null
) : BootstrapForm<T>(id, model) {
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
behaviors = behaviors
)
type?.let { type(it) }
validators?.forEach { add(it) }
}
} | apache-2.0 | e21786c0822e71c85846e553283280b0 | 31.867925 | 124 | 0.698449 | 4.277641 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/layout/BlockViewModel.kt | 1 | 8672 | package io.rover.sdk.experiences.ui.blocks.concerns.layout
import io.rover.sdk.core.data.domain.Block
import io.rover.sdk.core.data.domain.ButtonBlock
import io.rover.sdk.core.data.domain.Height
import io.rover.sdk.core.data.domain.HorizontalAlignment
import io.rover.sdk.core.data.domain.VerticalAlignment
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.whenNotNull
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.share
import io.rover.sdk.experiences.ui.RectF
import io.rover.sdk.experiences.ui.layout.ViewType
import io.rover.sdk.experiences.ui.layout.screen.ScreenViewModel
import io.rover.sdk.experiences.ui.navigation.NavigateToFromBlock
/**
* A mixin used by all blocks that contains the block layout and positioning concerns.
*
* - LayoutableViewModel probably needs to split, because we want to be able to delegate the frame()
* method to the new mixin version of BlockViewModel but obviously it should not specify view type
*/
internal class BlockViewModel(
private val block: Block,
private val paddingDeflections: Set<LayoutPaddingDeflection> = emptySet(),
private val measurable: Measurable? = null
) : BlockViewModelInterface {
override val viewType: ViewType
get() = throw RuntimeException(
"When delegating BlockViewModelInterface to an instance of BlockViewModel, you must still implement viewType yourself."
)
override fun stackedHeight(bounds: RectF): Float {
val alignment = block.position.verticalAlignment
return when (alignment) {
is VerticalAlignment.Stacked -> {
this.height(bounds) + alignment.topOffset.toFloat() + alignment.bottomOffset.toFloat()
}
else -> 0.0f
}
}
override val insets: Insets
get() = Insets(
block.insets.top,
block.insets.left,
block.insets.bottom,
block.insets.right
)
override val padding: Padding
get() = (listOf(Padding(
block.insets.left,
block.insets.top,
block.insets.right,
block.insets.bottom
)) + paddingDeflections.map { it.paddingDeflection }).reduce { acc, next -> acc + next }
override val isStacked: Boolean
get() = block.position.verticalAlignment is VerticalAlignment.Stacked
override val opacity: Float
get() = block.opacity.toFloat()
override fun frame(bounds: RectF): RectF {
val x = x(bounds)
val y = y(bounds)
val width = width(bounds)
val height = height(bounds)
return RectF(
x,
y,
(width + x),
(y + height)
)
}
/**
* Computes the Block's height.
*/
fun height(bounds: RectF): Float {
val verticalAlignment = block.position.verticalAlignment
return when (verticalAlignment) {
is VerticalAlignment.Fill -> {
val top = verticalAlignment.topOffset
val bottom = verticalAlignment.bottomOffset
bounds.height() - top.toFloat() - bottom.toFloat()
}
is VerticalAlignment.Stacked, is VerticalAlignment.Middle, is VerticalAlignment.Bottom, is VerticalAlignment.Top -> {
// we use the Measured interface to get at the height field on all of the non-Fill types.
val height = (verticalAlignment as VerticalAlignment.Measured).height
when (height) {
is Height.Intrinsic -> {
val boundsConsideringInsets = RectF(
bounds.left + insets.left + paddingDeflections.map { it.paddingDeflection.left }.sum(),
bounds.top,
bounds.left + width(bounds) - insets.right - paddingDeflections.map { it.paddingDeflection.right }.sum(),
bounds.bottom
)
bounds.width()
// TODO: boundsConsideringInsets could go negative if the insets are bigger than the
// bounds, causing illegal/undefined behaviour further down the chain.
// https://github.com/RoverPlatform/rover/issues/1460
if (measurable == null) {
log.w("Block is set to auto-height but no measurable is given.")
0f
} else {
measurable.intrinsicHeight(boundsConsideringInsets) +
insets.bottom +
insets.top +
paddingDeflections.map {
it.paddingDeflection.top + it.paddingDeflection.bottom
}.sum()
}
}
is Height.Static -> {
height.value.toFloat()
}
}
}
}
}
/**
* Computes the Block's width.
*/
override fun width(bounds: RectF): Float {
val alignment = block.position.horizontalAlignment
return when (alignment) {
is HorizontalAlignment.Fill -> {
bounds.width() - alignment.leftOffset.toFloat() - alignment.rightOffset.toFloat()
}
is HorizontalAlignment.Right, is HorizontalAlignment.Center, is HorizontalAlignment.Left -> {
listOf((alignment as HorizontalAlignment.Measured).width.toFloat(), 0.0f).max()!!
}
}
}
private val eventSource = PublishSubject<BlockViewModelInterface.Event>()
override val events = eventSource.share()
override val isClickable: Boolean
get() = block is ButtonBlock || block.tapBehavior != Block.TapBehavior.None
override fun click() {
// I don't have an epic (any other asynchronous behaviour to compose) here, just a single
// event emitter, so I'll just publish an event directly.
val tapBehavior = block.tapBehavior
val navigateTo = when (tapBehavior) {
is Block.TapBehavior.GoToScreen -> { NavigateToFromBlock.GoToScreenAction(tapBehavior.screenId, block) }
is Block.TapBehavior.OpenUri -> { NavigateToFromBlock.External(tapBehavior.uri, block) }
is Block.TapBehavior.PresentWebsite -> { NavigateToFromBlock.PresentWebsiteAction(tapBehavior.url, block) }
is Block.TapBehavior.None -> { NavigateToFromBlock.None(block) }
is Block.TapBehavior.Custom -> { NavigateToFromBlock.Custom(block) }
}
navigateTo.whenNotNull {
eventSource.onNext(
BlockViewModelInterface.Event.Clicked(it, block.id)
)
}
}
override fun touched() {
eventSource.onNext(
BlockViewModelInterface.Event.Touched(block.id)
)
}
override fun released() {
eventSource.onNext(
BlockViewModelInterface.Event.Released(block.id)
)
}
/**
* Computes the Block's absolute horizontal coordinate in the [ScreenViewModel]'s coordinate
* space.
*/
private fun x(bounds: RectF): Float {
val width = width(bounds)
val alignment = block.position.horizontalAlignment
return when (alignment) {
is HorizontalAlignment.Center -> bounds.left + ((bounds.width() - width) / 2) + alignment.offset.toFloat()
is HorizontalAlignment.Fill -> bounds.left + alignment.leftOffset.toFloat()
is HorizontalAlignment.Left -> bounds.left + alignment.offset.toFloat()
is HorizontalAlignment.Right -> bounds.right - width - alignment.offset.toFloat()
}
}
/**
* Computes the Block's absolute vertical coordinate in the [ScreenViewModel]'s coordinate
* space.
*/
private fun y(bounds: RectF): Float {
val height = height(bounds)
val alignment = block.position.verticalAlignment
return when (alignment) {
is VerticalAlignment.Bottom -> bounds.bottom - height - alignment.offset.toFloat()
is VerticalAlignment.Fill -> bounds.top + alignment.topOffset.toFloat()
is VerticalAlignment.Top -> bounds.top + alignment.offset.toFloat()
is VerticalAlignment.Middle -> bounds.top + ((bounds.height() - height) / 2) + alignment.offset.toFloat()
is VerticalAlignment.Stacked -> bounds.top + alignment.topOffset.toFloat()
}
}
}
| apache-2.0 | bc59821569ada7aab5c67d2d35f68cbe | 38.963134 | 133 | 0.603782 | 5.09219 | false | false | false | false |
PaulWoitaschek/Voice | folderPicker/src/main/kotlin/voice/folderPicker/selectType/FolderModeSelectionCard.kt | 1 | 2792 | package voice.folderPicker.selectType
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Card
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import voice.common.compose.VoiceTheme
import voice.data.folders.FolderType
import voice.folderPicker.FolderTypeIcon
import voice.folderPicker.R
@Composable
internal fun FolderModeSelectionCard(
onFolderModeSelected: (FolderMode) -> Unit,
selectedFolderMode: FolderMode,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
Column(
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
FolderMode.values().forEach { folderMode ->
val selectFolder = { onFolderModeSelected(folderMode) }
FolderModeColumn(selectFolder = selectFolder, selectedFolderMode = selectedFolderMode, folderMode = folderMode)
}
}
}
}
@Composable
private fun FolderModeColumn(
selectedFolderMode: FolderMode,
folderMode: FolderMode,
selectFolder: () -> Unit,
) {
Row(
modifier = Modifier
.clickable(onClick = selectFolder)
.padding(end = 24.dp, start = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = selectedFolderMode == folderMode,
onClick = selectFolder,
)
Spacer(Modifier.size(16.dp))
Text(
text = stringResource(id = folderMode.title()),
modifier = Modifier
.weight(1F)
.padding(vertical = 8.dp),
)
FolderTypeIcon(
folderType = when (folderMode) {
FolderMode.Audiobooks -> FolderType.Root
FolderMode.SingleBook -> FolderType.SingleFolder
},
)
}
}
@StringRes
private fun FolderMode.title(): Int {
return when (this) {
FolderMode.Audiobooks -> R.string.folder_mode_root
FolderMode.SingleBook -> R.string.folder_mode_single
}
}
@Composable
@Preview
private fun FolderModeSelectionCardPreview() {
VoiceTheme {
FolderModeSelectionCard(
onFolderModeSelected = {},
selectedFolderMode = FolderMode.Audiobooks,
)
}
}
| gpl-3.0 | 9031e6fa3acb5ebbc624248132a0fbbd | 27.783505 | 119 | 0.737822 | 4.335404 | false | false | false | false |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/repo/internals/migrations/Migration39to40.kt | 1 | 884 | package voice.data.repo.internals.migrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.squareup.anvil.annotations.ContributesMultibinding
import voice.common.AppScope
import javax.inject.Inject
@ContributesMultibinding(
scope = AppScope::class,
boundType = Migration::class,
)
class Migration39to40
@Inject constructor() : IncrementalMigration(39) {
private val BOOK_TABLE_NAME = "tableBooks"
private val BOOK_TIME = "bookTime"
override fun migrate(db: SupportSQLiteDatabase) {
val positionZeroContentValues = ContentValues().apply {
put(BOOK_TIME, 0)
}
db.update(
BOOK_TABLE_NAME,
SQLiteDatabase.CONFLICT_FAIL,
positionZeroContentValues,
"$BOOK_TIME < ?",
arrayOf(0),
)
}
}
| gpl-3.0 | 5b13aa956ac4ebd0db6f0462244ef469 | 25.787879 | 61 | 0.752262 | 4.270531 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/wukong0.kt | 1 | 2884 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import java.net.URL
class Wukong0 : DslJsoupNovelContext() {init {
hide = true
site {
name = "悟空看书0"
baseUrl = "https://www.wkxs.net"
logo = "https://imgsa.baidu.com/forum/w%3D580/sign=95ca1b6f75310a55c424defc87474387/930dadd12f2eb938f9acfb6ed9628535e7dd6f50.jpg"
}
search {
get {
// 电脑版搜索要验证码,
// https://m.wkxs.net/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&t_btnsearch=
charset = "GBK"
url = "//m.wkxs.net/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
if (URL(root.ownerDocument().location()).path.startsWith("/book_")) {
single {
name("tbody > tr > td.info > h1") {
it.ownText()
}
author("tbody > tr > td.info > p:nth-child(2) > a")
}
} else {
items("body > div.waps_r > table > tbody > tr") {
name("> td:nth-child(2) > div > a:nth-child(1)")
author("> td:nth-child(2) > div > p > span.mr15", block = pickString("作者:(\\S*)"))
}
}
}
}
// https://www.wkxs.net/book_885/
bookIdRegex = "/book_(\\d+)"
detailPageTemplate = "/book_%s/"
detail {
document {
novel {
name("#info > h1") {
it.ownText()
}
author("#info > h1 > small > a")
}
image("#picbox > div > img")
update("#info > div.update", format = "yyyy-MM-dd HH:mm", block = pickString(".*(([^(]*))"))
introduction("#intro", block = ownLinesString())
}
}
chapters {
document {
items("body > div.zjbox > dl > dd > a")
lastUpdate("#info > div.update", format = "yyyy-MM-dd HH:mm", block = pickString(".*(([^(]*))"))
}
}
bookIdWithChapterIdRegex = "/book_(\\d+/\\d+)"
contentPageTemplate = "/book_%s.html"
content {
document {
items("#content", block = ownLinesSplitWhitespace())
}.dropWhile {
it.startsWith("悟空看书")
|| it.startsWith("www.wkxs.net")
|| it.startsWith("www.wukong.la")
|| it == "最新章节!"
}.dropLastWhile {
it == "-->>"
}
}
}
}
| gpl-3.0 | a430d7783bb0353da6f57aceb0ce4b1d | 32.950617 | 137 | 0.464364 | 3.731343 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/simple_class_2/simple_class_2.kt | 1 | 414 | class simple_class_2_MyClass(val b: Int, var c: Int)
fun simple_class_2_genMyClass(i: Int): simple_class_2_MyClass {
return simple_class_2_MyClass(i, i)
}
fun simple_class_2_change(x: Int): Int {
val y = simple_class_2_MyClass(x, x)
y.c = x
y.c = x
y.c = 1
y.c = x + 1
return y.c
}
fun simple_class_2_testGen(i: Int): Int {
val j = simple_class_2_genMyClass(i)
return j.b
}
| mit | 02ff22a03ad2bfbd5fe3c56bf956bd6d | 19.7 | 63 | 0.60628 | 2.493976 | false | false | false | false |
Le-Chiffre/Yttrium | Core/src/com/rimmer/yttrium/serialize/JsonWriter.kt | 2 | 4326 | package com.rimmer.yttrium.serialize
import com.rimmer.yttrium.*
import io.netty.buffer.ByteBuf
import org.joda.time.DateTime
import java.util.*
/** Utility functions for generating json data. */
class JsonWriter(val buffer: ByteBuf) {
private var depth = 0
private var hasValue = 0
fun startObject(): JsonWriter {
buffer.writeByte('{'.toInt())
depth++
return this
}
fun endObject(): JsonWriter {
buffer.writeByte('}'.toInt())
depth--
hasValue = depth
return this
}
fun startArray(): JsonWriter {
buffer.writeByte('['.toInt())
depth++
return this
}
fun endArray(): JsonWriter {
buffer.writeByte(']'.toInt())
depth--
hasValue = depth
return this
}
fun arrayField(): JsonWriter {
if(hasValue < depth) {
hasValue = depth
} else {
buffer.writeByte(','.toInt())
}
return this
}
fun field(name: ByteArray): JsonWriter {
if(hasValue < depth) {
hasValue = depth
} else {
buffer.writeByte(','.toInt())
}
buffer.writeByte('"'.toInt())
buffer.writeBytes(name)
buffer.writeByte('"'.toInt())
buffer.writeByte(':'.toInt())
return this
}
fun field(name: String) = field(name.toByteArray())
fun nullValue() {
buffer.writeBytes(nullBytes)
}
fun value(s: String): JsonWriter {
buffer.writeByte('"'.toInt())
val escaped = StringBuilder(s.length)
for(c in s) {
when {
c == '"' -> escaped.append("\\\"")
c == '\\' -> escaped.append("\\\\")
c < 0x20.toChar() -> when(c) {
'\b' -> escaped.append("\\b")
0x0C.toChar() -> escaped.append("\\f")
'\n' -> escaped.append("\\n")
'\r' -> escaped.append("\\r")
'\t' -> escaped.append("\\t")
}
else -> escaped.append(c)
}
}
buffer.writeBytes(escaped.toString().toByteArray())
buffer.writeByte('"'.toInt())
return this
}
fun value(s: ByteString): JsonWriter {
buffer.writeByte('"'.toInt())
val escaped = ByteStringBuilder(s.size)
for(c in s) {
when {
c == '"'.toByte() -> escaped.append("\\\"".utf8)
c == '\\'.toByte() -> escaped.append("\\\\".utf8)
c < 0x20.toByte() -> when(c) {
'\b'.toByte() -> escaped.append("\\b".utf8)
0x0C.toByte() -> escaped.append("\\f".utf8)
'\n'.toByte() -> escaped.append("\\n".utf8)
'\r'.toByte() -> escaped.append("\\r".utf8)
'\t'.toByte() -> escaped.append("\\t".utf8)
}
else -> escaped.append(c)
}
}
escaped.string.write(buffer)
buffer.writeByte('"'.toInt())
return this
}
fun value(i: Double): JsonWriter {
buffer.writeBytes(i.toString().toByteArray())
return this
}
fun value(i: Long): JsonWriter {
buffer.writeBytes(i.toString().toByteArray())
return this
}
fun value(i: DateTime) = value(i.millis)
fun value(i: Float) = value(i.toDouble())
fun value(i: Int) = value(i.toLong())
fun value(i: Short) = value(i.toLong())
fun value(i: Byte) = value(i.toLong())
fun value(i: Boolean): JsonWriter {
buffer.writeBytes(if(i) trueBytes else falseBytes)
return this
}
fun value(i: ByteBuf): JsonWriter {
buffer.writeByte('"'.toInt())
val base64 = Base64.getEncoder().encode(i.nioBuffer())
buffer.writeBytes(base64)
buffer.writeByte('"'.toInt())
return this
}
fun value(i: ByteArray): JsonWriter {
buffer.writeByte('"'.toInt())
val base64 = Base64.getEncoder().encode(i)
buffer.writeBytes(base64)
buffer.writeByte('"'.toInt())
return this
}
companion object {
val trueBytes = "true".toByteArray()
val falseBytes = "false".toByteArray()
val nullBytes = "null".toByteArray()
}
} | mit | 8b54540ce1ec90a31b14587ec17a5989 | 27.097403 | 65 | 0.506241 | 4.405295 | false | false | false | false |
is00hcw/anko | preview/intentions/src/org/jetbrains/anko/idea/intentions/AnkoIntention.kt | 2 | 8625 | package org.jetbrains.anko.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.intentions.JetSelfTargetingIntention
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.ExplicitImportsScope
import org.jetbrains.kotlin.resolve.scopes.utils.asLexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsFileScope
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.lowerIfFlexible
abstract class AnkoIntention<TElement : JetElement>(
elementType: Class<TElement>,
text: String,
familyName: String = text
) : JetSelfTargetingIntention<TElement>(elementType, text, familyName) {
private fun isTypeOf(descriptor: ClassifierDescriptor, vararg fqName: String): Boolean {
val resolvedName = DescriptorUtils.getFqNameSafe(descriptor).asString()
return fqName.any { it == resolvedName }
}
protected fun JetCallExpression.isValueParameterTypeOf(parameterIndex: Int, resolvedCall: ResolvedCall<*>?, vararg fqName: String): Boolean {
val ctxArgumentDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.valueParameters?.get(parameterIndex)?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(ctxArgumentDescriptor, *fqName)
}
protected fun JetCallExpression.isReceiverParameterTypeOf(resolvedCall: ResolvedCall<*>?, vararg fqName: String): Boolean {
val receiverDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.dispatchReceiverParameter?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(receiverDescriptor, *fqName)
}
protected val JetDotQualifiedExpression.receiver: JetExpression?
get() = receiverExpression
protected val JetDotQualifiedExpression.selector: JetExpression?
get() = selectorExpression
protected val PsiElement.text: String
get() = getText()
protected val JetBinaryExpressionWithTypeRHS.operation: JetSimpleNameExpression
get() = operationReference
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null, sub: E.() -> Boolean): Boolean {
return require<E>(name) && (this as E).sub()
}
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null): Boolean {
if (this !is E) return false
if (name != null && name != this.getText()) return false
return true
}
protected inline fun PsiElement?.requireCall(functionName: String? = null, argCount: Int? = null, sub: JetCallExpression.() -> Boolean): Boolean {
return requireCall(functionName, argCount) && (this as JetCallExpression).sub()
}
suppress("NOTHING_TO_INLINE")
protected inline fun PsiElement?.requireCall(functionName: String? = null, argCount: Int? = null): Boolean {
if (this !is JetCallExpression) return false
if (functionName != null && functionName != calleeExpression?.getText()) return false
if (argCount != null && argCount != valueArguments.size()) return false
return true
}
private fun getResolutionScope(descriptor: DeclarationDescriptor): LexicalScope {
return when (descriptor) {
is PackageFragmentDescriptor -> {
val moduleDescriptor = descriptor.containingDeclaration
getResolutionScope(moduleDescriptor.getPackage(descriptor.fqName))
}
is PackageViewDescriptor ->
descriptor.memberScope.memberScopeAsFileScope()
is ClassDescriptorWithResolutionScopes ->
descriptor.scopeForMemberDeclarationResolution
is ClassDescriptor -> {
val outerScope = getResolutionScope(descriptor.containingDeclaration)
ClassResolutionScopesSupport(descriptor, LockBasedStorageManager.NO_LOCKS, { outerScope })
.scopeForMemberDeclarationResolution()
}
is FunctionDescriptor ->
FunctionDescriptorUtil.getFunctionInnerScope(getResolutionScope(descriptor.containingDeclaration),
descriptor, RedeclarationHandler.DO_NOTHING)
is PropertyDescriptor ->
JetScopeUtils.getPropertyDeclarationInnerScope(descriptor,
getResolutionScope(descriptor.containingDeclaration),
RedeclarationHandler.DO_NOTHING)
is LocalVariableDescriptor -> {
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor) as JetDeclaration
declaration.analyze()[BindingContext.RESOLUTION_SCOPE, declaration]!!.asLexicalScope()
}
else -> throw IllegalArgumentException("Cannot find resolution scope for $descriptor")
}
}
abstract fun replaceWith(element: TElement, psiFactory: JetPsiFactory): NewElement?
final override fun applyTo(element: TElement, editor: Editor) {
val project = editor.project ?: return
val resolutionFacade = element.getResolutionFacade()
val containingJetDeclaration = JetStubbedPsiUtil.getContainingDeclaration(element) ?: return
val containingDeclaration = resolutionFacade.resolveToDescriptor(containingJetDeclaration)
as? CallableDescriptor ?: return
val jetFile = element.getContainingJetFile()
val psiFactory = JetPsiFactory(project)
val newElement = replaceWith(element, psiFactory) ?: return
val newExpression = newElement.element
val explicitlyImportedSymbols = newElement.newFqNames.flatMap { fqName ->
resolutionFacade.resolveImportReference(jetFile.findModuleDescriptor(), FqName("$ANKO_PACKAGE$fqName"))
}
val symbolScope = getResolutionScope(containingDeclaration)
val scope = LexicalChainedScope(symbolScope, containingDeclaration,
false, null, "ReplaceWith resolution scope", ExplicitImportsScope(explicitlyImportedSymbols))
var bindingContext = analyzeInContext(newExpression, containingDeclaration, scope, resolutionFacade)
val functionDescriptor = newExpression.getResolvedCall(bindingContext)?.resultingDescriptor ?: return
ImportInsertHelper.getInstance(project).importDescriptor(element.getContainingJetFile(), functionDescriptor)
element.replace(newExpression)
}
private fun analyzeInContext(
expression: JetExpression,
symbolDescriptor: CallableDescriptor,
scope: LexicalScope,
resolutionFacade: ResolutionFacade
): BindingContext {
val traceContext = BindingTraceContext()
resolutionFacade.getFrontendService(symbolDescriptor.module, ExpressionTypingServices::class.java)
.getTypeInfo(scope, expression, TypeUtils.NO_EXPECTED_TYPE, DataFlowInfo.EMPTY, traceContext, false)
return traceContext.bindingContext
}
private companion object {
private val ANKO_PACKAGE = "org.jetbrains.anko."
}
}
object FqNames {
val ACTIVITY_FQNAME = "android.app.Activity"
val CONTEXT_FQNAME = "android.content.Context"
val VIEW_FQNAME = "android.view.View"
}
class NewElement(val element: JetExpression, vararg newFqNames: String) {
val newFqNames = newFqNames.toList()
} | apache-2.0 | df4619a5a9e0b4d2566cbbfbb89dcf20 | 47.189944 | 150 | 0.728232 | 5.600649 | false | false | false | false |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/chat/house/HouseOnboardingConversation.kt | 1 | 32914 | package com.hedvig.botService.chat.house
import com.hedvig.botService.utils.ssnLookupAndStore
import com.hedvig.botService.utils.storeAndTrimAndAddSSNToChat
import com.hedvig.botService.utils.storeFamilyName
import com.hedvig.botService.chat.*
import com.hedvig.botService.chat.FreeChatConversation.FREE_CHAT_ONBOARDING_START
import com.hedvig.botService.chat.OnboardingConversationDevi.ProductTypes
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ANCILLARY_AREA
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HAS_EXTRA_BUILDINGS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HAS_WATER_EXTRA_BUILDING
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_LAST_NAME
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ADDRESS_LOOK_UP_SUCCESS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_EXTRA_BUILDING_TYPE_ONE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_BATHROOMS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_EXTRA_BUILDINGS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HOUSEHOLD_MEMBERS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_OR_APARTMENT
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_MORE_EXTRA_BUILDING_TYPE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_REAL_ESTATE_LOOKUP_CORRECT
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS_EXTRA_BUILDING
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS_FAILED_LOOKUP
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SSN
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SSN_UNDER_EIGHTEEN
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_STREET_ADDRESS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SUBLETTING_HOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_YEAR_OF_CONSTRUCTION
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ZIP_CODE
import com.hedvig.botService.chat.house.HouseConversationConstants.CONVERSATION_APARTMENT_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.CONVERSATION_RENT_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.HOUSE_CONVERSATION_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.HOUSE_FIRST
import com.hedvig.botService.chat.house.HouseConversationConstants.IN_LOOP_ASK_EXTRA_BUILDING_TYPE
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_BATHROOMS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_EXTRA_BUILDINGS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_FLOORS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_TOTAL_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_MORE_THAN_FOUR_FLOORS
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_ATTEFALL
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_FRIGGEBO
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_GARAGE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_HAS_WATER_NO
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_HAS_WATER_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_ADDRESS_LOOK_UP_SUCCESS_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_APARTMENT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_BOATHOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_CARPORT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_GUESTHOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_SAUNA
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_RENT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_SUBLETTING_HOUSE_YES
import com.hedvig.botService.dataTypes.*
import com.hedvig.botService.enteties.UserContext
import com.hedvig.botService.enteties.message.*
import com.hedvig.botService.serviceIntegration.lookupService.LookupService
import com.hedvig.botService.serviceIntegration.lookupService.dto.RealEstateDto
import com.hedvig.botService.serviceIntegration.memberService.MemberService
import com.hedvig.botService.serviceIntegration.memberService.dto.Nationality
import com.hedvig.botService.serviceIntegration.productPricing.dto.ExtraBuildingType
import com.hedvig.botService.services.events.HouseUnderwritingLimitCallMeExceedsEvent
import com.hedvig.botService.utils.ConversationUtils.isYoungerThan18
import com.hedvig.botService.utils.MessageUtil
import com.hedvig.libs.translations.Translations
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationEventPublisher
class HouseOnboardingConversation
constructor(
private val memberService: MemberService,
private val lookupService: LookupService,
override var eventPublisher: ApplicationEventPublisher,
private val conversationFactory: ConversationFactory,
translations: Translations,
userContext: UserContext
) : Conversation(eventPublisher, translations, userContext) {
var queuePos: Int? = null
init {
createInputMessage(
HOUSE_FIRST
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_RENT.value -> {
userContext.onBoardingData.houseType = ProductTypes.RENT.toString()
ASK_SSN.id
}
else -> {
userContext.onBoardingData.houseType = ProductTypes.HOUSE.toString()
ASK_SSN.id
}
}
}
createInputMessage(
ASK_SSN
) { body, userContext, message ->
handleSsnResponse(body, message)
}
this.setExpectedReturnType(ASK_SSN.id, SSNSweden())
createInputMessage(
ASK_SSN_UNDER_EIGHTEEN
) { body, userContext, message ->
handleSsnResponse(body, message)
}
this.setExpectedReturnType(ASK_SSN_UNDER_EIGHTEEN.id, SSNSweden())
createInputMessage(
ASK_LAST_NAME
) { body, userContext, message ->
userContext.storeFamilyName(body)
addToChat(message)
ASK_STREET_ADDRESS.id
}
createInputMessage(
ASK_STREET_ADDRESS
) { _, userContext, message ->
userContext.onBoardingData.addressStreet = message.body.text
addToChat(message)
ASK_ZIP_CODE.id
}
createInputMessage(
ASK_ZIP_CODE
) { body, userContext, message ->
userContext.onBoardingData.addressZipCode = message.body.text
addToChat(message)
if (userContext.hasHouseProduct()) {
realEstateLookup()
} else {
ASK_SQUARE_METERS.id
}
}
this.setExpectedReturnType(ASK_ZIP_CODE.id, ZipCodeSweden())
createInputMessage(
ASK_SQUARE_METERS
) { body, userContext, message ->
handleSquareMetersResponse(message)
}
this.setExpectedReturnType(ASK_SQUARE_METERS.id, HouseLivingSpaceSquareMeters())
createInputMessage(
ASK_SQUARE_METERS_FAILED_LOOKUP
) { body, userContext, message ->
handleSquareMetersResponse(message)
}
this.setExpectedReturnType(ASK_SQUARE_METERS_FAILED_LOOKUP.id, HouseLivingSpaceSquareMeters())
createInputMessage(
ASK_ANCILLARY_AREA
) { body, userContext, message ->
val ancillaryArea = (message.body as MessageBodyNumber).value
userContext.onBoardingData.houseAncillaryArea = ancillaryArea
addToChat(message)
if (ancillaryArea + userContext.onBoardingData.livingSpace > MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM) {
MORE_TOTAL_SQM_QUESTIONS_CALL.id
} else {
ASK_YEAR_OF_CONSTRUCTION.id
}
}
this.setExpectedReturnType(ASK_ANCILLARY_AREA.id, AncillaryAreaSquareMeters())
createInputMessage(
ASK_YEAR_OF_CONSTRUCTION
) { body, userContext, message ->
val yearOfConstruction = (message.body as MessageBodyNumber).value
userContext.onBoardingData.yearOfConstruction = yearOfConstruction
addToChat(message)
if (yearOfConstruction < MIN_YEAR_OF_CONSTRUCTION) {
MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL.id
} else {
ASK_NUMBER_OF_BATHROOMS.id
}
}
this.setExpectedReturnType(ASK_YEAR_OF_CONSTRUCTION.id, HouseYearOfConstruction())
createInputMessage(
ASK_NUMBER_OF_BATHROOMS
) { body, userContext, message ->
handleNumberOfBathroomsResponse(message)
}
this.setExpectedReturnType(ASK_NUMBER_OF_BATHROOMS.id, HouseBathrooms())
createInputMessage(
ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP
) { body, userContext, message ->
handleNumberOfBathroomsResponse(message)
}
this.setExpectedReturnType(ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP.id, HouseBathrooms())
createInputMessage(
ASK_HOUSE_HOUSEHOLD_MEMBERS
) { body, userContext, message ->
handleHouseholdMembersResponse(message)
}
this.setExpectedReturnType(ASK_HOUSE_HOUSEHOLD_MEMBERS.id, HouseholdMemberNumber())
createInputMessage(
ASK_SUBLETTING_HOUSE
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_SUBLETTING_HOUSE_YES.value -> {
userContext.onBoardingData.isSubLetting = true
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES.id
}
else -> {
userContext.onBoardingData.isSubLetting = false
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO.id
}
}
}
createInputMessage(
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES
) { body, userContext, message ->
handleFloorsResponse(body, message)
}
createInputMessage(
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO
) { body, userContext, message ->
handleFloorsResponse(body, message)
}
createInputMessage(
ASK_HAS_EXTRA_BUILDINGS
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_YES.value -> {
userContext.onBoardingData.hasExtraBuildings = true
ASK_NUMBER_OF_EXTRA_BUILDINGS.id
}
else -> {
userContext.onBoardingData.hasExtraBuildings = false
userContext.onBoardingData.nrExtraBuildings = 0
HOUSE_CONVERSATION_DONE
}
}
}
createInputMessage(
ASK_NUMBER_OF_EXTRA_BUILDINGS
) { body, userContext, message ->
addToChat(message)
userContext.onBoardingData.nrExtraBuildings = body.value
when {
body.value == 0 -> {
HOUSE_CONVERSATION_DONE
}
body.value > MAX_NUMBER_OF_EXTRA_BUILDING -> {
MORE_EXTRA_BUILDINGS_QUESTIONS_CALL.id
}
body.value == 1 -> {
ASK_EXTRA_BUILDING_TYPE_ONE.id
}
else -> {
ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE.id
}
}
}
this.setExpectedReturnType(ASK_NUMBER_OF_EXTRA_BUILDINGS.id, HouseExtraBuildings())
createInputMessage(
ASK_EXTRA_BUILDING_TYPE_ONE
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, 1)
}
createInputMessage(
ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, 1)
}
for (buildingNumber in 1..4) {
if (buildingNumber != 1) {
createInputMessage(
IN_LOOP_ASK_EXTRA_BUILDING_TYPE,
buildingNumber
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, buildingNumber)
}
}
createInputMessage(
ASK_MORE_EXTRA_BUILDING_TYPE,
buildingNumber
) { body, userContext, message ->
handleMoreExtraBuildingTypeResponse(body, userContext, message, buildingNumber)
}
createInputMessage(
ASK_SQUARE_METERS_EXTRA_BUILDING,
buildingNumber
) { body, userContext, message ->
val extraBuildingSQM = (message.body as MessageBodyNumber).value
userContext.onBoardingData.setHouseExtraBuildingSQM(
extraBuildingSQM,
buildingNumber
)
addToChat(message)
if (extraBuildingSQM > MAX_EXTRA_BUILDING_SQM) {
MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL.id
} else {
ASK_HAS_WATER_EXTRA_BUILDING.id + buildingNumber
}
}
this.setExpectedReturnType(ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber, HouseExtraBuildingSQM())
createInputMessage(
ASK_HAS_WATER_EXTRA_BUILDING,
buildingNumber
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_HAS_WATER_YES.value -> {
userContext.onBoardingData.setHouseExtraBuildingHasWater(true, buildingNumber)
}
SELECT_EXTRA_BUILDING_HAS_WATER_NO.value -> {
userContext.onBoardingData.setHouseExtraBuildingHasWater(false, buildingNumber)
}
}
if (userContext.onBoardingData.nrExtraBuildings <= buildingNumber) {
HOUSE_CONVERSATION_DONE
} else {
IN_LOOP_ASK_EXTRA_BUILDING_TYPE.id + (1 + buildingNumber)
}
}
}
createInputMessage(
ASK_ADDRESS_LOOK_UP_SUCCESS
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_ADDRESS_LOOK_UP_SUCCESS_YES.value -> {
if (userContext.hasHouseProduct()) {
realEstateLookup()
} else {
ASK_SQUARE_METERS.id
}
}
else -> ASK_STREET_ADDRESS.id
}
}
createInputMessage(
ASK_REAL_ESTATE_LOOKUP_CORRECT
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES.value -> {
when {
userContext.onBoardingData.livingSpace > MAX_LIVING_SPACE_SQM ->
MORE_SQM_QUESTIONS_CALL.id
(userContext.onBoardingData.houseAncillaryArea +
userContext.onBoardingData.livingSpace) > MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM ->
MORE_TOTAL_SQM_QUESTIONS_CALL.id
userContext.onBoardingData.yearOfConstruction < MIN_YEAR_OF_CONSTRUCTION ->
MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL.id
else ->
ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP.id
}
}
else -> ASK_SQUARE_METERS.id
}
}
addAskMoreQuestionsMessage(MORE_SQM_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_TOTAL_SQM_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_FLOORS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_BATHROOMS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_EXTRA_BUILDINGS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL)
//To be able edit house/apartment answer
createInputMessage(
ASK_HOUSE_OR_APARTMENT
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_APARTMENT.value -> {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_LAGENHET_NO_PERSONNUMMER
)
CONVERSATION_APARTMENT_DONE
}
else -> ASK_SSN.id
}
}
}
private fun realEstateLookup(): String =
lookupService.realEstateLookup(
userContext.memberId,
RealEstateDto(
userContext.onBoardingData.addressStreet,
userContext.onBoardingData.addressZipCode.replace(" ", "")
)
)?.let { realEstate ->
userContext.onBoardingData.apply {
houseAncillaryArea = realEstate.ancillaryArea
yearOfConstruction = realEstate.yearOfConstruction
livingSpace = realEstate.livingSpace.toFloat()
}
ASK_REAL_ESTATE_LOOKUP_CORRECT.id
} ?: ASK_SQUARE_METERS.id
private fun handleSsnResponse(body: MessageBodyNumber, message: Message): String {
val (trimmedSSN, memberBirthDate) = userContext.storeAndTrimAndAddSSNToChat(body) {
message.body.text = it
addToChat(message)
it
}
if (isYoungerThan18(memberBirthDate)) {
return ASK_SSN_UNDER_EIGHTEEN.id
}
val hasAddress = memberService.ssnLookupAndStore(userContext, trimmedSSN, Nationality.SWEDEN)
return if (hasAddress) {
ASK_ADDRESS_LOOK_UP_SUCCESS.id
} else {
ASK_LAST_NAME.id
}
}
private fun addAskMoreQuestionsMessage(message: NumberInputMessage) {
createInputMessage(
message
) { body, userContext, message ->
addToChat(message)
userContext.completeConversation(this)
val phoneNumber = message.body.text
userContext.onBoardingData.phoneNumber = phoneNumber
val reason = MessageUtil.getBaseMessageId(message.id)
.replace("message.house.more.questions.call.", "")
.replace(".", " ")
eventPublisher.publishEvent(
HouseUnderwritingLimitCallMeExceedsEvent(
userContext.memberId,
userContext.onBoardingData.firstName,
userContext.onBoardingData.familyName,
phoneNumber,
reason
)
)
val conversation = conversationFactory.createConversation(FreeChatConversation::class.java, userContext)
userContext.startConversation(conversation, FREE_CHAT_ONBOARDING_START)
FREE_CHAT_ONBOARDING_START
}
}
private fun handleFloorsResponse(body: MessageBodySingleSelect, message: Message): String {
message.body.text = body.selectedItem.text
addToChat(message)
return when (body.selectedItem.value) {
SELECT_MORE_THAN_FOUR_FLOORS.value -> {
MORE_FLOORS_QUESTIONS_CALL.id
}
else -> {
ASK_HAS_EXTRA_BUILDINGS.id
}
}
}
private fun handleSquareMetersResponse(message: Message): String {
val livingSpace = (message.body as MessageBodyNumber).value.toFloat()
userContext.onBoardingData.livingSpace = livingSpace
addToChat(message)
return if (userContext.hasHouseProduct()) {
if (livingSpace > MAX_LIVING_SPACE_SQM) {
MORE_SQM_QUESTIONS_CALL.id
} else {
ASK_ANCILLARY_AREA.id
}
} else {
if (livingSpace > OnboardingConversationDevi.MAX_LIVING_SPACE_RENT_SQM) {
MORE_SQM_QUESTIONS_CALL.id
} else {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_ASK_NR_RESIDENTS
)
CONVERSATION_RENT_DONE
}
}
}
private fun handleNumberOfBathroomsResponse(message: Message): String {
val bathrooms = (message.body as MessageBodyNumber).value
userContext.onBoardingData.numberOfBathrooms = bathrooms
addToChat(message)
return if (bathrooms > MAX_NUMBER_OF_BATHROOMS) {
MORE_BATHROOMS_QUESTIONS_CALL.id
} else {
ASK_HOUSE_HOUSEHOLD_MEMBERS.id
}
}
private fun handleHouseholdMembersResponse(message: Message): String {
val nrPersons = (message.body as MessageBodyNumber).value
userContext.onBoardingData.setPersonInHouseHold(nrPersons)
addToChat(message)
return if (nrPersons > MAX_NUMBER_OF_HOUSE_HOLD_MEMBERS) {
MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL.id
} else {
ASK_SUBLETTING_HOUSE.id
}
}
private fun handleExtraBuildingTypeResponse(
body: MessageBodySingleSelect,
userContext: UserContext,
message: Message,
buildingNumber: Int
): String {
message.body.text = body.selectedItem.text
addToChat(message)
return when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_GARAGE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.GARAGE,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
SELECT_EXTRA_BUILDING_FRIGGEBO.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.FRIGGEBOD,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
SELECT_EXTRA_BUILDING_ATTEFALL.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.ATTEFALL,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
else -> {
ASK_MORE_EXTRA_BUILDING_TYPE.id + buildingNumber
}
}
}
private fun handleMoreExtraBuildingTypeResponse(
body: MessageBodySingleSelect,
userContext: UserContext,
message: Message,
buildingNumber: Int
): String {
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_GUESTHOUSE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.GUESTHOUSE,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_CARPORT.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.CARPORT,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_SAUNA.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.SAUNA,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_BOATHOUSE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.BOATHOUSE,
buildingNumber,
this.userContext.locale,
translations
)
}
else -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.OTHER,
buildingNumber,
this.userContext.locale,
translations
)
}
}
return ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
public override fun completeRequest(nxtMsg: String) {
var nxtMsg = nxtMsg
when (nxtMsg) {
HOUSE_CONVERSATION_DONE -> {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_50K_LIMIT
)
}
"" -> {
log.error("I dont know where to go next...")
nxtMsg = "error"
}
}
super.completeRequest(nxtMsg)
}
override fun init() {
log.info("Starting house conversation")
startConversation(HOUSE_FIRST.id)
}
override fun init(startMessage: String) {
log.info("Starting house onboarding conversation with message: $startMessage")
startConversation(startMessage) // Id of first message
}
override fun handleMessage(m: Message) {
var nxtMsg = ""
if (!validateReturnType(m)) {
return
}
// Lambda
if (this.hasSelectItemCallback(m.id) && m.body.javaClass == MessageBodySingleSelect::class.java) {
// MessageBodySingleSelect body = (MessageBodySingleSelect) m.body;
nxtMsg = this.execSelectItemCallback(m.id, m.body as MessageBodySingleSelect)
addToChat(m)
}
val onBoardingData = userContext.onBoardingData
// ... and then the incoming message id
nxtMsg = m.id
addToChat(m)
completeRequest(nxtMsg)
}
override fun receiveEvent(e: EventTypes, value: String) {
when (e) {
// This is used to let Hedvig say multiple message after another
EventTypes.MESSAGE_FETCHED -> {
log.info("Message fetched: $value")
// New way of handeling relay messages
val relay = getRelay(value)
if (relay != null) {
completeRequest(relay)
}
}
}
}
override fun canAcceptAnswerToQuestion(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSelectItemsForAnswer(): List<SelectItem> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun createInputMessage(
message: SingleSelectMessage,
ordinal: Int? = null,
callback: (MessageBodySingleSelect, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodySingleSelect(
message.text,
message.selectOptions.map { SelectOption(it.text, it.value) }
),
receiveMessageCallback = callback
)
)
}
private fun createInputMessage(
message: NumberInputMessage,
ordinal: Int? = null,
callback: (MessageBodyNumber, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodyNumber(
message.text,
message.placeholder
),
receiveMessageCallback = callback
)
)
}
private fun createInputMessage(
message: TextInputMessage,
ordinal: Int? = null,
callback: (MessageBodyText, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodyText(
message.text,
message.textContentType,
message.keyboardType,
message.placeholder
),
receiveMessageCallback = callback
)
)
}
private fun UserContext.hasHouseProduct() =
this.onBoardingData.houseType == ProductTypes.HOUSE.toString()
companion object {
private val log = LoggerFactory.getLogger(HouseOnboardingConversation::class.java)
private const val MAX_LIVING_SPACE_SQM = 250
private const val MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM = 300
private const val MIN_YEAR_OF_CONSTRUCTION = 1925
private const val MAX_NUMBER_OF_HOUSE_HOLD_MEMBERS = 6
private const val MAX_NUMBER_OF_BATHROOMS = 2
private const val MAX_NUMBER_OF_EXTRA_BUILDING = 4
private const val MAX_EXTRA_BUILDING_SQM = 75
}
}
| agpl-3.0 | ff6767ebd288d0e9e52a5895816be90c | 40.193992 | 122 | 0.623261 | 5.215338 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/extensions/XmlAttributeExtensions.kt | 1 | 2609 | package co.nums.intellij.aem.htl.extensions
import co.nums.intellij.aem.htl.HtlLanguage
import co.nums.intellij.aem.htl.definitions.HtlBlock
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.*
private val htlBlockTypes = HtlBlock.values().map { it.type }
private val htlVariableBlockTypes = HtlBlock.values().filter { it.identifierType.isVariable() }.map { it.type }
private val htlImplicitVariableBlockTypes = HtlBlock.values().filter { it.iterable }.map { it.type }
fun XmlAttribute.isHtlBlock() = (firstChild as? XmlToken)?.isHtlBlock() ?: false
fun XmlAttribute.isHtlVariableBlock(): Boolean {
val blockType = (firstChild as? XmlToken)?.text?.substringBefore(".")?.toLowerCase()
return blockType in htlVariableBlockTypes
}
fun XmlAttribute.isHtlVariableDeclaration(): Boolean {
val blockName = (firstChild as? XmlToken)?.text ?: return false
val blockType = blockName.substringBefore(".").toLowerCase()
return blockType in htlVariableBlockTypes
&& (blockType in htlImplicitVariableBlockTypes || blockHasIdentifier(blockName))
}
private fun blockHasIdentifier(blockName: String): Boolean {
val blockIdentifier = blockName.substringAfter('.', missingDelimiterValue = "")
return blockIdentifier.isNotEmpty()
}
fun XmlAttribute.isHtlTemplateBlock(): Boolean {
val blockName = (firstChild as? XmlToken)?.text ?: return false
val blockType = blockName.substringBefore(".").toLowerCase()
return blockType == HtlBlock.TEMPLATE.type
}
fun XmlToken.isHtlBlock() = htlBlockTypes.contains(text.substringBefore(".").toLowerCase())
/**
* Returns declared use object type from XML attribute or from HTL expression in XML attribute.
* Returns `null` if type cannot be retrieved. Method does not check whether this XML attribute
* is actually `data-sly-use`.
*
* @return use object type or `null`
*/
fun XmlAttribute.getUseObjectType(): String? {
var useObjectType: String
val blockValue = this.valueElement ?: return null
val htlFile = blockValue.containingFile.viewProvider.getPsi(HtlLanguage) ?: return null
val htlExpressionStart = htlFile.findElementAt(blockValue.textOffset) ?: return null
if (htlExpressionStart.isHtlExpressionToken()) {
val nextToken = PsiTreeUtil.nextVisibleLeaf(htlExpressionStart) ?: return null
useObjectType = if (nextToken.isPartOfHtlString()) nextToken.text else ""
} else {
useObjectType = blockValue.text
}
useObjectType = useObjectType.trim('"', '\'', ' ')
if (useObjectType.isBlank()) {
return null
}
return useObjectType
}
| gpl-3.0 | 75b320abc2154f52ff4686d74a5ba7ed | 41.080645 | 111 | 0.74013 | 4.642349 | false | false | false | false |
kjkrol/kotlin4fun-eshop-app | customer-register-service/src/main/kotlin/kotlin4fun/eshop/customerregister/customer/Customer.kt | 1 | 1134 | package kotlin4fun.eshop.customerregister.customer
import org.hibernate.annotations.Type
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.query.Param
import java.util.UUID
import java.util.UUID.randomUUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "customers")
data class Customer(@Id @Type(type = "uuid-char") val id: UUID = randomUUID(),
@Column(name = "firstname") val firstName: String,
@Column(name = "lastname") val lastName: String)
interface CustomerRepository : JpaRepository<Customer, UUID> {
fun findByFirstNameAndLastName(@Param("firstName") firstName: String,
@Param("lastName") lastName: String, pageable: Pageable): Page<Customer>
fun findByFirstName(firstName: String, pageable: Pageable): Page<Customer>
fun findByLastName(lastName: String, pageable: Pageable): Page<Customer>
} | apache-2.0 | 80be14b3bb66ad5a8db12e2588b9e702 | 42.653846 | 107 | 0.748677 | 4.361538 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/featured/FeaturedArticleCardView.kt | 1 | 4555 | package org.wikipedia.feed.featured
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import org.wikipedia.databinding.ViewCardFeaturedArticleBinding
import org.wikipedia.feed.view.CardFooterView
import org.wikipedia.feed.view.DefaultFeedCardView
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.settings.SiteInfoClient
import org.wikipedia.views.ImageZoomHelper
@Suppress("LeakingThis")
open class FeaturedArticleCardView(context: Context) : DefaultFeedCardView<FeaturedArticleCard>(context) {
private val binding = ViewCardFeaturedArticleBinding.inflate(LayoutInflater.from(context), this, true)
init {
binding.viewFeaturedArticleCardContentContainer.setOnClickListener {
card?.let {
callback?.onSelectPage(it, it.historyEntry(), binding.viewWikiArticleCard.getSharedElements())
}
}
binding.viewFeaturedArticleCardContentContainer.setOnLongClickListener { view ->
if (ImageZoomHelper.isZooming) {
ImageZoomHelper.dispatchCancelEvent(binding.viewFeaturedArticleCardContentContainer)
} else {
LongPressMenu(view, true, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) {
card?.let {
callback?.onSelectPage(it, entry, false)
}
}
override fun onOpenInNewTab(entry: HistoryEntry) {
card?.let {
callback?.onSelectPage(it, entry, true)
}
}
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
callback?.onAddPageToList(entry, addToDefault)
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
callback?.onMovePageToList(page!!.listId, entry)
}
}).show(card?.historyEntry())
}
false
}
}
override var card: FeaturedArticleCard? = null
set(value) {
field = value
value?.let {
setLayoutDirectionByWikiSite(it.wikiSite(), binding.viewFeaturedArticleCardContentContainer)
articleTitle(it.articleTitle())
articleSubtitle(it.articleSubtitle())
extract(it.extract())
image(it.image())
header(it)
footer(it)
}
}
override var callback: FeedAdapter.Callback? = null
set(value) {
field = value
binding.viewFeaturedArticleCardHeader.setCallback(value)
}
private fun articleTitle(articleTitle: String) {
binding.viewWikiArticleCard.setTitle(articleTitle)
}
private fun articleSubtitle(articleSubtitle: String?) {
binding.viewWikiArticleCard.setDescription(articleSubtitle)
}
private fun extract(extract: String?) {
binding.viewWikiArticleCard.setExtract(extract, EXTRACT_MAX_LINES)
}
private fun header(card: FeaturedArticleCard) {
binding.viewFeaturedArticleCardHeader.setTitle(card.title())
.setLangCode(card.wikiSite().languageCode)
.setCard(card)
.setCallback(callback)
}
private fun footer(card: FeaturedArticleCard) {
binding.viewFeaturedArticleCardFooter.callback = footerCallback
binding.viewFeaturedArticleCardFooter.setFooterActionText(card.footerActionText(), card.wikiSite().languageCode)
}
private fun image(uri: Uri?) {
binding.viewWikiArticleCard.setImageUri(uri, false)
uri?.run {
ImageZoomHelper.setViewZoomable(binding.viewWikiArticleCard.getImageView())
}
}
open val footerCallback: CardFooterView.Callback?
get() = CardFooterView.Callback {
card?.let {
callback?.onSelectPage(it, HistoryEntry(PageTitle(
SiteInfoClient.getMainPageForLang(it.wikiSite().languageCode), it.wikiSite()),
it.historyEntry().source), false
)
}
}
companion object {
const val EXTRACT_MAX_LINES = 8
}
}
| apache-2.0 | 784aa98551e4705fdd36341a56d64ea8 | 36.03252 | 120 | 0.629199 | 5.47476 | false | false | false | false |
bl-lia/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/notification/NotificationAdapter.kt | 3 | 4942 | package com.bl_lia.kirakiratter.presentation.adapter.notification
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Notification
import com.bl_lia.kirakiratter.domain.entity.Status
import io.reactivex.subjects.PublishSubject
class NotificationAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
enum class ViewType(val value: Int) {
Follow(1), Boost(2), Favourite(3), Reblog(4), Mention(5);
companion object {
fun valueOf(value: Int): ViewType? =
ViewType.values().find { it.value == value }
}
}
val onClickAccount = PublishSubject.create<Pair<Account, ImageView>>()
val onClickReply = PublishSubject.create<Status>()
val onClickReblog = PublishSubject.create<Notification>()
val onClickFavourite = PublishSubject.create<Notification>()
val onClickTranslate = PublishSubject.create<Notification>()
private val list: MutableList<Notification> = mutableListOf()
val maxId: Int?
get() {
if (list.isEmpty()) {
return null
}
return list.last().id
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder =
when (ViewType.valueOf(viewType)) {
ViewType.Boost,
ViewType.Favourite,
ViewType.Reblog,
ViewType.Mention -> {
val view = LayoutInflater.from(parent?.context).inflate(NotificationItemViewHolder.LAYOUT, parent, false)
NotificationItemViewHolder.newInstance(view)
}
ViewType.Follow -> {
val view = LayoutInflater.from(parent?.context).inflate(NotificationFollowItemViewHolder.LAYOUT, parent, false)
NotificationFollowItemViewHolder.newInstance(view)
}
else -> throw RuntimeException("No ViewHolder found")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is NotificationItemViewHolder) {
holder.bind(list[position])
holder.onClickAccount.subscribe(onClickAccount)
holder.onClickReply.subscribe(onClickReply)
holder.onClickReblog.subscribe(onClickReblog)
holder.onClickFavourite.subscribe(onClickFavourite)
holder.onClickTranslate.subscribe(onClickTranslate)
return
}
if (holder is NotificationFollowItemViewHolder) {
holder.bind(list[position])
holder.onClickAccount.subscribe(onClickAccount)
return
}
}
override fun getItemViewType(position: Int): Int =
when (list[position].type) {
"follow" -> ViewType.Follow.value
"favourite" -> ViewType.Favourite.value
"reblog" -> ViewType.Reblog.value
"boost" -> ViewType.Boost.value
"mention" -> ViewType.Mention.value
else -> -1
}
fun reset(newList: List<Notification>) {
list.clear()
list.addAll(newList)
notifyDataSetChanged()
}
fun add(moreList: List<Notification>) {
list.addAll(moreList)
notifyDataSetChanged()
}
fun update(notification: Notification) {
list.indexOfFirst {
it.id == notification.id
}.also { index ->
if (index > -1) {
list.set(index, notification)
notifyItemChanged(index)
}
}
}
fun addTranslatedText(notification: Notification, translatedText: String) {
list.indexOfFirst {
it.id == notification.id
}.also { index ->
if (index > -1) {
val s = if (notification.status?.reblog != null) {
notification.copy(
status = notification.status.copy(
reblog = notification.status.reblog.copy(
content = notification.status.reblog.content?.copy(translatedText = translatedText)
)
)
)
} else {
notification.copy(
status = notification.status?.copy(
content = notification.status.content?.copy(translatedText = translatedText)
)
)
}
list.set(index, s)
notifyItemChanged(index)
}
}
}
} | mit | 84f390b5f0fbba805e8fa1b7289d8a8f | 36.165414 | 131 | 0.569 | 5.412924 | false | false | false | false |
stripe/stripe-android | financial-connections/src/main/java/com/stripe/android/financialconnections/model/BankAccount.kt | 1 | 637 | package com.stripe.android.financialconnections.model
import androidx.annotation.RestrictTo
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Required
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
data class BankAccount(
@SerialName(value = "id") @Required
val id: String,
@SerialName(value = "last4") @Required
val last4: String,
@SerialName(value = "bank_name") val bankName: String? = null,
@SerialName(value = "routing_number") val routingNumber: String? = null
) : PaymentAccount()
| mit | 88e9b4078c28d139343e85a9b82d300a | 25.541667 | 75 | 0.767661 | 4.136364 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/network/Domain.kt | 1 | 79713 | package pl.wendigo.chrome.api.network
import kotlinx.serialization.json.Json
/**
* Network domain allows tracking network activities of the page. It exposes information about http,
file, data and other requests and responses, their headers, bodies, timing, etc.
*
* @link Protocol [Network](https://chromedevtools.github.io/devtools-protocol/tot/Network) domain documentation.
*/
class NetworkDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain(
"Network",
"""Network domain allows tracking network activities of the page. It exposes information about http,
file, data and other requests and responses, their headers, bodies, timing, etc.""",
connection
) {
/**
* Tells whether clearing browser cache is supported.
*
* @link Protocol [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canClearBrowserCache is deprecated.")
fun canClearBrowserCache(): io.reactivex.rxjava3.core.Single<CanClearBrowserCacheResponse> = connection.request("Network.canClearBrowserCache", null, CanClearBrowserCacheResponse.serializer())
/**
* Tells whether clearing browser cookies is supported.
*
* @link Protocol [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canClearBrowserCookies is deprecated.")
fun canClearBrowserCookies(): io.reactivex.rxjava3.core.Single<CanClearBrowserCookiesResponse> = connection.request("Network.canClearBrowserCookies", null, CanClearBrowserCookiesResponse.serializer())
/**
* Tells whether emulation of network conditions is supported.
*
* @link Protocol [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canEmulateNetworkConditions is deprecated.")
fun canEmulateNetworkConditions(): io.reactivex.rxjava3.core.Single<CanEmulateNetworkConditionsResponse> = connection.request("Network.canEmulateNetworkConditions", null, CanEmulateNetworkConditionsResponse.serializer())
/**
* Clears browser cache.
*
* @link Protocol [Network#clearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCache) method documentation.
*/
fun clearBrowserCache(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.clearBrowserCache", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Clears browser cookies.
*
* @link Protocol [Network#clearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCookies) method documentation.
*/
fun clearBrowserCookies(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.clearBrowserCookies", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Response to Network.requestIntercepted which either modifies the request to continue with any
modifications, or blocks it, or completes it with the provided response bytes. If a network
fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
event will be sent with the same InterceptionId.
Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
*
* @link Protocol [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "continueInterceptedRequest is deprecated.")
@pl.wendigo.chrome.protocol.Experimental
fun continueInterceptedRequest(input: ContinueInterceptedRequestRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.continueInterceptedRequest", Json.encodeToJsonElement(ContinueInterceptedRequestRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Deletes browser cookies with matching name and url or domain/path pair.
*
* @link Protocol [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) method documentation.
*/
fun deleteCookies(input: DeleteCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.deleteCookies", Json.encodeToJsonElement(DeleteCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disables network tracking, prevents network events from being sent to the client.
*
* @link Protocol [Network#disable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Activates emulation of network conditions.
*
* @link Protocol [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) method documentation.
*/
fun emulateNetworkConditions(input: EmulateNetworkConditionsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.emulateNetworkConditions", Json.encodeToJsonElement(EmulateNetworkConditionsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enables network tracking, network events will now be delivered to the client.
*
* @link Protocol [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) method documentation.
*/
fun enable(input: EnableRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.enable", Json.encodeToJsonElement(EnableRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Returns all browser cookies. Depending on the backend support, will return detailed cookie
information in the `cookies` field.
*
* @link Protocol [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) method documentation.
*/
fun getAllCookies(): io.reactivex.rxjava3.core.Single<GetAllCookiesResponse> = connection.request("Network.getAllCookies", null, GetAllCookiesResponse.serializer())
/**
* Returns the DER-encoded certificate.
*
* @link Protocol [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getCertificate(input: GetCertificateRequest): io.reactivex.rxjava3.core.Single<GetCertificateResponse> = connection.request("Network.getCertificate", Json.encodeToJsonElement(GetCertificateRequest.serializer(), input), GetCertificateResponse.serializer())
/**
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
*
* @link Protocol [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
*/
fun getCookies(input: GetCookiesRequest): io.reactivex.rxjava3.core.Single<GetCookiesResponse> = connection.request("Network.getCookies", Json.encodeToJsonElement(GetCookiesRequest.serializer(), input), GetCookiesResponse.serializer())
/**
* Returns content served for the given request.
*
* @link Protocol [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
*/
fun getResponseBody(input: GetResponseBodyRequest): io.reactivex.rxjava3.core.Single<GetResponseBodyResponse> = connection.request("Network.getResponseBody", Json.encodeToJsonElement(GetResponseBodyRequest.serializer(), input), GetResponseBodyResponse.serializer())
/**
* Returns post data sent with the request. Returns an error when no data was sent with the request.
*
* @link Protocol [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
*/
fun getRequestPostData(input: GetRequestPostDataRequest): io.reactivex.rxjava3.core.Single<GetRequestPostDataResponse> = connection.request("Network.getRequestPostData", Json.encodeToJsonElement(GetRequestPostDataRequest.serializer(), input), GetRequestPostDataResponse.serializer())
/**
* Returns content served for the given currently intercepted request.
*
* @link Protocol [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getResponseBodyForInterception(input: GetResponseBodyForInterceptionRequest): io.reactivex.rxjava3.core.Single<GetResponseBodyForInterceptionResponse> = connection.request("Network.getResponseBodyForInterception", Json.encodeToJsonElement(GetResponseBodyForInterceptionRequest.serializer(), input), GetResponseBodyForInterceptionResponse.serializer())
/**
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
*
* @link Protocol [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun takeResponseBodyForInterceptionAsStream(input: TakeResponseBodyForInterceptionAsStreamRequest): io.reactivex.rxjava3.core.Single<TakeResponseBodyForInterceptionAsStreamResponse> = connection.request("Network.takeResponseBodyForInterceptionAsStream", Json.encodeToJsonElement(TakeResponseBodyForInterceptionAsStreamRequest.serializer(), input), TakeResponseBodyForInterceptionAsStreamResponse.serializer())
/**
* This method sends a new XMLHttpRequest which is identical to the original one. The following
parameters should be identical: method, url, async, request body, extra headers, withCredentials
attribute, user, password.
*
* @link Protocol [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun replayXHR(input: ReplayXHRRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.replayXHR", Json.encodeToJsonElement(ReplayXHRRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Searches for given string in response content.
*
* @link Protocol [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun searchInResponseBody(input: SearchInResponseBodyRequest): io.reactivex.rxjava3.core.Single<SearchInResponseBodyResponse> = connection.request("Network.searchInResponseBody", Json.encodeToJsonElement(SearchInResponseBodyRequest.serializer(), input), SearchInResponseBodyResponse.serializer())
/**
* Blocks URLs from loading.
*
* @link Protocol [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setBlockedURLs(input: SetBlockedURLsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setBlockedURLs", Json.encodeToJsonElement(SetBlockedURLsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Toggles ignoring of service worker for each request.
*
* @link Protocol [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setBypassServiceWorker(input: SetBypassServiceWorkerRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setBypassServiceWorker", Json.encodeToJsonElement(SetBypassServiceWorkerRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Toggles ignoring cache for each request. If `true`, cache will not be used.
*
* @link Protocol [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) method documentation.
*/
fun setCacheDisabled(input: SetCacheDisabledRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setCacheDisabled", Json.encodeToJsonElement(SetCacheDisabledRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @link Protocol [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
*/
fun setCookie(input: SetCookieRequest): io.reactivex.rxjava3.core.Single<SetCookieResponse> = connection.request("Network.setCookie", Json.encodeToJsonElement(SetCookieRequest.serializer(), input), SetCookieResponse.serializer())
/**
* Sets given cookies.
*
* @link Protocol [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) method documentation.
*/
fun setCookies(input: SetCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setCookies", Json.encodeToJsonElement(SetCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* For testing.
*
* @link Protocol [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setDataSizeLimitsForTest(input: SetDataSizeLimitsForTestRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setDataSizeLimitsForTest", Json.encodeToJsonElement(SetDataSizeLimitsForTestRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Specifies whether to always send extra HTTP headers with the requests from this page.
*
* @link Protocol [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) method documentation.
*/
fun setExtraHTTPHeaders(input: SetExtraHTTPHeadersRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setExtraHTTPHeaders", Json.encodeToJsonElement(SetExtraHTTPHeadersRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Specifies whether to attach a page script stack id in requests
*
* @link Protocol [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setAttachDebugStack(input: SetAttachDebugStackRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setAttachDebugStack", Json.encodeToJsonElement(SetAttachDebugStackRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Sets the requests to intercept that match the provided patterns and optionally resource types.
Deprecated, please use Fetch.enable instead.
*
* @link Protocol [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "setRequestInterception is deprecated.")
@pl.wendigo.chrome.protocol.Experimental
fun setRequestInterception(input: SetRequestInterceptionRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setRequestInterception", Json.encodeToJsonElement(SetRequestInterceptionRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Allows overriding user agent with the given string.
*
* @link Protocol [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) method documentation.
*/
fun setUserAgentOverride(input: SetUserAgentOverrideRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setUserAgentOverride", Json.encodeToJsonElement(SetUserAgentOverrideRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Returns information about the COEP/COOP isolation status.
*
* @link Protocol [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getSecurityIsolationStatus(input: GetSecurityIsolationStatusRequest): io.reactivex.rxjava3.core.Single<GetSecurityIsolationStatusResponse> = connection.request("Network.getSecurityIsolationStatus", Json.encodeToJsonElement(GetSecurityIsolationStatusRequest.serializer(), input), GetSecurityIsolationStatusResponse.serializer())
/**
* Fetches the resource and returns the content.
*
* @link Protocol [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun loadNetworkResource(input: LoadNetworkResourceRequest): io.reactivex.rxjava3.core.Single<LoadNetworkResourceResponse> = connection.request("Network.loadNetworkResource", Json.encodeToJsonElement(LoadNetworkResourceRequest.serializer(), input), LoadNetworkResourceResponse.serializer())
/**
* Fired when data chunk was received over the network.
*/
fun dataReceived(): io.reactivex.rxjava3.core.Flowable<DataReceivedEvent> = connection.events("Network.dataReceived", DataReceivedEvent.serializer())
/**
* Fired when EventSource message is received.
*/
fun eventSourceMessageReceived(): io.reactivex.rxjava3.core.Flowable<EventSourceMessageReceivedEvent> = connection.events("Network.eventSourceMessageReceived", EventSourceMessageReceivedEvent.serializer())
/**
* Fired when HTTP request has failed to load.
*/
fun loadingFailed(): io.reactivex.rxjava3.core.Flowable<LoadingFailedEvent> = connection.events("Network.loadingFailed", LoadingFailedEvent.serializer())
/**
* Fired when HTTP request has finished loading.
*/
fun loadingFinished(): io.reactivex.rxjava3.core.Flowable<LoadingFinishedEvent> = connection.events("Network.loadingFinished", LoadingFinishedEvent.serializer())
/**
* Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
mocked.
Deprecated, use Fetch.requestPaused instead.
*/
fun requestIntercepted(): io.reactivex.rxjava3.core.Flowable<RequestInterceptedEvent> = connection.events("Network.requestIntercepted", RequestInterceptedEvent.serializer())
/**
* Fired if request ended up loading from cache.
*/
fun requestServedFromCache(): io.reactivex.rxjava3.core.Flowable<RequestServedFromCacheEvent> = connection.events("Network.requestServedFromCache", RequestServedFromCacheEvent.serializer())
/**
* Fired when page is about to send HTTP request.
*/
fun requestWillBeSent(): io.reactivex.rxjava3.core.Flowable<RequestWillBeSentEvent> = connection.events("Network.requestWillBeSent", RequestWillBeSentEvent.serializer())
/**
* Fired when resource loading priority is changed
*/
fun resourceChangedPriority(): io.reactivex.rxjava3.core.Flowable<ResourceChangedPriorityEvent> = connection.events("Network.resourceChangedPriority", ResourceChangedPriorityEvent.serializer())
/**
* Fired when a signed exchange was received over the network
*/
fun signedExchangeReceived(): io.reactivex.rxjava3.core.Flowable<SignedExchangeReceivedEvent> = connection.events("Network.signedExchangeReceived", SignedExchangeReceivedEvent.serializer())
/**
* Fired when HTTP response is available.
*/
fun responseReceived(): io.reactivex.rxjava3.core.Flowable<ResponseReceivedEvent> = connection.events("Network.responseReceived", ResponseReceivedEvent.serializer())
/**
* Fired when WebSocket is closed.
*/
fun webSocketClosed(): io.reactivex.rxjava3.core.Flowable<WebSocketClosedEvent> = connection.events("Network.webSocketClosed", WebSocketClosedEvent.serializer())
/**
* Fired upon WebSocket creation.
*/
fun webSocketCreated(): io.reactivex.rxjava3.core.Flowable<WebSocketCreatedEvent> = connection.events("Network.webSocketCreated", WebSocketCreatedEvent.serializer())
/**
* Fired when WebSocket message error occurs.
*/
fun webSocketFrameError(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameErrorEvent> = connection.events("Network.webSocketFrameError", WebSocketFrameErrorEvent.serializer())
/**
* Fired when WebSocket message is received.
*/
fun webSocketFrameReceived(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameReceivedEvent> = connection.events("Network.webSocketFrameReceived", WebSocketFrameReceivedEvent.serializer())
/**
* Fired when WebSocket message is sent.
*/
fun webSocketFrameSent(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameSentEvent> = connection.events("Network.webSocketFrameSent", WebSocketFrameSentEvent.serializer())
/**
* Fired when WebSocket handshake response becomes available.
*/
fun webSocketHandshakeResponseReceived(): io.reactivex.rxjava3.core.Flowable<WebSocketHandshakeResponseReceivedEvent> = connection.events("Network.webSocketHandshakeResponseReceived", WebSocketHandshakeResponseReceivedEvent.serializer())
/**
* Fired when WebSocket is about to initiate handshake.
*/
fun webSocketWillSendHandshakeRequest(): io.reactivex.rxjava3.core.Flowable<WebSocketWillSendHandshakeRequestEvent> = connection.events("Network.webSocketWillSendHandshakeRequest", WebSocketWillSendHandshakeRequestEvent.serializer())
/**
* Fired upon WebTransport creation.
*/
fun webTransportCreated(): io.reactivex.rxjava3.core.Flowable<WebTransportCreatedEvent> = connection.events("Network.webTransportCreated", WebTransportCreatedEvent.serializer())
/**
* Fired when WebTransport handshake is finished.
*/
fun webTransportConnectionEstablished(): io.reactivex.rxjava3.core.Flowable<WebTransportConnectionEstablishedEvent> = connection.events("Network.webTransportConnectionEstablished", WebTransportConnectionEstablishedEvent.serializer())
/**
* Fired when WebTransport is disposed.
*/
fun webTransportClosed(): io.reactivex.rxjava3.core.Flowable<WebTransportClosedEvent> = connection.events("Network.webTransportClosed", WebTransportClosedEvent.serializer())
/**
* Fired when additional information about a requestWillBeSent event is available from the
network stack. Not every requestWillBeSent event will have an additional
requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
or requestWillBeSentExtraInfo will be fired first for the same request.
*/
fun requestWillBeSentExtraInfo(): io.reactivex.rxjava3.core.Flowable<RequestWillBeSentExtraInfoEvent> = connection.events("Network.requestWillBeSentExtraInfo", RequestWillBeSentExtraInfoEvent.serializer())
/**
* Fired when additional information about a responseReceived event is available from the network
stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
it, and responseReceivedExtraInfo may be fired before or after responseReceived.
*/
fun responseReceivedExtraInfo(): io.reactivex.rxjava3.core.Flowable<ResponseReceivedExtraInfoEvent> = connection.events("Network.responseReceivedExtraInfo", ResponseReceivedExtraInfoEvent.serializer())
/**
* Fired exactly once for each Trust Token operation. Depending on
the type of the operation and whether the operation succeeded or
failed, the event is fired before the corresponding request was sent
or after the response was received.
*/
fun trustTokenOperationDone(): io.reactivex.rxjava3.core.Flowable<TrustTokenOperationDoneEvent> = connection.events("Network.trustTokenOperationDone", TrustTokenOperationDoneEvent.serializer())
/**
* Returns list of dependant domains that should be enabled prior to enabling this domain.
*/
override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> {
return arrayListOf(
pl.wendigo.chrome.api.debugger.DebuggerDomain(connection),
pl.wendigo.chrome.api.runtime.RuntimeDomain(connection),
pl.wendigo.chrome.api.security.SecurityDomain(connection),
)
}
}
/**
* Represents response frame that is returned from [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) operation call.
* Tells whether clearing browser cache is supported.
*
* @link [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) method documentation.
* @see [NetworkDomain.canClearBrowserCache]
*/
@kotlinx.serialization.Serializable
data class CanClearBrowserCacheResponse(
/**
* True if browser cache can be cleared.
*/
val result: Boolean
)
/**
* Represents response frame that is returned from [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) operation call.
* Tells whether clearing browser cookies is supported.
*
* @link [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) method documentation.
* @see [NetworkDomain.canClearBrowserCookies]
*/
@kotlinx.serialization.Serializable
data class CanClearBrowserCookiesResponse(
/**
* True if browser cookies can be cleared.
*/
val result: Boolean
)
/**
* Represents response frame that is returned from [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) operation call.
* Tells whether emulation of network conditions is supported.
*
* @link [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) method documentation.
* @see [NetworkDomain.canEmulateNetworkConditions]
*/
@kotlinx.serialization.Serializable
data class CanEmulateNetworkConditionsResponse(
/**
* True if emulation of network conditions is supported.
*/
val result: Boolean
)
/**
* Represents request frame that can be used with [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) operation call.
*
* Response to Network.requestIntercepted which either modifies the request to continue with any
modifications, or blocks it, or completes it with the provided response bytes. If a network
fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
event will be sent with the same InterceptionId.
Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
* @link [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) method documentation.
* @see [NetworkDomain.continueInterceptedRequest]
*/
@kotlinx.serialization.Serializable
data class ContinueInterceptedRequestRequest(
/**
*
*/
val interceptionId: InterceptionId,
/**
* If set this causes the request to fail with the given reason. Passing `Aborted` for requests
marked with `isNavigationRequest` also cancels the navigation. Must not be set in response
to an authChallenge.
*/
val errorReason: ErrorReason? = null,
/**
* If set the requests completes using with the provided base64 encoded raw response, including
HTTP status line and headers etc... Must not be set in response to an authChallenge. (Encoded as a base64 string when passed over JSON)
*/
val rawResponse: String? = null,
/**
* If set the request url will be modified in a way that's not observable by page. Must not be
set in response to an authChallenge.
*/
val url: String? = null,
/**
* If set this allows the request method to be overridden. Must not be set in response to an
authChallenge.
*/
val method: String? = null,
/**
* If set this allows postData to be set. Must not be set in response to an authChallenge.
*/
val postData: String? = null,
/**
* If set this allows the request headers to be changed. Must not be set in response to an
authChallenge.
*/
val headers: Headers? = null,
/**
* Response to a requestIntercepted with an authChallenge. Must not be set otherwise.
*/
val authChallengeResponse: AuthChallengeResponse? = null
)
/**
* Represents request frame that can be used with [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) operation call.
*
* Deletes browser cookies with matching name and url or domain/path pair.
* @link [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) method documentation.
* @see [NetworkDomain.deleteCookies]
*/
@kotlinx.serialization.Serializable
data class DeleteCookiesRequest(
/**
* Name of the cookies to remove.
*/
val name: String,
/**
* If specified, deletes all the cookies with the given name where domain and path match
provided URL.
*/
val url: String? = null,
/**
* If specified, deletes only cookies with the exact domain.
*/
val domain: String? = null,
/**
* If specified, deletes only cookies with the exact path.
*/
val path: String? = null
)
/**
* Represents request frame that can be used with [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) operation call.
*
* Activates emulation of network conditions.
* @link [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) method documentation.
* @see [NetworkDomain.emulateNetworkConditions]
*/
@kotlinx.serialization.Serializable
data class EmulateNetworkConditionsRequest(
/**
* True to emulate internet disconnection.
*/
val offline: Boolean,
/**
* Minimum latency from request sent to response headers received (ms).
*/
val latency: Double,
/**
* Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.
*/
val downloadThroughput: Double,
/**
* Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling.
*/
val uploadThroughput: Double,
/**
* Connection type if known.
*/
val connectionType: ConnectionType? = null
)
/**
* Represents request frame that can be used with [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) operation call.
*
* Enables network tracking, network events will now be delivered to the client.
* @link [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) method documentation.
* @see [NetworkDomain.enable]
*/
@kotlinx.serialization.Serializable
data class EnableRequest(
/**
* Buffer size in bytes to use when preserving network payloads (XHRs, etc).
*/
@pl.wendigo.chrome.protocol.Experimental val maxTotalBufferSize: Int? = null,
/**
* Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc).
*/
@pl.wendigo.chrome.protocol.Experimental val maxResourceBufferSize: Int? = null,
/**
* Longest post body size (in bytes) that would be included in requestWillBeSent notification
*/
val maxPostDataSize: Int? = null
)
/**
* Represents response frame that is returned from [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) operation call.
* Returns all browser cookies. Depending on the backend support, will return detailed cookie
information in the `cookies` field.
*
* @link [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) method documentation.
* @see [NetworkDomain.getAllCookies]
*/
@kotlinx.serialization.Serializable
data class GetAllCookiesResponse(
/**
* Array of cookie objects.
*/
val cookies: List<Cookie>
)
/**
* Represents request frame that can be used with [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) operation call.
*
* Returns the DER-encoded certificate.
* @link [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
* @see [NetworkDomain.getCertificate]
*/
@kotlinx.serialization.Serializable
data class GetCertificateRequest(
/**
* Origin to get certificate for.
*/
val origin: String
)
/**
* Represents response frame that is returned from [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) operation call.
* Returns the DER-encoded certificate.
*
* @link [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
* @see [NetworkDomain.getCertificate]
*/
@kotlinx.serialization.Serializable
data class GetCertificateResponse(
/**
*
*/
val tableNames: List<String>
)
/**
* Represents request frame that can be used with [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) operation call.
*
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
* @link [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
* @see [NetworkDomain.getCookies]
*/
@kotlinx.serialization.Serializable
data class GetCookiesRequest(
/**
* The list of URLs for which applicable cookies will be fetched.
If not specified, it's assumed to be set to the list containing
the URLs of the page and all of its subframes.
*/
val urls: List<String>? = null
)
/**
* Represents response frame that is returned from [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) operation call.
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
*
* @link [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
* @see [NetworkDomain.getCookies]
*/
@kotlinx.serialization.Serializable
data class GetCookiesResponse(
/**
* Array of cookie objects.
*/
val cookies: List<Cookie>
)
/**
* Represents request frame that can be used with [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) operation call.
*
* Returns content served for the given request.
* @link [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
* @see [NetworkDomain.getResponseBody]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyRequest(
/**
* Identifier of the network request to get content for.
*/
val requestId: RequestId
)
/**
* Represents response frame that is returned from [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) operation call.
* Returns content served for the given request.
*
* @link [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
* @see [NetworkDomain.getResponseBody]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyResponse(
/**
* Response body.
*/
val body: String,
/**
* True, if content was sent as base64.
*/
val base64Encoded: Boolean
)
/**
* Represents request frame that can be used with [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) operation call.
*
* Returns post data sent with the request. Returns an error when no data was sent with the request.
* @link [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
* @see [NetworkDomain.getRequestPostData]
*/
@kotlinx.serialization.Serializable
data class GetRequestPostDataRequest(
/**
* Identifier of the network request to get content for.
*/
val requestId: RequestId
)
/**
* Represents response frame that is returned from [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) operation call.
* Returns post data sent with the request. Returns an error when no data was sent with the request.
*
* @link [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
* @see [NetworkDomain.getRequestPostData]
*/
@kotlinx.serialization.Serializable
data class GetRequestPostDataResponse(
/**
* Request body string, omitting files from multipart requests
*/
val postData: String
)
/**
* Represents request frame that can be used with [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) operation call.
*
* Returns content served for the given currently intercepted request.
* @link [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
* @see [NetworkDomain.getResponseBodyForInterception]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyForInterceptionRequest(
/**
* Identifier for the intercepted request to get body for.
*/
val interceptionId: InterceptionId
)
/**
* Represents response frame that is returned from [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) operation call.
* Returns content served for the given currently intercepted request.
*
* @link [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
* @see [NetworkDomain.getResponseBodyForInterception]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyForInterceptionResponse(
/**
* Response body.
*/
val body: String,
/**
* True, if content was sent as base64.
*/
val base64Encoded: Boolean
)
/**
* Represents request frame that can be used with [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) operation call.
*
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
* @link [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
* @see [NetworkDomain.takeResponseBodyForInterceptionAsStream]
*/
@kotlinx.serialization.Serializable
data class TakeResponseBodyForInterceptionAsStreamRequest(
/**
*
*/
val interceptionId: InterceptionId
)
/**
* Represents response frame that is returned from [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) operation call.
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
*
* @link [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
* @see [NetworkDomain.takeResponseBodyForInterceptionAsStream]
*/
@kotlinx.serialization.Serializable
data class TakeResponseBodyForInterceptionAsStreamResponse(
/**
*
*/
val stream: pl.wendigo.chrome.api.io.StreamHandle
)
/**
* Represents request frame that can be used with [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) operation call.
*
* This method sends a new XMLHttpRequest which is identical to the original one. The following
parameters should be identical: method, url, async, request body, extra headers, withCredentials
attribute, user, password.
* @link [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) method documentation.
* @see [NetworkDomain.replayXHR]
*/
@kotlinx.serialization.Serializable
data class ReplayXHRRequest(
/**
* Identifier of XHR to replay.
*/
val requestId: RequestId
)
/**
* Represents request frame that can be used with [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) operation call.
*
* Searches for given string in response content.
* @link [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
* @see [NetworkDomain.searchInResponseBody]
*/
@kotlinx.serialization.Serializable
data class SearchInResponseBodyRequest(
/**
* Identifier of the network response to search.
*/
val requestId: RequestId,
/**
* String to search for.
*/
val query: String,
/**
* If true, search is case sensitive.
*/
val caseSensitive: Boolean? = null,
/**
* If true, treats string parameter as regex.
*/
val isRegex: Boolean? = null
)
/**
* Represents response frame that is returned from [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) operation call.
* Searches for given string in response content.
*
* @link [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
* @see [NetworkDomain.searchInResponseBody]
*/
@kotlinx.serialization.Serializable
data class SearchInResponseBodyResponse(
/**
* List of search matches.
*/
val result: List<pl.wendigo.chrome.api.debugger.SearchMatch>
)
/**
* Represents request frame that can be used with [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) operation call.
*
* Blocks URLs from loading.
* @link [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) method documentation.
* @see [NetworkDomain.setBlockedURLs]
*/
@kotlinx.serialization.Serializable
data class SetBlockedURLsRequest(
/**
* URL patterns to block. Wildcards ('*') are allowed.
*/
val urls: List<String>
)
/**
* Represents request frame that can be used with [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) operation call.
*
* Toggles ignoring of service worker for each request.
* @link [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) method documentation.
* @see [NetworkDomain.setBypassServiceWorker]
*/
@kotlinx.serialization.Serializable
data class SetBypassServiceWorkerRequest(
/**
* Bypass service worker and load from network.
*/
val bypass: Boolean
)
/**
* Represents request frame that can be used with [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) operation call.
*
* Toggles ignoring cache for each request. If `true`, cache will not be used.
* @link [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) method documentation.
* @see [NetworkDomain.setCacheDisabled]
*/
@kotlinx.serialization.Serializable
data class SetCacheDisabledRequest(
/**
* Cache disabled state.
*/
val cacheDisabled: Boolean
)
/**
* Represents request frame that can be used with [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) operation call.
*
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
* @link [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
* @see [NetworkDomain.setCookie]
*/
@kotlinx.serialization.Serializable
data class SetCookieRequest(
/**
* Cookie name.
*/
val name: String,
/**
* Cookie value.
*/
val value: String,
/**
* The request-URI to associate with the setting of the cookie. This value can affect the
default domain, path, source port, and source scheme values of the created cookie.
*/
val url: String? = null,
/**
* Cookie domain.
*/
val domain: String? = null,
/**
* Cookie path.
*/
val path: String? = null,
/**
* True if cookie is secure.
*/
val secure: Boolean? = null,
/**
* True if cookie is http-only.
*/
val httpOnly: Boolean? = null,
/**
* Cookie SameSite type.
*/
val sameSite: CookieSameSite? = null,
/**
* Cookie expiration date, session cookie if not set
*/
val expires: TimeSinceEpoch? = null,
/**
* Cookie Priority type.
*/
@pl.wendigo.chrome.protocol.Experimental val priority: CookiePriority? = null,
/**
* True if cookie is SameParty.
*/
@pl.wendigo.chrome.protocol.Experimental val sameParty: Boolean? = null,
/**
* Cookie source scheme type.
*/
@pl.wendigo.chrome.protocol.Experimental val sourceScheme: CookieSourceScheme? = null,
/**
* Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port.
An unspecified port value allows protocol clients to emulate legacy cookie scope for the port.
This is a temporary ability and it will be removed in the future.
*/
@pl.wendigo.chrome.protocol.Experimental val sourcePort: Int? = null
)
/**
* Represents response frame that is returned from [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) operation call.
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @link [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
* @see [NetworkDomain.setCookie]
*/
@kotlinx.serialization.Serializable
data class SetCookieResponse(
/**
* Always set to true. If an error occurs, the response indicates protocol error.
*/
val success: Boolean
)
/**
* Represents request frame that can be used with [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) operation call.
*
* Sets given cookies.
* @link [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) method documentation.
* @see [NetworkDomain.setCookies]
*/
@kotlinx.serialization.Serializable
data class SetCookiesRequest(
/**
* Cookies to be set.
*/
val cookies: List<CookieParam>
)
/**
* Represents request frame that can be used with [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) operation call.
*
* For testing.
* @link [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) method documentation.
* @see [NetworkDomain.setDataSizeLimitsForTest]
*/
@kotlinx.serialization.Serializable
data class SetDataSizeLimitsForTestRequest(
/**
* Maximum total buffer size.
*/
val maxTotalSize: Int,
/**
* Maximum per-resource size.
*/
val maxResourceSize: Int
)
/**
* Represents request frame that can be used with [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) operation call.
*
* Specifies whether to always send extra HTTP headers with the requests from this page.
* @link [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) method documentation.
* @see [NetworkDomain.setExtraHTTPHeaders]
*/
@kotlinx.serialization.Serializable
data class SetExtraHTTPHeadersRequest(
/**
* Map with extra HTTP headers.
*/
val headers: Headers
)
/**
* Represents request frame that can be used with [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) operation call.
*
* Specifies whether to attach a page script stack id in requests
* @link [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) method documentation.
* @see [NetworkDomain.setAttachDebugStack]
*/
@kotlinx.serialization.Serializable
data class SetAttachDebugStackRequest(
/**
* Whether to attach a page script stack for debugging purpose.
*/
val enabled: Boolean
)
/**
* Represents request frame that can be used with [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) operation call.
*
* Sets the requests to intercept that match the provided patterns and optionally resource types.
Deprecated, please use Fetch.enable instead.
* @link [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) method documentation.
* @see [NetworkDomain.setRequestInterception]
*/
@kotlinx.serialization.Serializable
data class SetRequestInterceptionRequest(
/**
* Requests matching any of these patterns will be forwarded and wait for the corresponding
continueInterceptedRequest call.
*/
val patterns: List<RequestPattern>
)
/**
* Represents request frame that can be used with [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) operation call.
*
* Allows overriding user agent with the given string.
* @link [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) method documentation.
* @see [NetworkDomain.setUserAgentOverride]
*/
@kotlinx.serialization.Serializable
data class SetUserAgentOverrideRequest(
/**
* User agent to use.
*/
val userAgent: String,
/**
* Browser langugage to emulate.
*/
val acceptLanguage: String? = null,
/**
* The platform navigator.platform should return.
*/
val platform: String? = null,
/**
* To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData
*/
@pl.wendigo.chrome.protocol.Experimental val userAgentMetadata: pl.wendigo.chrome.api.emulation.UserAgentMetadata? = null
)
/**
* Represents request frame that can be used with [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) operation call.
*
* Returns information about the COEP/COOP isolation status.
* @link [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
* @see [NetworkDomain.getSecurityIsolationStatus]
*/
@kotlinx.serialization.Serializable
data class GetSecurityIsolationStatusRequest(
/**
* If no frameId is provided, the status of the target is provided.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null
)
/**
* Represents response frame that is returned from [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) operation call.
* Returns information about the COEP/COOP isolation status.
*
* @link [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
* @see [NetworkDomain.getSecurityIsolationStatus]
*/
@kotlinx.serialization.Serializable
data class GetSecurityIsolationStatusResponse(
/**
*
*/
val status: SecurityIsolationStatus
)
/**
* Represents request frame that can be used with [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) operation call.
*
* Fetches the resource and returns the content.
* @link [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
* @see [NetworkDomain.loadNetworkResource]
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourceRequest(
/**
* Frame id to get the resource for.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId,
/**
* URL of the resource to get content for.
*/
val url: String,
/**
* Options for the request.
*/
val options: LoadNetworkResourceOptions
)
/**
* Represents response frame that is returned from [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) operation call.
* Fetches the resource and returns the content.
*
* @link [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
* @see [NetworkDomain.loadNetworkResource]
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourceResponse(
/**
*
*/
val resource: LoadNetworkResourcePageResult
)
/**
* Fired when data chunk was received over the network.
*
* @link [Network#dataReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-dataReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class DataReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Data chunk length.
*/
val dataLength: Int,
/**
* Actual bytes received (might be less than dataLength for compressed encodings).
*/
val encodedDataLength: Int
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "dataReceived"
}
/**
* Fired when EventSource message is received.
*
* @link [Network#eventSourceMessageReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-eventSourceMessageReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class EventSourceMessageReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Message type.
*/
val eventName: String,
/**
* Message identifier.
*/
val eventId: String,
/**
* Message content.
*/
val data: String
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "eventSourceMessageReceived"
}
/**
* Fired when HTTP request has failed to load.
*
* @link [Network#loadingFailed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFailed) event documentation.
*/
@kotlinx.serialization.Serializable
data class LoadingFailedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Resource type.
*/
val type: ResourceType,
/**
* User friendly error message.
*/
val errorText: String,
/**
* True if loading was canceled.
*/
val canceled: Boolean? = null,
/**
* The reason why loading was blocked, if any.
*/
val blockedReason: BlockedReason? = null,
/**
* The reason why loading was blocked by CORS, if any.
*/
val corsErrorStatus: CorsErrorStatus? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "loadingFailed"
}
/**
* Fired when HTTP request has finished loading.
*
* @link [Network#loadingFinished](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFinished) event documentation.
*/
@kotlinx.serialization.Serializable
data class LoadingFinishedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Total number of bytes received for this request.
*/
val encodedDataLength: Double,
/**
* Set when 1) response was blocked by Cross-Origin Read Blocking and also
2) this needs to be reported to the DevTools console.
*/
val shouldReportCorbBlocking: Boolean? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "loadingFinished"
}
/**
* Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
mocked.
Deprecated, use Fetch.requestPaused instead.
*
* @link [Network#requestIntercepted](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestIntercepted) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestInterceptedEvent(
/**
* Each request the page makes will have a unique id, however if any redirects are encountered
while processing that fetch, they will be reported with the same id as the original fetch.
Likewise if HTTP authentication is needed then the same fetch id will be used.
*/
val interceptionId: InterceptionId,
/**
*
*/
val request: Request,
/**
* The id of the frame that initiated the request.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId,
/**
* How the requested resource will be used.
*/
val resourceType: ResourceType,
/**
* Whether this is a navigation request, which can abort the navigation completely.
*/
val isNavigationRequest: Boolean,
/**
* Set if the request is a navigation that will result in a download.
Only present after response is received from the server (i.e. HeadersReceived stage).
*/
val isDownload: Boolean? = null,
/**
* Redirect location, only sent if a redirect was intercepted.
*/
val redirectUrl: String? = null,
/**
* Details of the Authorization Challenge encountered. If this is set then
continueInterceptedRequest must contain an authChallengeResponse.
*/
val authChallenge: AuthChallenge? = null,
/**
* Response error if intercepted at response stage or if redirect occurred while intercepting
request.
*/
val responseErrorReason: ErrorReason? = null,
/**
* Response code if intercepted at response stage or if redirect occurred while intercepting
request or auth retry occurred.
*/
val responseStatusCode: Int? = null,
/**
* Response headers if intercepted at the response stage or if redirect occurred while
intercepting request or auth retry occurred.
*/
val responseHeaders: Headers? = null,
/**
* If the intercepted request had a corresponding requestWillBeSent event fired for it, then
this requestId will be the same as the requestId present in the requestWillBeSent event.
*/
val requestId: RequestId? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestIntercepted"
}
/**
* Fired if request ended up loading from cache.
*
* @link [Network#requestServedFromCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestServedFromCache) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestServedFromCacheEvent(
/**
* Request identifier.
*/
val requestId: RequestId
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestServedFromCache"
}
/**
* Fired when page is about to send HTTP request.
*
* @link [Network#requestWillBeSent](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSent) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestWillBeSentEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Loader identifier. Empty string if the request is fetched from worker.
*/
val loaderId: LoaderId,
/**
* URL of the document this request is loaded for.
*/
val documentURL: String,
/**
* Request data.
*/
val request: Request,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Timestamp.
*/
val wallTime: TimeSinceEpoch,
/**
* Request initiator.
*/
val initiator: Initiator,
/**
* Redirect response data.
*/
val redirectResponse: Response? = null,
/**
* Type of this resource.
*/
val type: ResourceType? = null,
/**
* Frame identifier.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null,
/**
* Whether the request is initiated by a user gesture. Defaults to false.
*/
val hasUserGesture: Boolean? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestWillBeSent"
}
/**
* Fired when resource loading priority is changed
*
* @link [Network#resourceChangedPriority](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-resourceChangedPriority) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResourceChangedPriorityEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* New priority
*/
val newPriority: ResourcePriority,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "resourceChangedPriority"
}
/**
* Fired when a signed exchange was received over the network
*
* @link [Network#signedExchangeReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-signedExchangeReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Information about the signed exchange response.
*/
val info: SignedExchangeInfo
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "signedExchangeReceived"
}
/**
* Fired when HTTP response is available.
*
* @link [Network#responseReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResponseReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Loader identifier. Empty string if the request is fetched from worker.
*/
val loaderId: LoaderId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Resource type.
*/
val type: ResourceType,
/**
* Response data.
*/
val response: Response,
/**
* Frame identifier.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "responseReceived"
}
/**
* Fired when WebSocket is closed.
*
* @link [Network#webSocketClosed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketClosed) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketClosedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketClosed"
}
/**
* Fired upon WebSocket creation.
*
* @link [Network#webSocketCreated](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketCreated) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketCreatedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* WebSocket request URL.
*/
val url: String,
/**
* Request initiator.
*/
val initiator: Initiator? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketCreated"
}
/**
* Fired when WebSocket message error occurs.
*
* @link [Network#webSocketFrameError](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameError) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameErrorEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket error message.
*/
val errorMessage: String
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameError"
}
/**
* Fired when WebSocket message is received.
*
* @link [Network#webSocketFrameReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketFrame
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameReceived"
}
/**
* Fired when WebSocket message is sent.
*
* @link [Network#webSocketFrameSent](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameSent) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameSentEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketFrame
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameSent"
}
/**
* Fired when WebSocket handshake response becomes available.
*
* @link [Network#webSocketHandshakeResponseReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketHandshakeResponseReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketHandshakeResponseReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketResponse
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketHandshakeResponseReceived"
}
/**
* Fired when WebSocket is about to initiate handshake.
*
* @link [Network#webSocketWillSendHandshakeRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketWillSendHandshakeRequest) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketWillSendHandshakeRequestEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* UTC Timestamp.
*/
val wallTime: TimeSinceEpoch,
/**
* WebSocket request data.
*/
val request: WebSocketRequest
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketWillSendHandshakeRequest"
}
/**
* Fired upon WebTransport creation.
*
* @link [Network#webTransportCreated](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportCreated) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportCreatedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* WebTransport request URL.
*/
val url: String,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Request initiator.
*/
val initiator: Initiator? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportCreated"
}
/**
* Fired when WebTransport handshake is finished.
*
* @link [Network#webTransportConnectionEstablished](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportConnectionEstablished) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportConnectionEstablishedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportConnectionEstablished"
}
/**
* Fired when WebTransport is disposed.
*
* @link [Network#webTransportClosed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportClosed) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportClosedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportClosed"
}
/**
* Fired when additional information about a requestWillBeSent event is available from the
network stack. Not every requestWillBeSent event will have an additional
requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
or requestWillBeSentExtraInfo will be fired first for the same request.
*
* @link [Network#requestWillBeSentExtraInfo](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSentExtraInfo) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestWillBeSentExtraInfoEvent(
/**
* Request identifier. Used to match this information to an existing requestWillBeSent event.
*/
val requestId: RequestId,
/**
* A list of cookies potentially associated to the requested URL. This includes both cookies sent with
the request and the ones not sent; the latter are distinguished by having blockedReason field set.
*/
val associatedCookies: List<BlockedCookieWithReason>,
/**
* Raw request headers as they will be sent over the wire.
*/
val headers: Headers,
/**
* The client security state set for the request.
*/
val clientSecurityState: ClientSecurityState? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestWillBeSentExtraInfo"
}
/**
* Fired when additional information about a responseReceived event is available from the network
stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
it, and responseReceivedExtraInfo may be fired before or after responseReceived.
*
* @link [Network#responseReceivedExtraInfo](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceivedExtraInfo) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResponseReceivedExtraInfoEvent(
/**
* Request identifier. Used to match this information to another responseReceived event.
*/
val requestId: RequestId,
/**
* A list of cookies which were not stored from the response along with the corresponding
reasons for blocking. The cookies here may not be valid due to syntax errors, which
are represented by the invalid cookie line string instead of a proper cookie.
*/
val blockedCookies: List<BlockedSetCookieWithReason>,
/**
* Raw response headers as they were received over the wire.
*/
val headers: Headers,
/**
* The IP address space of the resource. The address space can only be determined once the transport
established the connection, so we can't send it in `requestWillBeSentExtraInfo`.
*/
val resourceIPAddressSpace: IPAddressSpace,
/**
* Raw response header text as it was received over the wire. The raw text may not always be
available, such as in the case of HTTP/2 or QUIC.
*/
val headersText: String? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "responseReceivedExtraInfo"
}
/**
* Fired exactly once for each Trust Token operation. Depending on
the type of the operation and whether the operation succeeded or
failed, the event is fired before the corresponding request was sent
or after the response was received.
*
* @link [Network#trustTokenOperationDone](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-trustTokenOperationDone) event documentation.
*/
@kotlinx.serialization.Serializable
data class TrustTokenOperationDoneEvent(
/**
* Detailed success or error status of the operation.
'AlreadyExists' also signifies a successful operation, as the result
of the operation already exists und thus, the operation was abort
preemptively (e.g. a cache hit).
*/
val status: String,
/**
*
*/
val type: TrustTokenOperationType,
/**
*
*/
val requestId: RequestId,
/**
* Top level origin. The context in which the operation was attempted.
*/
val topLevelOrigin: String? = null,
/**
* Origin of the issuer in case of a "Issuance" or "Redemption" operation.
*/
val issuerOrigin: String? = null,
/**
* The number of obtained Trust Tokens on a successful "Issuance" operation.
*/
val issuedTokenCount: Int? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "trustTokenOperationDone"
}
| apache-2.0 | ff80c8019554f6c202335c129d2f6b8f | 37.695631 | 413 | 0.736881 | 4.803724 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/world/StarManager.kt | 1 | 4675 | package au.com.codeka.warworlds.client.game.world
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.store.StarCursor
import au.com.codeka.warworlds.client.util.eventbus.EventHandler
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.*
import au.com.codeka.warworlds.common.sim.MutableStar
import au.com.codeka.warworlds.common.sim.Simulation
import au.com.codeka.warworlds.common.sim.StarModifier
import au.com.codeka.warworlds.common.sim.SuspiciousModificationException
import com.google.common.collect.Lists
import java.util.*
/**
* Manages the [Star]s we keep cached and stuff.
*/
object StarManager {
private val log = Log("StarManager")
private val stars = App.dataStore.stars()
private val starModifier = StarModifier { 0 }
fun create() {
App.eventBus.register(eventListener)
}
/** Gets the star with the given ID. Might return null if don't have that star cached yet. */
fun getStar(id: Long): Star? {
// TODO: this probably shouldn't happen on a UI thread...
return stars[id]
}
/** Gets all of the stars in the given sector. */
fun searchSectorStars(sectorCoord: SectorCoord): StarCursor {
return stars.searchSectorStars(sectorCoord)
}
val myStars: StarCursor
get() = stars.myStars
fun searchMyStars(search: String?): StarCursor {
return stars.searchMyStars(search!!)
}
/**
* Gets the most recent value of last_simulation out of all our empire's stars. This is sent to
* the server in the [au.com.codeka.warworlds.common.proto.HelloPacket], so that the server
* can update us on all our stars that have been updated since we last connected.
*/
val lastSimulationOfOurStar: Long?
get() = stars.lastSimulationOfOurStar
/**
* Queue up the given [Star] to be simulated. The star will be simulated in the background
* and will be posted to the event bus when complete.
*/
fun queueSimulateStar(star: Star) {
// Something more scalable that just queuing them all to the background thread pool...
App.taskRunner.runTask(Runnable { simulateStarSync(star) }, Threads.BACKGROUND)
}
/**
* Simulate the star on the current thread.
*/
fun simulateStarSync(star: Star) {
val mutableStar = MutableStar.from(star)
Simulation().simulate(mutableStar)
// No need to save the star, it's just a simulation, but publish it to the event bus so
// clients can see it.
App.eventBus.publish(mutableStar.build())
}
fun updateStar(star: Star, m: StarModification) {
// Be sure to record our empire_id in the request.
val modification = m.copy(empire_id = EmpireManager.getMyEmpire().id)
App.taskRunner.runTask(Runnable {
// If there's any auxiliary stars, grab them now, too.
var auxiliaryStars: MutableList<Star>? = null
if (modification.star_id != null) {
auxiliaryStars = ArrayList()
val s = stars[modification.star_id!!]
if (s != null) {
auxiliaryStars.add(s)
}
}
// Modify the star.
val mutableStar = MutableStar.from(star)
try {
starModifier.modifyStar(mutableStar, Lists.newArrayList(modification), auxiliaryStars)
} catch (e: SuspiciousModificationException) {
// Mostly we don't care about these on the client, but it'll be good to log them.
log.error("Unexpected suspicious modification.", e)
return@Runnable
}
// Save the now-modified star.
val newStar = mutableStar.build()
stars.put(star.id, newStar, EmpireManager.getMyEmpire())
App.eventBus.publish(newStar)
// Send the modification to the server as well.
App.server.send(Packet(
modify_star = ModifyStarPacket(
star_id = star.id,
modification = Lists.newArrayList(modification))))
}, Threads.BACKGROUND)
}
private val eventListener: Any = object : Any() {
/**
* When the server tells us that a star has been updated, we'll want to update our cached copy
* of it.
*/
@EventHandler(thread = Threads.BACKGROUND)
fun onStarUpdatedPacket(pkt: StarUpdatedPacket) {
log.info("Stars updating, saving to database.")
val startTime = System.nanoTime()
val values: MutableMap<Long?, Star> = HashMap()
for (star in pkt.stars) {
App.eventBus.publish(star)
values[star.id] = star
}
stars.putAll(values, EmpireManager.getMyEmpire())
val endTime = System.nanoTime()
log.info("Updated %d stars in DB in %d ms", pkt.stars.size, (endTime - startTime) / 1000000L)
}
}
} | mit | 93ece4a3041ef6484e65ba71ee782558 | 34.424242 | 99 | 0.690053 | 3.995726 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/empire/ColoniesView.kt | 1 | 11390 | package au.com.codeka.warworlds.client.game.empire
import android.content.Context
import android.widget.FrameLayout
/**
* ColoniesView shows a list of stars, which you can expand to see colonies that
* belong to those stars.
*/
class ColoniesView(context: Context?) /*
private StarsListAdapter adapter;
private EmpireStarsFetcher fetcher;
public ColoniesView() {
fetcher = new EmpireStarsFetcher(EmpireStarsFetcher.Filter.Colonies, null);
// fetch the first few stars
fetcher.getStars(0, 20);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.empire_colonies_tab, container, false);
ExpandableListView starsList = (ExpandableListView) v.findViewById(R.id.stars);
adapter = new ColonyStarsListAdapter(inflater, fetcher);
starsList.setAdapter(adapter);
starsList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Star star = (Star) adapter.getGroup(groupPosition);
Colony colony = (Colony) adapter.getChild(groupPosition, childPosition);
Planet planet = (Planet) star.getPlanets()[colony.getPlanetIndex() - 1];
// end this activity, go back to the starfield and navigate to the given colony
Intent intent = new Intent();
intent.putExtra("au.com.codeka.warworlds.Result",
EmpireActivity.EmpireActivityResult.NavigateToPlanet.getValue());
intent.putExtra("au.com.codeka.warworlds.SectorX", star.getSectorX());
intent.putExtra("au.com.codeka.warworlds.SectorY", star.getSectorY());
intent.putExtra("au.com.codeka.warworlds.StarOffsetX", star.getOffsetX());
intent.putExtra("au.com.codeka.warworlds.StarOffsetY", star.getOffsetY());
intent.putExtra("au.com.codeka.warworlds.StarKey", star.getKey());
intent.putExtra("au.com.codeka.warworlds.PlanetIndex", planet.getIndex());
getActivity().setResult(EmpireActivity.RESULT_OK, intent);
getActivity().finish();
return false;
}
});
final EditText searchBox = (EditText) v.findViewById(R.id.search_text);
searchBox.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch(searchBox.getText().toString());
return true;
}
return false;
}
});
ImageButton searchBtn = (ImageButton) v.findViewById(R.id.search_button);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performSearch(searchBox.getText().toString());
}
});
return v;
}
@Override
public void onStart() {
super.onStart();
StarManager.eventBus.register(eventHandler);
}
@Override
public void onStop() {
super.onStop();
StarManager.eventBus.unregister(eventHandler);
}
private void performSearch(String search) {
fetcher = new EmpireStarsFetcher(EmpireStarsFetcher.Filter.Colonies, search);
adapter.updateFetcher(fetcher);
}
private Object eventHandler = new Object() {
@EventHandler
public void onStarUpdated(Star star) {
adapter.notifyDataSetChanged();
}
};
public static class ColonyStarsListAdapter extends StarsListAdapter {
private LayoutInflater inflater;
private MyEmpire empire;
public ColonyStarsListAdapter(LayoutInflater inflater, EmpireStarsFetcher fetcher) {
super(fetcher);
this.inflater = inflater;
empire = EmpireManager.i.getEmpire();
}
@Override
public int getNumChildren(Star star) {
int numColonies = 0;
for (int i = 0; i < star.getColonies().size(); i++) {
Integer empireID = ((Colony) star.getColonies().get(i)).getEmpireID();
if (empireID != null && empireID == empire.getID()) {
numColonies ++;
}
}
return numColonies;
}
@Override
public Object getChild(Star star, int index) {
int colonyIndex = 0;
for (int i = 0; i < star.getColonies().size(); i++) {
Integer empireID = ((Colony) star.getColonies().get(i)).getEmpireID();
if (empireID != null && empireID == empire.getID()) {
if (colonyIndex == index) {
return star.getColonies().get(i);
}
colonyIndex ++;
}
}
// Shouldn't get here...
return null;
}
@Override
public View getStarView(Star star, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.empire_colony_list_star_row, parent, false);
}
ImageView starIcon = (ImageView) view.findViewById(R.id.star_icon);
TextView starName = (TextView) view.findViewById(R.id.star_name);
TextView starType = (TextView) view.findViewById(R.id.star_type);
TextView starGoodsDelta = (TextView) view.findViewById(R.id.star_goods_delta);
TextView starGoodsTotal = (TextView) view.findViewById(R.id.star_goods_total);
TextView starMineralsDelta = (TextView) view.findViewById(R.id.star_minerals_delta);
TextView starMineralsTotal = (TextView) view.findViewById(R.id.star_minerals_total);
if (star == null) {
starIcon.setImageBitmap(null);
starName.setText("");
starType.setText("");
starGoodsDelta.setText("");
starGoodsTotal.setText("???");
starMineralsDelta.setText("");
starMineralsTotal.setText("???");
} else {
int imageSize = (int)(star.getSize() * star.getStarType().getImageScale() * 2);
Sprite sprite = StarImageManager.getInstance().getSprite(star, imageSize, true);
starIcon.setImageDrawable(new SpriteDrawable(sprite));
starName.setText(star.getName());
starType.setText(star.getStarType().getDisplayName());
MyEmpire myEmpire = EmpireManager.i.getEmpire();
EmpirePresence empirePresence = null;
for (BaseEmpirePresence baseEmpirePresence : star.getEmpirePresences()) {
if (baseEmpirePresence.getEmpireKey().equals(myEmpire.getKey())) {
empirePresence = (EmpirePresence) baseEmpirePresence;
break;
}
}
if (StarSimulationQueue.needsSimulation(star) || empirePresence == null) {
// if the star hasn't been simulated for > 5 minutes, schedule a simulation
// now and just display ??? for the various parameters
starGoodsDelta.setText("");
starGoodsTotal.setText("???");
starMineralsDelta.setText("");
starMineralsTotal.setText("???");
StarSimulationQueue.i.simulate(star, false);
} else {
starGoodsDelta.setText(String.format(Locale.ENGLISH, "%s%d/hr",
empirePresence.getDeltaGoodsPerHour() < 0 ? "-" : "+",
Math.abs(Math.round(empirePresence.getDeltaGoodsPerHour()))));
if (empirePresence.getDeltaGoodsPerHour() < 0) {
starGoodsDelta.setTextColor(Color.RED);
} else {
starGoodsDelta.setTextColor(Color.GREEN);
}
starGoodsTotal.setText(String.format(Locale.ENGLISH, "%d / %d",
Math.round(empirePresence.getTotalGoods()),
Math.round(empirePresence.getMaxGoods())));
starMineralsDelta.setText(String.format(Locale.ENGLISH, "%s%d/hr",
empirePresence.getDeltaMineralsPerHour() < 0 ? "-" : "+",
Math.abs(Math.round(empirePresence.getDeltaMineralsPerHour()))));
if (empirePresence.getDeltaMineralsPerHour() < 0) {
starMineralsDelta.setTextColor(Color.RED);
} else {
starMineralsDelta.setTextColor(Color.GREEN);
}
starMineralsTotal.setText(String.format(Locale.ENGLISH, "%d / %d",
Math.round(empirePresence.getTotalMinerals()),
Math.round(empirePresence.getMaxMinerals())));
}
}
return view;
}
@Override
public View getChildView(Star star, int index, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.empire_colony_list_colony_row, parent, false);
}
ImageView planetIcon = (ImageView) view.findViewById(R.id.planet_icon);
TextView colonyName = (TextView) view.findViewById(R.id.colony_name);
TextView colonySummary = (TextView) view.findViewById(R.id.colony_summary);
planetIcon.setImageBitmap(null);
colonyName.setText("");
colonySummary.setText("");
if (star != null) {
Colony colony = (Colony) getChild(star, index);
Planet planet = (Planet) star.getPlanets()[colony.getPlanetIndex() - 1];
if (planet != null) {
Sprite sprite = PlanetImageManager.getInstance().getSprite(planet);
planetIcon.setImageDrawable(new SpriteDrawable(sprite));
colonyName.setText(String.format("%s %s", star.getName(),
RomanNumeralFormatter.format(planet.getIndex())));
if (star.getLastSimulation().compareTo(DateTime.now(DateTimeZone.UTC)
.minusMinutes(5)) < 0) {
// if the star hasn't been simulated for > 5 minutes, just display ???
// for the various parameters (a simulation will be scheduled)
colonySummary.setText("Pop: ?");
} else {
colonySummary.setText(String.format("Pop: %d",
(int) colony.getPopulation()));
}
}
}
return view;
}
}*/ : FrameLayout(context!!) | mit | ec6c40ba881476d59409816b48c73dea | 43.496094 | 96 | 0.560755 | 5.302607 | false | false | false | false |
alfadur/gridfold | src/GameStage.kt | 1 | 1279 | interface GameStage
{
fun handleController(controller: Controller)
fun update()
val root: PIXI.DisplayObject
val gameSize: Point
val ended: Boolean
}
class IngameStage(val size: Point, val levelIndex: Int): GameStage
{
val node = PIXI.Container()
val level = Level(node, Layout.levels[levelIndex], size)
var running = true
override fun handleController(controller: Controller)
{
/*if (controller.isActive(ControllerAction.Step))
{
running = false
level.update()
}*/
if (controller.isActive(ControllerAction.Up))
{
level.jump()
}
if (controller.isActive(ControllerAction.Select))
{
level.action()
}
when
{
controller.isActive(ControllerAction.Left) ->
level.moveLeft()
controller.isActive(ControllerAction.Right) ->
level.moveRight()
}
}
override fun update()
{
if (running)
{
level.update()
}
}
override val root: PIXI.DisplayObject
get() = node
override val gameSize: Point
get() = size
override val ended: Boolean
get() = level.completed
}
| mit | ce3309d27c4ccc71ad7982872dbc2cd2 | 20.677966 | 66 | 0.559812 | 4.684982 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/InboxMessageListFragment.kt | 1 | 11919 | package com.habitrpg.android.habitica.ui.fragments.social
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.MainNavDirections
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.FragmentInboxMessageListBinding
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.ui.activities.FullProfileActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.adapter.social.InboxAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.KeyboardUtil
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewmodels.InboxViewModel
import com.habitrpg.android.habitica.ui.viewmodels.InboxViewModelFactory
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class InboxMessageListFragment : BaseMainFragment<FragmentInboxMessageListBinding>() {
override var binding: FragmentInboxMessageListBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentInboxMessageListBinding {
return FragmentInboxMessageListBinding.inflate(inflater, container, false)
}
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var configManager: AppConfigManager
private var chatAdapter: InboxAdapter? = null
private var chatRoomUser: String? = null
private var replyToUserUUID: String? = null
private val viewModel: InboxViewModel by viewModels(factoryProducer = {
InboxViewModelFactory(replyToUserUUID, chatRoomUser)
})
private var refreshDisposable: Disposable? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
showsBackButton = true
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = InboxMessageListFragmentArgs.fromBundle(it)
setReceivingUser(args.username, args.userID)
}
val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.getActivity())
layoutManager.reverseLayout = true
layoutManager.stackFromEnd = false
binding?.recyclerView?.layoutManager = layoutManager
val observable = if (replyToUserUUID?.isNotBlank() == true) {
apiClient.getMember(replyToUserUUID!!)
} else {
apiClient.getMemberWithUsername(chatRoomUser ?: "")
}
compositeSubscription.add(
observable.subscribe(
{ member ->
setReceivingUser(member.username, member.id)
activity?.title = member.displayName
chatAdapter = InboxAdapter(viewModel.user.value, member)
chatAdapter?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart == 0) {
binding?.recyclerView?.scrollToPosition(0)
}
}
})
viewModel.messages.observe(this.viewLifecycleOwner) {
markMessagesAsRead(it)
chatAdapter?.submitList(it)
}
binding?.recyclerView?.adapter = chatAdapter
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
chatAdapter?.let { adapter ->
compositeSubscription.add(
adapter.getUserLabelClickFlowable().subscribe(
{
FullProfileActivity.open(it)
},
RxErrorHandler.handleEmptyError()
)
)
compositeSubscription.add(adapter.getDeleteMessageFlowable().subscribe({ this.showDeleteConfirmationDialog(it) }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getFlagMessageClickFlowable().subscribe({ this.showFlagConfirmationDialog(it) }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getCopyMessageFlowable().subscribe({ this.copyMessageToClipboard(it) }, RxErrorHandler.handleEmptyError()))
}
},
RxErrorHandler.handleEmptyError()
)
)
binding?.chatBarView?.sendAction = { sendMessage(it) }
binding?.chatBarView?.maxChatLength = configManager.maxChatLength()
binding?.chatBarView?.hasAcceptedGuidelines = true
}
override fun onResume() {
if (replyToUserUUID?.isNotBlank() != true && chatRoomUser?.isNotBlank() != true) {
parentFragmentManager.popBackStack()
}
startAutoRefreshing()
super.onResume()
}
override fun onAttach(context: Context) {
view?.invalidate()
view?.forceLayout()
super.onAttach(context)
}
override fun onDestroyView() {
super.onDestroyView()
stopAutoRefreshing()
}
override fun onPause() {
super.onPause()
stopAutoRefreshing()
}
override fun onDestroy() {
socialRepository.close()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
this.activity?.menuInflater?.inflate(R.menu.inbox_chat, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.open_profile -> {
openProfile()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun markMessagesAsRead(messages: List<ChatMessage>) {
socialRepository.markSomePrivateMessagesAsRead(viewModel.user.value, messages)
}
private fun startAutoRefreshing() {
if (refreshDisposable != null && refreshDisposable?.isDisposed != true) {
refreshDisposable?.dispose()
}
refreshDisposable = Observable.interval(30, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
refreshConversation()
},
RxErrorHandler.handleEmptyError()
)
refreshConversation()
}
private fun stopAutoRefreshing() {
if (refreshDisposable?.isDisposed != true) {
refreshDisposable?.dispose()
refreshDisposable = null
}
}
private fun refreshConversation() {
if (viewModel.memberID?.isNotBlank() != true) { return }
compositeSubscription.add(
this.socialRepository.retrieveInboxMessages(replyToUserUUID ?: "", 0)
.subscribe(
{}, RxErrorHandler.handleEmptyError(),
{
viewModel.invalidateDataSource()
}
)
)
}
private fun sendMessage(chatText: String) {
viewModel.memberID?.let { userID ->
socialRepository.postPrivateMessage(userID, chatText)
.delay(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
viewModel.invalidateDataSource()
},
{ error ->
RxErrorHandler.reportError(error)
binding?.let {
val alert = HabiticaAlertDialog(it.chatBarView.context)
alert.setTitle("You cannot reply to this conversation")
alert.setMessage("This user is unable to receive your private message")
alert.addOkButton()
alert.show()
}
binding?.chatBarView?.message = chatText
}
)
KeyboardUtil.dismissKeyboard(getActivity())
}
}
private fun setReceivingUser(chatRoomUser: String?, replyToUserUUID: String?) {
this.chatRoomUser = chatRoomUser
this.replyToUserUUID = replyToUserUUID
activity?.title = chatRoomUser
}
private fun copyMessageToClipboard(chatMessage: ChatMessage) {
val clipMan = getActivity()?.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
val messageText = ClipData.newPlainText("Chat message", chatMessage.text)
clipMan?.setPrimaryClip(messageText)
val activity = getActivity() as? MainActivity
if (activity != null) {
showSnackbar(activity.snackbarContainer, getString(R.string.chat_message_copied), HabiticaSnackbar.SnackbarDisplayType.NORMAL)
}
}
private fun showFlagConfirmationDialog(chatMessage: ChatMessage) {
val directions = MainNavDirections.actionGlobalReportMessageActivity(chatMessage.text ?: "", chatMessage.user ?: "", chatMessage.id, null)
MainNavigationController.navigate(directions)
}
private fun showDeleteConfirmationDialog(chatMessage: ChatMessage) {
val context = context
if (context != null) {
AlertDialog.Builder(context)
.setTitle(R.string.confirm_delete_tag_title)
.setMessage(R.string.confirm_delete_tag_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.yes) { _, _ -> socialRepository.deleteMessage(chatMessage).subscribe({ }, RxErrorHandler.handleEmptyError()) }
.setNegativeButton(R.string.no, null).show()
}
}
private fun openProfile() {
replyToUserUUID?.let { FullProfileActivity.open(it) }
}
}
| gpl-3.0 | 62a647ffeab91ff0199d954a5c4fa6ca | 39.821053 | 174 | 0.63017 | 5.834068 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/data/structures/area348/BaseInfo.kt | 2 | 1403 | package nl.rsdt.japp.jotial.data.structures.area348
import android.os.Parcel
import android.os.Parcelable
import com.google.android.gms.maps.model.LatLng
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 20-10-2015
* Class that servers as a deserialization object for the most abstract Info.
*/
open class BaseInfo
/**
* Initializes a new instance of BaseInfo from the parcel.
*/
protected constructor(`in`: Parcel) : Parcelable {
/**
* The id of the Info.
*/
var id: Int = 0
/**
* The latitude of the Info.
*/
var latitude: Double = 0.toDouble()
/**
* The longitude of the Info.
*/
var longitude: Double = 0.toDouble()
val latLng: LatLng
get() = LatLng(latitude, longitude)
init {
id = `in`.readInt()
latitude = `in`.readDouble()
longitude = `in`.readDouble()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
dest.writeDouble(latitude)
dest.writeDouble(longitude)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR: Parcelable.Creator<BaseInfo>{
override fun createFromParcel(`in`: Parcel): BaseInfo {
return BaseInfo(`in`)
}
override fun newArray(size: Int): Array<BaseInfo?> {
return arrayOfNulls(size)
}
}
}
| apache-2.0 | fbc4af6953723c7333e63da081f68280 | 21.269841 | 77 | 0.613685 | 4.138643 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/refactoring/ElmImportOptimizer.kt | 1 | 2469 | package org.elm.ide.refactoring
import com.intellij.lang.ImportOptimizer
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.elm.ide.inspections.ImportVisitor
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.removeItem
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.prevSiblings
import org.elm.lang.core.resolve.scope.ModuleScope
class ElmImportOptimizer: ImportOptimizer {
override fun supports(file: PsiFile): Boolean =
file is ElmFile
override fun processFile(file: PsiFile): Runnable {
if (file !is ElmFile) error("expected an Elm File!")
// Pre-compute the unused elements prior to performing the
// actual edits in the Runnable on the UI thread.
val visitor = ImportVisitor(ModuleScope.getImportDecls(file))
file.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
element.accept(visitor)
super.visitElement(element)
}
})
return Runnable {
val documentManager = PsiDocumentManager.getInstance(file.project)
val document = documentManager.getDocument(file)
if (document != null) {
documentManager.commitDocument(document)
}
execute(visitor)
}
}
private fun execute(visitor: ImportVisitor) {
for (unusedImport in visitor.unusedImports) {
val prevNewline = unusedImport.prevSiblings.firstOrNull { it.textContains('\n') }
if (prevNewline == null) unusedImport.delete()
else unusedImport.parent.deleteChildRange(prevNewline, unusedImport)
}
for (item in visitor.unusedExposedItems) {
val exposingList = item.parentOfType<ElmImportClause>()?.exposingList ?: continue
if (exposingList.allExposedItems.size <= 1) exposingList.delete()
else exposingList.removeItem(item)
}
for (alias in visitor.unusedModuleAliases) {
val parent = alias.parentOfType<ElmImportClause>() ?: continue
// Delete the alias and the preceding whitespace
parent.deleteChildRange(parent.moduleQID.nextSibling, alias)
}
}
}
| mit | bc8127002b8a78008751ba8d0b37cfea | 38.190476 | 93 | 0.682868 | 4.812865 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/builder/KotlinAnalysisJob.kt | 1 | 3939 | /*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.builder
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.core.runtime.IStatus
import org.eclipse.core.runtime.NullProgressMonitor
import org.eclipse.core.runtime.Status
import org.eclipse.core.runtime.jobs.IJobChangeEvent
import org.eclipse.core.runtime.jobs.Job
import org.eclipse.core.runtime.jobs.JobChangeAdapter
import org.eclipse.jdt.core.IJavaProject
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache
import org.jetbrains.kotlin.progress.CompilationCanceledException
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
public class KotlinAnalysisJob(private val javaProject: IJavaProject) : Job("Kotlin Analysis") {
init {
setPriority(DECORATE)
setSystem(true)
}
val familyIndicator = constructFamilyIndicator(javaProject)
@Volatile var canceled = false
override fun run(monitor: IProgressMonitor): IStatus {
try {
canceled = false
ProgressIndicatorAndCompilationCanceledStatus.setCompilationCanceledStatus(object : CompilationCanceledStatus {
override fun checkCanceled() {
if (canceled) throw CompilationCanceledException()
}
})
if (!javaProject.isOpen) {
return Status.OK_STATUS
}
val analysisResult = KotlinAnalysisProjectCache.getAnalysisResult(javaProject)
return AnalysisResultStatus(Status.OK_STATUS, analysisResult)
} catch (e: CompilationCanceledException) {
return AnalysisResultStatus(Status.CANCEL_STATUS, AnalysisResult.EMPTY)
} finally {
ProgressIndicatorAndCompilationCanceledStatus.setCompilationCanceledStatus(null)
}
}
override fun belongsTo(family: Any): Boolean = family == familyIndicator
override fun canceling() {
super.canceling()
canceled = true
}
class AnalysisResultStatus(val status: IStatus, val analysisResult: AnalysisResult): IStatus by status
}
private fun constructFamilyIndicator(javaProject: IJavaProject): String {
return javaProject.getProject().getName() + "_kotlinAnalysisFamily"
}
fun runCancellableAnalysisFor(javaProject: IJavaProject, postAnalysisTask: (AnalysisResult) -> Unit = {}) {
val family = constructFamilyIndicator(javaProject)
Job.getJobManager().cancel(family)
Job.getJobManager().join(family, NullProgressMonitor()) // It should be fast enough
KotlinAnalysisProjectCache.resetCache(javaProject.project)
val analysisJob = KotlinAnalysisJob(javaProject)
analysisJob.addJobChangeListener(object : JobChangeAdapter() {
override fun done(event: IJobChangeEvent) {
val result = event.result
if (result is KotlinAnalysisJob.AnalysisResultStatus && result.isOK) {
postAnalysisTask(result.analysisResult)
}
}
})
analysisJob.schedule()
} | apache-2.0 | e27cbf2ebafedc4413294eb6b42b03ad | 38.4 | 123 | 0.687484 | 5.189723 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/MinecraftSettings.kt | 1 | 3007 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.editor.markup.EffectType
@State(name = "MinecraftSettings", storages = [Storage("minecraft_dev.xml")])
class MinecraftSettings : PersistentStateComponent<MinecraftSettings.State> {
data class State(
var isShowProjectPlatformIcons: Boolean = true,
var isShowEventListenerGutterIcons: Boolean = true,
var isShowChatColorGutterIcons: Boolean = true,
var isShowChatColorUnderlines: Boolean = false,
var underlineType: UnderlineType = UnderlineType.DOTTED
)
private var state = State()
override fun getState(): State {
return state
}
override fun loadState(state: State) {
this.state = state
}
// State mappings
var isShowProjectPlatformIcons: Boolean
get() = state.isShowProjectPlatformIcons
set(showProjectPlatformIcons) {
state.isShowProjectPlatformIcons = showProjectPlatformIcons
}
var isShowEventListenerGutterIcons: Boolean
get() = state.isShowEventListenerGutterIcons
set(showEventListenerGutterIcons) {
state.isShowEventListenerGutterIcons = showEventListenerGutterIcons
}
var isShowChatColorGutterIcons: Boolean
get() = state.isShowChatColorGutterIcons
set(showChatColorGutterIcons) {
state.isShowChatColorGutterIcons = showChatColorGutterIcons
}
var isShowChatColorUnderlines: Boolean
get() = state.isShowChatColorUnderlines
set(showChatColorUnderlines) {
state.isShowChatColorUnderlines = showChatColorUnderlines
}
var underlineType: UnderlineType
get() = state.underlineType
set(underlineType) {
state.underlineType = underlineType
}
val underlineTypeIndex: Int
get() {
val type = underlineType
return UnderlineType.values().indices.firstOrNull { type == UnderlineType.values()[it] } ?: 0
}
enum class UnderlineType(private val regular: String, val effectType: EffectType) {
NORMAL("Normal", EffectType.LINE_UNDERSCORE),
BOLD("Bold", EffectType.BOLD_LINE_UNDERSCORE),
DOTTED("Dotted", EffectType.BOLD_DOTTED_LINE),
BOXED("Boxed", EffectType.BOXED),
ROUNDED_BOXED("Rounded Boxed", EffectType.ROUNDED_BOX),
WAVED("Waved", EffectType.WAVE_UNDERSCORE);
override fun toString(): String {
return regular
}
}
companion object {
val instance: MinecraftSettings
get() = ApplicationManager.getApplication().getService(MinecraftSettings::class.java)
}
}
| mit | 3c1762c0d7ee6bbd88eb10f0a0e52084 | 30.652632 | 105 | 0.687729 | 5.350534 | false | false | false | false |
devromik/black-and-white | sources/src/test/kotlin/net/devromik/bw/x/FixedRootColorSingleChildXResultTest.kt | 1 | 29725 | package net.devromik.bw.x
import net.devromik.bw.Color.*
import net.devromik.bw.Coloring
import net.devromik.bw.INVALID_MAX_WHITE
import net.devromik.bw.checkColoring
import net.devromik.tree.Tree
import net.devromik.tree.root
import org.junit.Test
import org.junit.Assert.*
/**
* @author Shulnyaev Roman
*/
class FixedRootColorSingleChildXResultTest {
/**
* root -> child -> child
*/
@Test fun maxWhiteMap_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun maxWhiteMap_2() {
val tree = Tree<String>(
root() {
child {
child()
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun maxWhiteMap_3() {
val tree = Tree<String>(
root() {
child {
child {
child {
child()
child()
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(2, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(4, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
}
/**
* root -> child -> child
*/
@Test fun coloring_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun coloring_2() {
val tree = Tree<String>(
root() {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 0)
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun coloring_3() {
val tree = Tree<String>(
root() {
child {
child {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 4, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 4, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 2)
result.color(coloring, lastChainNodeColor = WHITE, black = 2, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 2)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 1)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 4)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 4)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
}
/**
* root -> child -> child
*/
@Test fun subtreeSize_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(3, result.subtreeSize())
assertEquals(tree.root.childAt(0).childAt(0), result.lastChainNode)
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun subtreeSize_2() {
val tree = Tree<String>(
root() {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(2, result.subtreeSize())
assertEquals(tree.root.childAt(0), result.lastChainNode)
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun subtreeSize_3() {
val tree = Tree<String>(
root() {
child {
child {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(4, result.subtreeSize())
assertEquals(tree.root.childAt(0).childAt(0).childAt(0), result.lastChainNode)
}
} | mit | 20b00fb3ddb32afe558c36f0fe53e60d | 46.485623 | 90 | 0.607906 | 4.55416 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-util/src/main/java/org/ccci/gto/android/common/util/CurrencyUtils.kt | 2 | 1283 | package org.ccci.gto.android.common.util
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Currency
import java.util.Locale
import org.ccci.gto.android.common.compat.util.LocaleCompat
import org.ccci.gto.android.common.compat.util.LocaleCompat.Category
import timber.log.Timber
@JvmOverloads
fun Double.formatCurrency(currency: String?, locale: Locale = LocaleCompat.getDefault(Category.FORMAT)) =
formatCurrency(currency?.toCurrencyOrNull(), locale)
fun Double.formatCurrency(
currency: Currency? = null,
locale: Locale = LocaleCompat.getDefault(Category.FORMAT)
): String = NumberFormat.getCurrencyInstance(locale)
.also {
if (currency != null) {
it.currency = currency
it.minimumFractionDigits = currency.defaultFractionDigits
it.maximumFractionDigits = currency.defaultFractionDigits
} else if (it is DecimalFormat) {
val symbols = it.decimalFormatSymbols
symbols.currencySymbol = ""
it.decimalFormatSymbols = symbols
}
}
.format(this)
fun String.toCurrencyOrNull() = try {
Currency.getInstance(this)
} catch (e: IllegalArgumentException) {
Timber.tag("CurrencyUtils").e(e, "Unsupported currency: %s", this)
null
}
| mit | c54bb7005b28355fe1202a75bc1ce771 | 33.675676 | 105 | 0.719408 | 4.349153 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/bilibilicomics/src/eu/kanade/tachiyomi/extension/en/bilibilicomics/BilibiliComics.kt | 1 | 13392 | package eu.kanade.tachiyomi.extension.en.bilibilicomics
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.jsoup.Jsoup
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
@Nsfw
class BilibiliComics : HttpSource() {
override val name = "BILIBILI COMICS"
override val baseUrl = "https://www.bilibilicomics.com"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS))
.build()
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add("Accept", ACCEPT_JSON)
.add("Origin", baseUrl)
.add("Referer", "$baseUrl/")
private val json: Json by injectLazy()
override fun popularMangaRequest(page: Int): Request {
val requestPayload = buildJsonObject {
put("id", FEATURED_ID)
put("isAll", 0)
put("page_num", 1)
put("page_size", 6)
}
val requestBody = requestPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetClassPageSixComics?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun popularMangaParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliFeaturedDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.rollSixComics
.map(::popularMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun popularMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = comic.title
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.comicId}"
}
override fun latestUpdatesRequest(page: Int): Request {
val requestPayload = buildJsonObject {
put("day", day)
}
val requestBody = requestPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetSchedule?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun latestUpdatesParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliScheduleDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.list
.map(::latestMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun latestMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = comic.title
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.comicId}"
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return when {
query.startsWith(prefixIdSearch) -> {
val id = query.removePrefix(prefixIdSearch)
client.newCall(mangaDetailsApiRequestById(id)).asObservableSuccess()
.map { response ->
mangaDetailsParse(response).let { MangasPage(listOf(it), false) }
}
}
else -> {
client.newCall(searchMangaRequest(page, query, filters)).asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
}
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val jsonPayload = buildJsonObject {
put("area_id", -1)
put("is_finish", -1)
put("is_free", 1)
put("key_word", query)
put("order", 0)
put("page_num", page)
put("page_size", 9)
put("style_id", -1)
}
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val refererUrl = "$baseUrl/search".toHttpUrl().newBuilder()
.addQueryParameter("keyword", query)
.toString()
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.add("X-Page", page.toString())
.set("Referer", refererUrl)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/Search?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun searchMangaParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliSearchDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.list
.map(::searchMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun searchMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = Jsoup.parse(comic.title).text()
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.id}"
}
// Workaround to allow "Open in browser" use the real URL.
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsApiRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
}
private fun mangaDetailsApiRequest(manga: SManga): Request {
val comicId = manga.url.substringAfterLast("/mc").toInt()
val jsonPayload = buildJsonObject { put("comic_id", comicId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", baseUrl + manga.url)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ComicDetail?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
private fun mangaDetailsApiRequestById(id: String): Request {
val comicId = id.toInt()
val jsonPayload = buildJsonObject { put("comic_id", comicId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", "$baseUrl/detail/mc$id")
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ComicDetail?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun mangaDetailsParse(response: Response): SManga = SManga.create().apply {
val result = json.decodeFromString<BilibiliResultDto<BilibiliComicDto>>(response.body!!.string())
val comic = result.data!!
title = comic.title
author = comic.authorName.joinToString()
status = if (comic.isFinish == 1) SManga.COMPLETED else SManga.ONGOING
genre = comic.styles.joinToString()
description = comic.classicLines
thumbnail_url = comic.verticalCover
}
// Chapters are available in the same url of the manga details.
override fun chapterListRequest(manga: SManga): Request = mangaDetailsApiRequest(manga)
override fun chapterListParse(response: Response): List<SChapter> {
val result = json.decodeFromString<BilibiliResultDto<BilibiliComicDto>>(response.body!!.string())
if (result.code != 0)
return emptyList()
return result.data!!.episodeList
.filter { episode -> episode.isLocked.not() }
.map { ep -> chapterFromObject(ep, result.data.id) }
}
private fun chapterFromObject(episode: BilibiliEpisodeDto, comicId: Int): SChapter = SChapter.create().apply {
name = "Ep. " + episode.order.toString().removeSuffix(".0") +
" - " + episode.title
chapter_number = episode.order
scanlator = this@BilibiliComics.name
date_upload = episode.publicationTime.substringBefore("T").toDate()
url = "/mc$comicId/${episode.id}"
}
override fun pageListRequest(chapter: SChapter): Request {
val chapterId = chapter.url.substringAfterLast("/").toInt()
val jsonPayload = buildJsonObject { put("ep_id", chapterId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", baseUrl + chapter.url)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetImageIndex?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun pageListParse(response: Response): List<Page> {
val result = json.decodeFromString<BilibiliResultDto<BilibiliReader>>(response.body!!.string())
if (result.code != 0) {
return emptyList()
}
return result.data!!.images
.mapIndexed { i, page -> Page(i, page.path, "") }
}
override fun imageUrlRequest(page: Page): Request {
val jsonPayload = buildJsonObject {
put("urls", buildJsonArray { add(page.url) }.toString())
}
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ImageToken?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun imageUrlParse(response: Response): String {
val result = json.decodeFromString<BilibiliResultDto<List<BilibiliPageDto>>>(response.body!!.string())
val page = result.data!![0]
return "${page.url}?token=${page.token}"
}
private fun String.toDate(): Long {
return try {
DATE_FORMATTER.parse(this)?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
private val day: Int
get() {
return when (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> 0
Calendar.MONDAY -> 1
Calendar.TUESDAY -> 2
Calendar.WEDNESDAY -> 3
Calendar.THURSDAY -> 4
Calendar.FRIDAY -> 5
else -> 6
}
}
companion object {
private const val BASE_API_ENDPOINT = "twirp/comic.v1.Comic"
private const val ACCEPT_JSON = "application/json, text/plain, */*"
private val JSON_MEDIA_TYPE = "application/json;charset=UTF-8".toMediaType()
private const val FEATURED_ID = 3
const val prefixIdSearch = "id:"
private val DATE_FORMATTER by lazy { SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH) }
}
}
| apache-2.0 | be22c857477740c1a91d6cf59774623d | 34.903485 | 114 | 0.627165 | 4.808618 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/geom/Circle.kt | 1 | 3669 | package pl.shockah.godwit.geom
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import pl.shockah.godwit.ease.Easable
import pl.shockah.godwit.ease.ease
import pl.shockah.godwit.geom.polygon.Polygon
import kotlin.math.sqrt
class Circle(
position: Vec2 = ImmutableVec2.ZERO,
var radius: Float
) : Shape.Filled, Shape.Outline, Easable<Circle> {
var position: MutableVec2 = position.mutableCopy()
override val boundingBox: Rectangle
get() = Rectangle.centered(position, vec2(radius * 2, radius * 2))
override val center: Vec2
get() = position
companion object {
init {
Shape.registerCollisionHandler { a: Circle, b: Circle ->
(b.position - a.position).length < b.radius + a.radius
}
Shape.registerCollisionHandler { circle: Circle, line: Line ->
line.point1 in circle || line.point2 in circle || !(circle intersect line).isEmpty()
}
Shape.registerCollisionHandler { circle: Circle, rectangle: Rectangle ->
val testPoint = circle.position.mutableCopy()
if (circle.position.x < rectangle.position.x)
testPoint.x = rectangle.position.x
else if (circle.position.x > rectangle.position.x + rectangle.size.x)
testPoint.x = rectangle.position.x + rectangle.size.x
if (circle.position.y < rectangle.position.y)
testPoint.y = rectangle.position.y
else if (circle.position.y > rectangle.position.y + rectangle.size.y)
testPoint.y = rectangle.position.y + rectangle.size.y
return@registerCollisionHandler (circle.position - testPoint).length < circle.radius
}
Shape.registerCollisionHandler { circle: Circle, polygon: Polygon ->
for (line in polygon.lines) {
if (circle collides line)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
}
}
override fun copy(): Circle {
return Circle(position, radius)
}
override fun equals(other: Any?): Boolean {
return other is Circle && position == other.position && radius == other.radius
}
override fun hashCode(): Int {
return position.hashCode() * 31 + radius.hashCode()
}
override fun translate(vector: Vec2) {
position.xy += vector
}
override fun mirror(horizontal: Boolean, vertical: Boolean) {
if (horizontal)
position.x *= -1f
if (vertical)
position.y *= -1f
}
override fun scale(scale: Float) {
position.xy *= scale
radius *= scale
}
override operator fun contains(point: Vec2): Boolean {
return (position - point).length <= radius
}
infix fun intersect(line: Line): List<ImmutableVec2> {
val baX = line.point2.x - line.point1.x
val baY = line.point2.y - line.point1.y
val caX = position.x - line.point1.x
val caY = position.y - line.point1.y
val a = baX * baX + baY * baY
val bBy2 = baX * caX + baY * caY
val c = caX * caX + caY * caY - radius * radius
val pBy2 = bBy2 / a
val q = c / a
val disc = pBy2 * pBy2 - q
if (disc < 0)
return emptyList()
val tmpSqrt = sqrt(disc)
val abScalingFactor1 = -pBy2 + tmpSqrt
val abScalingFactor2 = -pBy2 - tmpSqrt
val p1 = vec2(line.point1.x - baX * abScalingFactor1, line.point1.y - baY * abScalingFactor1)
if (disc == 0f)
return listOf(p1)
val p2 = vec2(line.point1.x - baX * abScalingFactor2, line.point1.y - baY * abScalingFactor2)
return listOf(p1, p2)
}
override fun ease(other: Circle, f: Float): Circle {
return Circle(
position.ease(other.position, f),
f.ease(radius, other.radius)
)
}
private fun draw(shapes: ShapeRenderer) {
shapes.circle(position.x, position.y, radius)
}
override fun drawFilled(shapes: ShapeRenderer) {
draw(shapes)
}
override fun drawOutline(shapes: ShapeRenderer) {
draw(shapes)
}
} | apache-2.0 | 9f441b142e6225df5e20674767c26dd3 | 26.593985 | 95 | 0.693649 | 3.246903 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/format/fbx/fbxDocument.kt | 2 | 51783 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
package assimp.format.fbx
import assimp.*
import glm_.bool
import glm_.c
import glm_.i
/** @file FBXDocument.h
* @brief FBX DOM */
//#define _AI_CONCAT(a,b) a ## b
//#define AI_CONCAT(a,b) _AI_CONCAT(a,b)
/** Represents a delay-parsed FBX objects. Many objects in the scene
* are not needed by assimp, so it makes no sense to parse them
* upfront. */
class LazyObject(val id: Long, val element: Element, val doc: Document) {
var object_: Object? = null
var flags = Flags.NULL.ordinal
enum class Flags { NULL, BEING_CONSTRUCTED, FAILED_TO_CONSTRUCT }
infix fun Int.wo(other: Flags) = and(other.ordinal.inv())
infix fun Int.or(f: LazyObject.Flags) = or(f.ordinal)
fun <T> get(dieOnError: Boolean = false) = get(dieOnError) as? T
fun get(dieOnError: Boolean = false): Object? {
if (isBeingConstructed || failedToConstruct) return null
if (object_ != null) return object_
/* if this is the root object, we return a dummy since there is no root object int he fbx file - it is just
referenced with id 0. */
if (id == 0L) {
object_ = Object(id, element, "Model::RootNode")
return object_
}
val key = element.keyToken
val tokens = element.tokens
if (tokens.size < 3) domError("expected at least 3 tokens: id, name and class tag", element)
var name = tokens[1].parseAsString
/* small fix for binary reading: binary fbx files don't use prefixes such as Model:: in front of their names.
The loading code expects this at many places, though!
so convert the binary representation (a 0x0001) to the double colon notation. */
if (tokens[1].isBinary)
for (i in name.indices) {
if (name[i].i == 0x0 && name[i + 1].i == 0x1)
name = name.substring(i + 2) + "::" + name.substring(0, i)
}
else name = name.trimNUL()
val classtag = tokens[2].parseAsString
// prevent recursive calls
flags = flags or Flags.BEING_CONSTRUCTED
try {
// this needs to be relatively fast since it happens a lot,
// so avoid constructing strings all the time.
val obType = key.begin
val length = key.end - key.begin
// For debugging
//dumpObjectClassInfo( objtype, classtag )
object_ = when {
buffer.strncmp("Geometry", obType, length) -> MeshGeometry(id, element, name, doc).takeIf { classtag == "Mesh" }
buffer.strncmp("NodeAttribute", obType, length) -> when (classtag) {
"Camera" -> Camera(id, element, doc, name)
"CameraSwitcher" -> CameraSwitcher(id, element, doc, name)
"Light" -> Light(id, element, doc, name)
"Null" -> Null(id, element, doc, name)
"LimbNode" -> LimbNode(id, element, doc, name)
else -> null
}
buffer.strncmp("Deformer", obType, length) -> when (classtag) {
"Cluster" -> Cluster(id, element, doc, name)
"Skin" -> Skin(id, element, doc, name)
else -> null
}
buffer.strncmp("Model", obType, length) -> // FK and IK effectors are not supported
Model(id, element, doc, name).takeIf { classtag != "IKEffector" && classtag != "FKEffector" }
buffer.strncmp("Material", obType, length) -> Material(id, element, doc, name)
buffer.strncmp("Texture", obType, length) -> Texture(id, element, doc, name)
buffer.strncmp("LayeredTexture", obType, length) -> LayeredTexture(id, element, doc, name)
buffer.strncmp("Video", obType, length) -> Video(id, element, doc, name)
buffer.strncmp("AnimationStack", obType, length) -> AnimationStack(id, element, name, doc)
buffer.strncmp("AnimationLayer", obType, length) -> AnimationLayer(id, element, name, doc)
// note: order matters for these two
buffer.strncmp("AnimationCurve", obType, length) -> AnimationCurve(id, element, name, doc)
buffer.strncmp("AnimationCurveNode", obType, length) -> AnimationCurveNode(id, element, name, doc)
else -> object_
}
} catch (ex: Exception) {
flags = flags wo Flags.BEING_CONSTRUCTED
flags = flags or Flags.FAILED_TO_CONSTRUCT
// note: the error message is already formatted, so raw logging is ok
logger.error(ex) {}
if (dieOnError || doc.settings.strictMode) throw Exception()
}
if (object_ == null) {
//DOMError("failed to convert element to DOM object, class: " + classtag + ", name: " + name,&element);
}
flags = flags wo Flags.BEING_CONSTRUCTED
return object_
}
// inline fun <reified T> get(dieOnError: Boolean = false): T {
// const Object * const ob = Get(dieOnError)
// return ob ? dynamic_cast<const T*>(ob) : NULL
// }
val isBeingConstructed get() = flags == Flags.BEING_CONSTRUCTED.ordinal
val failedToConstruct get() = flags == Flags.FAILED_TO_CONSTRUCT.ordinal
}
/** Base class for in-memory (DOM) representations of FBX objects */
open class Object(val id: Long, val element: Element, val name: String)
/** DOM class for generic FBX NoteAttribute blocks. NoteAttribute's just hold a property table,
* fixed members are added by deriving classes. */
open class NodeAttribute(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val props: PropertyTable
init {
val sc = element.scope
val classname = element[2].parseAsString
/* hack on the deriving type but Null/LimbNode attributes are the only case in which the property table is by
design absent and no warning should be generated for it. */
val isNullOrLimb = classname == "Null" || classname == "LimbNode"
props = getPropertyTable(doc, "NodeAttribute.Fbx$classname", element, sc, isNullOrLimb)
}
}
/** DOM base class for FBX camera settings attached to a node */
class CameraSwitcher(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
val cameraId = element.scope["CameraId"]?.let { it[0].parseAsInt } ?: 0
val cameraName = element.scope["CameraName"]?.let { it[0].stringContents } ?: ""
val cameraIndexName = element.scope["CameraIndex"]?.let { it[0].stringContents } ?: ""
}
//
//
//#define fbx_stringize(a) #a
//
//#define fbx_simple_property(name, type, default_value) \
//type name() const {
// \
// return PropertyGet<type>(Props(), fbx_stringize(name), (default_value)); \
//}
//
//// XXX improve logging
//#define fbx_simple_enum_property(name, type, default_value) \
//type name() const {
// \
// const int ival = PropertyGet<int>(Props(), fbx_stringize(name), static_cast<int>(default_value)); \
// if (ival < 0 || ival >= AI_CONCAT(type, _MAX)) {
// \
// ai_assert(static_cast<int>(default_value) >= 0 && static_cast<int>(default_value) < AI_CONCAT(type, _MAX)); \
// return static_cast<type>(default_value); \
// } \
// return static_cast<type>(ival); \
//}
//
/** DOM base class for FBX cameras attached to a node */
class Camera(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
val position get() = props("Position", AiVector3D())
val upVector get() = props("UpVector", AiVector3D(0, 1, 0))
val interestPosition get() = props("InterestPosition", AiVector3D())
val aspectWidth get() = props("AspectWidth", 1f)
val aspectHeight get() = props("AspectHeight", 1f)
val filmWidth get() = props("FilmWidth", 1f)
val filmHeight get() = props("FilmHeight", 1f)
val nearPlane get() = props("NearPlane", 0.1f)
val farPlane get() = props("FarPlane", 100f)
val filmAspectRatio get() = props("FilmAspectRatio", 1f)
val apertureMode get() = props("ApertureMode", 0)
val fieldOfView get() = props("FieldOfView", 1f)
val focalLength get() = props("FocalLength", 1f)
}
/** DOM base class for FBX null markers attached to a node */
class Null(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name)
/** DOM base class for FBX limb node markers attached to a node */
class LimbNode(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name)
/** DOM base class for FBX lights attached to a node */
class Light(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
enum class Type { Point, Directional, Spot, Area, Volume }
enum class Decay { None, Linear, Quadratic, Cubic }
val color get() = props("Color", AiVector3D(1))
val type get() = Type.values()[props("Type", Type.Point.ordinal)]
val castLightOnObject get() = props("CastLightOnObject", defaultValue = false)
val drawVolumetricLight get() = props("DrawVolumetricLight", defaultValue = true)
val drawGroundProjection get() = props("DrawGroundProjection", defaultValue = true)
val drawFrontFacingVolumetricLight get() = props("DrawFrontFacingVolumetricLight", defaultValue = false)
val intensity get() = props("Intensity", 100f)
val innerAngle get() = props("InnerAngle", 0f)
val outerAngle get() = props("OuterAngle", 45f)
val fog get() = props("Fog", 50)
val decayType get() = Decay.values()[props("DecayType", Decay.Quadratic.ordinal)]
val decayStart get() = props("DecayStart", 1f)
val fileName get() = props("FileName", "")
val enableNearAttenuation get() = props("EnableNearAttenuation", defaultValue = false)
val nearAttenuationStart get() = props("NearAttenuationStart", 0f)
val nearAttenuationEnd get() = props("NearAttenuationEnd", 0f)
val enableFarAttenuation get() = props("EnableFarAttenuation", defaultValue = false)
val farAttenuationStart get() = props("FarAttenuationStart", 0f)
val farAttenuationEnd get() = props("FarAttenuationEnd", 0f)
val castShadows get() = props("CastShadows", defaultValue = true)
val shadowColor get() = props("ShadowColor", AiVector3D())
val areaLightShape get() = props("AreaLightShape", 0)
val LeftBarnDoor get() = props("LeftBarnDoor", 20f)
val RightBarnDoor get() = props("RightBarnDoor", 20f)
val TopBarnDoor get() = props("TopBarnDoor", 20f)
val BottomBarnDoor get() = props("BottomBarnDoor", 20f)
val EnableBarnDoor get() = props("EnableBarnDoor", defaultValue = true)
}
//
/** DOM base class for FBX models (even though its semantics are more "node" than "model" */
class Model(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val materials = ArrayList<Material>()
val geometry = ArrayList<Geometry>()
val attributes = ArrayList<NodeAttribute>()
val shading = element.scope["Shading"]?.get(0)?.stringContents ?: "Y"
val culling = element.scope["Culling"]?.get(0)?.parseAsString ?: ""
val props = getPropertyTable(doc, "Model.FbxNode", element, element.scope)
init {
resolveLinks(element, doc)
}
enum class RotOrder { EulerXYZ, EulerXZY, EulerYZX, EulerYXZ, EulerZXY, EulerZYX, SphericXYZ }
enum class TransformInheritance { RrSs, RSrs, Rrs }
val quaternionInterpolate get() = props("QuaternionInterpolate", 0)
val rotationOffset get() = props("RotationOffset", AiVector3D())
val rotationPivot get() = props("RotationPivot", AiVector3D())
val scalingOffset get() = props("ScalingOffset", AiVector3D())
val scalingPivot get() = props("ScalingPivot", AiVector3D())
val translationActive get() = props("TranslationActive", defaultValue = false)
val translationMin get() = props("TranslationMin", AiVector3D())
val translationMax get() = props("TranslationMax", AiVector3D())
val translationMinX get() = props("TranslationMinX", defaultValue = false)
val translationMaxX get() = props("TranslationMaxX", defaultValue = false)
val translationMinY get() = props("TranslationMinY", defaultValue = false)
val translationMaxY get() = props("TranslationMaxY", defaultValue = false)
val translationMinZ get() = props("TranslationMinZ", defaultValue = false)
val translationMaxZ get() = props("TranslationMaxZ", defaultValue = false)
val rotationOrder get() = RotOrder.values()[props("RotationOrder", RotOrder.EulerXYZ.ordinal)]
val rotationSpaceForLimitOnly get() = props("RotationSpaceForLimitOnlyMaxZ", defaultValue = false)
val rotationStiffnessX get() = props("RotationStiffnessX", 0f)
val rotationStiffnessY get() = props("RotationStiffnessY", 0f)
val rotationStiffnessZ get() = props("RotationStiffnessZ", 0f)
val axisLen get() = props("AxisLen", 0f)
val preRotation get() = props("PreRotation", AiVector3D())
val postRotation get() = props("PostRotation", AiVector3D())
val rotationActive get() = props("RotationActive", defaultValue = false)
val rotationMin get() = props("RotationMin", AiVector3D())
val rotationMax get() = props("RotationMax", AiVector3D())
val rotationMinX get() = props("RotationMinX", defaultValue = false)
val rotationMaxX get() = props("RotationMaxX", defaultValue = false)
val rotationMinY get() = props("RotationMinY", defaultValue = false)
val rotationMaxY get() = props("RotationMaxY", defaultValue = false)
val rotationMinZ get() = props("RotationMinZ", defaultValue = false)
val rotationMaxZ get() = props("RotationMaxZ", defaultValue = false)
val inheritType get() = TransformInheritance.values()[props("InheritType", TransformInheritance.RrSs.ordinal)]
val scalingActive get() = props("ScalingActive", defaultValue = false)
val scalingMin get() = props("ScalingMin", AiVector3D())
val scalingMax get() = props("ScalingMax", AiVector3D(1f))
val scalingMinX get() = props("ScalingMinX", defaultValue = false)
val scalingMaxX get() = props("ScalingMaxX", defaultValue = false)
val scalingMinY get() = props("ScalingMinY", defaultValue = false)
val scalingMaxY get() = props("ScalingMaxY", defaultValue = false)
val scalingMinZ get() = props("ScalingMinZ", defaultValue = false)
val scalingMaxZ get() = props("ScalingMaxZ", defaultValue = false)
val geometricTranslation get() = props("GeometricTranslation", AiVector3D())
val geometricRotation get() = props("GeometricRotation", AiVector3D())
val geometricScaling get() = props("GeometricScaling", AiVector3D(1f))
val minDampRangeX get() = props("MinDampRangeX", 0f)
val minDampRangeY get() = props("MinDampRangeY", 0f)
val minDampRangeZ get() = props("MinDampRangeZ", 0f)
val maxDampRangeX get() = props("MaxDampRangeX", 0f)
val maxDampRangeY get() = props("MaxDampRangeY", 0f)
val maxDampRangeZ get() = props("MaxDampRangeZ", 0f)
val minDampStrengthX get() = props("MinDampStrengthX", 0f)
val minDampStrengthY get() = props("MinDampStrengthY", 0f)
val minDampStrengthZ get() = props("MinDampStrengthZ", 0f)
val maxDampStrengthX get() = props("MaxDampStrengthX", 0f)
val maxDampStrengthY get() = props("MaxDampStrengthY", 0f)
val maxDampStrengthZ get() = props("MaxDampStrengthZ", 0f)
val preferredAngleX get() = props("PreferredAngleX", 0f)
val preferredAngleY get() = props("PreferredAngleY", 0f)
val preferredAngleZ get() = props("PreferredAngleZ", 0f)
val show get() = props["Show"] ?: true
val lodBox get() = props["LODBox"] ?: false
val freeze get() = props["Freeze"] ?: false
/** convenience method to check if the node has a Null node marker */
val isNull get() = attributes.any { it is Null }
fun resolveLinks(element: Element, doc: Document) {
val arr = arrayOf("Geometry", "Material", "NodeAttribute")
// resolve material
val conns = doc.getConnectionsByDestinationSequenced(id, arr)
materials.ensureCapacity(conns.size)
geometry.ensureCapacity(conns.size)
attributes.ensureCapacity(conns.size)
for (con in conns) {
// material and geometry links should be Object-Object connections
if (con.prop.isNotEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for incoming Model link, ignoring", element)
continue
}
var `continue` = true
when (ob) {
is Material -> materials += ob
is Geometry -> geometry += ob
is NodeAttribute -> attributes += ob
else -> `continue` = false
}
if(`continue`) continue
domWarning("source object for model link is neither Material, NodeAttribute nor Geometry, ignoring", element)
continue
}
}
}
/** DOM class for generic FBX textures */
class Texture(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val uvTrans = element.scope["ModelUVTranslation"]?.let { AiVector2D(it[0].parseAsFloat, it[1].parseAsFloat) }
?: AiVector2D()
val uvScaling = element.scope["ModelUVScaling"]?.let { AiVector2D(it[0].parseAsFloat, it[1].parseAsFloat) }
?: AiVector2D(1)
val type = element.scope["Type"]?.get(0)?.parseAsString ?: ""
val relativeFileName = element.scope["RelativeFileName"]?.get(0)?.parseAsString ?: ""
val fileName = element.scope["FileName"]?.get(0)?.parseAsString ?: ""
val alphaSource = element.scope["Texture_Alpha_Source"]?.get(0)?.parseAsString ?: ""
val props = getPropertyTable(doc, "Texture.FbxFileTexture", element, element.scope)
val crop = element.scope["Cropping"].let { sc -> IntArray(4, { sc?.get(it)?.parseAsInt ?: 0 }) }
var media: Video? = null
init {
// resolve video links
if (doc.settings.readTextures) {
val conns = doc.getConnectionsByDestinationSequenced(id)
for (con in conns) {
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
media = ob as? Video
}
}
}
}
/** DOM class for layered FBX textures */
class LayeredTexture(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val textures = ArrayList<Texture>()
val blendMode = element.scope["BlendModes"]?.let { BlendMode.values()[it[0].parseAsInt] }
?: BlendMode.Translucent
val alpha = element.scope["Alphas"]?.get(0)?.parseAsFloat ?: 0f
//Can only be called after construction of the layered texture object due to construction flag.
fun fillTexture(doc: Document) {
val conns = doc.getConnectionsByDestinationSequenced(id)
for (i in 0 until conns.size) {
val con = conns[i]
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
(ob as? Texture)?.let { textures += it }
}
}
val textureCount get() = textures.size
enum class BlendMode { Translucent, Additive, Modulate, Modulate2, Over, Normal, Dissolve, Darken, ColorBurn,
LinearBurn, DarkerColor, Lighten, Screen, ColorDodge, LinearDodge, LighterColor, SoftLight, HardLight,
VividLight, LinearLight, PinLight, HardMix, Difference, Exclusion, Subtract, Divide, Hue, Saturation, Color,
Luminosity, Overlay, BlendModeCount
}
}
/** DOM class for generic FBX videos */
class Video(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val type = element.scope["Type"]?.get(0)?.parseAsString ?: ""
val relativeFileName = element.scope["RelativeFilename"]?.get(0)?.parseAsString ?: ""
val fileName = element.scope["FileName"]?.get(0)?.parseAsString ?: ""
var contentLength = 0
var content = byteArrayOf()
init {
element.scope["Content"]?.let {
//this field is ommited when the embedded texture is already loaded, let's ignore if it´s not found
try {
val token = it[0]
val data = token.begin
when {
!token.isBinary -> domWarning("video content is not binary data, ignoring", element)
token.end - data < 5 -> domError("binary data array is too short, need five (5) bytes for type signature and element count", element)
buffer[data].c != 'R' -> domWarning("video content is not raw binary data, ignoring", element)
else -> {
// read number of elements
val len = buffer.getInt(data + 1)
contentLength = len
content = ByteArray(len, { buffer.get(data + 5 + it) })
}
}
} catch (runtimeError: Exception) {
//we don´t need the content data for contents that has already been loaded
}
}
}
fun relinquishContent(): ByteArray {
val ptr = content
content = byteArrayOf()
return ptr
}
val props = getPropertyTable(doc, "Video.FbxVideo", element, element.scope)
}
/** DOM class for generic FBX materials */
class Material(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val shading: String
val multiLayer: Boolean
val props: PropertyTable
init {
val sc = element.scope
val shadingModel = sc["ShadingModel"]
multiLayer = (sc["MultiLayer"]?.get(0)?.parseAsInt ?: 0).bool
shading = if (shadingModel != null) shadingModel[0].parseAsString
else "phong".also { domWarning("shading mode not specified, assuming phong", element) }
val templateName = when (shading.toLowerCase()) {
"phong" -> "Material.FbxSurfacePhong"
"lambert" -> "Material.FbxSurfaceLambert"
else -> "".also { domWarning("shading mode not recognized: $shading", element) }
}
props = getPropertyTable(doc, templateName, element, sc)
}
val textures = mutableMapOf<String, Texture>()
val layeredTextures = mutableMapOf<String, LayeredTexture>()
init {
// resolve texture links
val conns = doc.getConnectionsByDestinationSequenced(id)
for (con in conns) {
// texture link to properties, not objects
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
val tex = ob as? Texture
if (tex == null) {
val layeredTexture = ob as? LayeredTexture
if (layeredTexture == null) {
domWarning("source object for texture link is not a texture or layered texture, ignoring", element)
continue
}
val prop = con.prop
if (layeredTextures.contains(prop)) domWarning("duplicate layered texture link: $prop", element)
layeredTextures[prop] = layeredTexture
layeredTexture.fillTexture(doc)
} else {
val prop = con.prop
if (textures.contains(prop)) domWarning("duplicate texture link: $prop", element)
textures[prop] = tex
}
}
}
}
/** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefor) */
class AnimationCurve(id: Long, element: Element, name: String, doc: Document) : Object(id, element, name) {
/** get list of keyframe positions (time). Invariant: |GetKeys()| > 0 */
val keys = ArrayList<Long>()
/** list of keyframe values. Invariant: |GetKeys()| == |GetValues()| && |GetKeys()| > 0 */
val values = ArrayList<Float>()
val attributes = ArrayList<Float>()
val flags = ArrayList<Int>()
init {
val sc = element.scope
val keyTime = sc["KeyTime"]!!
val keyValueFloat = sc["KeyValueFloat"]!!
keyTime.parseLongsDataArray(keys)
keyValueFloat.parseFloatsDataArray(values)
if (keys.size != values.size) domError("the number of key times does not match the number of keyframe values", keyTime)
// check if the key times are well-ordered
for (i in 0 until keys.size - 1)
if (keys[i] <= keys[i + 1])
domError("the keyframes are not in ascending order", keyTime)
sc["KeyAttrDataFloat"]?.parseFloatsDataArray(attributes)
sc["KeyAttrFlags"]?.parseIntsDataArray(flags)
}
}
/** Represents a FBX animation curve (i.e. a mapping from single animation curves to nodes) */
class AnimationCurveNode(id: Long, element: Element, name: String, val doc: Document,
targetPropWhitelist: ArrayList<String> = arrayListOf()) : Object(id, element, name) {
/** Object the curve is assigned to, this can be NULL if the target object has no DOM representation or could not
* be read for other reasons.*/
var target: Object? = null
val props: PropertyTable
val curves = mutableMapOf<String, AnimationCurve>()
/** Property of Target() that is being animated*/
var prop = ""
/* the optional white list specifies a list of property names for which the caller wants animations for.
If the curve node does not match one of these, std::range_error will be thrown. */
init {
val sc = element.scope
// find target node
val whitelist = arrayOf("Model", "NodeAttribute")
val conns = doc.getConnectionsBySourceSequenced(id, whitelist)
for (con in conns) {
// link should go for a property
if (con.prop.isEmpty()) continue
if (targetPropWhitelist.isNotEmpty()) {
val s = con.prop
var ok = false
for (p in targetPropWhitelist) {
if (s == p) {
ok = true
break
}
}
if (!ok) throw Exception("AnimationCurveNode target property is not in whitelist") // TODO handle better std::range_error?
}
val ob = con.destinationObject
if (ob == null) {
domWarning("failed to read destination object for AnimationCurveNode->Model link, ignoring", element)
continue
}
// XXX support constraints as DOM class
//ai_assert(dynamic_cast<const Model*>(ob) || dynamic_cast<const NodeAttribute*>(ob));
target = ob
if (target == null) continue
prop = con.prop
break
}
if (target == null) domWarning("failed to resolve target Model/NodeAttribute/Constraint for AnimationCurveNode", element)
props = getPropertyTable(doc, "AnimationCurveNode.FbxAnimCurveNode", element, sc, false)
}
fun curves(): MutableMap<String, AnimationCurve> {
if (curves.isEmpty()) {
// resolve attached animation curves
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationCurve")
for (con in conns) {
// link should go for a property
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationCurve->AnimationCurveNode link, ignoring", element)
continue
}
val anim = ob as? AnimationCurve
if (anim == null) {
domWarning("source object for ->AnimationCurveNode link is not an AnimationCurve", element)
continue
}
curves[con.prop] = anim
}
}
return curves
}
val targetAsModel get() = target as? Model
val targetAsNodeAttribute get() = target as? NodeAttribute
}
/** Represents a FBX animation layer (i.e. a list of node animations) */
class AnimationLayer(id: Long, element: Element, name: String, val doc: Document) : Object(id, element, name) {
/** note: the props table here bears little importance and is usually absent */
val props = getPropertyTable(doc, "AnimationLayer.FbxAnimLayer", element, element.scope, true)
/* the optional white list specifies a list of property names for which the caller
wants animations for. Curves not matching this list will not be added to the
animation layer. */
fun nodes(targetPropWhitelist: Array<String> = arrayOf()): ArrayList<AnimationCurveNode> {
val nodes = ArrayList<AnimationCurveNode>()
// resolve attached animation nodes
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationCurveNode")
nodes.ensureCapacity(conns.size)
for (con in conns) {
// link should not go to a property
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationCurveNode->AnimationLayer link, ignoring", element)
continue
}
val anim = ob as? AnimationCurveNode
if (anim == null) {
domWarning("source object for ->AnimationLayer link is not an AnimationCurveNode", element)
continue
}
if (targetPropWhitelist.isNotEmpty()) {
val s = anim.prop
var ok = false
for (p in targetPropWhitelist) {
if (s == p) {
ok = true
break
}
}
if (!ok) continue
}
nodes += anim
}
return nodes // pray for NRVO
}
}
/** Represents a FBX animation stack (i.e. a list of animation layers) */
class AnimationStack(id: Long, element: Element, name: String, doc: Document) : Object(id, element, name) {
// note: we don't currently use any of these properties so we shouldn't bother if it is missing
val props = getPropertyTable(doc, "AnimationStack.FbxAnimStack", element, element.scope, true)
val layers = ArrayList<AnimationLayer>()
init {
// resolve attached animation layers
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationLayer")
layers.ensureCapacity(conns.size)
for (con in conns) {
// link should not go to a property
if (con.prop.isNotEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationLayer->AnimationStack link, ignoring", element)
continue
}
val anim = ob as? AnimationLayer
if (anim == null) {
domWarning("source object for ->AnimationStack link is not an AnimationLayer", element)
continue
}
layers += anim
}
}
val localStart get() = props("LocalStart", 0L)
val localStop get() = props("LocalStop", 0L)
val referenceStart get() = props("ReferenceStart", 0L)
val referenceStop get() = props("ReferenceStop", 0L)
}
/** DOM class for deformers */
open class Deformer(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val props = getPropertyTable(doc, "Deformer.Fbx" + element[2].parseAsString, element, element.scope, true)
}
/** DOM class for skin deformer clusters (aka subdeformers) */
class Cluster(id: Long, element: Element, doc: Document, name: String) : Deformer(id, element, doc, name) {
/** get the list of deformer weights associated with this cluster. Use #GetIndices() to get the associated vertices.
* Both arrays have the same size (and may also be empty). */
val weights = ArrayList<Float>()
/** get indices into the vertex data of the geometry associated with this cluster. Use #GetWeights() to get the
* associated weights. Both arrays have the same size (and may also be empty). */
val indices = ArrayList<Int>()
val transform: AiMatrix4x4
val transformLink: AiMatrix4x4
var node: Model? = null
init {
val sc = element.scope
val loadedIndexes = sc.getArray("Indexes")
val loadedWeights = sc.getArray("Weights")
val transform = getRequiredElement(sc, "Transform", element)
val transformLink = getRequiredElement(sc, "TransformLink", element)
this.transform = transform.readMatrix()
this.transformLink = transformLink.readMatrix()
// it is actually possible that there be Deformer's with no weights
if (loadedIndexes.isNotEmpty() != loadedWeights.isNotEmpty()) domError("either Indexes or Weights are missing from Cluster", element)
if (loadedIndexes.isNotEmpty()) {
loadedIndexes[0].parseIntsDataArray(indices)
loadedWeights[0].parseFloatsDataArray(weights)
}
if (indices.size != weights.size) domError("sizes of index and weight array don't match up", element)
// read assigned node
val conns = doc.getConnectionsByDestinationSequenced(id, "Model")
for (con in conns) {
val mod = processSimpleConnection<Model>(con, false, "Model -> Cluster", element)
if (mod != null) {
node = mod
break
}
}
if (node == null) domError("failed to read target Node for Cluster", element)
}
}
/** DOM class for skin deformers */
class Skin(id: Long, element: Element, doc: Document, name: String) : Deformer(id, element, doc, name) {
val accuracy = element.scope["Link_DeformAcuracy"]?.get(0)?.parseAsFloat ?: 0f
val clusters = ArrayList<Cluster>()
init {
// resolve assigned clusters
val conns = doc.getConnectionsByDestinationSequenced(id, "Deformer")
clusters.ensureCapacity(conns.size)
for (con in conns) {
val cluster = processSimpleConnection<Cluster>(con, false, "Cluster -> Skin", element)
if (cluster != null) {
clusters += cluster
continue
}
}
}
}
/** Represents a link between two FBX objects. */
class Connection(val insertionOrder: Long, val src: Long, val dest: Long, val prop: String, val doc: Document) : Comparable<Connection> {
init {
assert(doc.objects.contains(src))
// dest may be 0 (root node)
assert(dest != 0L || doc.objects.contains(dest))
}
/** note: a connection ensures that the source and dest objects exist, but not that they have DOM representations,
* so the return value of one of these functions can still be NULL. */
val sourceObject get() = doc[src]!!.get()
val destinationObject get() = doc[dest]!!.get()
// these, however, are always guaranteed to be valid
val lazySourceObject get() = doc[src]!!
val lazyDestinationObject get() = doc[dest]!!
override fun compareTo(other: Connection) = insertionOrder.compareTo(other.insertionOrder)
// bool Compare(const Connection* c)
// const {
// ai_assert(NULL != c)
//
// return InsertionOrder() < c->InsertionOrder()
// }
}
//
//// XXX again, unique_ptr would be useful. shared_ptr is too
//// bloated since the objects have a well-defined single owner
//// during their entire lifetime (Document). FBX files have
//// up to many thousands of objects (most of which we never use),
//// so the memory overhead for them should be kept at a minimum.
//typedef std::map<uint64_t, LazyObject*> ObjectMap
//typedef std::fbx_unordered_map<std::string, std::shared_ptr<const PropertyTable> > PropertyTemplateMap
//
//typedef std::multimap<uint64_t, const Connection*> ConnectionMap
/** DOM class for global document settings, a single instance per document can
* be accessed via Document.Globals(). */
class FileGlobalSettings(val doc: Document, val props: PropertyTable) {
val upAxis get() = props("UpAxis", 1)
val upAxisSign get() = props("UpAxisSign", 1)
val frontAxis get() = props("FrontAxis", 2)
val frontAxisSign get() = props("FrontAxisSign", 1)
val coordAxis get() = props("CoordAxis", 1)
val coordAxisSign get() = props("CoordAxisSign", 1)
val originalUpAxis get() = props("OriginalUpAxis", 1)
val originalUpAxisSign get() = props("OriginalUpAxisSign", 1)
val unitScaleFactor get() = props("UnitScaleFactor", 1.0)
val originalUnitScaleFactor get() = props("OriginalUnitScaleFactor", 1.0)
val ambientColor get() = props("AmbientColor", AiVector3D())
val defaultCamera get() = props("DefaultCamera", "")
enum class FrameRate { DEFAULT, _120, _100, _60, _50, _48, _30, _30_DROP, NTSC_DROP_FRAME, NTSC_FULL_FRAME, PAL,
CINEMA, _1000, CINEMA_ND, CUSTOM // end-of-enum sentinel
}
val timeMode get() = FrameRate.values()[props("TimeMode", FrameRate.DEFAULT.ordinal)]
val timeSpanStart get() = props("TimeSpanStart", 0L)
val timeSpanStop get() = props("TimeSpanStop", 0L)
val customFrameRate get() = props("CustomFrameRate", -1f)
}
/** DOM root for a FBX file */
class Document(val parser: Parser, val settings: ImportSettings) {
val objects = mutableMapOf<Long, LazyObject>()
val templates = HashMap<String, PropertyTable>()
val srcConnections = mutableMapOf<Long, ArrayList<Connection>>()
val destConnections = mutableMapOf<Long, ArrayList<Connection>>()
var fbxVersion = 0
var creator = ""
val creationTimeStamp = IntArray(7)
private val animationStacks = ArrayList<Long>()
val animationStacksResolved = ArrayList<AnimationStack>()
var globals: FileGlobalSettings? = null
init {
readHeader()
readPropertyTemplates()
readGlobalSettings()
/* This order is important, connections need parsed objects to check whether connections are ok or not.
Objects may not be evaluated yet, though, since this may require valid connections. */
readObjects()
readConnections()
}
operator fun get(id: Long) = objects[id]
//
// bool IsBinary()
// const {
// return parser.IsBinary()
// }
//
// unsigned int FBXVersion()
// const {
// return fbxVersion
// }
//
// const std::string& Creator()
// const {
// return creator
// }
//
// // elements (in this order): Year, Month, Day, Hour, Second, Millisecond
// const unsigned int* CreationTimeStamp()
// const {
// return creationTimeStamp
// }
//
// const FileGlobalSettings& GlobalSettings()
// const {
// ai_assert(globals.get())
// return * globals.get()
// }
//
// const PropertyTemplateMap& Templates()
// const {
// return templates
// }
//
// const ObjectMap& Objects()
// const {
// return objects
// }
//
// const ImportSettings& Settings()
// const {
// return settings
// }
//
// const ConnectionMap& ConnectionsBySource()
// const {
// return src_connections
// }
//
// const ConnectionMap& ConnectionsByDestination()
// const {
// return dest_connections
// }
//
/* note: the implicit rule in all DOM classes is to always resolve from destination to source (since the FBX object
hierarchy is, with very few exceptions, a DAG, this avoids cycles). In all cases that may involve back-facing
edges in the object graph, use LazyObject::IsBeingConstructed() to check. */
fun getConnectionsBySourceSequenced(source: Long) = getConnectionsSequenced(source, srcConnections)
fun getConnectionsByDestinationSequenced(dest: Long) = getConnectionsSequenced(dest, destConnections)
fun getConnectionsBySourceSequenced(source: Long, classname: String) = getConnectionsBySourceSequenced(source, arrayOf(classname))
fun getConnectionsByDestinationSequenced(dest: Long, classname: String) = getConnectionsByDestinationSequenced(dest, arrayOf(classname))
fun getConnectionsBySourceSequenced(source: Long, classnames: Array<String>) = getConnectionsSequenced(source, true, srcConnections, classnames)
fun getConnectionsByDestinationSequenced(dest: Long, classnames: Array<String>) = getConnectionsSequenced(dest, false, destConnections, classnames)
fun animationStacks(): ArrayList<AnimationStack> {
if (animationStacksResolved.isNotEmpty() || animationStacks.isEmpty()) return animationStacksResolved
animationStacksResolved.ensureCapacity(animationStacks.size)
for (id in animationStacks) {
val stack = get(id)?.get<AnimationStack>()
if (stack == null) {
domWarning("failed to read AnimationStack object")
continue
}
animationStacksResolved += stack
}
return animationStacksResolved
}
fun getConnectionsSequenced(id: Long, conns: MutableMap<Long, ArrayList<Connection>>): ArrayList<Connection> {
val range = conns[id] ?: arrayListOf()
return ArrayList<Connection>(range.size).apply {// NRVO should handle this
addAll(range)
sort()
}
}
val MAX_CLASSNAMES = 6
fun getConnectionsSequenced(id: Long, isSrc: Boolean, conns: MutableMap<Long, ArrayList<Connection>>, classnames: Array<String>): ArrayList<Connection> {
assert(classnames.size in 1..MAX_CLASSNAMES)
val temp = ArrayList<Connection>()
val range = conns[id] ?: return temp
temp.ensureCapacity(range.size)
for (it in range) {
val key = (if (isSrc) it.lazyDestinationObject else it.lazySourceObject).element.keyToken
var obType = key.begin
for (name in classnames) {
assert(name.isNotEmpty())
if (key.end - key.begin == name.length && buffer.strncmp(name, obType)) {
obType = 0
break
}
}
if (obType != 0) continue
temp += it
}
temp.sort()
return temp // NRVO should handle this
}
fun readHeader() {
// Read ID objects from "Objects" section
val sc = parser.root
val eHead = sc["FBXHeaderExtension"]
if (eHead?.compound == null) domError("no FBXHeaderExtension dictionary found")
val sHead = eHead.compound!!
fbxVersion = getRequiredElement(sHead, "FBXVersion", eHead)[0].parseAsInt
// While we may have some success with newer files, we don't support the older 6.n fbx format
if (fbxVersion < lowerSupportedVersion) domError("unsupported, old format version, supported are only FBX 2011, FBX 2012 and FBX 2013")
if (fbxVersion > upperSupportedVersion)
if (settings.strictMode) domError("unsupported, newer format version, supported are only FBX 2011, FBX 2012 and FBX 2013 (turn off strict mode to try anyhow) ")
else domWarning("unsupported, newer format version, supported are only FBX 2011, FBX 2012 and FBX 2013, trying to read it nevertheless")
sHead["Creator"]?.let { creator = it[0].parseAsString }
sHead["CreationTimeStamp"]?.let {
it.compound?.let {
creationTimeStamp[0] = it["Year"]!![0].parseAsInt
creationTimeStamp[1] = it["Month"]!![0].parseAsInt
creationTimeStamp[2] = it["Day"]!![0].parseAsInt
creationTimeStamp[3] = it["Hour"]!![0].parseAsInt
creationTimeStamp[4] = it["Minute"]!![0].parseAsInt
creationTimeStamp[5] = it["Second"]!![0].parseAsInt
creationTimeStamp[6] = it["Millisecond"]!![0].parseAsInt
}
}
}
fun readObjects() {
// read ID objects from "Objects" section
val sc = parser.root
val eObjects = sc["Objects"]
if (eObjects?.compound == null) domError("no Objects dictionary found")
// add a dummy entry to represent the Model::RootNode object (id 0), which is only indirectly defined in the input file
objects[0L] = LazyObject(0L, eObjects, this)
val sObjects = eObjects.compound!!
for (el in sObjects.elements) {
val key = el.key
for (e in el.value) {
// extract ID
val tok = e.tokens
if (tok.isEmpty()) domError("expected ID after object key", e)
val id = tok[0].parseAsId
// id=0 is normally implicit
if (id == 0L) domError("encountered object with implicitly defined id 0", e)
if (objects.contains(id)) domWarning("encountered duplicate object id, ignoring first occurrence", e)
objects[id] = LazyObject(id, e, this)
// grab all animation stacks upfront since there is no listing of them
if (key == "AnimationStack") animationStacks += id
}
}
}
fun readPropertyTemplates() {
// read property templates from "Definitions" section
val eDefs = parser.root["Definitions"]
if (eDefs?.compound == null) {
domWarning("no Definitions dictionary found")
return
}
val sDefs = eDefs.compound!!
val oTypes = sDefs.getCollection("ObjectType")
for (el in oTypes) {
val sc = el.compound
if (sc == null) {
domWarning("expected nested scope in ObjectType, ignoring", el)
continue
}
val tok = el.tokens
if (tok.isEmpty()) {
domWarning("expected name for ObjectType element, ignoring", el)
continue
}
val oName = tok[0].parseAsString
val templs = sc.getCollection("PropertyTemplate")
for (e in templs) {
val s = e.compound
if (s == null) {
domWarning("expected nested scope in PropertyTemplate, ignoring", e)
continue
}
val t = e.tokens
if (t.isEmpty()) {
domWarning("expected name for PropertyTemplate element, ignoring", e)
continue
}
val pName = t[0].parseAsString
s["Properties70"]?.let {
val props = PropertyTable(it, null)
templates[oName + "." + pName] = props
}
}
}
}
fun readConnections() {
val sc = parser.root
// read property templates from "Definitions" section
val eConns = sc["Connections"]
if (eConns?.compound == null) domError("no Connections dictionary found")
var insertionOrder = 0L
val sConns = eConns.compound!!
val conns = sConns.getCollection("C")
for (el in conns) {
val type = el[0].parseAsString
// PP = property-property connection, ignored for now
// (tokens: "PP", ID1, "Property1", ID2, "Property2")
if (type == "PP") continue
val src = el[1].parseAsId
val dest = el[2].parseAsId
// OO = object-object connection
// OP = object-property connection, in which case the destination property follows the object ID
val prop = if (type == "OP") el[3].parseAsString else ""
if (!objects.contains(src)) {
domWarning("source object for connection does not exist", el)
continue
}
// dest may be 0 (root node) but we added a dummy object before
if (!objects.contains(dest)) {
domWarning("destination object for connection does not exist", el)
continue
}
// add new connection
val c = Connection(insertionOrder++, src, dest, prop, this)
srcConnections.getOrPut(src, ::arrayListOf) += c
destConnections.getOrPut(dest, ::arrayListOf) += c
}
}
fun readGlobalSettings() {
val sc = parser.root
val eHead = sc["GlobalSettings"]
if (eHead?.compound == null) {
domWarning("no GlobalSettings dictionary found")
globals = FileGlobalSettings(this, PropertyTable())
return
}
val props = getPropertyTable(this, "", eHead, eHead.compound!!, true)
if (props.lazyProps.isEmpty() && props.props.isEmpty())
domError("GlobalSettings dictionary contains no property table")
globals = FileGlobalSettings(this, props)
}
//
// private :
// const ImportSettings& settings
//
// ObjectMap objects
// const Parser& parser
//
// PropertyTemplateMap templates
// ConnectionMap src_connections
// ConnectionMap dest_connections
//
// unsigned int fbxVersion
// std::string creator
// unsigned int creationTimeStamp[7]
//
// std::vector<uint64_t> animationStacks
// mutable std::vector<const AnimationStack*> animationStacksResolved
//
// std::unique_ptr<FileGlobalSettings> globals
companion object {
val lowerSupportedVersion = 7100
val upperSupportedVersion = 7400
}
} | mit | 0b916278b7a16779254c15e2567e4070 | 38.893683 | 172 | 0.623105 | 4.481651 | false | false | false | false |
WillowChat/Hopper | src/main/kotlin/chat/willow/hopper/routes/connection/ConnectionStartRouteHandler.kt | 1 | 1945 | package chat.willow.hopper.routes.connection
import chat.willow.hopper.connections.IHopperConnections
import chat.willow.hopper.logging.loggerFor
import chat.willow.hopper.routes.*
import chat.willow.hopper.routes.shared.EmptyBody
import chat.willow.hopper.routes.shared.ErrorResponseBody
import chat.willow.hopper.websocket.IWebSocketUserTracker
import chat.willow.hopper.websocket.messages.ConnectionStarted
import com.squareup.moshi.Moshi
import spark.Request
data class ConnectionStartContext(val authenticatedContext: AuthenticatedContext, val id: String) {
companion object Builder: IContextBuilder<ConnectionStartContext> {
override fun build(request: Request): ConnectionStartContext? {
val authContext = AuthenticatedContext.Builder.build(request) ?: return null
val id = request.params("connection_id") ?: return null
return ConnectionStartContext(authContext, id)
}
}
}
class ConnectionStartRouteHandler(moshi: Moshi, private val connections: IHopperConnections, private val tracker: IWebSocketUserTracker) :
JsonRouteHandler<EmptyBody, EmptyBody, ConnectionStartContext>(
EmptyBody,
EmptyBody,
moshi.stringSerialiser(),
ConnectionStartContext.Builder
) {
private val LOGGER = loggerFor<ConnectionStartRouteHandler>()
override fun handle(request: EmptyBody, context: ConnectionStartContext): RouteResult<EmptyBody, ErrorResponseBody> {
LOGGER.info("handling GET /connection/<id>/start: $request")
// todo: sanity check id
val server = connections[context.id] ?: return jsonFailure(404, message = "couldn't find a server with id ${context.id}")
connections.start(context.id)
tracker.send(ConnectionStarted.Payload(id = context.id), user = context.authenticatedContext.user)
return RouteResult.success(value = EmptyBody)
}
} | isc | 0c3a1d3dac64fb32ce045305181a2f2e | 39.541667 | 138 | 0.736247 | 4.802469 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/getDelegate/memberProperty.kt | 2 | 704 | // IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.isAccessible
import kotlin.test.*
object Delegate {
var storage = ""
operator fun getValue(instance: Any?, property: KProperty<*>) = storage
operator fun setValue(instance: Any?, property: KProperty<*>, value: String) { storage = value }
}
class Foo {
var result: String by Delegate
}
fun box(): String {
val foo = Foo()
foo.result = "Fail"
val d = (Foo::result).apply { isAccessible = true }.getDelegate(foo) as Delegate
foo.result = "OK"
assertEquals(d, (Foo::result).apply { isAccessible = true }.getDelegate(foo))
return d.getValue(foo, Foo::result)
}
| apache-2.0 | b3daa1a0a33af1cc7d904694659ee2e8 | 27.16 | 100 | 0.678977 | 3.826087 | false | false | false | false |
santoslucas/guarda-filme-android | app/src/main/java/com/guardafilme/ui/main/MainActivity.kt | 1 | 2747 | package com.guardafilme.ui.main
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.firebase.ui.auth.IdpResponse
import com.google.android.gms.ads.MobileAds
import com.guardafilme.R
import com.guardafilme.data.AuthProvider
import com.guardafilme.ui.welcome.WelcomeActivity
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), MainContract.View {
val RC_SIGN_IN = 1234
@Inject
lateinit var presenter: MainContract.Presenter
@Inject
lateinit var authProvider: AuthProvider
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
presenter.attach(this)
setContentView(R.layout.activity_main)
window.statusBarColor = ContextCompat.getColor(this, R.color.colorAccentDark)
MobileAds.initialize(this, getString(R.string.admob_id))
}
override fun onStart() {
super.onStart()
presenter.loadCurrentUser()
login_button.setOnClickListener {
presenter.loginClicked()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
// Successfully signed in
if (resultCode == Activity.RESULT_OK) {
presenter.loadCurrentUser()
} else {
// Sign in failed
presenter.loginError(response?.error?.errorCode)
}
}
}
override fun showLoginMessage() {
login_message_layout.visibility = View.VISIBLE
}
override fun openLogin() {
startActivityForResult(
authProvider.getAuthIntent(),
RC_SIGN_IN)
}
override fun openWelcome() {
startActivity(WelcomeActivity.createIntent(this))
finish()
}
override fun showCanceledLoginMessage() {
showSnackbar(R.string.sign_in_cancelled)
}
override fun showNetworkErrorMessage() {
showSnackbar(R.string.no_internet_connection)
}
override fun showUnknownErrorMessage() {
showSnackbar(R.string.unknown_error)
}
fun showSnackbar(messageId: Int) {
val snack = Snackbar.make(findViewById(R.id.main_layout), messageId, Snackbar.LENGTH_LONG)
snack.show()
}
}
| gpl-3.0 | 3c5198b145181dce951cb244ffcca5f0 | 27.319588 | 98 | 0.680379 | 4.663837 | false | false | false | false |
KeenenCharles/AndroidUnplash | androidunsplash/src/main/java/com/keenencharles/unsplash/models/CurrentUserCollection.kt | 1 | 592 | package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class CurrentUserCollection(
var id: Int? = null,
var title: String? = null,
var curated: Boolean? = null,
@SerializedName("user") var user: User? = null,
@SerializedName("cover_photo") var coverPhoto: CoverPhoto? = null,
@SerializedName("published_at") var publishedAt: String? = null,
@SerializedName("updated_at") var updatedAt: String? = null,
) : Parcelable | mit | 67eff4f786c88cf9c977b52d1815f6ab | 36.0625 | 74 | 0.701014 | 4.228571 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/controller/push/AccountPushController.kt | 2 | 3327 | package com.fsck.k9.controller.push
import com.fsck.k9.Account
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.Preferences
import com.fsck.k9.backend.BackendManager
import com.fsck.k9.backend.api.BackendPusher
import com.fsck.k9.backend.api.BackendPusherCallback
import com.fsck.k9.controller.MessagingController
import com.fsck.k9.mailstore.FolderRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
internal class AccountPushController(
private val backendManager: BackendManager,
private val messagingController: MessagingController,
private val preferences: Preferences,
private val folderRepository: FolderRepository,
backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val account: Account
) {
private val coroutineScope = CoroutineScope(backgroundDispatcher)
@Volatile
private var backendPusher: BackendPusher? = null
private val backendPusherCallback = object : BackendPusherCallback {
override fun onPushEvent(folderServerId: String) {
syncFolders(folderServerId)
}
override fun onPushError(exception: Exception) {
messagingController.handleException(account, exception)
}
override fun onPushNotSupported() {
Timber.v("AccountPushController(%s) - Push not supported. Disabling Push for account.", account.uuid)
disablePush()
}
}
fun start() {
Timber.v("AccountPushController(%s).start()", account.uuid)
startBackendPusher()
startListeningForPushFolders()
}
fun stop() {
Timber.v("AccountPushController(%s).stop()", account.uuid)
stopListeningForPushFolders()
stopBackendPusher()
}
fun reconnect() {
Timber.v("AccountPushController(%s).reconnect()", account.uuid)
backendPusher?.reconnect()
}
private fun startBackendPusher() {
val backend = backendManager.getBackend(account)
backendPusher = backend.createPusher(backendPusherCallback).also { backendPusher ->
backendPusher.start()
}
}
private fun stopBackendPusher() {
backendPusher?.stop()
backendPusher = null
}
private fun startListeningForPushFolders() {
coroutineScope.launch {
folderRepository.getPushFoldersFlow(account).collect { remoteFolders ->
val folderServerIds = remoteFolders.map { it.serverId }
updatePushFolders(folderServerIds)
}
}
}
private fun stopListeningForPushFolders() {
coroutineScope.cancel()
}
private fun updatePushFolders(folderServerIds: List<String>) {
Timber.v("AccountPushController(%s).updatePushFolders(): %s", account.uuid, folderServerIds)
backendPusher?.updateFolders(folderServerIds)
}
private fun syncFolders(folderServerId: String) {
messagingController.synchronizeMailboxBlocking(account, folderServerId)
}
private fun disablePush() {
account.folderPushMode = FolderMode.NONE
preferences.saveAccount(account)
}
}
| apache-2.0 | 14db000f71861416c5c73f242d80264d | 31.300971 | 113 | 0.707845 | 5.0181 | false | false | false | false |
JoeSteven/HuaBan | app/src/main/java/com/joe/zatuji/module/favorite/FavoriteTagFragment.kt | 1 | 5609 | package com.joe.zatuji.module.favorite
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.joe.zatuji.R
import com.joe.zatuji.base.staggered.BasePicListFragment
import com.joe.zatuji.base.staggered.BasePicListPresenter
import com.joe.zatuji.base.staggered.IBasePicListView
import com.joe.zatuji.helper.DialogHelper
import com.joe.zatuji.module.gallery.GalleryActivity
import com.joe.zatuji.repo.bean.Empty
import com.joe.zatuji.repo.bean.FavoriteTag
import com.joe.zatuji.view.DownloadTagDialog
import com.joe.zatuji.view.FavoriteTagDialog
import com.joe.zatuji.view.FavoriteTagMenuDialog
import com.joe.zatuji.view.LockTagDialog
import com.joey.cheetah.core.list.AbsItemViewBinder
import com.joey.cheetah.core.utils.ResGetter
import com.joey.cheetah.mvp.auto.Presenter
/**
* Description:
* author:Joey
* date:2018/11/22
*/
class FavoriteTagFragment : BasePicListFragment<FavoriteTag>(), IFavoriteTagView, FavoriteTagDialog.OnCreateCallBack, FavoriteTagMenuDialog.OnMenuClickListener, LockTagDialog.OnPwdListener {
@Presenter
private val presenter = FavoriteTagPresenter(this)
private val createTagView: FavoriteTagDialog by lazy {
FavoriteTagDialog(activity).setOnCreateCallBack(this)
}
private val editTagView: FavoriteTagMenuDialog by lazy {
FavoriteTagMenuDialog(activity).setOnMenuClickListener(this)
}
private val downloadView: DownloadTagDialog by lazy {
DownloadTagDialog(activity!!)
}
private val lockTagView: LockTagDialog by lazy {
LockTagDialog(activity).setOnPwdListener(this)
}
companion object {
private const val EDIT_TAG = 1
private const val DELETE_TAG = 2
private const val ENTER = 3
private const val DOWNLOAD = 4
}
override fun initArguments(p0: Bundle?) {}
override fun initView() {
super.initView()
setHasOptionsMenu(true)
updateTitle()
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden) {
updateTitle()
}
}
private fun updateTitle() {
activity?.title = ResGetter.string(R.string.tab_home_favorite)
}
override fun switchMenu(show: Boolean) {
setMenuVisibility(show)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_favorite, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_add) {
createTagView.show(null)
}
return true
}
override fun onItemClick(pos: Int, item: FavoriteTag) {
if (item.is_lock) {
lockTagView.show(item, ENTER)
} else {
GalleryActivity.start(activity!!, item)
}
}
override fun onItemLongClick(pos: Int, item: FavoriteTag): Boolean {
editTagView.show(item)
return true
}
override fun emptyView(): AbsItemViewBinder<Empty, *> {
return FavoriteEmptyItemViewBinder()
}
override fun layoutManager(): RecyclerView.LayoutManager {
return GridLayoutManager(activity, 2)
}
override fun viewBinder(): AbsItemViewBinder<FavoriteTag, *> {
return FavoriteTagItemViewBinder()
}
override fun itemType(): Class<FavoriteTag> {
return FavoriteTag::class.java
}
override fun listPresenter(): BasePicListPresenter<IBasePicListView> {
return presenter as BasePicListPresenter<IBasePicListView>
}
override fun initLayout(): Int {
return R.layout.fragment_favorite
}
override fun onCreate(tag: FavoriteTag) {
presenter.createTag(tag)
}
override fun onUpdate(tag: FavoriteTag) {
presenter.updateTag(tag)
}
override fun onEdit(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, EDIT_TAG)
} else {
createTagView.show(tag)
}
}
override fun onPwdSuccess(tag: FavoriteTag, action: Int) {
when (action) {
EDIT_TAG -> createTagView.show(tag)
DELETE_TAG -> delete(tag)
ENTER -> GalleryActivity.start(activity!!, tag)
DOWNLOAD -> presenter.download(tag)
}
}
override fun onDelete(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, DELETE_TAG)
} else {
delete(tag)
}
}
private fun delete(tag: FavoriteTag) {
DialogHelper.confirmDialog(getString(R.string.delete_tag), ResGetter.stringFormat(R.string.delete_tag_hint, tag.tag), {
presenter.deleteTag(tag)
true
})
}
override fun onDownload(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, DOWNLOAD)
} else {
presenter.download(tag)
}
}
override fun onLoadMore() {
// 不支持load more
}
override fun onDestroy() {
super.onDestroy()
createTagView.dismiss()
editTagView.dismiss()
lockTagView.dismiss()
}
override fun showDownload(tag:FavoriteTag) {
downloadView.show(tag, {
presenter.cancelDownload()
})
}
override fun completeDownload() {
downloadView.dismiss()
toast("下载完成")
}
override fun updateProgress(it: Int) {
downloadView.updateProgress(it)
}
} | apache-2.0 | 4f12eaa98c159717dcc527cc8e45f3a4 | 26.98 | 190 | 0.659696 | 4.465283 | false | false | false | false |
ingokegel/intellij-community | platform/script-debugger/debugger-ui/src/SuspendContextView.kt | 10 | 9986 | // 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.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.intellij.xdebugger.settings.XDebuggerSettingsManager
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.rejectedPromise
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.debugger.frame.CallFrameView
import org.jetbrains.debugger.values.StringValue
import java.awt.Color
import java.util.*
/**
* Debugging several VMs simultaneously should be similar to debugging multi-threaded Java application when breakpoints suspend only one thread.
* 1. When thread is paused and another thread reaches breakpoint, show notification about it with possibility to switch thread.
* 2. Stepping and releasing affects only current thread.
* 3. When another thread is selected in Frames view, it changes its icon from (0) to (v) and becomes current, i.e. step/release commands
* are applied to it.
* 4. Stepping/releasing updates current thread icon and clears frame, but doesn't switch thread. To release other threads, user needs to
* select them firstly.
*/
abstract class SuspendContextView(protected val debugProcess: MultiVmDebugProcess,
activeStack: ExecutionStackView,
@Volatile var activeVm: Vm)
: XSuspendContext() {
private val stacks: MutableMap<Vm, ScriptExecutionStack> = Collections.synchronizedMap(LinkedHashMap<Vm, ScriptExecutionStack>())
init {
val mainVm = debugProcess.mainVm
val vmList = debugProcess.collectVMs
if (mainVm != null && !vmList.isEmpty()) {
// main vm should go first
vmList.forEach {
val context = it.suspendContextManager.context
val stack: ScriptExecutionStack =
if (context == null) {
RunningThreadExecutionStackView(it)
}
else if (context == activeStack.suspendContext) {
activeStack
}
else {
logger<SuspendContextView>().error("Paused VM was lost.")
InactiveAtBreakpointExecutionStackView(it)
}
stacks[it] = stack
}
}
else {
stacks[activeVm] = activeStack
}
}
override fun getActiveExecutionStack(): ScriptExecutionStack? = stacks[activeVm]
override fun getExecutionStacks(): Array<out XExecutionStack> = stacks.values.toTypedArray()
fun evaluateExpression(expression: String): Promise<String> {
val activeStack = stacks[activeVm]!!
val frame = activeStack.topFrame ?: return rejectedPromise("Top frame is null")
if (frame !is CallFrameView) return rejectedPromise("Can't evaluate on non-paused thread")
return evaluateExpression(frame.callFrame.evaluateContext, expression)
}
private fun evaluateExpression(evaluateContext: EvaluateContext, expression: String) = evaluateContext.evaluate(expression)
.thenAsync {
val value = it.value
if (value is StringValue && value.isTruncated) {
value.fullString
}
else {
resolvedPromise(value.valueString!!)
}
}
fun pauseInactiveThread(inactiveThread: ExecutionStackView) {
stacks[inactiveThread.vm] = inactiveThread
}
fun hasPausedThreads(): Boolean {
return stacks.values.any { it is ExecutionStackView }
}
fun resume(vm: Vm) {
val prevStack = stacks[vm]
if (prevStack is ExecutionStackView) {
stacks[vm] = RunningThreadExecutionStackView(prevStack.vm)
}
}
fun resumeCurrentThread() {
resume(activeVm)
}
fun setActiveThread(selectedStackFrame: XStackFrame?): Boolean {
if (selectedStackFrame !is CallFrameView) return false
var selectedVm: Vm? = null
for ((key, value) in stacks) {
if (value is ExecutionStackView && value.topFrame?.vm == selectedStackFrame.vm) {
selectedVm = key
break
}
}
val selectedVmStack = stacks[selectedVm]
if (selectedVm != null && selectedVmStack is ExecutionStackView) {
activeVm = selectedVm
stacks[selectedVm] = selectedVmStack.copyWithIsCurrent(true)
stacks.keys.forEach {
val stack = stacks[it]
if (it != selectedVm && stack is ExecutionStackView) {
stacks[it] = stack.copyWithIsCurrent(false)
}
}
return stacks[selectedVm] !== selectedVmStack
}
return false
}
}
class RunningThreadExecutionStackView(vm: Vm) : ScriptExecutionStack(vm, vm.presentableName, AllIcons.Debugger.ThreadRunning) {
override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) {
// add dependency to DebuggerBundle?
container?.errorOccurred(XDebuggerBundle.message("debugger.frames.dialog.message.not.available.for.unsuspended"))
}
override fun getTopFrame(): XStackFrame? = null
}
class InactiveAtBreakpointExecutionStackView(vm: Vm) : ScriptExecutionStack(vm, vm.presentableName, AllIcons.Debugger.ThreadAtBreakpoint) {
override fun getTopFrame(): XStackFrame? = null
override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) {}
}
abstract class ScriptExecutionStack(val vm: Vm, @NlsContexts.ListItem displayName : String, icon: javax.swing.Icon)
: XExecutionStack(displayName, icon) {
override fun hashCode(): Int {
return vm.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is ScriptExecutionStack && other.vm == vm
}
}
// TODO should be AllIcons.Debugger.ThreadCurrent, but because of strange logic to add non-equal XExecutionStacks we can't update icon.
private fun getThreadIcon(isCurrent: Boolean) = AllIcons.Debugger.ThreadAtBreakpoint
class ExecutionStackView(val suspendContext: SuspendContext<*>,
internal val viewSupport: DebuggerViewSupport,
private val topFrameScript: Script?,
private val topFrameSourceInfo: SourceInfo? = null,
@NlsContexts.ListItem displayName: String = "",
isCurrent: Boolean = true)
: ScriptExecutionStack(suspendContext.vm, displayName, getThreadIcon(isCurrent)) {
private var topCallFrameView: CallFrameView? = null
override fun getTopFrame(): CallFrameView? {
val topCallFrame = suspendContext.topFrame
if (topCallFrameView == null || topCallFrameView!!.callFrame != topCallFrame) {
topCallFrameView = topCallFrame?.let { CallFrameView(it, viewSupport, topFrameScript, topFrameSourceInfo,
vm = suspendContext.vm,
methodReturnValue = suspendContext.methodReturnValue) }
}
return topCallFrameView
}
override fun computeStackFrames(firstFrameIndex: Int, container: XExecutionStack.XStackFrameContainer) {
// WipSuspendContextManager set context to null on resume _before_ vm.getDebugListener().resumed() call() (in any case, XFramesView can queue event to EDT), so, IDE state could be outdated compare to VM (our) state
suspendContext.frames
.onSuccess(suspendContext) { frames ->
val count = frames.size - firstFrameIndex
val result: List<XStackFrame>
if (count < 1) {
result = emptyList()
}
else {
result = ArrayList(count)
for (i in firstFrameIndex until frames.size) {
if (i == 0) {
result.add(topFrame!!)
continue
}
val frame = frames[i]
val asyncFunctionName = frame.asyncFunctionName
if (asyncFunctionName != null) {
result.add(AsyncFramesHeader(asyncFunctionName))
}
// if script is null, it is native function (Object.forEach for example), so, skip it
val script = suspendContext.vm.scriptManager.getScript(frame)
if (script != null) {
val sourceInfo = viewSupport.getSourceInfo(script, frame)
val isInLibraryContent = sourceInfo != null && viewSupport.isInLibraryContent(sourceInfo, script)
if (isInLibraryContent && !XDebuggerSettingsManager.getInstance().dataViewSettings.isShowLibraryStackFrames) {
continue
}
result.add(CallFrameView(frame, viewSupport, script, sourceInfo, isInLibraryContent, suspendContext.vm))
}
}
}
container.addStackFrames(result, true)
}
}
fun copyWithIsCurrent(isCurrent: Boolean): ExecutionStackView {
if (icon == getThreadIcon(isCurrent)) return this
return ExecutionStackView(suspendContext, viewSupport, topFrameScript, topFrameSourceInfo, displayName, isCurrent)
}
}
private val ASYNC_HEADER_ATTRIBUTES = SimpleTextAttributes(SimpleTextAttributes.STYLE_UNDERLINE or SimpleTextAttributes.STYLE_BOLD,
UIUtil.getInactiveTextColor())
private class AsyncFramesHeader(val asyncFunctionName: String) : XStackFrame(), XDebuggerFramesList.ItemWithCustomBackgroundColor {
override fun customizePresentation(component: ColoredTextContainer) {
component.append(XDebuggerBundle.message("debugger.frames.label.async.call.from.function", asyncFunctionName), ASYNC_HEADER_ATTRIBUTES)
}
override fun getBackgroundColor(): Color? = null
} | apache-2.0 | d1378c6747bd2fc6e001a19835c61053 | 40.098765 | 218 | 0.691768 | 5.100102 | false | false | false | false |
plombardi89/KOcean | src/test/kotlin/com/github/plombardi89/kocean/ClientExceptionTest.kt | 1 | 867 | package com.github.plombardi89.kocean
import com.github.plombardi89.kocean.model.HostAndPort
import org.junit.Test
import org.junit.Assert.*
class ClientExceptionTest {
Test fun noProxySpecified_invalidResponseReceivedMessageDoesNotContainProxyInformation() {
val configWithoutProxy = KOceanConfig("foobar")
val exception = ClientException.invalidResponse(configWithoutProxy)
assertEquals("Invalid response (host: api.digitalocean.com:443)", exception.getMessage())
}
Test fun invalidResponseReceivedMessageIsFormattedCorrectlyWhenUsingAProxy() {
val configWithProxy = KOceanConfig(apiToken = "foobar", proxyHost = HostAndPort("localhost", 8033))
val exception = ClientException.invalidResponse(configWithProxy)
assertEquals("Invalid response (host: api.digitalocean.com:443, proxy: localhost:8033)", exception.getMessage())
}
} | mit | 6b990a5d140cc7742ae141d65b0a4487 | 36.73913 | 116 | 0.797001 | 4.492228 | false | true | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/handler/ReceiveHandler.kt | 1 | 3095 | package com.janyo.janyoshare.handler
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.app.AlertDialog
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.activity.FileTransferActivity
import com.janyo.janyoshare.activity.FileTransferConfigureActivity
import com.janyo.janyoshare.service.ReceiveFileService
import com.janyo.janyoshare.util.FileTransferHelper
import com.janyo.janyoshare.util.SocketUtil
import com.zyao89.view.zloading.ZLoadingDialog
class ReceiveHandler : Handler()
{
lateinit var spotsDialog: ZLoadingDialog
lateinit var context: Context
override fun handleMessage(msg: Message)
{
when (msg.what)
{
FileTransferConfigureActivity.CREATE_CONNECTION ->
{
spotsDialog.setHintText(context.getString(R.string.hint_socket_connecting))
}
FileTransferConfigureActivity.VERIFY_DEVICE ->
{
@Suppress("UNCHECKED_CAST")
val map = msg.obj as HashMap<String, Any>
val socketUtil = map["socket"] as SocketUtil
AlertDialog.Builder(context)
.setCancelable(false)
.setTitle(R.string.hint_socket_verify_device_title)
.setMessage(String.format(context.getString(R.string.hint_socket_verify_device_message), map["message"]))
.setPositiveButton(R.string.action_done, { _, _ ->
Thread(Runnable {
socketUtil.sendMessage(FileTransferConfigureActivity.VERIFY_DONE)
val message = Message()
message.what = FileTransferConfigureActivity.CONNECTED
message.obj = map["message"]
sendMessage(message)
FileTransferHelper.getInstance().ip = socketUtil.ip
socketUtil.clientDisconnect()
}).start()
})
.setNegativeButton(R.string.action_cancel, { _, _ ->
Thread(Runnable {
socketUtil.sendMessage(FileTransferConfigureActivity.VERIFY_CANCEL)
val message = Message()
message.what = FileTransferConfigureActivity.VERIFY_ERROR
sendMessage(message)
}).start()
})
.show()
}
FileTransferConfigureActivity.CONNECTED ->
{
spotsDialog.dismiss()
Toast.makeText(context, R.string.hint_socket_connected, Toast.LENGTH_SHORT)
.show()
FileTransferHelper.getInstance().tag = 2
context.startService(Intent(context, ReceiveFileService::class.java))
(context as Activity).finish()
context.startActivity(Intent(context, FileTransferActivity::class.java), ActivityOptionsCompat.makeSceneTransitionAnimation(context as Activity).toBundle())
}
FileTransferConfigureActivity.SCAN_COMPLETE ->
{
spotsDialog.dismiss()
val isDeviceFind = msg.obj as Boolean
if (!isDeviceFind)
Toast.makeText(context, R.string.hint_socket_scan_complete, Toast.LENGTH_SHORT)
.show()
}
FileTransferConfigureActivity.VERIFY_ERROR ->
{
spotsDialog.dismiss()
Toast.makeText(context, R.string.hint_socket_verify_error, Toast.LENGTH_SHORT)
.show()
}
}
}
} | gpl-3.0 | dacd499b07a67902744c069be21c3ac7 | 34.181818 | 160 | 0.734087 | 4.083113 | false | true | false | false |
andgate/Ikou | core/src/com/andgate/ikou/actor/CommandProcessor.kt | 1 | 871 | package com.andgate.ikou.actor
import java.util.*
class CommandProcessor
{
private val TAG: String = "CommandProcessor"
// Command history stores commands that were executed and are now finished
var history = Vector<Command>()
// Command buffer stores commands to be executed when the current command is finished
var buffer = LinkedList<Command>()
var is_accepting = true
fun update()
{
for(i in buffer.indices) buffer[i].execute()
history.addAll(buffer)
buffer.clear()
}
fun accept(new_comm: Command)
{
if(is_accepting) buffer.add(new_comm)
}
fun nuke_history()
{
history.clear()
}
fun nuke_buffer()
{
buffer.clear()
}
fun rejectAll()
{
is_accepting = false
}
fun acceptAll()
{
is_accepting = true
}
} | gpl-2.0 | dfb6e984d67efc490396db59c65bdceb | 17.956522 | 89 | 0.600459 | 4.147619 | false | false | false | false |
hzsweers/CatchUp | services/github/src/main/kotlin/io/sweers/catchup/service/github/model/SearchQuery.kt | 1 | 1280 | /*
* 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.github.model
import java.time.LocalDate
import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
internal data class SearchQuery(val createdSince: LocalDate?, val minStars: Int) {
override fun toString(): String {
// Returning null here is not ideal, but it lets retrofit drop the query param altogether.
val builder = StringBuilder()
if (createdSince != null) {
builder.append("created:>=")
.append(ISO_LOCAL_DATE.format(createdSince))
.append(' ')
}
if (minStars != 0) {
builder.append("stars:>=")
.append(minStars)
}
return builder.toString()
.trim { it <= ' ' }
}
}
| apache-2.0 | f7ec0238df8bed478bf78beaf5c55771 | 32.684211 | 94 | 0.692188 | 4 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt | 2 | 17585 | // 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 git4idea.ui.branch.dashboard
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.icons.AllIcons
import com.intellij.ide.CommonActionsManager
import com.intellij.ide.DataManager
import com.intellij.ide.DefaultTreeExpander
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ActionPlaces.VCS_LOG_BRANCHES_PLACE
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.speedSearch.SpeedSearch
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.StatusText.getDefaultEmptyText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy
import com.intellij.vcs.log.VcsLogBranchLikeFilter
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.MainVcsLogUiProperties
import com.intellij.vcs.log.impl.VcsLogApplicationSettings
import com.intellij.vcs.log.impl.VcsLogContentProvider.MAIN_LOG_ID
import com.intellij.vcs.log.impl.VcsLogManager
import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory
import com.intellij.vcs.log.impl.VcsLogNavigationUtil.jumpToBranch
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties
import com.intellij.vcs.log.ui.VcsLogColorManager
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.VcsLogUiImpl
import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx
import com.intellij.vcs.log.ui.frame.MainFrame
import com.intellij.vcs.log.ui.frame.ProgressStripe
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePackRefresher
import com.intellij.vcs.log.visible.VisiblePackRefresherImpl
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import git4idea.i18n.GitBundle.message
import git4idea.i18n.GitBundleExtensions.messagePointer
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import java.awt.datatransfer.DataFlavor
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.TransferHandler
import javax.swing.event.TreeSelectionListener
internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable {
private val uiController = BranchesDashboardController(project, this)
private val tree = BranchesTreeComponent(project).apply {
accessibleContext.accessibleName = message("git.log.branches.tree.accessible.name")
}
private val filteringTree = FilteringBranchesTree(project, tree, uiController, place = VCS_LOG_BRANCHES_PLACE, disposable = this)
private val branchViewSplitter = BranchViewSplitter()
private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT))
private val branchesScrollPane = ScrollPaneFactory.createScrollPane(filteringTree.component, true)
private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private val branchesTreeWithLogPanel = simplePanel()
private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) }
private val branchesSearchFieldPanel = simplePanel()
private val branchesSearchField = filteringTree.installSearchField().apply {
textEditor.border = JBUI.Borders.emptyLeft(5)
accessibleContext.accessibleName = message("git.log.branches.search.field.accessible.name")
// fixme: this needs to be dynamic
accessibleContext.accessibleDescription = message("git.log.branches.search.field.accessible.description",
KeymapUtil.getFirstKeyboardShortcutText("Vcs.Log.FocusTextFilter"))
}
private val branchesSearchFieldWrapper = NonOpaquePanel(branchesSearchField).apply(UIUtil::setNotOpaqueRecursively)
private lateinit var branchesPanelExpandableController: ExpandablePanelController
private val treeSelectionListener = TreeSelectionListener {
if (!branchesPanelExpandableController.isExpanded()) return@TreeSelectionListener
val ui = logUi
val properties = ui.properties
if (properties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) {
updateLogBranchFilter()
}
else if (properties[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY]) {
navigateToSelectedBranch(false)
}
}
internal fun updateLogBranchFilter() {
val ui = logUi
val selectedFilters = filteringTree.getSelectedBranchFilters()
val oldFilters = ui.filterUi.filters
val newFilters = if (selectedFilters.isNotEmpty()) {
oldFilters.without(VcsLogBranchLikeFilter::class.java).with(VcsLogFilterObject.fromBranches(selectedFilters))
} else {
oldFilters.without(VcsLogBranchLikeFilter::class.java)
}
ui.filterUi.filters = newFilters
}
internal fun navigateToSelectedBranch(focus: Boolean) {
val selectedReference = filteringTree.getSelectedBranchFilters().singleOrNull() ?: return
logUi.jumpToBranch(selectedReference, false, focus)
}
internal fun toggleGrouping(key: GroupingKey, state: Boolean) {
filteringTree.toggleGrouping(key, state)
}
internal fun isGroupingEnabled(key: GroupingKey) = filteringTree.isGroupingEnabled(key)
internal fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> {
return filteringTree.getSelectedRepositories(branchInfo)
}
internal fun getSelectedRemotes(): Set<RemoteInfo> {
return filteringTree.getSelectedRemotes()
}
internal fun getRootsToFilter(): Set<VirtualFile> {
val roots = logUi.logData.roots.toSet()
if (roots.size == 1) return roots
return VcsLogUtil.getAllVisibleRoots(roots, logUi.filterUi.filters)
}
private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() {
override fun getOrderedComponents(): List<Component> = listOf(filteringTree.component, logUi.table,
logUi.changesBrowser.preferredFocusedComponent,
logUi.filterUi.textFilterComponent.textField)
}
private val showBranches get() = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY)
init {
initMainUi()
installLogUi()
toggleBranchesPanelVisibility()
}
@RequiresEdt
private fun installLogUi() {
uiController.registerDataPackListener(logUi.logData)
uiController.registerLogUiPropertiesListener(logUi.properties)
uiController.registerLogUiFilterListener(logUi.filterUi)
branchesSearchFieldWrapper.setVerticalSizeReferent(logUi.toolbar)
branchViewSplitter.secondComponent = logUi.mainLogComponent
mainPanel.add(branchesTreeWithLogPanel)
filteringTree.component.addTreeSelectionListener(treeSelectionListener)
}
@RequiresEdt
private fun disposeBranchesUi() {
branchViewSplitter.secondComponent.removeAll()
uiController.removeDataPackListener(logUi.logData)
uiController.removeLogUiPropertiesListener(logUi.properties)
filteringTree.component.removeTreeSelectionListener(treeSelectionListener)
}
private fun initMainUi() {
val diffAction = ShowBranchDiffAction()
diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel)
val deleteAction = DeleteBranchAction()
val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts(
"EditorDeleteToLineStart").shortcuts
deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel)
createFocusFilterFieldAction(branchesSearchFieldWrapper)
installPasteAction(filteringTree)
val toggleFavoriteAction = ToggleFavoriteAction()
val fetchAction = FetchAction(this)
val showMyBranchesAction = ShowMyBranchesAction(uiController)
val newBranchAction = ActionManager.getInstance().getAction("Git.New.Branch.In.Log")
val updateSelectedAction = UpdateSelectedBranchAction()
val defaultTreeExpander = DefaultTreeExpander(filteringTree.component)
val commonActionsManager = CommonActionsManager.getInstance()
val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val actionManager = ActionManager.getInstance()
val hideBranchesAction = actionManager.getAction("Git.Log.Hide.Branches")
val settings = actionManager.getAction("Git.Log.Branches.Settings")
val group = DefaultActionGroup()
group.add(hideBranchesAction)
group.add(Separator())
group.add(newBranchAction)
group.add(updateSelectedAction)
group.add(deleteAction)
group.add(diffAction)
group.add(showMyBranchesAction)
group.add(fetchAction)
group.add(toggleFavoriteAction)
group.add(actionManager.getAction("Git.Log.Branches.Navigate.Log.To.Selected.Branch"))
group.add(Separator())
group.add(settings)
group.add(actionManager.getAction("Git.Log.Branches.Grouping.Settings"))
group.add(expandAllAction)
group.add(collapseAllAction)
val toolbar = actionManager.createActionToolbar("Git.Log.Branches", group, false)
toolbar.setTargetComponent(branchesTreePanel)
val branchesButton = ExpandStripeButton(messagePointer("action.Git.Log.Show.Branches.text"), AllIcons.Actions.ArrowExpand)
.apply {
border = createBorder(JBColor.border(), SideBorder.RIGHT)
addActionListener {
if (logUi.properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) {
logUi.properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, true)
}
}
}
branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM))
branchesSearchFieldPanel.addToCenter(branchesSearchFieldWrapper)
branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe)
branchesPanelExpandableController = ExpandablePanelController(toolbar.component, branchesButton, branchesTreePanel)
branchViewSplitter.firstComponent = branchesTreePanel
branchesTreeWithLogPanel.addToLeft(branchesPanelExpandableController.expandControlPanel).addToCenter(branchViewSplitter)
mainPanel.isFocusCycleRoot = true
mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY
}
fun toggleBranchesPanelVisibility() {
branchesPanelExpandableController.toggleExpand(showBranches)
updateBranchesTree(true)
}
private fun createFocusFilterFieldAction(searchField: Component) {
DumbAwareAction.create { e ->
val project = e.getRequiredData(CommonDataKeys.PROJECT)
if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(filteringTree.component) != null) {
IdeFocusManager.getInstance(project).requestFocus(searchField, true)
}
else {
IdeFocusManager.getInstance(project).requestFocus(filteringTree.component, true)
}
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel)
}
private fun installPasteAction(tree: FilteringBranchesTree) {
tree.component.actionMap.put(TransferHandler.getPasteAction().getValue(Action.NAME), object: AbstractAction () {
override fun actionPerformed(e: ActionEvent?) {
val speedSearch = tree.searchModel.speedSearch as? SpeedSearch ?: return
val pasteContent =
CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor)
// the same filtering logic as in javax.swing.text.PlainDocument.insertString (e.g. DnD to search field)
?.let { StringUtil.convertLineSeparators(it, " ") }
speedSearch.type(pasteContent)
speedSearch.update()
}
})
}
inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider {
override fun getData(dataId: String): Any? {
return when {
GIT_BRANCHES.`is`(dataId) -> filteringTree.getSelectedBranches()
GIT_BRANCH_FILTERS.`is`(dataId) -> filteringTree.getSelectedBranchFilters()
BRANCHES_UI_CONTROLLER.`is`(dataId) -> uiController
VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId) -> logUi.properties
else -> null
}
}
}
fun getMainComponent(): JComponent {
return mainPanel
}
fun updateBranchesTree(initial: Boolean) {
if (showBranches) {
filteringTree.update(initial)
}
}
fun refreshTree() {
filteringTree.refreshTree()
}
fun refreshTreeModel() {
filteringTree.refreshNodeDescriptorsModel()
}
fun startLoadingBranches() {
filteringTree.component.emptyText.text = message("action.Git.Loading.Branches.progress")
branchesTreePanel.isEnabled = false
branchesProgressStripe.startLoading()
}
fun stopLoadingBranches() {
filteringTree.component.emptyText.text = getDefaultEmptyText()
branchesTreePanel.isEnabled = true
branchesProgressStripe.stopLoading()
}
override fun dispose() {
disposeBranchesUi()
}
}
internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null)
: BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) {
override fun createVcsLogUiImpl(logId: String,
logData: VcsLogData,
properties: MainVcsLogUiProperties,
colorManager: VcsLogColorManager,
refresher: VisiblePackRefresherImpl,
filters: VcsLogFilterCollection?) =
BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters)
}
internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager,
uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher,
initialFilters: VcsLogFilterCollection?) :
VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) {
private val branchesUi =
BranchesDashboardUi(logData.project, this)
.also { branchesUi -> Disposer.register(this, branchesUi) }
internal val mainLogComponent: JComponent
get() = mainFrame
internal val changesBrowser: ChangesBrowserBase
get() = mainFrame.changesBrowser
override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties,
filterUi: VcsLogFilterUiEx, isEditorDiffPreview: Boolean) =
MainFrame(logData, this, uiProperties, filterUi, isEditorDiffPreview, this)
.apply {
isFocusCycleRoot = false
focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree
}
override fun getMainComponent() = branchesUi.getMainComponent()
}
@ApiStatus.Internal
val SHOW_GIT_BRANCHES_LOG_PROPERTY =
object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") {
override fun defaultValue(logId: String) = logId == MAIN_LOG_ID
}
@ApiStatus.Internal
val CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Change.Log.Filter.on.Branch.Selection") {
override fun defaultValue() = false
}
@ApiStatus.Internal
val NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Navigate.Log.To.Branch.on.Branch.Selection") {
override fun defaultValue() = false
}
private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null)
: OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) {
init {
firstComponent = first
secondComponent = second
}
}
| apache-2.0 | a74d2fa9e2ad69b56c52eb9fa7a1a0bd | 43.859694 | 140 | 0.774694 | 5.050258 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/GoogleCastManager.kt | 1 | 2222 | package ch.abertschi.adfree
import android.app.Notification
import android.service.notification.StatusBarNotification
import ch.abertschi.adfree.model.PreferencesFactory
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import org.jetbrains.anko.warn
import java.lang.Exception
class GoogleCastManager(val prefs: PreferencesFactory) : AnkoLogger {
companion object {
private val ID = "com.google.android.gms|g:com.google.android.gms.cast.rcn.NOTIFICATIONS"
}
private var enabled: Boolean = false
private var action: Notification.Action? = null
init {
enabled = prefs.isGoogleCastEnabled()
}
fun setEnabled(e: Boolean) {
enabled = e
prefs.setGoogleCastEnabled(e)
}
fun isEnabled(): Boolean {
return enabled
}
// val act = sbn.notification.actions.get(1)
// info { act.title }
// act?.run {
// if (act.title.contains("Unmute")) {
// act.actionIntent.send()
// info { "send intent" }
// }
// }
// recordNotification(sbn)
// info { "debug this" }
fun updateNotification(sbn: StatusBarNotification) {
if (sbn.groupKey.contains(ID)) {
info { sbn.groupKey }
if (sbn.notification?.actions?.size == 4) {
val act = sbn.notification.actions[1]
info { "updating action for chromecast manager"}
info { act.title }
info { act }
action = act
}
}
}
fun muteAudio() {
if (!enabled) return
try {
info { "muting google cast audio with action $action" }
action?.run { action?.actionIntent?.send() }
} catch (e: Exception) {
warn { "muting failed" }
warn { e }
}
}
fun unmuteAudio() {
if (!enabled) return
try {
info { "unmuting google cast audio with action $action" }
action?.run { action?.actionIntent?.send() }
} catch (e: Exception) {
warn { "unmuting failed" }
warn { e }
}
}
} | apache-2.0 | b5534f99ced9c3d048bd0f70995d4b3b | 27.139241 | 97 | 0.549505 | 4.382643 | false | false | false | false |
ktorio/ktor | ktor-io/js/test/io/ktor/utils/io/ISOTest.kt | 1 | 954 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.utils.io
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*
private const val TEXT = "test\u00f0."
private val BYTES = byteArrayOf(0x74, 0x65, 0x73, 0x74, 0xf0.toByte(), 0x2e)
class ISOTest {
@Ignore
@Test
fun testEncode() {
val bytes = Charsets.ISO_8859_1.newEncoder().encode(TEXT).readBytes()
assertTrue {
bytes.contentEquals(BYTES)
}
}
@Ignore
@Test
fun testEncodeUnmappable() {
assertFailsWith<MalformedInputException> {
Charsets.ISO_8859_1.newEncoder().encode("\u0422")
}
}
@Ignore
@Test
fun testDecode() {
val pkt = ByteReadPacket(BYTES)
val result = Charsets.ISO_8859_1.newDecoder().decode(pkt)
assertEquals(TEXT, result)
}
}
| apache-2.0 | 2b1af706d1be601c02c6b9b43bdcf557 | 23.461538 | 119 | 0.63522 | 3.586466 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt | 2 | 24937 | package eu.kanade.tachiyomi.data.notification
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.ContextCompat
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.backup.BackupRestoreService
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.notificationManager
import eu.kanade.tachiyomi.util.system.toShareIntent
import eu.kanade.tachiyomi.util.system.toast
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.io.File
import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID
/**
* Global [BroadcastReceiver] that runs on UI thread
* Pending Broadcasts should be made from here.
* NOTE: Use local broadcasts if possible.
*/
class NotificationReceiver : BroadcastReceiver() {
private val downloadManager: DownloadManager by injectLazy()
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
// Dismiss notification
ACTION_DISMISS_NOTIFICATION -> dismissNotification(context, intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1))
// Resume the download service
ACTION_RESUME_DOWNLOADS -> DownloadService.start(context)
// Pause the download service
ACTION_PAUSE_DOWNLOADS -> {
DownloadService.stop(context)
downloadManager.pauseDownloads()
}
// Clear the download queue
ACTION_CLEAR_DOWNLOADS -> downloadManager.clearQueue(true)
// Launch share activity and dismiss notification
ACTION_SHARE_IMAGE ->
shareImage(
context,
intent.getStringExtra(EXTRA_FILE_LOCATION)!!,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Delete image from path and dismiss notification
ACTION_DELETE_IMAGE ->
deleteImage(
context,
intent.getStringExtra(EXTRA_FILE_LOCATION)!!,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Share backup file
ACTION_SHARE_BACKUP ->
shareFile(
context,
intent.getParcelableExtra(EXTRA_URI)!!,
"application/x-protobuf+gzip",
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
ACTION_CANCEL_RESTORE -> cancelRestore(
context,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Cancel library update and dismiss notification
ACTION_CANCEL_LIBRARY_UPDATE -> cancelLibraryUpdate(context, Notifications.ID_LIBRARY_PROGRESS)
// Open reader activity
ACTION_OPEN_CHAPTER -> {
openChapter(
context,
intent.getLongExtra(EXTRA_MANGA_ID, -1),
intent.getLongExtra(EXTRA_CHAPTER_ID, -1)
)
}
// Mark updated manga chapters as read
ACTION_MARK_AS_READ -> {
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
if (notificationId > -1) {
dismissNotification(context, notificationId, intent.getIntExtra(EXTRA_GROUP_ID, 0))
}
val urls = intent.getStringArrayExtra(EXTRA_CHAPTER_URL) ?: return
val mangaId = intent.getLongExtra(EXTRA_MANGA_ID, -1)
if (mangaId > -1) {
markAsRead(urls, mangaId)
}
}
// Download manga chapters
ACTION_DOWNLOAD_CHAPTER -> {
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
if (notificationId > -1) {
dismissNotification(context, notificationId, intent.getIntExtra(EXTRA_GROUP_ID, 0))
}
val urls = intent.getStringArrayExtra(EXTRA_CHAPTER_URL) ?: return
val mangaId = intent.getLongExtra(EXTRA_MANGA_ID, -1)
if (mangaId > -1) {
downloadChapters(urls, mangaId)
}
}
// Share crash dump file
ACTION_SHARE_CRASH_LOG ->
shareFile(
context,
intent.getParcelableExtra(EXTRA_URI)!!,
"text/plain",
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
}
}
/**
* Dismiss the notification
*
* @param notificationId the id of the notification
*/
private fun dismissNotification(context: Context, notificationId: Int) {
context.notificationManager.cancel(notificationId)
}
/**
* Called to start share intent to share image
*
* @param context context of application
* @param path path of file
* @param notificationId id of notification
*/
private fun shareImage(context: Context, path: String, notificationId: Int) {
dismissNotification(context, notificationId)
context.startActivity(File(path).getUriCompat(context).toShareIntent(context))
}
/**
* Called to start share intent to share backup file
*
* @param context context of application
* @param path path of file
* @param notificationId id of notification
*/
private fun shareFile(context: Context, uri: Uri, fileMimeType: String, notificationId: Int) {
dismissNotification(context, notificationId)
context.startActivity(uri.toShareIntent(context, fileMimeType))
}
/**
* Starts reader activity
*
* @param context context of application
* @param mangaId id of manga
* @param chapterId id of chapter
*/
private fun openChapter(context: Context, mangaId: Long, chapterId: Long) {
val db = DatabaseHelper(context)
val manga = db.getManga(mangaId).executeAsBlocking()
val chapter = db.getChapter(chapterId).executeAsBlocking()
if (manga != null && chapter != null) {
val intent = ReaderActivity.newIntent(context, manga, chapter).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
context.startActivity(intent)
} else {
context.toast(context.getString(R.string.chapter_error))
}
}
/**
* Called to delete image
*
* @param path path of file
* @param notificationId id of notification
*/
private fun deleteImage(context: Context, path: String, notificationId: Int) {
// Dismiss notification
dismissNotification(context, notificationId)
// Delete file
val file = File(path)
file.delete()
DiskUtil.scanMedia(context, file)
}
/**
* Method called when user wants to stop a backup restore job.
*
* @param context context of application
* @param notificationId id of notification
*/
private fun cancelRestore(context: Context, notificationId: Int) {
BackupRestoreService.stop(context)
ContextCompat.getMainExecutor(context).execute { dismissNotification(context, notificationId) }
}
/**
* Method called when user wants to stop a library update
*
* @param context context of application
* @param notificationId id of notification
*/
private fun cancelLibraryUpdate(context: Context, notificationId: Int) {
LibraryUpdateService.stop(context)
ContextCompat.getMainExecutor(context).execute { dismissNotification(context, notificationId) }
}
/**
* Method called when user wants to mark manga chapters as read
*
* @param chapterUrls URLs of chapter to mark as read
* @param mangaId id of manga
*/
private fun markAsRead(chapterUrls: Array<String>, mangaId: Long) {
val db: DatabaseHelper = Injekt.get()
val preferences: PreferencesHelper = Injekt.get()
val sourceManager: SourceManager = Injekt.get()
launchIO {
chapterUrls.mapNotNull { db.getChapter(it, mangaId).executeAsBlocking() }
.forEach {
it.read = true
db.updateChapterProgress(it).executeAsBlocking()
if (preferences.removeAfterMarkedAsRead()) {
val manga = db.getManga(mangaId).executeAsBlocking()
if (manga != null) {
val source = sourceManager.get(manga.source)
if (source != null) {
downloadManager.deleteChapters(listOf(it), manga, source)
}
}
}
}
}
}
/**
* Method called when user wants to download chapters
*
* @param chapterUrls URLs of chapter to download
* @param mangaId id of manga
*/
private fun downloadChapters(chapterUrls: Array<String>, mangaId: Long) {
val db: DatabaseHelper = Injekt.get()
launchIO {
val chapters = chapterUrls.mapNotNull { db.getChapter(it, mangaId).executeAsBlocking() }
val manga = db.getManga(mangaId).executeAsBlocking()
if (chapters.isNotEmpty() && manga != null) {
downloadManager.downloadChapters(manga, chapters)
}
}
}
companion object {
private const val NAME = "NotificationReceiver"
private const val ACTION_SHARE_IMAGE = "$ID.$NAME.SHARE_IMAGE"
private const val ACTION_DELETE_IMAGE = "$ID.$NAME.DELETE_IMAGE"
private const val ACTION_SHARE_BACKUP = "$ID.$NAME.SEND_BACKUP"
private const val ACTION_SHARE_CRASH_LOG = "$ID.$NAME.SEND_CRASH_LOG"
private const val ACTION_CANCEL_RESTORE = "$ID.$NAME.CANCEL_RESTORE"
private const val ACTION_CANCEL_LIBRARY_UPDATE = "$ID.$NAME.CANCEL_LIBRARY_UPDATE"
private const val ACTION_MARK_AS_READ = "$ID.$NAME.MARK_AS_READ"
private const val ACTION_OPEN_CHAPTER = "$ID.$NAME.ACTION_OPEN_CHAPTER"
private const val ACTION_DOWNLOAD_CHAPTER = "$ID.$NAME.ACTION_DOWNLOAD_CHAPTER"
private const val ACTION_RESUME_DOWNLOADS = "$ID.$NAME.ACTION_RESUME_DOWNLOADS"
private const val ACTION_PAUSE_DOWNLOADS = "$ID.$NAME.ACTION_PAUSE_DOWNLOADS"
private const val ACTION_CLEAR_DOWNLOADS = "$ID.$NAME.ACTION_CLEAR_DOWNLOADS"
private const val ACTION_DISMISS_NOTIFICATION = "$ID.$NAME.ACTION_DISMISS_NOTIFICATION"
private const val EXTRA_FILE_LOCATION = "$ID.$NAME.FILE_LOCATION"
private const val EXTRA_URI = "$ID.$NAME.URI"
private const val EXTRA_NOTIFICATION_ID = "$ID.$NAME.NOTIFICATION_ID"
private const val EXTRA_GROUP_ID = "$ID.$NAME.EXTRA_GROUP_ID"
private const val EXTRA_MANGA_ID = "$ID.$NAME.EXTRA_MANGA_ID"
private const val EXTRA_CHAPTER_ID = "$ID.$NAME.EXTRA_CHAPTER_ID"
private const val EXTRA_CHAPTER_URL = "$ID.$NAME.EXTRA_CHAPTER_URL"
/**
* Returns a [PendingIntent] that resumes the download of a chapter
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun resumeDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_RESUME_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that pauses the download queue
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun pauseDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_PAUSE_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns a [PendingIntent] that clears the download queue
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun clearDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CLEAR_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which dismissed the notification
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun dismissNotificationPendingBroadcast(context: Context, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DISMISS_NOTIFICATION
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which dismissed the notification
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun dismissNotification(context: Context, notificationId: Int, groupId: Int? = null) {
/*
Group notifications always have at least 2 notifications:
- Group summary notification
- Single manga notification
If the single notification is dismissed by the system, ie by a user swipe or tapping on the notification,
it will auto dismiss the group notification if there's no other single updates.
When programmatically dismissing this notification, the group notification is not automatically dismissed.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val groupKey = context.notificationManager.activeNotifications.find {
it.id == notificationId
}?.groupKey
if (groupId != null && groupId != 0 && groupKey != null && groupKey.isNotEmpty()) {
val notifications = context.notificationManager.activeNotifications.filter {
it.groupKey == groupKey
}
if (notifications.size == 2) {
context.notificationManager.cancel(groupId)
return
}
}
}
context.notificationManager.cancel(notificationId)
}
/**
* Returns [PendingIntent] that starts a service which cancels the notification and starts a share activity
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which removes an image from disk
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun deleteImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DELETE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a reader activity containing chapter.
*
* @param context context of application
* @param manga manga of chapter
* @param chapter chapter that needs to be opened
*/
internal fun openChapterPendingActivity(context: Context, manga: Manga, chapter: Chapter): PendingIntent {
val newIntent = ReaderActivity.newIntent(context, manga, chapter)
return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the manga info controller.
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun openChapterPendingActivity(context: Context, manga: Manga, groupId: Int): PendingIntent {
val newIntent =
Intent(context, MainActivity::class.java).setAction(MainActivity.SHORTCUT_MANGA)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(MangaController.MANGA_EXTRA, manga.id)
.putExtra("notificationId", manga.id.hashCode())
.putExtra("groupId", groupId)
return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that marks a chapter as read and deletes it if preferred
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun markAsReadPendingBroadcast(
context: Context,
manga: Manga,
chapters: Array<Chapter>,
groupId: Int
): PendingIntent {
val newIntent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_MARK_AS_READ
putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray())
putExtra(EXTRA_MANGA_ID, manga.id)
putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode())
putExtra(EXTRA_GROUP_ID, groupId)
}
return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that downloads chapters
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun downloadChaptersPendingBroadcast(
context: Context,
manga: Manga,
chapters: Array<Chapter>,
groupId: Int
): PendingIntent {
val newIntent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DOWNLOAD_CHAPTER
putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray())
putExtra(EXTRA_MANGA_ID, manga.id)
putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode())
putExtra(EXTRA_GROUP_ID, groupId)
}
return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which stops the library update
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun cancelLibraryUpdatePendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CANCEL_LIBRARY_UPDATE
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the extensions controller.
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun openExtensionsPendingActivity(context: Context): PendingIntent {
val intent = Intent(context, MainActivity::class.java).apply {
action = MainActivity.SHORTCUT_EXTENSIONS
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a share activity for a backup file.
*
* @param context context of application
* @param uri uri of backup file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareBackupPendingBroadcast(context: Context, uri: Uri, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_BACKUP
putExtra(EXTRA_URI, uri)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the error log file in an external viewer
*
* @param context context of application
* @param uri uri of error log file
* @return [PendingIntent]
*/
internal fun openErrorLogPendingActivity(context: Context, uri: Uri): PendingIntent {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
setDataAndType(uri, "text/plain")
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
return PendingIntent.getActivity(context, 0, intent, 0)
}
/**
* Returns [PendingIntent] that starts a share activity for a crash log dump file.
*
* @param context context of application
* @param uri uri of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareCrashLogPendingBroadcast(context: Context, uri: Uri, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_CRASH_LOG
putExtra(EXTRA_URI, uri)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that cancels a backup restore job.
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun cancelRestorePendingBroadcast(context: Context, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CANCEL_RESTORE
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
}
| apache-2.0 | d0760a3651d11de46a4950f7adf3637b | 41.266102 | 121 | 0.613947 | 5.225692 | false | false | false | false |
javecs/text2expr | src/main/kotlin/xyz/javecs/tools/text2expr/templates/TemplateLoader.kt | 1 | 724 | package xyz.javecs.tools.text2expr.templates
import org.yaml.snakeyaml.Yaml
import xyz.javecs.tools.text2expr.utils.read
private val printValue = "<if(value)><value><endif>"
internal data class Templates(var templates: List<RuleTemplate> = ArrayList<RuleTemplate>())
internal data class RuleTemplate(var rule: String = "", var template: String = "")
internal class TemplateLoader(path: String = "rule-template.yml", val defaultTemplate: String = printValue) {
private val config = Yaml().loadAs(read(path), Templates::class.java)
fun templateOf(rule: String): String {
val item = config.templates.find { it.rule == rule }
return if (item == null) defaultTemplate else read(item.template)
}
}
| mit | 37294dad01282707869f5370007f4549 | 41.588235 | 109 | 0.729282 | 3.871658 | false | true | false | false |
neva-dev/javarel-framework | resource/src/main/kotlin/com/neva/javarel/resource/api/ResourceDescriptor.kt | 1 | 994 | package com.neva.javarel.resource.api
import com.google.common.collect.ImmutableList
import org.apache.commons.io.FilenameUtils
class ResourceDescriptor(val uri: String) {
val protocol: String
val path: String
val baseName: String
val name: String
val extension: String
val parts: List<String>
init {
var parts = uri.split(ResourceMapper.PROTOCOL_SEPARATOR)
if (parts.size != 2) {
throw IllegalArgumentException("Resource descriptor URI '$uri' should contain " + "protocol separator '${ResourceMapper.PROTOCOL_SEPARATOR}'")
}
this.protocol = parts[0]
this.path = parts[1]
this.parts = ImmutableList.copyOf(path.split(ResourceMapper.PATH_SEPARATOR))
this.baseName = FilenameUtils.getBaseName(parts[1])
this.name = FilenameUtils.getName(parts[1])
this.extension = FilenameUtils.getExtension(parts[1])
}
override fun toString(): String {
return uri
}
}
| apache-2.0 | 8ce0fe7d58518ccb9134026730afd72e | 25.157895 | 154 | 0.672032 | 4.340611 | false | false | false | false |
marc-inn/learning-kotlin-from-jb | src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 1 | 755 | package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun task1(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
| mit | a7605e78fc2863c70e4dbc2d1e35c67d | 25.964286 | 102 | 0.611921 | 4.125683 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackedEntityInstancePersistenceCallFactory.kt | 1 | 3613 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.internal
import dagger.Reusable
import io.reactivex.Completable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandlerParams
import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitModuleDownloader
import org.hisp.dhis.android.core.relationship.internal.RelationshipItemRelatives
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
@Reusable
internal class TrackedEntityInstancePersistenceCallFactory @Inject constructor(
private val trackedEntityInstanceHandler: TrackedEntityInstanceHandler,
private val uidsHelper: TrackedEntityInstanceUidHelper,
private val organisationUnitDownloader: OrganisationUnitModuleDownloader
) {
fun persistTEIs(
trackedEntityInstances: List<TrackedEntityInstance>,
params: IdentifiableDataHandlerParams,
relatives: RelationshipItemRelatives
): Completable {
return persistTEIsInternal(trackedEntityInstances, params, relatives)
}
fun persistRelationships(trackedEntityInstances: List<TrackedEntityInstance>): Completable {
val params = IdentifiableDataHandlerParams(
hasAllAttributes = false,
overwrite = false,
asRelationship = true
)
return persistTEIsInternal(trackedEntityInstances, params, relatives = null)
}
private fun persistTEIsInternal(
trackedEntityInstances: List<TrackedEntityInstance>,
params: IdentifiableDataHandlerParams,
relatives: RelationshipItemRelatives?
): Completable {
return Completable.defer {
trackedEntityInstanceHandler.handleMany(
trackedEntityInstances, params, relatives
)
if (uidsHelper.hasMissingOrganisationUnitUids(trackedEntityInstances)) {
organisationUnitDownloader.refreshOrganisationUnits()
} else {
Completable.complete()
}
}
}
}
| bsd-3-clause | ac2a06ae3fc0ca1bf905377792f058a3 | 45.922078 | 96 | 0.754498 | 5.328909 | false | false | false | false |
theapache64/Mock-API | src/com/theah64/mock_api/database/Routes.kt | 1 | 18703 | package com.theah64.mock_api.database
import com.theah64.mock_api.models.Route
import com.theah64.webengine.database.BaseTable
import com.theah64.webengine.database.Connection
import com.theah64.webengine.database.querybuilders.QueryBuilderException
import java.sql.PreparedStatement
import java.sql.SQLException
import java.util.ArrayList
/**
* Created by theapache64 on 14/5/17.
*/
class Routes private constructor() : BaseTable<Route>("routes") {
@Throws(SQLException::class)
override fun addv3(route: Route): String {
var error: String? = null
var id: String? = null
val query = "INSERT INTO routes (project_id, name, default_response, description, is_secure, delay,external_api_url,updated_at_in_millis,method,request_body_type,json_req_body) VALUES (?,?,?,?,?,?,?,?,?,?,?);"
val con = Connection.getConnection()
try {
val ps0 = con.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS)
ps0.setString(1, route.projectId)
ps0.setString(2, route.name)
ps0.setString(3, route.defaultResponse)
ps0.setString(4, route.description)
ps0.setBoolean(5, route.isSecure)
ps0.setLong(6, route.delay)
ps0.setString(7, route.externalApiUrl)
ps0.setLong(8, System.currentTimeMillis())
ps0.setString(9, route.method)
ps0.setString(10, route.requestBodyType)
ps0.setString(11, route.jsonReqBody)
ps0.executeUpdate()
val rs = ps0.generatedKeys
if (rs.first()) {
id = rs.getString(1)
}
rs.close()
ps0.close()
route.id = id
Params.instance.addParamsFromRoute(route)
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
return id!!
}
@Throws(SQLException::class)
fun getAll(projectId: String): List<Route> {
val jsonList = ArrayList<Route>()
val query = "SELECT id, name,request_body_type,status_code, external_api_url FROM routes WHERE project_id = ? AND is_active = 1 ORDER BY id DESC"
var error: String? = null
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, projectId)
val rs = ps.executeQuery()
if (rs.first()) {
do {
val id = rs.getString(BaseTable.COLUMN_ID)
val route = rs.getString(BaseTable.COLUMN_NAME)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
jsonList.add(Route(id, projectId, route, requestBodyType, null, null, null, externalApiUrl, null, null, false, 0, -1, statusCode))
} while (rs.next())
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
return jsonList
}
@Throws(SQLException::class)
fun getAllDetailed(projectId: String): List<Route> {
var routeList: MutableList<Route> = ArrayList()
val query = "SELECT r.id,r.name,r.request_body_type,r.json_req_body,r.status_code, r.updated_at_in_millis,r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.id = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id;"
var error: String? = null
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, projectId)
val rs = ps.executeQuery()
if (rs.first()) {
routeList = ArrayList()
do {
val id = rs.getString(BaseTable.COLUMN_ID)
val routeName = rs.getString(BaseTable.COLUMN_NAME)
val response = rs.getString(COLUMN_DEFAULT_RESPONSE)
val description = rs.getString(COLUMN_DESCRIPTION)
val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY)
val isSecure = rs.getBoolean(COLUMN_IS_SECURE)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val delay = rs.getLong(COLUMN_DELAY)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS)
val method = rs.getString(COLUMN_METHOD)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id)
routeList.add(Route(id, projectId, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode))
} while (rs.next())
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
return routeList
}
@Throws(SQLException::class)
fun getRouteFrom(packageName: String, routeName: String): Route? {
var error: String? = null
var route: Route? = null
val query = "SELECT r.id,r.status_code, r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.package_name = ? AND r.name = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;"
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, packageName)
ps.setString(2, routeName)
val rs = ps.executeQuery()
if (rs.first()) {
val id = rs.getString(BaseTable.COLUMN_ID)
val response = rs.getString(COLUMN_DEFAULT_RESPONSE)
val description = rs.getString(COLUMN_DESCRIPTION)
val isSecure = rs.getBoolean(COLUMN_IS_SECURE)
val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val delay = rs.getLong(COLUMN_DELAY)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS)
val method = rs.getString(COLUMN_METHOD)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id)
route = Route(id, null, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode)
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
if (route == null) {
throw SQLException("No response found for $packageName:$routeName")
}
return route
}
@Throws(SQLException::class)
override fun get(projectName: String?, routeName: String?): Route? {
var error: String? = null
var route: Route? = null
val query = "SELECT r.id, r.status_code,r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.name = ? AND r.name = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;"
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, projectName)
ps.setString(2, routeName)
val rs = ps.executeQuery()
if (rs.first()) {
val id = rs.getString(BaseTable.COLUMN_ID)
val response = rs.getString(COLUMN_DEFAULT_RESPONSE)
val description = rs.getString(COLUMN_DESCRIPTION)
val isSecure = rs.getBoolean(COLUMN_IS_SECURE)
val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val delay = rs.getLong(COLUMN_DELAY)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS)
val method = rs.getString(COLUMN_METHOD)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id)
route = Route(id, null, routeName!!, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode)
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
if (route == null) {
throw SQLException("No response found for $projectName:$routeName")
}
return route
}
@Throws(SQLException::class)
fun getRouteBy(column: String, value: String): Route {
var error: String? = null
var route: Route? = null
val query = String.format("SELECT r.id,r.status_code,r.name,r.request_body_type, r.json_req_body, r.updated_at_in_millis,r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE r.%s = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;", column)
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, value)
val rs = ps.executeQuery()
if (rs.first()) {
val id = rs.getString(BaseTable.COLUMN_ID)
val routeName = rs.getString(BaseTable.COLUMN_NAME)
val response = rs.getString(COLUMN_DEFAULT_RESPONSE)
val description = rs.getString(COLUMN_DESCRIPTION)
val isSecure = rs.getBoolean(COLUMN_IS_SECURE)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY)
val delay = rs.getLong(COLUMN_DELAY)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS)
val method = rs.getString(COLUMN_METHOD)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id)
route = Route(id, null, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode)
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
if (route == null) {
throw SQLException("No response found for " + route!!)
}
return route
}
override fun update(route: Route): Boolean {
var isUpdated = false
val query = "UPDATE routes SET default_response = ?, description = ? , is_secure = ? , delay = ?, external_api_url = ?, updated_at_in_millis = ?, method = ?,request_body_type=?, json_req_body = ?, status_code = ? WHERE name = ? AND project_id = ?;"
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
val r = if (route.defaultResponse == null) get(BaseTable.COLUMN_ID, route.id!!, COLUMN_DEFAULT_RESPONSE, true) else route.defaultResponse
//set
ps.setString(1, r)
ps.setString(2, route.description)
ps.setBoolean(3, route.isSecure)
ps.setLong(4, route.delay)
ps.setString(5, route.externalApiUrl)
ps.setLong(6, System.currentTimeMillis())
ps.setString(7, route.method)
ps.setString(8, route.requestBodyType)
ps.setString(9, route.jsonReqBody)
ps.setInt(10, route.statusCode)
// where
ps.setString(11, route.name)
ps.setString(12, route.projectId)
Params.instance.updateParamFromRoute(route)
isUpdated = ps.executeUpdate() == 1
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
if (!isUpdated) {
throw IllegalArgumentException("Failed to update json")
}
return true
}
@Throws(SQLException::class)
fun updateBaseOGAPIURL(projectId: String, oldBaseUrl: String, newBaseUrl: String) {
val query = String.format("UPDATE routes SET %s = REPLACE(%s, ?, ?) WHERE INSTR(%s, ?) > 0 AND project_id = ?;", COLUMN_EXTERNAL_API_URL, COLUMN_EXTERNAL_API_URL, COLUMN_EXTERNAL_API_URL)
val con = Connection.getConnection()
var error: String? = null
try {
val ps = con.prepareStatement(query)
ps.setString(1, oldBaseUrl)
ps.setString(2, newBaseUrl)
ps.setString(3, oldBaseUrl)
ps.setString(4, projectId)
ps.executeUpdate()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
}
@Throws(SQLException::class)
fun getRouteLike(projectName: String, routeNameStarting: String): Route? {
var error: String? = null
var route: Route? = null
val query = "SELECT r.id,r.name,r.status_code, r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.name = ? AND r.name LIKE ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;"
val con = Connection.getConnection()
try {
val ps = con.prepareStatement(query)
ps.setString(1, projectName)
ps.setString(2, "$routeNameStarting%")
val rs = ps.executeQuery()
if (rs.first()) {
val id = rs.getString(BaseTable.COLUMN_ID)
val routeName = rs.getString(BaseTable.COLUMN_NAME)
val response = rs.getString(COLUMN_DEFAULT_RESPONSE)
val description = rs.getString(COLUMN_DESCRIPTION)
val isSecure = rs.getBoolean(COLUMN_IS_SECURE)
val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY)
val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE)
val delay = rs.getLong(COLUMN_DELAY)
val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL)
val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS)
val method = rs.getString(COLUMN_METHOD)
val statusCode = rs.getInt(COLUMN_STATUS_CODE)
val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id)
route = Route(id, null, routeName!!, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode)
}
rs.close()
ps.close()
} catch (e: SQLException) {
e.printStackTrace()
error = e.message
} finally {
try {
con.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
BaseTable.manageError(error)
if (route == null) {
throw SQLException("No response found with starting $projectName:$routeNameStarting")
}
return route
}
companion object {
const val COLUMN_ID = "id"
const val COLUMN_NAME = "name"
const val COLUMN_REQUEST_BODY_TYPE = "request_body_type"
const val COLUMN_JSON_REQ_BODY = "json_req_body"
const val COLUMN_DEFAULT_RESPONSE = "default_response"
const val COLUMN_PROJECT_ID = "project_id"
const val COLUMN_DESCRIPTION = "description"
const val COLUMN_IS_SECURE = "is_secure"
const val COLUMN_DELAY = "delay"
const val COLUMN_EXTERNAL_API_URL = "external_api_url"
const val COLUMN_UPDATED_AT_IN_MILLIS = "updated_at_in_millis"
const val KEY_PARAMS = "params"
const val COLUMN_STATUS_CODE = "status_code"
const val COLUMN_METHOD = "method"
val instance = Routes()
}
}
| apache-2.0 | 5cf09cc58edbacf8d1bbc35e3e5f9733 | 38.127615 | 359 | 0.574293 | 4.33743 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt | 4 | 18694 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.SpeedSearchComparator
import com.intellij.ui.TableSpeedSearch
import com.intellij.ui.TableUtil
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onMouseMotion
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.awt.Cursor
import java.awt.Dimension
import java.awt.KeyboardFocusManager
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.ListSelectionModel
import javax.swing.event.ListSelectionListener
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableColumn
import kotlin.math.roundToInt
internal typealias SearchResultStateChangeListener =
(PackageModel.SearchResult, NormalizedPackageVersion<*>?, PackageScope?) -> Unit
@Suppress("MagicNumber") // Swing dimension constants
internal class PackagesTable(
private val project: Project,
private val operationExecutor: OperationExecutor,
private val onSearchResultStateChanged: SearchResultStateChangeListener
) : JBTable(), CopyProvider, DataProvider {
private var lastSelectedDependency: UnifiedDependency? = null
private val operationFactory = PackageSearchOperationFactory()
private val tableModel: PackagesTableModel
get() = model as PackagesTableModel
var transferFocusUp: () -> Unit = { transferFocusBackward() }
private val columnWeights = listOf(
.5f, // Name column
.2f, // Scope column
.2f, // Version column
.1f // Actions column
)
private val nameColumn = NameColumn()
private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) }
private val versionColumn = VersionColumn { packageModel, newVersion ->
updatePackageVersion(packageModel, newVersion)
}
private val actionsColumn = ActionsColumn(project, operationExecutor = ::executeActionColumnOperations)
private val actionsColumnIndex: Int
private val autosizingColumnsIndices: List<Int>
private var targetModules: TargetModules = TargetModules.None
private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY
val selectedPackageStateFlow = MutableStateFlow<UiPackageModel<*>?>(null)
private val listSelectionListener = ListSelectionListener {
val item = getSelectedTableItem()
if (selectedIndex >= 0 && item != null) {
TableUtil.scrollSelectionToVisible(this)
updateAndRepaint()
selectedPackageStateFlow.tryEmit(item.uiPackageModel)
} else {
selectedPackageStateFlow.tryEmit(null)
}
}
val hasInstalledItems: Boolean
get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage }
val firstPackageIndex: Int
get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage }
var selectedIndex: Int
get() = selectedRow
set(value) {
if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) {
setRowSelectionInterval(value, value)
} else {
clearSelection()
}
}
init {
require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" }
model = PackagesTableModel(
nameColumn = nameColumn,
scopeColumn = scopeColumn,
versionColumn = versionColumn,
actionsColumn = actionsColumn
)
val columnInfos = tableModel.columnInfos
actionsColumnIndex = columnInfos.indexOf(actionsColumn)
autosizingColumnsIndices = listOf(
columnInfos.indexOf(scopeColumn),
columnInfos.indexOf(versionColumn),
actionsColumnIndex
)
setTableHeader(InvisibleResizableHeader())
getTableHeader().apply {
reorderingAllowed = false
resizingAllowed = true
}
columnSelectionAllowed = false
setShowGrid(false)
rowHeight = 20.scaled()
background = UIUtil.getTableBackground()
foreground = UIUtil.getTableForeground()
selectionBackground = UIUtil.getTableSelectionBackground(true)
selectionForeground = UIUtil.getTableSelectionForeground(true)
setExpandableItemsEnabled(false)
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
putClientProperty("terminateEditOnFocusLost", true)
intercellSpacing = Dimension(0, 2)
// By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable.
// In this table, we don't want to navigate between cells - so override the traversal keys by default values.
setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)
)
setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (tableModel.rowCount > 0 && selectedRows.isEmpty()) {
setRowSelectionInterval(0, 0)
}
}
})
PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "shift ENTER") {
clearSelection()
transferFocusUp()
}
selectionModel.addListSelectionListener(listSelectionListener)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (selectedIndex == -1) {
selectedIndex = firstPackageIndex
}
}
})
TableSpeedSearch(this) { item, _ ->
if (item is PackagesTableItem<*>) {
val rawIdentifier = item.packageModel.identifier.rawValue
val name = item.packageModel.remoteInfo?.name?.takeIf { !it.equals(rawIdentifier, ignoreCase = true) }
if (name != null) rawIdentifier + name else rawIdentifier
} else {
""
}
}.apply {
comparator = SpeedSearchComparator(false)
}
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights)
removeComponentListener(this)
}
})
onMouseMotion(
onMouseMoved = { mouseEvent ->
val point = mouseEvent.point
val hoverColumn = columnAtPoint(point)
val hoverRow = rowAtPoint(point)
if (tableModel.items.isEmpty() || hoverRow < 0) {
cursor = Cursor.getDefaultCursor()
return@onMouseMotion
}
val isHoveringActionsColumn = hoverColumn == actionsColumnIndex
cursor = if (isHoveringActionsColumn) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor()
}
)
project.uiStateSource.selectedDependencyFlow.onEach { lastSelectedDependency = it }
.onEach { setSelection(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private fun setSelection(lastSelectedDependencyCopy: UnifiedDependency): Boolean {
val index = tableModel.items.map { it.uiPackageModel }
.indexOfFirst {
it is UiPackageModel.Installed &&
it.selectedVersion.displayName == lastSelectedDependencyCopy.coordinates.version &&
it.packageModel.artifactId == lastSelectedDependencyCopy.coordinates.artifactId &&
it.packageModel.groupId == lastSelectedDependencyCopy.coordinates.groupId &&
(it.selectedScope.displayName == lastSelectedDependencyCopy.scope ||
(it.selectedScope.displayName == "[default]" && lastSelectedDependencyCopy.scope == null))
}
val indexFound = index >= 0
if (indexFound) setRowSelectionInterval(index, index)
return indexFound
}
override fun getCellRenderer(row: Int, column: Int): TableCellRenderer =
tableModel.columns.getOrNull(column)?.getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer()
override fun getCellEditor(row: Int, column: Int): TableCellEditor? =
tableModel.columns.getOrNull(column)?.getEditor(tableModel.items[row])
internal data class ViewModel(
val items: TableItems,
val onlyStable: Boolean,
val targetModules: TargetModules,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
) {
data class TableItems(
val items: List<PackagesTableItem<*>>,
) : List<PackagesTableItem<*>> by items {
companion object {
val EMPTY = TableItems(items = emptyList())
}
}
}
fun display(viewModel: ViewModel) {
knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules
targetModules = viewModel.targetModules
// We need to update those immediately before setting the items, on EDT, to avoid timing issues
// where the target modules or only stable flags get updated after the items data change, thus
// causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages)
versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules)
actionsColumn.updateData(
viewModel.onlyStable,
viewModel.targetModules,
viewModel.knownRepositoriesInTargetModules
)
selectionModel.removeListSelectionListener(listSelectionListener)
tableModel.items = viewModel.items
// TODO size columns
selectionModel.addListSelectionListener(listSelectionListener)
lastSelectedDependency?.let { lastSelectedDependencyCopy ->
if (setSelection(lastSelectedDependencyCopy)) {
lastSelectedDependency = null
}
}
updateAndRepaint()
}
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun performCopy(dataContext: DataContext) {
getSelectedTableItem()?.performCopy(dataContext)
}
override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false
override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false
private fun getSelectedTableItem(): PackagesTableItem<*>? {
if (selectedIndex == -1) {
return null
}
return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*>
}
private fun updatePackageScope(uiPackageModel: UiPackageModel<*>, newScope: PackageScope) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = operationFactory.createChangePackageScopeOperations(
packageModel = uiPackageModel.packageModel,
newScope = newScope,
targetModules = targetModules,
repoToInstall = null
)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for ${uiPackageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
val selectedVersion = uiPackageModel.selectedVersion
onSearchResultStateChanged(uiPackageModel.packageModel, selectedVersion, newScope)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for search result ${uiPackageModel.identifier}: '$newScope'."
}
updateAndRepaint()
}
}
}
private fun updatePackageVersion(uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = uiPackageModel.packageModel.usageInfo.flatMap {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
project = project,
packageModel = uiPackageModel.packageModel,
selectedVersion = newVersion.originalVersion
)
operationFactory.createChangePackageVersionOperations(
packageModel = uiPackageModel.packageModel,
newVersion = newVersion.originalVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for ${uiPackageModel.identifier}: '$newVersion'. " +
"This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
onSearchResultStateChanged(uiPackageModel.packageModel, newVersion, uiPackageModel.selectedScope)
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for search result ${uiPackageModel.identifier}: '$newVersion'."
}
updateAndRepaint()
}
}
}
private fun executeActionColumnOperations(operations: Deferred<List<PackageSearchOperation<*>>>) {
logDebug("PackagesTable#executeActionColumnOperations()") {
"The user has clicked the action for a package. This resulted in many operation(s)."
}
operationExecutor.executeOperations(operations)
}
private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) {
require(columnWeights.size == columns.size) {
"Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights"
}
for (column in columns) {
column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt()
}
}
}
| apache-2.0 | d06054815c9f5b0c268402db30c54b39 | 42.474419 | 152 | 0.67979 | 5.792997 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/markerblocks/providers/LinkReferenceDefinitionProvider.kt | 1 | 6407 | package org.intellij.markdown.parser.markerblocks.providers
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.LinkReferenceDefinitionMarkerBlock
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import java.util.*
import kotlin.text.Regex
public class LinkReferenceDefinitionProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> {
override fun createMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder,
stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> {
if (!MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)) {
return emptyList()
}
val matchResult = matchLinkDefinition(pos.textFromPosition) ?: return emptyList()
for ((i, range) in matchResult.withIndex()) {
productionHolder.addProduction(listOf(SequentialParser.Node(
addToRangeAndWiden(range, pos.offset), when (i) {
0 -> MarkdownElementTypes.LINK_LABEL
1 -> MarkdownElementTypes.LINK_DESTINATION
2 -> MarkdownElementTypes.LINK_TITLE
else -> throw AssertionError("There are no more than three groups in this regex")
})))
}
val matchLength = matchResult.last().endInclusive + 1
val endPosition = pos.nextPosition(matchLength)
if (endPosition != null && !isEndOfLine(endPosition)) {
return emptyList()
}
return listOf(LinkReferenceDefinitionMarkerBlock(stateInfo.currentConstraints, productionHolder.mark(),
pos.offset + matchLength))
}
override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean {
return false
}
companion object {
val WHSP = "[ \\t]*"
val NOT_CHARS = { c: String ->
val nonWhitespace = "(?:\\\\[$c]|[^ \\t\\n$c])"
val anyChar = "(?:\\\\[$c]|[^$c\\n])"
"$anyChar*(?:\\n$anyChar*$nonWhitespace$WHSP)*(?:\\n$WHSP)?"
}
val NONCONTROL = "(?:\\\\[\\(\\)]|[^ \\n\\t\\(\\)])"
val LINK_DESTINATION = "(?:<(?:\\\\[<>]|[^<>\\n])*>|${NONCONTROL}*\\(${NONCONTROL}*\\)${NONCONTROL}*|${NONCONTROL}+)"
val LINK_TITLE = "(?:\"${NOT_CHARS("\"")}\"|'${NOT_CHARS("'")}'|\\(${NOT_CHARS("\\)")}\\))"
fun addToRangeAndWiden(range: IntRange, t: Int): IntRange {
return IntRange(range.start + t, range.endInclusive + t + 1)
}
fun isEndOfLine(pos: LookaheadText.Position): Boolean {
return pos.offsetInCurrentLine == -1 || pos.charsToNonWhitespace() == null
}
fun matchLinkDefinition(text: CharSequence): List<IntRange>? {
var offset = 0
repeat(3) {
if (offset < text.length && text[offset] == ' ') {
offset++
}
}
val linkLabel = matchLinkLabel(text, offset) ?: return null
offset = linkLabel.endInclusive + 1
if (offset >= text.length || text[offset] != ':')
return null
offset++
offset = passOneNewline(text, offset)
val destination = Regex("^$LINK_DESTINATION").find(text.subSequence(offset, text.length))
?: return null
val destinationRange = IntRange(destination.range.start + offset, destination.range.endInclusive + offset)
offset += destination.range.endInclusive - destination.range.start + 1
offset = passOneNewline(text, offset)
val title = Regex("^$LINK_TITLE").find(text.subSequence(offset, text.length))
val result = ArrayList<IntRange>()
result.add(linkLabel)
result.add(destinationRange)
if (title != null) {
val titleRange = IntRange(title.range.start + offset, title.range.endInclusive + offset)
offset += title.range.endInclusive - title.range.start + 1
while (offset < text.length && text[offset].let { it == ' ' || it == '\t' })
offset++
if (offset >= text.length || text[offset] == '\n') {
result.add(titleRange)
}
}
return result
}
fun matchLinkLabel(text: CharSequence, start: Int): IntRange? {
var offset = start
if (offset >= text.length || text[offset] != '[') {
return null
}
offset++
var seenNonWhitespace = false
for (i in 1..999) {
if (offset >= text.length)
return null
var c = text[offset]
if (c == '[' || c == ']')
break
if (c == '\\') {
offset++
if (offset >= text.length)
return null
c = text[offset]
}
if (!c.isWhitespace()) {
seenNonWhitespace = true
}
offset++
}
if (!seenNonWhitespace || offset >= text.length || text[offset] != ']') {
return null;
}
return start..offset
}
private fun passOneNewline(text: CharSequence, start: Int): Int {
var offset = start
while (offset < text.length && text[offset].let { it == ' ' || it == '\t' })
offset++
if (offset < text.length && text[offset] == '\n') {
offset++
while (offset < text.length && text[offset].let { it == ' ' || it == '\t' })
offset++
}
return offset
}
}
}
| apache-2.0 | 5ddc34f52ce8352bfd36eda4b38d30d0 | 39.550633 | 125 | 0.535508 | 5.064822 | false | false | false | false |
dahlstrom-g/intellij-community | java/testFramework/src/com/intellij/codeInsight/FoldingTestUtil.kt | 19 | 847 | // 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.
@file:JvmName("FoldingTestUtil")
package com.intellij.codeInsight
import com.intellij.openapi.editor.Editor
fun Editor.assertFolded(foldedText: String, placeholder: String) {
val foldingRegions = foldingModel.allFoldRegions
val matchingRegion = foldingRegions.firstOrNull {
it.placeholderText == placeholder && it.document.text.substring(it.startOffset, it.endOffset) == foldedText
}
if (matchingRegion == null) {
val existingFoldingsString = foldingRegions.joinToString {
"'${it.document.text.substring(it.startOffset, it.endOffset)}' -> '${it.placeholderText}'"
}
throw AssertionError("no folding '$foldedText' -> '$placeholder' found in $existingFoldingsString")
}
}
| apache-2.0 | a05b86a205dcbe10df31183534d01725 | 41.35 | 140 | 0.750885 | 4.151961 | false | false | false | false |
Pagejects/pagejects-core | src/main/kotlin/net/pagejects/core/forms/FillFormUserAction.kt | 1 | 4225 | package net.pagejects.core.forms
import com.codeborne.selenide.SelenideElement
import net.pagejects.core.Element
import net.pagejects.core.UserAction
import net.pagejects.core.annotation.FillForm
import net.pagejects.core.annotation.FormObject
import net.pagejects.core.error.FillFormUserActionException
import net.pagejects.core.reflaction.pageObjectName
import net.pagejects.core.service.SelectorService
import net.pagejects.core.service.SelenideElementService
import org.openqa.selenium.By
import java.lang.reflect.Method
import kotlin.reflect.KClass
/**
* User action implementation for @[FillForm] annotation
*
* @author Andrey Paslavsky
* @since 0.1
*/
class FillFormUserAction(
private val `interface`: KClass<out Any>,
private val userActionMethod: Method,
private val selenideElementService: SelenideElementService,
private val selectorService: SelectorService
) : UserAction<Unit> {
override fun perform(params: Array<out Any?>): Unit {
if (params.size == 0) {
throw FillFormUserActionException("Method ${userActionMethod.name} has no arguments: form object is required")
} else if (params.size > 2) {
throw FillFormUserActionException("Method ${userActionMethod.name} has too many arguments")
}
val formObject = findFormObject(params)
val formObjectClass = formObject.javaClass
val formObjectAnnotation = formObjectClass.getAnnotation(FormObject::class.java)
val formElementName = if (formObjectAnnotation.value == FormObject.DEFAULT_NAME) {
formObjectClass.simpleName
} else {
formObjectAnnotation.value
}
val element = findSelenideElementInArguments(params) ?:
selenideElementService.get(`interface`.pageObjectName, formElementName)
Processor(formObject, formObjectClass, `interface`.pageObjectName, formElementName, element).execute()
}
private fun findFormObject(params: Array<out Any?>): Any {
params.forEach {
if (it != null) {
val javaClass = it.javaClass
if (javaClass.isAnnotationPresent(FormObject::class.java)) {
return it
}
}
}
throw FillFormUserActionException("Form object is not listed in arguments of the method ${userActionMethod.name} or form object is null")
}
private fun findSelenideElementInArguments(params: Array<out Any?>): SelenideElement? {
params.forEach {
if (it is Element) {
return it.selenideElement
} else if (it is SelenideElement) {
return it
} else if (it is By) {
return selenideElementService.getBy(it)
} else if (it is String) {
return selenideElementService.get(`interface`.pageObjectName, it)
}
}
return null
}
private inner class Processor(
val formObject: Any,
val formObjectClass: Class<Any>,
val pageObjectName: String,
val formElementName: String,
val selenideElement: SelenideElement
) {
fun execute() {
formObjectClass.kotlin.formFields.forEach {
try {
val elementName = it.elementName
val fullElementName = if (!formElementName.isBlank()) formElementName + ">" + elementName else elementName
val selector = if (selectorService.contains(pageObjectName, fullElementName)) {
selectorService.selector(pageObjectName, fullElementName)
} else {
selectorService.selector(pageObjectName, elementName)
}
val element = selenideElement.find(selector)
val handler = FormFieldHandlers[it.formField]
val value = it.getter.invoke(formObject)
handler.fillValue(element, value)
} catch(e: Exception) {
throw FillFormUserActionException("Failed to set ${it.name} to the form", e)
}
}
}
}
} | apache-2.0 | 038bc6e944ae080b4814c917b4f4a70d | 39.247619 | 145 | 0.632426 | 5.28786 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/search/delegates/ReceiptAdapterDelegate.kt | 2 | 2583 | package co.smartreceipts.android.search.delegates
import android.view.View
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.DrawableCompat
import co.smartreceipts.android.R
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.core.sync.provider.SyncProvider
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateLayoutContainer
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_receipt_card.*
fun receiptAdapterDelegate(itemClickedListener: (Receipt) -> Unit, syncProvider: SyncProvider) =
adapterDelegateLayoutContainer<Receipt, Any>(R.layout.item_receipt_card) {
itemView.setOnClickListener { itemClickedListener(item) }
bind {
card_menu.visibility = View.GONE
title.text = item.name
price.text = item.price.currencyFormattedPrice
card_category.visibility = View.VISIBLE
card_category.text = item.category.name
if (item.hasPDF()) {
setIcon(card_image, R.drawable.ic_file_black_24dp)
} else if (item.hasImage() && item.file != null) {
card_image.setPadding(0, 0, 0, 0)
Picasso.get()
.load(item.file!!)
.fit()
.centerCrop()
.into(card_image)
} else {
setIcon(card_image, R.drawable.ic_receipt_white_24dp)
}
if (syncProvider == SyncProvider.GoogleDrive) {
when {
item.syncState.isSynced(SyncProvider.GoogleDrive) -> card_sync_state.setImageResource(R.drawable.ic_cloud_done_24dp)
else -> card_sync_state.setImageResource(R.drawable.ic_cloud_queue_24dp)
}
}
}
}
private fun setIcon(view: ImageView, @DrawableRes drawableRes: Int) {
val context = view.context
val drawable = ResourcesCompat.getDrawable(context.resources, drawableRes, context.getTheme())
if (drawable != null) {
drawable.mutate() // hack to prevent fab icon tinting (fab has drawable with the same src)
DrawableCompat.setTint(drawable, ResourcesCompat.getColor(context.resources, R.color.card_image_tint, null))
val pixelPadding = context.resources.getDimensionPixelOffset(R.dimen.card_image_padding)
view.setImageDrawable(drawable)
view.setPadding(pixelPadding, pixelPadding, pixelPadding, pixelPadding)
}
} | agpl-3.0 | 84a8ba5b3c112d13ad404275ef69b5d8 | 40.677419 | 136 | 0.666667 | 4.507853 | false | false | false | false |
nick-rakoczy/Conductor | conductor-engine/src/main/java/urn/conductor/ExecutionManager.kt | 1 | 6358 | package urn.conductor
import org.apache.logging.log4j.LogManager
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.scanners.TypeAnnotationsScanner
import org.reflections.util.ConfigurationBuilder
import urn.conductor.registers.CanUseReflections
import urn.conductor.ssh.TransportComplexElementHandler
import java.lang.reflect.Modifier
import java.net.URLClassLoader
import java.nio.file.Files
import java.nio.file.Paths
import javax.xml.bind.JAXBContext
import javax.xml.bind.JAXBElement
import javax.xml.bind.annotation.XmlRegistry
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlSchema
import javax.xml.namespace.QName
class ExecutionManager(pluginsDir: String) {
private val logger = LogManager.getLogger("Internal")
private val attributeHandlers = HashMap<QName, AttributeHandler>()
private val simpleElementHandlers = HashMap<QName, SimpleElementHandler>()
private val complexElementHandlers = ElementHandlerMap()
private val preloaders = ArrayList<Preloader>()
private val objectFactories = HashSet<Class<*>>()
val Class<*>.xmlNamespace: String?
get() = this.getAnnotation(XmlRootElement::class.java)?.namespace?.takeIf { it != "##default" }
?: this.`package`?.getAnnotation(XmlSchema::class.java)?.namespace
val Class<*>.xmlElementName: String?
get() = this.getAnnotation(XmlRootElement::class.java)?.name
init {
logger.info("Scanning for plugins...")
val paths = pluginsDir.let {
Paths.get(it)
}.let {
attempt {
Files.newDirectoryStream(it)
} ?: error("Directory stream failed")
}.use {
it.filter {
it.fileName.toString().endsWith(".jar")
}.filterNotNull()
}
val classloaders = paths.map {
attempt {
it.toAbsolutePath().toUri().toURL()
}
}.filterNotNull().map {
arrayOf(it)
}.map(::URLClassLoader)
logger.info("Found ${classloaders.size} packages...")
classloaders.map {
it.urLs.singleOrNull()?.toString()
}.filterNotNull().forEach(logger::debug)
val reflectionsConfig = ConfigurationBuilder.build(this.javaClass.classLoader, *classloaders.toTypedArray(), SubTypesScanner(), TypeAnnotationsScanner())
val reflections = Reflections(reflectionsConfig)
reflections.getTypesAnnotatedWith(XmlRegistry::class.java)
.forEach { objectFactories.add(it) }
reflections.getSubTypesOf(ComponentRegistration::class.java).filter {
it.modifiers.let { mod ->
listOf(Modifier::isAbstract,
Modifier::isInterface,
Modifier::isPrivate,
Modifier::isProtected,
Modifier::isStatic)
.map { it.invoke(mod) }
.filter { it }
.none()
}
}.map {
attempt {
it.newInstance()
}
}.filterNotNull().forEach {
logger.debug("Found ComponentRegistration: ${it.javaClass.name}")
if (it is CanUseReflections) {
it.injectReflections(reflections)
}
it.init()
it.getAttributeHandlers().forEach {
attributeHandlers[it.handles] = it
}
it.getComplexElementHandlers().forEach {
complexElementHandlers[it.handles] = it
}
it.getSimpleElementHandlers().forEach {
simpleElementHandlers[it.handles] = it
}
it.getPreloaders().forEach {
preloaders.add(it)
}
}
fun logDetails(name: String, getCount: () -> Int, debugLines: () -> List<String>) {
logger.info("Found ${getCount()} $name...")
debugLines().sorted().forEach(logger::debug)
}
logger.info("Found ${attributeHandlers.size} attribute handlers...")
attributeHandlers.keys
.map(QName::toString)
.sorted()
.forEach(logger::debug)
logger.info("Found ${simpleElementHandlers.size} simple element handlers...")
simpleElementHandlers.keys
.map(QName::toString)
.sorted()
.forEach(logger::debug)
logger.info("Found ${complexElementHandlers.size} complex element handlers...")
complexElementHandlers.keys
.map { QName(it.xmlNamespace, it.xmlElementName).toString() }
.sorted()
.forEach(logger::debug)
logger.info("Found ${preloaders.size} preloaders...")
preloaders.sortedBy { it.priority }
.map { "[${it.priority}] ${it.friendlyName}" }
.forEach(logger::debug)
}
fun runHandlerFor(element: Any, engine: Engine, proceed: (Any) -> Unit) {
when {
element is JAXBElement<*> -> {
simpleElementHandlers[element.name]?.process(element.value, engine)
?: error("Unknown handler for simple element: ${element.name}")
}
else -> {
val handler = complexElementHandlers[element.javaClass]
?: error("Unknown handler for complex element: ${element.javaClass.name}")
@Suppress("UNCHECKED_CAST")
val elementAttributeHandler = handler as? CustomAttributeHandler<Any> ?: AutoAttributeHandler
val attributes = elementAttributeHandler.getAttributes(element)
val attributeOrder = attributes
.map { this.attributeHandlers[it.key] }
.filterNotNull()
.sortedBy { it.priority }
.map { it.handles }
.toMutableList()
fun processNextAttribute() {
if (attributeOrder.isNotEmpty()) {
val attributeName = attributeOrder.removeAt(0)
val attributeHandler = attributeHandlers[attributeName] ?: error("No attribute handler found for: $attributeName")
val attributeValue = attributes[attributeName] ?: ""
attributeHandler.process(element, attributeValue, engine, ::processNextAttribute)
} else {
when (handler) {
is TransportComplexElementHandler<Any> -> {
val host = handler.getHostRef(element)
.let(engine::interpolate)
.let(engine::get)
.let { it as Host }
val identity = handler.getIdentityRef(element)
.let(engine::interpolate)
.let(engine::get)
.let { it as Identity }
val transport = engine.sessionProvider.getTransport(host, identity)
handler.process(element, engine, proceed, transport)
}
is StandardComplexElementHandler<Any> -> handler.process(element, engine, proceed)
else -> error("Unknown element handler type: ${handler.javaClass.name}")
}
}
}
processNextAttribute()
}
}
}
fun createJaxbContext() = this.objectFactories.toTypedArray().let {
JAXBContext.newInstance(*it)
}
fun executePreloaders(engine: Engine) {
this.preloaders.sortedBy {
it.priority
}.forEach {
it.configure(engine)
}
}
} | gpl-3.0 | 906ea1d904ff7473cb0ee3672e3c8bf5 | 30.325123 | 155 | 0.703051 | 3.872107 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/vfu.kt | 2 | 8080 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
interface VFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : VFUEntity, ModifiableWorkspaceEntity<VFUEntity>, ObjBuilder<VFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl
}
companion object : Type<VFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): VFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUEntity, modification: VFUEntity.Builder.() -> Unit) = modifyEntity(
VFUEntity.Builder::class.java, entity, modification)
//endregion
interface VFUWithTwoPropertiesEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
val secondFileProperty: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : VFUWithTwoPropertiesEntity, ModifiableWorkspaceEntity<VFUWithTwoPropertiesEntity>, ObjBuilder<VFUWithTwoPropertiesEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl
override var secondFileProperty: VirtualFileUrl
}
companion object : Type<VFUWithTwoPropertiesEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: VirtualFileUrl,
secondFileProperty: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): VFUWithTwoPropertiesEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty
builder.secondFileProperty = secondFileProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUWithTwoPropertiesEntity,
modification: VFUWithTwoPropertiesEntity.Builder.() -> Unit) = modifyEntity(
VFUWithTwoPropertiesEntity.Builder::class.java, entity, modification)
//endregion
interface NullableVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NullableVFUEntity, ModifiableWorkspaceEntity<NullableVFUEntity>, ObjBuilder<NullableVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: VirtualFileUrl?
}
companion object : Type<NullableVFUEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NullableVFUEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NullableVFUEntity, modification: NullableVFUEntity.Builder.() -> Unit) = modifyEntity(
NullableVFUEntity.Builder::class.java, entity, modification)
//endregion
interface ListVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: List<VirtualFileUrl>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ListVFUEntity, ModifiableWorkspaceEntity<ListVFUEntity>, ObjBuilder<ListVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: MutableList<VirtualFileUrl>
}
companion object : Type<ListVFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: List<VirtualFileUrl>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ListVFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ListVFUEntity, modification: ListVFUEntity.Builder.() -> Unit) = modifyEntity(
ListVFUEntity.Builder::class.java, entity, modification)
//endregion
interface SetVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: Set<VirtualFileUrl>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SetVFUEntity, ModifiableWorkspaceEntity<SetVFUEntity>, ObjBuilder<SetVFUEntity> {
override var entitySource: EntitySource
override var data: String
override var fileProperty: MutableSet<VirtualFileUrl>
}
companion object : Type<SetVFUEntity, Builder>() {
operator fun invoke(data: String,
fileProperty: Set<VirtualFileUrl>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): SetVFUEntity {
val builder = builder()
builder.data = data
builder.fileProperty = fileProperty.toMutableWorkspaceSet()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SetVFUEntity, modification: SetVFUEntity.Builder.() -> Unit) = modifyEntity(
SetVFUEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addVFUEntity(
data: String,
fileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUEntity {
val vfuEntity = VFUEntity(data, virtualFileManager.fromUrl(fileUrl), source)
this.addEntity(vfuEntity)
return vfuEntity
}
fun MutableEntityStorage.addVFU2Entity(
data: String,
fileUrl: String,
secondFileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUWithTwoPropertiesEntity {
val vfuWithTwoPropertiesEntity = VFUWithTwoPropertiesEntity(data, virtualFileManager.fromUrl(fileUrl), virtualFileManager.fromUrl(secondFileUrl), source)
this.addEntity(vfuWithTwoPropertiesEntity)
return vfuWithTwoPropertiesEntity
}
fun MutableEntityStorage.addNullableVFUEntity(
data: String,
fileUrl: String?,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): NullableVFUEntity {
val nullableVFUEntity = NullableVFUEntity(data, source) {
this.fileProperty = fileUrl?.let { virtualFileManager.fromUrl(it) }
}
this.addEntity(nullableVFUEntity)
return nullableVFUEntity
}
fun MutableEntityStorage.addListVFUEntity(
data: String,
fileUrl: List<String>,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): ListVFUEntity {
val listVFUEntity = ListVFUEntity(data, fileUrl.map { virtualFileManager.fromUrl(it) }, source)
this.addEntity(listVFUEntity)
return listVFUEntity
}
| apache-2.0 | 2cdc633fdd26633950381434cae1b3ba | 33.678112 | 155 | 0.739109 | 5.511596 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.kt | 3 | 7851 | // 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.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.runBlockingUnderModalProgress
import com.intellij.ide.lightEdit.*
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.EDT
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileChooser.PathChooserDialog
import com.intellij.openapi.fileChooser.impl.FileChooserUtil
import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider
import com.intellij.openapi.fileTypes.ex.FileTypeChooser
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.openapi.wm.impl.welcomeScreen.NewWelcomeScreen
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.projectImport.ProjectOpenProcessor.Companion.getImportProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.file.Files
open class OpenFileAction : AnAction(), DumbAware, LightEditCompatible {
companion object {
@JvmStatic
fun openFile(filePath: String, project: Project) {
val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
if (file != null && file.isValid) {
openFile(file, project)
}
}
@JvmStatic
fun openFile(file: VirtualFile, project: Project) {
NonProjectFileWritingAccessProvider.allowWriting(listOf(file))
if (LightEdit.owns(project)) {
LightEditService.getInstance().openFile(file)
LightEditFeatureUsagesUtil.logFileOpen(project, LightEditFeatureUsagesUtil.OpenPlace.LightEditOpenAction)
}
else {
PsiNavigationSupport.getInstance().createNavigatable(project, file, -1).navigate(true)
}
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val showFiles = project != null || PlatformProjectOpenProcessor.getInstanceIfItExists() != null
val descriptor: FileChooserDescriptor = if (showFiles) ProjectOrFileChooserDescriptor() else ProjectOnlyFileChooserDescriptor()
var toSelect: VirtualFile? = null
if (!GeneralSettings.getInstance().defaultProjectDirectory.isNullOrEmpty()) {
toSelect = VfsUtil.findFileByIoFile(File(GeneralSettings.getInstance().defaultProjectDirectory), true)
}
descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, toSelect == null && showFiles)
FileChooser.chooseFiles(descriptor, project, toSelect ?: pathToSelect) { files ->
for (file in files) {
if (!descriptor.isFileSelectable(file)) {
val message = IdeBundle.message("error.dir.contains.no.project", file.presentableUrl)
Messages.showInfoMessage(project, message, IdeBundle.message("title.cannot.open.project"))
return@chooseFiles
}
}
runBlockingUnderModalProgress {
for (file in files) {
doOpenFile(project, file)
}
}
}
}
internal class OnWelcomeScreen : OpenFileAction() {
override fun update(e: AnActionEvent) {
val presentation = e.presentation
if (!NewWelcomeScreen.isNewWelcomeScreen(e)) {
presentation.isEnabledAndVisible = false
return
}
if (FlatWelcomeFrame.USE_TABBED_WELCOME_SCREEN) {
presentation.icon = AllIcons.Welcome.Open
presentation.selectedIcon = AllIcons.Welcome.OpenSelected
presentation.text = ActionsBundle.message("action.Tabbed.WelcomeScreen.OpenProject.text")
}
else {
presentation.icon = AllIcons.Actions.MenuOpen
}
}
}
protected val pathToSelect: VirtualFile?
get() = VfsUtil.getUserHomeDir()
override fun update(e: AnActionEvent) {
if (NewWelcomeScreen.isNewWelcomeScreen(e)) {
e.presentation.icon = AllIcons.Actions.MenuOpen
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
}
private class ProjectOnlyFileChooserDescriptor : OpenProjectFileChooserDescriptor(true) {
init {
title = IdeBundle.message("title.open.project")
}
}
// vanilla OpenProjectFileChooserDescriptor only accepts project files; this one is overridden to accept any files
private class ProjectOrFileChooserDescriptor : OpenProjectFileChooserDescriptor(true) {
private val myStandardDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor().withHideIgnored(false)
init {
title = IdeBundle.message("title.open.file.or.project")
}
override fun isFileVisible(file: VirtualFile, showHiddenFiles: Boolean): Boolean {
return if (file.isDirectory) super.isFileVisible(file, showHiddenFiles) else myStandardDescriptor.isFileVisible(file, showHiddenFiles)
}
override fun isFileSelectable(file: VirtualFile?): Boolean {
if (file == null) {
return false
}
return if (file.isDirectory) super.isFileSelectable(file) else myStandardDescriptor.isFileSelectable(file)
}
override fun isChooseMultiple() = true
}
private suspend fun doOpenFile(project: Project?, file: VirtualFile) {
val filePath = file.toNioPath()
if (Files.isDirectory(filePath)) {
@Suppress("TestOnlyProblems")
ProjectUtil.openExistingDir(filePath, project)
return
}
// try to open as a project - unless the file is an .ipr of the current one
if ((project == null || file != project.projectFile) && OpenProjectFileChooserDescriptor.isProjectFile(file)) {
val answer = shouldOpenNewProject(project, file)
if (answer == Messages.CANCEL) {
return
}
else if (answer == Messages.YES) {
val openedProject = ProjectUtil.openOrImportAsync(filePath, OpenProjectTask { projectToClose = project })
openedProject?.let {
FileChooserUtil.setLastOpenedFile(it, filePath)
}
return
}
}
LightEditUtil.markUnknownFileTypeAsPlainTextIfNeeded(project, file)
FileTypeChooser.getKnownFileTypeOrAssociate(file, project) ?: return
if (project != null && !project.isDefault) {
NonProjectFileWritingAccessProvider.allowWriting(listOf(file))
if (LightEdit.owns(project)) {
LightEditService.getInstance().openFile(file)
LightEditFeatureUsagesUtil.logFileOpen(project, LightEditFeatureUsagesUtil.OpenPlace.LightEditOpenAction)
}
else {
val navigatable = PsiNavigationSupport.getInstance().createNavigatable(project, file, -1)
withContext(Dispatchers.EDT) {
navigatable.navigate(true)
}
}
}
else {
PlatformProjectOpenProcessor.createTempProjectAndOpenFileAsync(filePath, OpenProjectTask { projectToClose = project })
}
}
@Messages.YesNoCancelResult
private suspend fun shouldOpenNewProject(project: Project?, file: VirtualFile): Int {
if (file.fileType is ProjectFileType) {
return Messages.YES
}
val provider = getImportProvider(file) ?: return Messages.CANCEL
return withContext(Dispatchers.EDT) { provider.askConfirmationForOpeningProject(file, project) }
} | apache-2.0 | e7f1b0236984246af29fe1a6a93607d5 | 38.857868 | 138 | 0.760413 | 4.749546 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structureView/KotlinStructureViewElement.kt | 1 | 5578 | // 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.structureView
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.ui.Queryable
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.psi.*
import javax.swing.Icon
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class KotlinStructureViewElement(
override val element: NavigatablePsiElement,
private val isInherited: Boolean = false
) : PsiTreeElementBase<NavigatablePsiElement>(element), Queryable, AbstractKotlinStructureViewElement {
private var kotlinPresentation
by AssignableLazyProperty {
KotlinStructureElementPresentation(isInherited, element, countDescriptor())
}
var visibility
by AssignableLazyProperty {
Visibility(countDescriptor())
}
private set
constructor(element: NavigatablePsiElement, descriptor: DeclarationDescriptor, isInherited: Boolean) : this(element, isInherited) {
if (element !is KtElement) {
// Avoid storing descriptor in fields
kotlinPresentation = KotlinStructureElementPresentation(isInherited, element, descriptor)
visibility = Visibility(descriptor)
}
}
override val accessLevel: Int?
get() = visibility.accessLevel
override val isPublic: Boolean
get() = visibility.isPublic
override fun getPresentation(): ItemPresentation = kotlinPresentation
override fun getLocationString(): String? = kotlinPresentation.locationString
override fun getIcon(open: Boolean): Icon? = kotlinPresentation.getIcon(open)
override fun getPresentableText(): String? = kotlinPresentation.presentableText
@TestOnly
override fun putInfo(info: MutableMap<in String, in String?>) {
// Sanity check for API consistency
assert(presentation.presentableText == presentableText) { "Two different ways of getting presentableText" }
assert(presentation.locationString == locationString) { "Two different ways of getting locationString" }
info["text"] = presentableText
info["location"] = locationString
}
override fun getChildrenBase(): Collection<StructureViewTreeElement> {
val children = when (val element = element) {
is KtFile -> element.declarations
is KtClass -> element.getStructureDeclarations()
is KtClassOrObject -> element.declarations
is KtFunction, is KtClassInitializer, is KtProperty -> element.collectLocalDeclarations()
else -> emptyList()
}
return children.map { KotlinStructureViewElement(it, false) }
}
private fun PsiElement.collectLocalDeclarations(): List<KtDeclaration> {
val result = mutableListOf<KtDeclaration>()
acceptChildren(object : KtTreeVisitorVoid() {
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
result.add(classOrObject)
}
override fun visitNamedFunction(function: KtNamedFunction) {
result.add(function)
}
})
return result
}
private fun countDescriptor(): DeclarationDescriptor? {
val element = element
return when {
!element.isValid -> null
element !is KtDeclaration -> null
element is KtAnonymousInitializer -> null
else -> runReadAction {
if (!DumbService.isDumb(element.getProject())) {
element.resolveToDescriptorIfAny()
} else null
}
}
}
class Visibility(descriptor: DeclarationDescriptor?) {
private val visibility = (descriptor as? DeclarationDescriptorWithVisibility)?.visibility
val isPublic: Boolean
get() = visibility == DescriptorVisibilities.PUBLIC
val accessLevel: Int?
get() = when {
visibility == DescriptorVisibilities.PUBLIC -> 1
visibility == DescriptorVisibilities.INTERNAL -> 2
visibility == DescriptorVisibilities.PROTECTED -> 3
visibility?.let { DescriptorVisibilities.isPrivate(it) } == true -> 4
else -> null
}
}
}
private class AssignableLazyProperty<in R, T : Any>(val init: () -> T) : ReadWriteProperty<R, T> {
private var _value: T? = null
override fun getValue(thisRef: R, property: KProperty<*>): T {
return _value ?: init().also { _value = it }
}
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
_value = value
}
}
fun KtClassOrObject.getStructureDeclarations() =
buildList {
primaryConstructor?.let { add(it) }
primaryConstructorParameters.filterTo(this) { it.hasValOrVar() }
addAll(declarations)
}
| apache-2.0 | 714902bb7b9656401f7e7e24bbf8cc79 | 37.736111 | 135 | 0.685909 | 5.709314 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceProtectedToPublishedApiCallFix.kt | 1 | 5904 | // 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.quickfix.replaceWith
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.resolve.source.getPsi
class ReplaceProtectedToPublishedApiCallFix(
element: KtExpression,
private val classOwnerPointer: SmartPsiElementPointer<KtClass>,
private val originalName: String,
private val paramNames: Map<String, String>,
private val newSignature: String,
private val isProperty: Boolean,
private val isVar: Boolean,
private val isPublishedMemberAlreadyExists: Boolean
) : KotlinQuickFixAction<KtExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("replace.with.publishedapi.bridge.call")
override fun getText() =
KotlinBundle.message(
"replace.with.generated.publishedapi.bridge.call.0",
originalName.newNameQuoted + if (!isProperty) "(...)" else ""
)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(project)
if (!isPublishedMemberAlreadyExists) {
val classOwner = classOwnerPointer.element ?: return
val newMember: KtDeclaration =
if (isProperty) {
psiFactory.createProperty(
"@kotlin.PublishedApi\n" +
"internal " + newSignature +
"\n" +
"get() = $originalName\n" +
if (isVar) "set(value) { $originalName = value }" else ""
)
} else {
psiFactory.createFunction(
"@kotlin.PublishedApi\n" +
"internal " + newSignature +
" = $originalName(${paramNames.keys.joinToString(", ") { it }})"
)
}
ShortenReferences.DEFAULT.process(classOwner.addDeclaration(newMember))
}
element.replace(psiFactory.createExpression(originalName.newNameQuoted))
}
companion object : KotlinSingleIntentionActionFactory() {
private val signatureRenderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions {
defaultParameterValueRenderer = null
startFromDeclarationKeyword = true
withoutReturnType = true
}
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val psiElement = diagnostic.psiElement as? KtExpression ?: return null
val descriptor = DiagnosticFactory.cast(
diagnostic, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.warningFactory, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.errorFactory
).a.let {
if (it is CallableMemberDescriptor) DescriptorUtils.getDirectMember(it) else it
}
val isProperty = descriptor is PropertyDescriptor
val isVar = descriptor is PropertyDescriptor && descriptor.isVar
val signature = signatureRenderer.render(descriptor)
val originalName = descriptor.name.asString()
val newSignature =
if (isProperty) {
signature.replaceFirst("$originalName:", "${originalName.newNameQuoted}:")
} else {
signature.replaceFirst("$originalName(", "${originalName.newNameQuoted}(")
}
val paramNameAndType = descriptor.valueParameters.associate { it.name.asString() to it.type.getJetTypeFqName(false) }
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return null
val source = classDescriptor.source.getPsi() as? KtClass ?: return null
val newName = Name.identifier(originalName.newName)
val contributedDescriptors = classDescriptor.unsubstitutedMemberScope.getDescriptorsFiltered {
it == newName
}
val isPublishedMemberAlreadyExists = contributedDescriptors.filterIsInstance<CallableMemberDescriptor>().any {
signatureRenderer.render(it) == newSignature
}
return ReplaceProtectedToPublishedApiCallFix(
psiElement, source.createSmartPointer(), originalName, paramNameAndType, newSignature,
isProperty, isVar, isPublishedMemberAlreadyExists
)
}
val String.newName: String
get() = "access\$$this"
val String.newNameQuoted: String
get() = "`$newName`"
}
}
| apache-2.0 | 3dc9735f6a0b3d0bfd6b5f5c7102f1e4 | 46.232 | 158 | 0.67124 | 5.52809 | false | false | false | false |
google/iosched | mobile/src/test/java/com/google/samples/apps/iosched/ui/codelabs/CodelabsViewModelTest.kt | 1 | 5777 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.iosched.ui.codelabs
import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository
import com.google.samples.apps.iosched.shared.data.codelabs.CodelabsRepository
import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage
import com.google.samples.apps.iosched.shared.domain.codelabs.GetCodelabsInfoCardShownUseCase
import com.google.samples.apps.iosched.shared.domain.codelabs.LoadCodelabsUseCase
import com.google.samples.apps.iosched.shared.domain.codelabs.SetCodelabsInfoCardShownUseCase
import com.google.samples.apps.iosched.test.data.MainCoroutineRule
import com.google.samples.apps.iosched.test.util.fakes.FakeAppDatabase
import com.google.samples.apps.iosched.test.util.fakes.FakeConferenceDataSource
import com.google.samples.apps.iosched.test.util.fakes.FakePreferenceStorage
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
/**
* Unit tests for [CodelabsViewModel]
*/
class CodelabsViewModelTest {
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
@Test
fun testData_codelabInfoShown() = runTest {
val prefs = FakePreferenceStorage(codelabsInfoShown = true)
val viewModel = createCodelabsViewModel(
getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs)
)
val codelabs = viewModel.screenContent.first()
// codelabs does not contain the info card
assertFalse(codelabs.contains(CodelabsInformationCard))
// We have other codelabs apart from the header item
assertTrue(codelabs.size > 1)
}
@Test
fun testData_codelabInfoNotShown() = runTest {
val prefs = FakePreferenceStorage(codelabsInfoShown = false)
val viewModel = createCodelabsViewModel(
getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs)
)
val codelabs = viewModel.screenContent.first()
// codelabs contain the info card
assertTrue(codelabs.contains(CodelabsInformationCard))
// We have other codelabs apart from the header item and info card
assertTrue(codelabs.size > 2)
}
@Test
fun testData_dismissCodelabInfoCard() = runTest {
val prefs = FakePreferenceStorage(codelabsInfoShown = false)
val viewModel = createCodelabsViewModel(
getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs),
setCodelabsInfoCardShownUseCase = createTestSetCodelabsInfoCardShownUseCase(prefs)
)
val initialCodelabs = viewModel.screenContent.first()
// codelabs contain the info card
assertTrue(initialCodelabs.contains(CodelabsInformationCard))
viewModel.dismissCodelabsInfoCard()
val newCodelabs = viewModel.screenContent.first()
assertFalse(newCodelabs.contains(CodelabsInformationCard))
}
private fun createCodelabsViewModel(
loadCodelabsUseCase: LoadCodelabsUseCase = createTestLoadCodelabsUseCase(),
getCodelabsInfoCardShownUseCase: GetCodelabsInfoCardShownUseCase =
createTestGetCodelabsInfoCardShownUseCase(),
setCodelabsInfoCardShownUseCase: SetCodelabsInfoCardShownUseCase =
createTestSetCodelabsInfoCardShownUseCase()
): CodelabsViewModel {
return CodelabsViewModel(
loadCodelabsUseCase,
getCodelabsInfoCardShownUseCase,
setCodelabsInfoCardShownUseCase
)
}
private fun createTestLoadCodelabsUseCase(): LoadCodelabsUseCase {
val conferenceDataRepository = createTestConferenceDataRepository()
val codelabsRepository: CodelabsRepository =
createTestCodelabsRepository(conferenceDataRepository)
return LoadCodelabsUseCase(
codelabsRepository,
coroutineRule.testDispatcher
)
}
private fun createTestConferenceDataRepository(): ConferenceDataRepository {
return ConferenceDataRepository(
remoteDataSource = FakeConferenceDataSource,
boostrapDataSource = FakeConferenceDataSource,
appDatabase = FakeAppDatabase()
)
}
private fun createTestCodelabsRepository(
conferenceDataRepository: ConferenceDataRepository
): CodelabsRepository {
return CodelabsRepository(conferenceDataRepository)
}
private fun createTestGetCodelabsInfoCardShownUseCase(
preferenceStorage: PreferenceStorage = FakePreferenceStorage()
): GetCodelabsInfoCardShownUseCase {
return GetCodelabsInfoCardShownUseCase(
preferenceStorage,
coroutineRule.testDispatcher
)
}
private fun createTestSetCodelabsInfoCardShownUseCase(
preferenceStorage: PreferenceStorage = FakePreferenceStorage()
): SetCodelabsInfoCardShownUseCase {
return SetCodelabsInfoCardShownUseCase(
preferenceStorage,
coroutineRule.testDispatcher
)
}
}
| apache-2.0 | 8f4c717c7647d11955acab9931c1f01a | 39.398601 | 95 | 0.743119 | 5.841254 | false | true | false | false |
exercism/xkotlin | exercises/practice/forth/.meta/src/reference/kotlin/Forth.kt | 1 | 3062 | import java.util.*
class Forth {
companion object {
private val NUMBER_PATTERN = Regex("""^-?\d+$""")
}
private val stack: Deque<Int> = ArrayDeque()
private val customOps: MutableMap<String, String> = mutableMapOf()
private val ops = mutableMapOf(
"+" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
stack.push(stack.pop() + stack.pop())
},
"-" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
val tmp = stack.pop()
stack.push(stack.pop() - tmp)
},
"*" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
stack.push(stack.pop() * stack.pop())
},
"/" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
val tmp = stack.pop()
require(tmp != 0) { "divide by zero" }
stack.push(stack.pop() / tmp)
},
"DUP" to {
require(stack.isNotEmpty()) { "empty stack" }
stack.push(stack.first)
},
"DROP" to {
require(stack.isNotEmpty()) { "empty stack" }
stack.pop()
},
"SWAP" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
val a = stack.pop()
val b = stack.pop()
stack.push(a)
stack.push(b)
},
"OVER" to {
require(stack.isNotEmpty()) { "empty stack" }
require(stack.size >= 2) { "only one value on the stack" }
stack.push(stack.elementAt(1))
}
);
fun evaluate(vararg lines: String): List<Int> {
lines.forEach { line ->
evaluateLine(line.uppercase())
}
return stack.reversed()
}
private fun evaluateLine(line: String) {
val tokens = line.split(" ")
if (tokens.first() == ":") {
val op = tokens[1]
val expression = tokens.subList(2, tokens.lastIndex)
require(!op.matches(NUMBER_PATTERN)) { "illegal operation" }
customOps[op] = expression.joinToString(" ") { customOps.getOrDefault(it, it) }
return
}
tokens.forEach { token ->
when {
token.matches(NUMBER_PATTERN) -> stack.push(token.toInt())
token in customOps.keys -> evaluateLine(customOps[token]!!)
token in ops.keys -> ops[token]!!()
else -> throw IllegalArgumentException("undefined operation")
}
}
}
}
| mit | 3bedd2b53ce59c7215240a2ada59b44e | 35.023529 | 91 | 0.470934 | 4.463557 | false | false | false | false |
allotria/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/lang/formatter/blocks/special/MarkdownWrappingFormattingBlock.kt | 3 | 1990 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.formatter.blocks.special
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.formatter.blocks.MarkdownBlocks
import org.intellij.plugins.markdown.lang.formatter.blocks.MarkdownFormattingBlock
import org.intellij.plugins.markdown.util.MarkdownTextUtil
import org.intellij.plugins.markdown.util.children
/**
* Markdown special formatting block that makes all
* [MarkdownTokenTypes.TEXT] elements inside wrap.
*
* It is used to make markdown paragraph wrap around
* right margin. So, it kind of emulates reflow formatting
* for paragraphs.
*/
internal class MarkdownWrappingFormattingBlock(
settings: CodeStyleSettings, spacing: SpacingBuilder,
node: ASTNode, alignment: Alignment? = null, wrap: Wrap? = null
) : MarkdownFormattingBlock(node, settings, spacing, alignment, wrap) {
companion object {
private val NORMAL_WRAP = Wrap.createWrap(WrapType.NORMAL, false)
}
/** Number of newlines in this block's text */
val newlines: Int
get() = node.text.count { it == '\n' }
override fun buildChildren(): List<Block> {
val filtered = MarkdownBlocks.filterFromWhitespaces(node.children())
val result = ArrayList<Block>()
for (node in filtered) {
if (node.elementType == MarkdownTokenTypes.TEXT) {
val splits = MarkdownTextUtil.getSplitBySpacesRanges(node.text, node.textRange.startOffset)
for (split in splits) {
result.add(MarkdownRangedFormattingBlock(node, split, settings, spacing, alignment, NORMAL_WRAP))
}
}
else {
result.add(MarkdownBlocks.create(node, settings, spacing) { alignment })
}
}
return result
}
}
| apache-2.0 | f4024a23b8145c27b64f0bd52375eeb7 | 35.181818 | 140 | 0.743719 | 4.252137 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/adapter/ConversationsAdapter.kt | 1 | 3831 | package com.glodanif.bluetoothchat.ui.adapter
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.ui.viewmodel.ConversationViewModel
class ConversationsAdapter : RecyclerView.Adapter<ConversationsAdapter.ConversationViewHolder>() {
var clickListener: ((ConversationViewModel) -> Unit)? = null
var longClickListener: ((ConversationViewModel, Boolean) -> Unit)? = null
private var isConnected: Boolean = false
private var conversations: ArrayList<ConversationViewModel> = ArrayList()
override fun onBindViewHolder(holder: ConversationViewHolder, position: Int) {
val conversation = conversations[position]
holder.name.text = conversation.fullName
holder.itemView.setOnClickListener {
clickListener?.invoke(conversation)
}
holder.itemView.setOnLongClickListener {
val isCurrent = isConnected && position == 0
longClickListener?.invoke(conversation, isCurrent)
return@setOnLongClickListener true
}
if (conversation.lastMessage != null) {
holder.messageContainer.visibility = View.VISIBLE
holder.lastMessage.text = conversation.lastMessage
} else {
holder.messageContainer.visibility = View.GONE
}
if (conversation.lastActivityText != null) {
holder.time.visibility = View.VISIBLE
holder.time.text = conversation.lastActivityText
} else {
holder.time.visibility = View.GONE
}
if (conversation.notSeen > 0) {
holder.notSeen.visibility = View.VISIBLE
holder.notSeen.text = conversation.notSeen.toString()
} else {
holder.notSeen.visibility = View.GONE
}
val isNotConnected = !isConnected || position > 0
holder.connected.visibility = if (isNotConnected) View.GONE else View.VISIBLE
val drawable = if (isNotConnected)
conversation.getGrayedAvatar() else conversation.getColoredAvatar()
holder.avatar.setImageDrawable(drawable)
}
override fun getItemCount(): Int {
return conversations.size
}
fun setData(items: ArrayList<ConversationViewModel>, connected: String?) {
conversations = items
setCurrentConversation(connected)
}
fun setCurrentConversation(connected: String?) {
isConnected = connected != null
val sortedList = conversations.sortedWith(
compareByDescending<ConversationViewModel> { it.address == connected }
.thenByDescending { it.lastActivity })
conversations = ArrayList()
conversations.addAll(sortedList)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConversationViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_conversation, parent, false)
return ConversationViewHolder(view)
}
class ConversationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val avatar: ImageView = itemView.findViewById(R.id.iv_avatar)
val name: TextView = itemView.findViewById(R.id.tv_name)
val connected: ImageView = itemView.findViewById(R.id.iv_connected)
val lastMessage: TextView = itemView.findViewById(R.id.tv_last_message)
val time: TextView = itemView.findViewById(R.id.tv_time)
val notSeen: TextView = itemView.findViewById(R.id.tv_not_seen)
val messageContainer: LinearLayout = itemView.findViewById(R.id.ll_message_info)
}
}
| apache-2.0 | 2c4e38142abd510baf82988e767e12a3 | 38.494845 | 98 | 0.690159 | 5.163073 | false | false | false | false |
zpao/buck | src/com/facebook/buck/multitenant/fs/FsAgnosticPath.kt | 1 | 1941 | /*
* Copyright (c) Facebook, Inc. and its 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.buck.multitenant.fs
import com.facebook.buck.core.path.ForwardRelativePath
import com.facebook.buck.multitenant.cache.AppendOnlyBidirectionalCache
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
/**
* Cache between path [String] and [ForwardRelativePath] wrapper around this [String] value.
* Soft references are used.
* Softly-referenced objects will be garbage-collected in a <i>globally</i> least-recently-used manner,
* in response to memory demand.
*/
private val PATH_CACHE: Cache<String, ForwardRelativePath> =
CacheBuilder.newBuilder().softValues().build()
/**
* Cache between [ForwardRelativePath] to unique [Int] value.
*/
private val PATH_TO_INDEX_CACHE = AppendOnlyBidirectionalCache<ForwardRelativePath>()
object FsAgnosticPath {
fun fromIndex(index: Int): ForwardRelativePath = PATH_TO_INDEX_CACHE.getByIndex(index)
fun toIndex(fsAgnosticPath: ForwardRelativePath): Int = PATH_TO_INDEX_CACHE.get(fsAgnosticPath)
/**
* @param path must be a normalized, relative path.
*/
fun of(path: String): ForwardRelativePath {
return PATH_CACHE.getIfPresent(path) ?: run {
val pathObject = ForwardRelativePath.of(path)
PATH_CACHE.put(path, pathObject)
pathObject
}
}
}
| apache-2.0 | d986b80152b0961fb177cf3bf94513c5 | 35.622642 | 103 | 0.733127 | 4.210412 | false | false | false | false |
google/oboe | samples/minimaloboe/src/main/java/com/example/minimaloboe/AudioPlayer.kt | 2 | 3021 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.minimaloboe
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
import kotlin.coroutines.CoroutineContext
object AudioPlayer : DefaultLifecycleObserver {
// Create a coroutine scope which we can launch coroutines from. This way, if our
// player is ever destroyed (for example, if it was no longer a singleton and had multiple
// instances) any jobs would also be cancelled.
private val coroutineScope = CoroutineScope(Dispatchers.Default) + Job()
private var _playerState = MutableStateFlow<PlayerState>(PlayerState.NoResultYet)
val playerState = _playerState.asStateFlow()
init {
// Load the library containing the native code including the JNI functions.
System.loadLibrary("minimaloboe")
}
fun setPlaybackEnabled(isEnabled: Boolean) {
// Start (and stop) Oboe from a coroutine in case it blocks for too long.
// If the AudioServer has died it may take several seconds to recover.
// That can cause an ANR if we are starting audio from the main UI thread.
coroutineScope.launch {
val result = if (isEnabled) {
startAudioStreamNative()
} else {
stopAudioStreamNative()
}
val newUiState = if (result == 0) {
if (isEnabled){
PlayerState.Started
} else {
PlayerState.Stopped
}
} else {
PlayerState.Unknown(result)
}
_playerState.update { newUiState }
}
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
setPlaybackEnabled(false)
}
private external fun startAudioStreamNative(): Int
private external fun stopAudioStreamNative(): Int
}
sealed interface PlayerState {
object NoResultYet : PlayerState
object Started : PlayerState
object Stopped : PlayerState
data class Unknown(val resultCode: Int) : PlayerState
}
| apache-2.0 | 6f55e8ebc755b2539aaadf687305d75f | 33.724138 | 94 | 0.694141 | 4.976936 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/recurringexpenseadd/RecurringExpenseEditActivity.kt | 1 | 13813 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.view.recurringexpenseadd
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.app.ProgressDialog
import android.os.Bundle
import android.view.MenuItem
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.benoitletondor.easybudgetapp.R
import com.benoitletondor.easybudgetapp.databinding.ActivityRecurringExpenseAddBinding
import com.benoitletondor.easybudgetapp.helper.*
import com.benoitletondor.easybudgetapp.parameters.Parameters
import com.benoitletondor.easybudgetapp.model.RecurringExpenseType
import com.benoitletondor.easybudgetapp.view.DatePickerDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.inject.Inject
import kotlin.math.abs
@AndroidEntryPoint
class RecurringExpenseEditActivity : BaseActivity<ActivityRecurringExpenseAddBinding>() {
private val viewModel: RecurringExpenseEditViewModel by viewModels()
@Inject lateinit var parameters: Parameters
// ------------------------------------------->
override fun createBinding(): ActivityRecurringExpenseAddBinding = ActivityRecurringExpenseAddBinding.inflate(layoutInflater)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setUpButtons()
setResult(Activity.RESULT_CANCELED)
if ( willAnimateActivityEnter() ) {
animateActivityEnter(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.descriptionEdittext.setFocus()
binding.saveExpenseFab.animateFABAppearance()
}
})
} else {
binding.descriptionEdittext.setFocus()
binding.saveExpenseFab.animateFABAppearance()
}
lifecycleScope.launchCollect(viewModel.editTypeFlow) { (isRevenue, isEditing) ->
setExpenseTypeTextViewLayout(isRevenue, isEditing)
}
val existingExpenseData = viewModel.existingExpenseData
if (existingExpenseData != null) {
setUpTextFields(
existingExpenseData.title,
existingExpenseData.amount,
type = existingExpenseData.type
)
} else {
setUpTextFields(description = null, amount = null, type = null)
}
lifecycleScope.launchCollect(viewModel.expenseDateFlow) { date ->
setUpDateButton(date)
}
var progressDialog: ProgressDialog? = null
lifecycleScope.launchCollect(viewModel.savingStateFlow) { savingState ->
when(savingState) {
RecurringExpenseEditViewModel.SavingState.Idle -> {
progressDialog?.dismiss()
progressDialog = null
}
is RecurringExpenseEditViewModel.SavingState.Saving -> {
progressDialog?.dismiss()
progressDialog = null
// Show a ProgressDialog
val dialog = ProgressDialog(this)
dialog.isIndeterminate = true
dialog.setTitle(R.string.recurring_expense_add_loading_title)
dialog.setMessage(getString(if (savingState.isRevenue) R.string.recurring_income_add_loading_message else R.string.recurring_expense_add_loading_message))
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.show()
progressDialog = dialog
}
}
}
lifecycleScope.launchCollect(viewModel.finishFlow) {
progressDialog?.dismiss()
progressDialog = null
setResult(Activity.RESULT_OK)
finish()
}
lifecycleScope.launchCollect(viewModel.errorFlow) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.recurring_expense_add_error_title)
.setMessage(getString(R.string.recurring_expense_add_error_message))
.setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
lifecycleScope.launchCollect(viewModel.expenseAddBeforeInitDateEventFlow) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.expense_add_before_init_date_dialog_title)
.setMessage(R.string.expense_add_before_init_date_dialog_description)
.setPositiveButton(R.string.expense_add_before_init_date_dialog_positive_cta) { _, _ ->
viewModel.onAddExpenseBeforeInitDateConfirmed(
getCurrentAmount(),
binding.descriptionEdittext.text.toString(),
getRecurringTypeFromSpinnerSelection(binding.expenseTypeSpinner.selectedItemPosition)
)
}
.setNegativeButton(R.string.expense_add_before_init_date_dialog_negative_cta) { _, _ ->
viewModel.onAddExpenseBeforeInitDateCancelled()
}
.show()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
// ----------------------------------->
/**
* Validate user inputs
*
* @return true if user inputs are ok, false otherwise
*/
private fun validateInputs(): Boolean {
var ok = true
val description = binding.descriptionEdittext.text.toString()
if (description.trim { it <= ' ' }.isEmpty()) {
binding.descriptionEdittext.error = resources.getString(R.string.no_description_error)
ok = false
}
val amount = binding.amountEdittext.text.toString()
if (amount.trim { it <= ' ' }.isEmpty()) {
binding.amountEdittext.error = resources.getString(R.string.no_amount_error)
ok = false
} else {
try {
val value = java.lang.Double.parseDouble(amount)
if (value <= 0) {
binding.amountEdittext.error = resources.getString(R.string.negative_amount_error)
ok = false
}
} catch (e: Exception) {
binding.amountEdittext.error = resources.getString(R.string.invalid_amount)
ok = false
}
}
return ok
}
/**
* Set-up revenue and payment buttons
*/
private fun setUpButtons() {
binding.expenseTypeSwitch.setOnCheckedChangeListener { _, isChecked ->
viewModel.onExpenseRevenueValueChanged(isChecked)
}
binding.expenseTypeTv.setOnClickListener {
viewModel.onExpenseRevenueValueChanged(!binding.expenseTypeSwitch.isChecked)
}
binding.saveExpenseFab.setOnClickListener {
if (validateInputs()) {
viewModel.onSave(
getCurrentAmount(),
binding.descriptionEdittext.text.toString(),
getRecurringTypeFromSpinnerSelection(binding.expenseTypeSpinner.selectedItemPosition),
)
}
}
}
/**
* Set revenue text view layout
*/
private fun setExpenseTypeTextViewLayout(isRevenue: Boolean, isEditing: Boolean) {
if (isRevenue) {
binding.expenseTypeTv.setText(R.string.income)
binding.expenseTypeTv.setTextColor(ContextCompat.getColor(this, R.color.budget_green))
binding.expenseTypeSwitch.isChecked = true
if( isEditing ) {
setTitle(R.string.title_activity_recurring_income_edit)
} else {
setTitle(R.string.title_activity_recurring_income_add)
}
} else {
binding.expenseTypeTv.setText(R.string.payment)
binding.expenseTypeTv.setTextColor(ContextCompat.getColor(this, R.color.budget_red))
binding.expenseTypeSwitch.isChecked = false
if( isEditing ) {
setTitle(R.string.title_activity_recurring_expense_edit)
} else {
setTitle(R.string.title_activity_recurring_expense_add)
}
}
}
/**
* Set up text field focus behavior
*/
private fun setUpTextFields(description: String?, amount: Double?, type: RecurringExpenseType?) {
binding.amountInputlayout.hint = resources.getString(R.string.amount, parameters.getUserCurrency().symbol)
val recurringTypesString = arrayOf(
getString(R.string.recurring_interval_daily),
getString(R.string.recurring_interval_weekly),
getString(R.string.recurring_interval_bi_weekly),
getString(R.string.recurring_interval_ter_weekly),
getString(R.string.recurring_interval_four_weekly),
getString(R.string.recurring_interval_monthly),
getString(R.string.recurring_interval_bi_monthly),
getString(R.string.recurring_interval_ter_monthly),
getString(R.string.recurring_interval_six_monthly),
getString(R.string.recurring_interval_yearly)
)
val adapter = ArrayAdapter(this, R.layout.spinner_item, recurringTypesString)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.expenseTypeSpinner.adapter = adapter
if( type != null ) {
setSpinnerSelectionFromRecurringType(type)
} else {
setSpinnerSelectionFromRecurringType(RecurringExpenseType.MONTHLY)
}
if (description != null) {
binding.descriptionEdittext.setText(description)
binding.descriptionEdittext.setSelection(binding.descriptionEdittext.text?.length ?: 0) // Put focus at the end of the text
}
binding.amountEdittext.preventUnsupportedInputForDecimals()
if (amount != null) {
binding.amountEdittext.setText(CurrencyHelper.getFormattedAmountValue(abs(amount)))
}
}
/**
* Get the recurring expense type associated with the spinner selection
*
* @param spinnerSelectedItem index of the spinner selection
* @return the corresponding expense type
*/
private fun getRecurringTypeFromSpinnerSelection(spinnerSelectedItem: Int): RecurringExpenseType {
when (spinnerSelectedItem) {
0 -> return RecurringExpenseType.DAILY
1-> return RecurringExpenseType.WEEKLY
2 -> return RecurringExpenseType.BI_WEEKLY
3 -> return RecurringExpenseType.TER_WEEKLY
4 -> return RecurringExpenseType.FOUR_WEEKLY
5 -> return RecurringExpenseType.MONTHLY
6 -> return RecurringExpenseType.BI_MONTHLY
7 -> return RecurringExpenseType.TER_MONTHLY
8 -> return RecurringExpenseType.SIX_MONTHLY
9 -> return RecurringExpenseType.YEARLY
}
throw IllegalStateException("getRecurringTypeFromSpinnerSelection unable to get value for $spinnerSelectedItem")
}
private fun setSpinnerSelectionFromRecurringType(type: RecurringExpenseType) {
val selectionIndex = when (type) {
RecurringExpenseType.DAILY -> 0
RecurringExpenseType.WEEKLY -> 1
RecurringExpenseType.BI_WEEKLY -> 2
RecurringExpenseType.TER_WEEKLY -> 3
RecurringExpenseType.FOUR_WEEKLY -> 4
RecurringExpenseType.MONTHLY -> 5
RecurringExpenseType.BI_MONTHLY -> 6
RecurringExpenseType.TER_MONTHLY -> 7
RecurringExpenseType.SIX_MONTHLY -> 8
RecurringExpenseType.YEARLY -> 9
}
binding.expenseTypeSpinner.setSelection(selectionIndex, false)
}
/**
* Set up the date button
*/
private fun setUpDateButton(date: LocalDate) {
val formatter = DateTimeFormatter.ofPattern(resources.getString(R.string.add_expense_date_format), Locale.getDefault())
binding.dateButton.text = formatter.format(date)
binding.dateButton.setOnClickListener {
val fragment = DatePickerDialogFragment(date) { _, year, monthOfYear, dayOfMonth ->
viewModel.onDateChanged(LocalDate.of(year, monthOfYear + 1, dayOfMonth))
}
fragment.show(supportFragmentManager, "datePicker")
}
}
private fun getCurrentAmount(): Double {
return java.lang.Double.parseDouble(binding.amountEdittext.text.toString())
}
} | apache-2.0 | 87c62e1ffb3db90b94d01de19883908e | 37.694678 | 174 | 0.639615 | 5.380989 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/main/MainActivity.kt | 1 | 42436 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.view.main
import android.app.Dialog
import android.app.ProgressDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.os.Bundle
import com.benoitletondor.easybudgetapp.view.welcome.WelcomeActivity
import com.google.android.material.snackbar.Snackbar
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.EditText
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.benoitletondor.easybudgetapp.R
import com.benoitletondor.easybudgetapp.databinding.ActivityMainBinding
import com.benoitletondor.easybudgetapp.model.Expense
import com.benoitletondor.easybudgetapp.model.RecurringExpenseDeleteType
import com.benoitletondor.easybudgetapp.view.main.calendar.CalendarFragment
import com.benoitletondor.easybudgetapp.view.selectcurrency.SelectCurrencyFragment
import com.roomorama.caldroid.CaldroidFragment
import com.roomorama.caldroid.CaldroidListener
import java.util.Calendar
import java.util.Locale
import com.benoitletondor.easybudgetapp.helper.*
import com.benoitletondor.easybudgetapp.iab.INTENT_IAB_STATUS_CHANGED
import com.benoitletondor.easybudgetapp.iab.Iab
import com.benoitletondor.easybudgetapp.parameters.*
import com.benoitletondor.easybudgetapp.view.expenseedit.ExpenseEditActivity
import com.benoitletondor.easybudgetapp.view.recurringexpenseadd.RecurringExpenseEditActivity
import com.benoitletondor.easybudgetapp.view.report.base.MonthlyReportBaseActivity
import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity
import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity.Companion.SHOW_BACKUP_INTENT_KEY
import com.benoitletondor.easybudgetapp.view.welcome.getOnboardingStep
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.BaseTransientBottomBar
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import javax.inject.Inject
/**
* Main activity containing Calendar and List of expenses
*
* @author Benoit LETONDOR
*/
@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding>() {
private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
INTENT_EXPENSE_DELETED -> {
val expense = intent.getParcelableExtra<Expense>("expense")!!
viewModel.onDeleteExpenseClicked(expense)
}
INTENT_RECURRING_EXPENSE_DELETED -> {
val expense = intent.getParcelableExtra<Expense>("expense")!!
val deleteType = RecurringExpenseDeleteType.fromValue(intent.getIntExtra("deleteType", RecurringExpenseDeleteType.ALL.value))!!
viewModel.onDeleteRecurringExpenseClicked(expense, deleteType)
}
SelectCurrencyFragment.CURRENCY_SELECTED_INTENT -> viewModel.onCurrencySelected()
INTENT_SHOW_WELCOME_SCREEN -> {
val startIntent = Intent(this@MainActivity, WelcomeActivity::class.java)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, WELCOME_SCREEN_ACTIVITY_CODE, null)
}
INTENT_IAB_STATUS_CHANGED -> viewModel.onIabStatusChanged()
INTENT_SHOW_CHECKED_BALANCE_CHANGED -> viewModel.onShowCheckedBalanceChanged()
INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED -> viewModel.onLowMoneyWarningThresholdChanged()
}
}
}
private lateinit var calendarFragment: CalendarFragment
private lateinit var expensesViewAdapter: ExpensesRecyclerViewAdapter
private val menuBackgroundAnimationDuration: Long = 150
private var menuExpandAnimation: Animation? = null
private var menuCollapseAnimation: Animation? = null
private var isMenuExpended = false
private var lastStopDate: LocalDate? = null
private val viewModel: MainViewModel by viewModels()
@Inject lateinit var parameters: Parameters
@Inject lateinit var iab: Iab
// ------------------------------------------>
override fun createBinding(): ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Launch welcome screen if needed
if (parameters.getOnboardingStep() != WelcomeActivity.STEP_COMPLETED) {
val startIntent = Intent(this, WelcomeActivity::class.java)
ActivityCompat.startActivityForResult(this, startIntent, WELCOME_SCREEN_ACTIVITY_CODE, null)
}
setSupportActionBar(binding.toolbar)
initCalendarFragment(savedInstanceState)
initFab()
initRecyclerView()
registerBroadcastReceiver()
performIntentActionIfAny()
observeViewModel()
}
private fun observeViewModel() {
lifecycleScope.launchCollect(viewModel.expenseDeletionSuccessEventFlow) { (deletedExpense, newBalance, maybeNewCheckecBalance) ->
expensesViewAdapter.removeExpense(deletedExpense)
updateBalanceDisplayForDay(
expensesViewAdapter.getDate(),
newBalance,
maybeNewCheckecBalance
)
calendarFragment.refreshView()
val snackbar = Snackbar.make(
binding.coordinatorLayout,
if (deletedExpense.isRevenue()) R.string.income_delete_snackbar_text else R.string.expense_delete_snackbar_text,
Snackbar.LENGTH_LONG
)
snackbar.setAction(R.string.undo) {
viewModel.onExpenseDeletionCancelled(deletedExpense)
}
snackbar.setActionTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.snackbar_action_undo
)
)
snackbar.duration = BaseTransientBottomBar.LENGTH_LONG
snackbar.show()
}
lifecycleScope.launchCollect(viewModel.expenseDeletionErrorEventFlow) {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.expense_delete_error_title)
.setMessage(R.string.expense_delete_error_message)
.setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
var expenseDeletionDialog: ProgressDialog? = null
lifecycleScope.launchCollect(viewModel.recurringExpenseDeletionProgressStateFlow) { state ->
when(state) {
is MainViewModel.RecurringExpenseDeleteProgressState.Deleting -> {
val dialog = ProgressDialog(this@MainActivity)
dialog.isIndeterminate = true
dialog.setTitle(R.string.recurring_expense_delete_loading_title)
dialog.setMessage(resources.getString(R.string.recurring_expense_delete_loading_message))
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.show()
expenseDeletionDialog = dialog
}
MainViewModel.RecurringExpenseDeleteProgressState.Idle -> {
expenseDeletionDialog?.dismiss()
expenseDeletionDialog = null
}
}
}
lifecycleScope.launchCollect(viewModel.recurringExpenseDeletionEventFlow) { event ->
when(event) {
is MainViewModel.RecurringExpenseDeletionEvent.ErrorCantDeleteBeforeFirstOccurrence -> {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.recurring_expense_delete_first_error_title)
.setMessage(R.string.recurring_expense_delete_first_error_message)
.setNegativeButton(R.string.ok, null)
.show()
}
is MainViewModel.RecurringExpenseDeletionEvent.ErrorIO -> {
showGenericRecurringDeleteErrorDialog()
}
is MainViewModel.RecurringExpenseDeletionEvent.ErrorRecurringExpenseDeleteNotAssociated -> {
showGenericRecurringDeleteErrorDialog()
}
is MainViewModel.RecurringExpenseDeletionEvent.Success -> {
val snackbar = Snackbar.make(
binding.coordinatorLayout,
R.string.recurring_expense_delete_success_message,
Snackbar.LENGTH_LONG
)
snackbar.setAction(R.string.undo) {
viewModel.onRestoreRecurringExpenseClicked(
event.recurringExpense,
event.restoreRecurring,
event.expensesToRestore
)
}
snackbar.setActionTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.snackbar_action_undo
)
)
snackbar.duration = BaseTransientBottomBar.LENGTH_LONG
snackbar.show()
}
}
}
var expenseRestoreDialog: Dialog? = null
lifecycleScope.launchCollect(viewModel.recurringExpenseRestoreProgressStateFlow) { state ->
when(state) {
MainViewModel.RecurringExpenseRestoreProgressState.Idle -> {
expenseRestoreDialog?.dismiss()
expenseRestoreDialog = null
}
is MainViewModel.RecurringExpenseRestoreProgressState.Restoring -> {
val dialog = ProgressDialog(this@MainActivity)
dialog.isIndeterminate = true
dialog.setTitle(R.string.recurring_expense_restoring_loading_title)
dialog.setMessage(resources.getString(R.string.recurring_expense_restoring_loading_message))
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.show()
expenseRestoreDialog = dialog
}
}
}
lifecycleScope.launchCollect(viewModel.recurringExpenseRestoreEventFlow) { event ->
when(event) {
is MainViewModel.RecurringExpenseRestoreEvent.ErrorIO -> {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.recurring_expense_restore_error_title)
.setMessage(resources.getString(R.string.recurring_expense_restore_error_message))
.setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
is MainViewModel.RecurringExpenseRestoreEvent.Success -> {
Snackbar.make(
binding.coordinatorLayout,
R.string.recurring_expense_restored_success_message,
Snackbar.LENGTH_LONG
).show()
}
}
}
lifecycleScope.launchCollect(viewModel.startCurrentBalanceEditorEventFlow) { currentBalance ->
val dialogView = layoutInflater.inflate(R.layout.dialog_adjust_balance, null)
val amountEditText = dialogView.findViewById<EditText>(R.id.balance_amount)
amountEditText.setText(
if (currentBalance == 0.0) "0" else CurrencyHelper.getFormattedAmountValue(
currentBalance
)
)
amountEditText.preventUnsupportedInputForDecimals()
amountEditText.setSelection(amountEditText.text.length) // Put focus at the end of the text
val builder = MaterialAlertDialogBuilder(this)
builder.setTitle(R.string.adjust_balance_title)
builder.setMessage(R.string.adjust_balance_message)
builder.setView(dialogView)
builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }
builder.setPositiveButton(R.string.ok) { dialog, _ ->
try {
val stringValue = amountEditText.text.toString()
if (stringValue.isNotBlank()) {
val newBalance = java.lang.Double.valueOf(stringValue)
viewModel.onNewBalanceSelected(
newBalance,
getString(R.string.adjust_balance_expense_title)
)
}
} catch (e: Exception) {
Logger.error("Error parsing new balance", e)
}
dialog.dismiss()
}
val dialog = builder.show()
// Directly show keyboard when the dialog pops
amountEditText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
// Check if the device doesn't have a physical keyboard
if (hasFocus && resources.configuration.keyboard == Configuration.KEYBOARD_NOKEYS) {
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
}
}
lifecycleScope.launchCollect(viewModel.currentBalanceEditingErrorEventFlow) {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.adjust_balance_error_title)
.setMessage(R.string.adjust_balance_error_message)
.setNegativeButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() }
.show()
}
lifecycleScope.launchCollect(viewModel.currentBalanceEditedEventFlow) { (expense, diff, newBalance) ->
//Show snackbar
val snackbar = Snackbar.make(
binding.coordinatorLayout,
resources.getString(
R.string.adjust_balance_snackbar_text,
CurrencyHelper.getFormattedCurrencyString(parameters, newBalance)
),
Snackbar.LENGTH_LONG
)
snackbar.setAction(R.string.undo) {
viewModel.onCurrentBalanceEditedCancelled(expense, diff)
}
snackbar.setActionTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.snackbar_action_undo
)
)
snackbar.duration = BaseTransientBottomBar.LENGTH_LONG
snackbar.show()
}
lifecycleScope.launchCollect(viewModel.currentBalanceRestoringErrorEventFlow) {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.adjust_balance_error_title)
.setMessage(R.string.adjust_balance_error_message)
.setNegativeButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() }
.show()
}
lifecycleScope.launchCollect(viewModel.premiumStatusFlow) {
invalidateOptionsMenu()
}
lifecycleScope.launchCollect(viewModel.selectedDateDataFlow) { (date, balance, maybeCheckedBalance, expenses) ->
refreshAllForDate(date, balance, maybeCheckedBalance, expenses)
}
lifecycleScope.launchCollect(viewModel.refreshDatesFlow) {
calendarFragment.refreshView()
}
lifecycleScope.launchCollect(viewModel.expenseCheckedErrorEventFlow) { exception ->
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.expense_check_error_title)
.setMessage(
getString(
R.string.expense_check_error_message,
exception.localizedMessage
)
)
.setNegativeButton(R.string.ok) { dialog2, _ -> dialog2.dismiss() }
.show()
}
lifecycleScope.launchCollect(viewModel.showGoToCurrentMonthButtonStateFlow) {
invalidateOptionsMenu()
}
lifecycleScope.launchCollect(viewModel.goBackToCurrentMonthEventFlow) {
calendarFragment.goToCurrentMonth()
}
lifecycleScope.launchCollect(viewModel.confirmCheckAllPastEntriesEventFlow) {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.check_all_past_expences_title)
.setMessage(getString(R.string.check_all_past_expences_message))
.setPositiveButton(R.string.check_all_past_expences_confirm_cta) { dialog2, _ ->
viewModel.onCheckAllPastEntriesConfirmPressed()
dialog2.dismiss()
}
.setNegativeButton(android.R.string.cancel) { dialog2, _ -> dialog2.dismiss() }
.show()
}
lifecycleScope.launchCollect(viewModel.checkAllPastEntriesErrorEventFlow) { error ->
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.check_all_past_expences_error_title)
.setMessage(
getString(
R.string.check_all_past_expences_error_message,
error.localizedMessage
)
)
.setNegativeButton(R.string.ok) { dialog2, _ -> dialog2.dismiss() }
.show()
}
}
private fun performIntentActionIfAny() {
if (intent != null) {
openSettingsIfNeeded(intent)
openMonthlyReportIfNeeded(intent)
openPremiumIfNeeded(intent)
openAddExpenseIfNeeded(intent)
openAddRecurringExpenseIfNeeded(intent)
openSettingsForBackupIfNeeded(intent)
}
}
private fun registerBroadcastReceiver() {
// Register receiver
val filter = IntentFilter()
filter.addAction(INTENT_EXPENSE_DELETED)
filter.addAction(INTENT_RECURRING_EXPENSE_DELETED)
filter.addAction(SelectCurrencyFragment.CURRENCY_SELECTED_INTENT)
filter.addAction(INTENT_SHOW_WELCOME_SCREEN)
filter.addAction(Intent.ACTION_VIEW)
filter.addAction(INTENT_IAB_STATUS_CHANGED)
filter.addAction(INTENT_SHOW_CHECKED_BALANCE_CHANGED)
filter.addAction(INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED)
LocalBroadcastManager.getInstance(applicationContext).registerReceiver(receiver, filter)
}
override fun onStart() {
super.onStart()
// If the last stop happened yesterday (or another day), set and refresh to the current date
if (lastStopDate != null) {
if (LocalDate.now() != lastStopDate) {
viewModel.onDayChanged()
}
lastStopDate = null
}
}
override fun onStop() {
lastStopDate = LocalDate.now()
super.onStop()
}
override fun onDestroy() {
LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(receiver)
super.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
calendarFragment.saveStatesToKey(outState, CALENDAR_SAVED_STATE)
super.onSaveInstanceState(outState)
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ADD_EXPENSE_ACTIVITY_CODE || requestCode == MANAGE_RECURRING_EXPENSE_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
viewModel.onExpenseAdded()
}
} else if (requestCode == WELCOME_SCREEN_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
viewModel.onWelcomeScreenFinished()
} else if (resultCode == RESULT_CANCELED) {
finish() // Finish activity if welcome screen is finish via back button
}
} else if (requestCode == SETTINGS_SCREEN_ACTIVITY_CODE) {
calendarFragment.setFirstDayOfWeek(parameters.getCaldroidFirstDayOfWeek())
}
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
/*if ( menu.isExpanded) {
menu.collapse()
} else {*/
super.onBackPressed()
//}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent == null) {
return
}
openSettingsIfNeeded(intent)
openMonthlyReportIfNeeded(intent)
openPremiumIfNeeded(intent)
openAddExpenseIfNeeded(intent)
openAddRecurringExpenseIfNeeded(intent)
openSettingsForBackupIfNeeded(intent)
}
// ------------------------------------------>
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
// Remove monthly report for non premium users
if ( !viewModel.premiumStatusFlow.value ) {
menu.removeItem(R.id.action_monthly_report)
menu.removeItem(R.id.action_check_all_past_entries)
} else if ( !parameters.hasUserSawMonthlyReportHint() ) {
binding.monthlyReportHint.visibility = View.VISIBLE
binding.monthlyReportHintButton.setOnClickListener {
binding.monthlyReportHint.visibility = View.GONE
parameters.setUserSawMonthlyReportHint()
}
}
// Remove back to today button if needed
if (!viewModel.showGoToCurrentMonthButtonStateFlow.value) {
menu.removeItem(R.id.action_go_to_current_month)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_settings -> {
val startIntent = Intent(this, SettingsActivity::class.java)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null)
return true
}
R.id.action_balance -> {
viewModel.onAdjustCurrentBalanceClicked()
return true
}
R.id.action_monthly_report -> {
val startIntent = Intent(this, MonthlyReportBaseActivity::class.java)
ActivityCompat.startActivity(this@MainActivity, startIntent, null)
return true
}
R.id.action_go_to_current_month -> {
viewModel.onGoBackToCurrentMonthButtonPressed()
return true
}
R.id.action_check_all_past_entries -> {
viewModel.onCheckAllPastEntriesPressed()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
// ------------------------------------------>
/**
* Update the balance for the given day
* TODO optimization
*/
private fun updateBalanceDisplayForDay(day: LocalDate, balance: Double, maybeCheckedBalance: Double?) {
val format = DateTimeFormatter.ofPattern(resources.getString(R.string.account_balance_date_format), Locale.getDefault())
var formatted = resources.getString(R.string.account_balance_format, format.format(day))
// FIXME it's ugly!!
if (formatted.endsWith(".:")) {
formatted = formatted.substring(0, formatted.length - 2) + ":" // Remove . at the end of the month (ex: nov.: -> nov:)
} else if (formatted.endsWith(". :")) {
formatted = formatted.substring(0, formatted.length - 3) + " :" // Remove . at the end of the month (ex: nov. : -> nov :)
}
binding.budgetLine.text = formatted
binding.budgetLineAmount.text = if (maybeCheckedBalance != null ) {
resources.getString(
R.string.account_balance_checked_format,
CurrencyHelper.getFormattedCurrencyString(parameters, balance),
CurrencyHelper.getFormattedCurrencyString(parameters, maybeCheckedBalance),
)
} else {
CurrencyHelper.getFormattedCurrencyString(parameters, balance)
}
binding.budgetLineAmount.setTextColor(ContextCompat.getColor(this, when {
balance <= 0 -> R.color.budget_red
balance < parameters.getLowMoneyWarningAmount() -> R.color.budget_orange
else -> R.color.budget_green
}))
}
/**
* Open the settings activity if the given intent contains the [.INTENT_REDIRECT_TO_SETTINGS_EXTRA]
* extra.
*/
private fun openSettingsIfNeeded(intent: Intent) {
if (intent.getBooleanExtra(INTENT_REDIRECT_TO_SETTINGS_EXTRA, false)) {
val startIntent = Intent(this, SettingsActivity::class.java)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null)
}
}
/**
* Open the settings activity to display backup options if the given intent contains the
* [.INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA] extra.
*/
private fun openSettingsForBackupIfNeeded(intent: Intent) {
if( intent.getBooleanExtra(INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA, false) ) {
val startIntent = Intent(this, SettingsActivity::class.java).apply {
putExtra(SHOW_BACKUP_INTENT_KEY, true)
}
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null)
}
}
/**
* Open the monthly report activity if the given intent contains the monthly uri part.
*
* @param intent
*/
private fun openMonthlyReportIfNeeded(intent: Intent) {
try {
val data = intent.data
if (data != null && "true" == data.getQueryParameter("monthly")) {
val startIntent = Intent(this, MonthlyReportBaseActivity::class.java)
startIntent.putExtra(MonthlyReportBaseActivity.FROM_NOTIFICATION_EXTRA, true)
ActivityCompat.startActivity(this@MainActivity, startIntent, null)
}
} catch (e: Exception) {
Logger.error("Error while opening report activity", e)
}
}
/**
* Open the premium screen if the given intent contains the [.INTENT_REDIRECT_TO_PREMIUM_EXTRA]
* extra.
*
* @param intent
*/
private fun openPremiumIfNeeded(intent: Intent) {
if (intent.getBooleanExtra(INTENT_REDIRECT_TO_PREMIUM_EXTRA, false)) {
val startIntent = Intent(this, SettingsActivity::class.java)
startIntent.putExtra(SettingsActivity.SHOW_PREMIUM_INTENT_KEY, true)
ActivityCompat.startActivityForResult(this, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null)
}
}
/**
* Open the add expense screen if the given intent contains the [.INTENT_SHOW_ADD_EXPENSE]
* extra.
*
* @param intent
*/
private fun openAddExpenseIfNeeded(intent: Intent) {
if (intent.getBooleanExtra(INTENT_SHOW_ADD_EXPENSE, false)) {
val startIntent = Intent(this, ExpenseEditActivity::class.java)
startIntent.putExtra("date", LocalDate.now().toEpochDay())
ActivityCompat.startActivityForResult(this, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null)
}
}
/**
* Open the add recurring expense screen if the given intent contains the [.INTENT_SHOW_ADD_RECURRING_EXPENSE]
* extra.
*
* @param intent
*/
private fun openAddRecurringExpenseIfNeeded(intent: Intent) {
if (intent.getBooleanExtra(INTENT_SHOW_ADD_RECURRING_EXPENSE, false)) {
val startIntent = Intent(this, RecurringExpenseEditActivity::class.java)
startIntent.putExtra("dateStart", LocalDate.now().toEpochDay())
ActivityCompat.startActivityForResult(this, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null)
}
}
// ------------------------------------------>
private fun initCalendarFragment(savedInstanceState: Bundle?) {
calendarFragment = CalendarFragment()
if (savedInstanceState != null && savedInstanceState.containsKey(CALENDAR_SAVED_STATE) ) {
calendarFragment.restoreStatesFromKey(savedInstanceState, CALENDAR_SAVED_STATE)
} else {
val args = Bundle()
val cal = Calendar.getInstance()
args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1)
args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR))
args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true)
args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, false)
args.putInt(CaldroidFragment.START_DAY_OF_WEEK, parameters.getCaldroidFirstDayOfWeek())
args.putBoolean(CaldroidFragment.ENABLE_CLICK_ON_DISABLED_DATES, false)
args.putInt(CaldroidFragment.THEME_RESOURCE, R.style.caldroid_style)
calendarFragment.arguments = args
calendarFragment.setMinDate((parameters.getInitDate() ?: LocalDate.now()).computeCalendarMinDateFromInitDate())
}
val listener = object : CaldroidListener() {
override fun onSelectDate(date: LocalDate, view: View) {
viewModel.onSelectDate(date)
}
override fun onLongClickDate(date: LocalDate, view: View?) // Add expense on long press
{
val startIntent = Intent(this@MainActivity, ExpenseEditActivity::class.java)
startIntent.putExtra("date", date.toEpochDay())
// Get the absolute location on window for Y value
val viewLocation = IntArray(2)
view!!.getLocationInWindow(viewLocation)
startIntent.putExtra(ANIMATE_TRANSITION_KEY, true)
startIntent.putExtra(CENTER_X_KEY, view.x.toInt() + view.width / 2)
startIntent.putExtra(CENTER_Y_KEY, viewLocation[1] + view.height / 2)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null)
}
override fun onChangeMonth(month: Int, year: Int) {
viewModel.onMonthChanged(month - 1, year)
}
override fun onCaldroidViewCreated() {
val viewPager = calendarFragment.dateViewPager
val leftButton = calendarFragment.leftArrowButton
val rightButton = calendarFragment.rightArrowButton
val textView = calendarFragment.monthTitleTextView
val weekDayGreedView = calendarFragment.weekdayGridView
val topLayout = this@MainActivity.findViewById<LinearLayout>(com.caldroid.R.id.calendar_title_view)
val params = textView.layoutParams as LinearLayout.LayoutParams
params.gravity = Gravity.TOP
params.setMargins(0, 0, 0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_month_text_padding_bottom))
textView.layoutParams = params
topLayout.setPadding(0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_month_padding_top), 0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_month_padding_bottom))
val leftButtonParams = leftButton.layoutParams as LinearLayout.LayoutParams
leftButtonParams.setMargins(this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_month_buttons_margin), 0, 0, 0)
leftButton.layoutParams = leftButtonParams
val rightButtonParams = rightButton.layoutParams as LinearLayout.LayoutParams
rightButtonParams.setMargins(0, 0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_month_buttons_margin), 0)
rightButton.layoutParams = rightButtonParams
textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_header_month_color))
topLayout.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_header_background))
leftButton.text = "<"
leftButton.textSize = 25f
leftButton.gravity = Gravity.CENTER
leftButton.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_month_button_color))
leftButton.setBackgroundResource(R.drawable.calendar_month_switcher_button_drawable)
rightButton.text = ">"
rightButton.textSize = 25f
rightButton.gravity = Gravity.CENTER
rightButton.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_month_button_color))
rightButton.setBackgroundResource(R.drawable.calendar_month_switcher_button_drawable)
weekDayGreedView.setPadding(0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_weekdays_padding_top), 0, this@MainActivity.resources.getDimensionPixelSize(R.dimen.calendar_weekdays_padding_bottom))
viewPager.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_background))
(viewPager.parent as View?)?.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_background))
}
}
calendarFragment.caldroidListener = listener
val t = supportFragmentManager.beginTransaction()
t.replace(R.id.calendarView, calendarFragment)
t.commit()
}
private fun initFab() {
isMenuExpended = binding.fabChoicesBackground.visibility == View.VISIBLE
binding.fabChoicesBackground.setOnClickListener { collapseMenu() }
binding.fabChoices.setOnClickListener {
if (isMenuExpended) {
collapseMenu()
} else {
expandMenu()
}
}
listOf(binding.fabNewExpense, binding.fabNewExpenseText).forEach {
it.setOnClickListener {
val startIntent = Intent(this@MainActivity, ExpenseEditActivity::class.java)
startIntent.putExtra("date", calendarFragment.getSelectedDate().toEpochDay())
startIntent.putExtra(ANIMATE_TRANSITION_KEY, true)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null)
collapseMenu()
}
}
listOf(binding.fabNewRecurringExpense, binding.fabNewRecurringExpenseText).forEach {
it.setOnClickListener {
val startIntent = Intent(this@MainActivity, RecurringExpenseEditActivity::class.java)
startIntent.putExtra("dateStart", calendarFragment.getSelectedDate().toEpochDay())
startIntent.putExtra(ANIMATE_TRANSITION_KEY, true)
ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null)
collapseMenu()
}
}
}
private fun initRecyclerView() {
binding.expensesRecyclerView.layoutManager = LinearLayoutManager(this)
expensesViewAdapter = ExpensesRecyclerViewAdapter(this, parameters, iab, LocalDate.now()) { expense, checked ->
viewModel.onExpenseChecked(expense, checked)
}
binding.expensesRecyclerView.adapter = expensesViewAdapter
}
private fun collapseMenu() {
isMenuExpended = false
menuExpandAnimation?.cancel()
menuCollapseAnimation?.cancel()
menuCollapseAnimation = AlphaAnimation(1.0f, 0.0f)
menuCollapseAnimation?.duration = menuBackgroundAnimationDuration
menuCollapseAnimation?.fillAfter = true
menuCollapseAnimation?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
binding.fabChoicesBackground.visibility = View.GONE
binding.fabChoicesBackground.isClickable = false
binding.fabNewRecurringExpenseContainer.isVisible = false
binding.fabNewExpenseContainer.isVisible = false
}
override fun onAnimationRepeat(animation: Animation) {
}
})
binding.fabChoicesBackground.startAnimation(menuCollapseAnimation)
binding.fabNewRecurringExpense.startAnimation(menuCollapseAnimation)
binding.fabNewRecurringExpenseText.startAnimation(menuCollapseAnimation)
binding.fabNewExpense.startAnimation(menuCollapseAnimation)
binding.fabNewExpenseText.startAnimation(menuCollapseAnimation)
}
private fun expandMenu() {
isMenuExpended = true
menuExpandAnimation?.cancel()
menuCollapseAnimation?.cancel()
menuExpandAnimation = AlphaAnimation(0.0f, 1.0f)
menuExpandAnimation?.duration = menuBackgroundAnimationDuration
menuExpandAnimation?.fillAfter = true
menuExpandAnimation?.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
binding.fabChoicesBackground.visibility = View.VISIBLE
binding.fabChoicesBackground.isClickable = true
binding.fabNewRecurringExpenseContainer.isVisible = true
binding.fabNewExpenseContainer.isVisible = true
}
override fun onAnimationEnd(animation: Animation) {
}
override fun onAnimationRepeat(animation: Animation) {
}
})
binding.fabChoicesBackground.startAnimation(menuExpandAnimation)
binding.fabNewRecurringExpense.startAnimation(menuExpandAnimation)
binding.fabNewRecurringExpenseText.startAnimation(menuExpandAnimation)
binding.fabNewExpense.startAnimation(menuExpandAnimation)
binding.fabNewExpenseText.startAnimation(menuExpandAnimation)
}
private fun refreshRecyclerViewForDate(date: LocalDate, expenses: List<Expense>) {
expensesViewAdapter.setDate(date, expenses)
if ( expenses.isNotEmpty() ) {
binding.expensesRecyclerView.visibility = View.VISIBLE
binding.emptyExpensesRecyclerViewPlaceholder.visibility = View.GONE
} else {
binding.expensesRecyclerView.visibility = View.GONE
binding.emptyExpensesRecyclerViewPlaceholder.visibility = View.VISIBLE
}
}
private fun refreshAllForDate(date: LocalDate, balance: Double, maybeCheckedBalance: Double?, expenses: List<Expense>) {
refreshRecyclerViewForDate(date, expenses)
updateBalanceDisplayForDay(date, balance, maybeCheckedBalance)
calendarFragment.setSelectedDate(date)
calendarFragment.refreshView()
}
/**
* Show a generic alert dialog telling the user an error occured while deleting recurring expense
*/
private fun showGenericRecurringDeleteErrorDialog() {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle(R.string.recurring_expense_delete_error_title)
.setMessage(R.string.recurring_expense_delete_error_message)
.setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
companion object {
const val ADD_EXPENSE_ACTIVITY_CODE = 101
const val MANAGE_RECURRING_EXPENSE_ACTIVITY_CODE = 102
const val WELCOME_SCREEN_ACTIVITY_CODE = 103
const val SETTINGS_SCREEN_ACTIVITY_CODE = 104
const val INTENT_EXPENSE_DELETED = "intent.expense.deleted"
const val INTENT_RECURRING_EXPENSE_DELETED = "intent.expense.monthly.deleted"
const val INTENT_SHOW_WELCOME_SCREEN = "intent.welcomscreen.show"
const val INTENT_SHOW_ADD_EXPENSE = "intent.addexpense.show"
const val INTENT_SHOW_ADD_RECURRING_EXPENSE = "intent.addrecurringexpense.show"
const val INTENT_SHOW_CHECKED_BALANCE_CHANGED = "intent.showcheckedbalance.changed"
const val INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED = "intent.lowmoneywarningthreshold.changed"
const val INTENT_REDIRECT_TO_PREMIUM_EXTRA = "intent.extra.premiumshow"
const val INTENT_REDIRECT_TO_SETTINGS_EXTRA = "intent.extra.redirecttosettings"
const val INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA = "intent.extra.redirecttosettingsforbackup"
const val ANIMATE_TRANSITION_KEY = "animate"
const val CENTER_X_KEY = "centerX"
const val CENTER_Y_KEY = "centerY"
private const val CALENDAR_SAVED_STATE = "calendar_saved_state"
}
} | apache-2.0 | 9c99bd7151629b82952b1d34485b2824 | 42.214868 | 232 | 0.643534 | 5.444003 | false | false | false | false |
Raizlabs/DBFlow | coroutines/src/main/kotlin/com/dbflow5/coroutines/Coroutines.kt | 1 | 6403 | package com.dbflow5.coroutines
import com.dbflow5.config.DBFlowDatabase
import com.dbflow5.query.Queriable
import com.dbflow5.structure.delete
import com.dbflow5.structure.insert
import com.dbflow5.structure.load
import com.dbflow5.structure.save
import com.dbflow5.structure.update
import com.dbflow5.transaction.FastStoreModelTransaction
import com.dbflow5.transaction.Transaction
import com.dbflow5.transaction.fastDelete
import com.dbflow5.transaction.fastInsert
import com.dbflow5.transaction.fastSave
import com.dbflow5.transaction.fastUpdate
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* Turns this [Transaction.Builder] into a [Deferred] object to use in coroutines.
*/
fun <R : Any?> Transaction.Builder<R>.defer(): Deferred<R> {
val deferred = CompletableDeferred<R>()
val transaction = success { _, result -> deferred.complete(result) }
.error { _, throwable -> deferred.completeExceptionally(throwable) }
.build()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
transaction.cancel()
}
}
transaction.execute()
return deferred
}
inline fun <R : Any?> constructCoroutine(continuation: CancellableContinuation<R>,
databaseDefinition: DBFlowDatabase,
crossinline fn: () -> R) {
val transaction = databaseDefinition.beginTransactionAsync { fn() }
.success { _, result -> continuation.resume(result) }
.error { _, throwable ->
if (continuation.isCancelled) return@error
continuation.resumeWithException(throwable)
}.build()
transaction.execute()
continuation.invokeOnCancellation {
if (continuation.isCancelled) {
transaction.cancel()
}
}
}
/**
* Description: Puts this [Queriable] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <Q : Queriable, R : Any?> Q.awaitTransact(
dbFlowDatabase: DBFlowDatabase,
crossinline queriableFunction: Q.(DBFlowDatabase) -> R) = suspendCancellableCoroutine<R> { continuation ->
com.dbflow5.coroutines.constructCoroutine(continuation, dbFlowDatabase) { queriableFunction(dbFlowDatabase) }
}
/**
* Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <reified M : Any> M.awaitSave(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation ->
constructCoroutine(continuation, databaseDefinition) { save(databaseDefinition) }
}
/**
* Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <reified M : Any> M.awaitInsert(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation ->
constructCoroutine(continuation, databaseDefinition) { insert(databaseDefinition) }
}
/**
* Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <reified M : Any> M.awaitDelete(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation ->
constructCoroutine(continuation, databaseDefinition) { delete(databaseDefinition) }
}
/**
* Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <reified M : Any> M.awaitUpdate(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation ->
constructCoroutine(continuation, databaseDefinition) { update(databaseDefinition) }
}
/**
* Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction]
* execute the db operation.
*/
suspend inline fun <reified M : Any> M.awaitLoad(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Unit> { continuation ->
constructCoroutine(continuation, databaseDefinition) { load(databaseDefinition) }
}
/**
* Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine.
*/
suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitSave(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation ->
constructFastCoroutine(continuation, databaseDefinition) { fastSave() }
}
/**
* Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine.
*/
suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitInsert(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation ->
constructFastCoroutine(continuation, databaseDefinition) { fastInsert() }
}
/**
* Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine.
*/
suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitUpdate(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation ->
constructFastCoroutine(continuation, databaseDefinition) { fastUpdate() }
}
/**
* Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine.
*/
suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitDelete(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation ->
constructFastCoroutine(continuation, databaseDefinition) { fastDelete() }
}
inline fun <R : Any?> constructFastCoroutine(continuation: CancellableContinuation<Long>,
databaseDefinition: DBFlowDatabase,
crossinline fn: () -> FastStoreModelTransaction.Builder<R>) {
val transaction = databaseDefinition.beginTransactionAsync(fn().build())
.success { _, result -> continuation.resume(result) }
.error { _, throwable ->
if (continuation.isCancelled) return@error
continuation.resumeWithException(throwable)
}.build()
transaction.execute()
continuation.invokeOnCancellation {
transaction.cancel()
}
} | mit | 1e3248e189542b716711ced3d3937106 | 41.131579 | 167 | 0.727159 | 5.014096 | false | false | false | false |
leafclick/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ContractInferenceIndex.kt | 1 | 7107 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.inference
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiMethod
import com.intellij.psi.impl.source.JavaLightStubBuilder
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.JavaElementType.*
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.gist.GistManager
import java.util.*
import kotlin.collections.HashMap
/**
* @author peter
*/
private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 12, MethodDataExternalizer) { file ->
indexFile(file.node.lighterAST)
}
private fun indexFile(tree: LighterAST): Map<Int, MethodData> {
val visitor = InferenceVisitor(tree)
visitor.visitNode(tree.root)
return visitor.result
}
internal data class ClassData(val hasSuper : Boolean, val hasPureInitializer : Boolean, val fieldModifiers : Map<String, LighterASTNode?>)
private class InferenceVisitor(val tree : LighterAST) : RecursiveLighterASTNodeWalkingVisitor(tree) {
var methodIndex = 0
val classData = HashMap<LighterASTNode, ClassData>()
val result = HashMap<Int, MethodData>()
override fun visitNode(element: LighterASTNode) {
when(element.tokenType) {
CLASS, ANONYMOUS_CLASS -> {
classData[element] = calcClassData(element)
}
METHOD -> {
calcData(element)?.let { data -> result[methodIndex] = data }
methodIndex++
}
}
if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return
super.visitNode(element)
}
private fun calcClassData(aClass: LighterASTNode) : ClassData {
var hasSuper = aClass.tokenType == ANONYMOUS_CLASS
val fieldModifiers = HashMap<String, LighterASTNode?>()
val initializers = ArrayList<LighterASTNode>()
for (child in tree.getChildren(aClass)) {
when(child.tokenType) {
EXTENDS_LIST -> {
if (LightTreeUtil.firstChildOfType(tree, child, JAVA_CODE_REFERENCE) != null) {
hasSuper = true
}
}
FIELD -> {
val fieldName = JavaLightTreeUtil.getNameIdentifierText(tree, child)
if (fieldName != null) {
val modifiers = LightTreeUtil.firstChildOfType(tree, child, MODIFIER_LIST)
fieldModifiers[fieldName] = modifiers
val isStatic = LightTreeUtil.firstChildOfType(tree, modifiers, JavaTokenType.STATIC_KEYWORD) != null
if (!isStatic) {
val initializer = JavaLightTreeUtil.findExpressionChild(tree, child)
if (initializer != null) {
initializers.add(initializer)
}
}
}
}
CLASS_INITIALIZER -> {
val modifiers = LightTreeUtil.firstChildOfType(tree, child, MODIFIER_LIST)
val isStatic = LightTreeUtil.firstChildOfType(tree, modifiers, JavaTokenType.STATIC_KEYWORD) != null
if (!isStatic) {
val body = LightTreeUtil.firstChildOfType(tree, child, CODE_BLOCK)
if (body != null) {
initializers.add(body)
}
}
}
}
}
var pureInitializer = true
if (initializers.isNotEmpty()) {
val visitor = PurityInferenceVisitor(tree, aClass, fieldModifiers, true)
for (initializer in initializers) {
walkMethodBody(initializer, visitor::visitNode)
val result = visitor.result
pureInitializer = result != null && result.singleCall == null && result.mutatedRefs.isEmpty()
if (!pureInitializer) break
}
}
return ClassData(hasSuper, pureInitializer, fieldModifiers)
}
private fun calcData(method: LighterASTNode): MethodData? {
val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null
val clsData = classData[tree.getParent(method)]
val fieldMap = clsData?.fieldModifiers ?: emptyMap()
// Constructor which has super classes may implicitly call impure super constructor, so don't infer purity for subclasses
val ctor = LightTreeUtil.firstChildOfType(tree, method, TYPE) == null
val maybeImpureCtor = ctor && (clsData == null || clsData.hasSuper || !clsData.hasPureInitializer)
val statements = ContractInferenceInterpreter.getStatements(body, tree)
val contractInference = ContractInferenceInterpreter(tree, method, body)
val contracts = contractInference.inferContracts(statements)
val nullityVisitor = MethodReturnInferenceVisitor(tree, contractInference.parameters, body)
val purityVisitor = PurityInferenceVisitor(tree, body, fieldMap, ctor)
for (statement in statements) {
walkMethodBody(statement) {
nullityVisitor.visitNode(it)
if (!maybeImpureCtor) {
purityVisitor.visitNode(it)
}
}
}
val notNullParams = inferNotNullParameters(tree, method, statements)
return createData(body, contracts, nullityVisitor.result, if (maybeImpureCtor) null else purityVisitor.result, notNullParams)
}
private fun walkMethodBody(root: LighterASTNode, processor: (LighterASTNode) -> Unit) {
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
override fun visitNode(element: LighterASTNode) {
val type = element.tokenType
if (type === CLASS || type === FIELD || type === METHOD || type === ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return
processor(element)
super.visitNode(element)
}
}.visitNode(root)
}
private fun createData(body: LighterASTNode,
contracts: List<PreContract>,
methodReturn: MethodReturnInferenceResult?,
purity: PurityInferenceResult?,
notNullParams: BitSet): MethodData? {
if (methodReturn == null && purity == null && contracts.isEmpty() && notNullParams.isEmpty) return null
return MethodData(methodReturn, purity, contracts, notNullParams, body.startOffset, body.endOffset)
}
}
fun getIndexedData(method: PsiMethodImpl): MethodData? {
val file = method.containingFile
val map = CachedValuesManager.getCachedValue(file) {
val fileData = gist.getFileData(file)
val result = hashMapOf<PsiMethod, MethodData>()
if (fileData != null) {
val spine = (file as PsiFileImpl).stubbedSpine
var methodIndex = 0
for (i in 0 until spine.stubCount) {
if (spine.getStubType(i) === METHOD) {
fileData[methodIndex]?.let { result[spine.getStubPsi(i) as PsiMethod] = it }
methodIndex++
}
}
}
CachedValueProvider.Result.create(result, file)
}
return map[method]
} | apache-2.0 | 4daf8f8208cb04f9ab18e3def60d473f | 39.617143 | 140 | 0.691853 | 4.728543 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/properties/kt2331.kt | 3 | 191 | class P {
var x : Int = 0
private set
fun foo() {
({ x = 4 })()
}
}
fun box() : String {
val p = P()
p.foo()
return if (p.x == 4) "OK" else "fail"
}
| apache-2.0 | 9bce3267583e26c0172786a7c7826002 | 12.642857 | 41 | 0.387435 | 2.808824 | false | false | false | false |
smmribeiro/intellij-community | plugins/editorconfig/src/org/editorconfig/language/services/impl/EditorConfigOptionDescriptorStorage.kt | 12 | 1981 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.services.impl
import com.intellij.psi.PsiElement
import com.intellij.util.containers.CollectionFactory
import org.editorconfig.language.schema.descriptors.impl.EditorConfigOptionDescriptor
import org.editorconfig.language.util.EditorConfigDescriptorUtil
class EditorConfigOptionDescriptorStorage(source: Iterable<EditorConfigOptionDescriptor>) {
val allDescriptors: List<EditorConfigOptionDescriptor>
private val descriptors: Map<String, List<EditorConfigOptionDescriptor>>
private val badDescriptors: List<EditorConfigOptionDescriptor>
init {
val allDescriptors = mutableListOf<EditorConfigOptionDescriptor>()
val descriptors = CollectionFactory.createCaseInsensitiveStringMap<MutableList<EditorConfigOptionDescriptor>>()
val badDescriptors = mutableListOf<EditorConfigOptionDescriptor>()
for (optionDescriptor in source) {
allDescriptors.add(optionDescriptor)
val constants = EditorConfigDescriptorUtil.collectConstants(optionDescriptor.key)
if (constants.isEmpty()) {
badDescriptors.add(optionDescriptor)
continue
}
for (constant in constants) {
var list = descriptors[constant]
if (list == null) {
list = mutableListOf()
descriptors[constant] = list
}
list.add(optionDescriptor)
}
}
this.allDescriptors = allDescriptors
this.descriptors = descriptors
this.badDescriptors = badDescriptors
}
operator fun get(key: PsiElement, parts: List<String>): EditorConfigOptionDescriptor? {
for (part in parts) {
val partDescriptors = descriptors[part] ?: continue
for (descriptor in partDescriptors) {
if (descriptor.key.matches(key)) return descriptor
}
}
return badDescriptors.firstOrNull { it.key.matches(key) }
}
}
| apache-2.0 | 594527415b6b44a3938b527742c55fd9 | 37.843137 | 140 | 0.746593 | 5.240741 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/nullability/NullabilityConstraintsCollector.kt | 6 | 2442 | // 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.nj2k.inference.nullability
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.nj2k.inference.common.*
import org.jetbrains.kotlin.nj2k.inference.common.collectors.ConstraintsCollector
import org.jetbrains.kotlin.psi.*
class NullabilityConstraintsCollector : ConstraintsCollector() {
override fun ConstraintBuilder.collectConstraints(
element: KtElement,
boundTypeCalculator: BoundTypeCalculator,
inferenceContext: InferenceContext,
resolutionFacade: ResolutionFacade
) {
when {
element is KtBinaryExpression &&
(element.left?.isNullExpression() == true
|| element.right?.isNullExpression() == true) -> {
val notNullOperand =
if (element.left?.isNullExpression() == true) element.right
else element.left
notNullOperand?.isTheSameTypeAs(State.UPPER, ConstraintPriority.COMPARE_WITH_NULL)
}
element is KtQualifiedExpression -> {
element.receiverExpression.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
element is KtForExpression -> {
element.loopRange?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
element is KtWhileExpressionBase -> {
element.condition?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
element is KtIfExpression -> {
element.condition?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
element is KtValueArgument && element.isSpread -> {
element.getArgumentExpression()?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
element is KtBinaryExpression && !KtPsiUtil.isAssignment(element) -> {
element.left?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
element.right?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER)
}
}
}
} | apache-2.0 | b2dc17076e5e2e5e6b74a449f2e61a0a | 46.901961 | 158 | 0.664619 | 5.48764 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/overloads.kt | 13 | 3597 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.util.SmartList
import com.intellij.util.containers.minimalElements
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.filterSameSignatureCandidates
import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability
import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability.canBeApplicable
import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability.inapplicable
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyOverloadResolver
/**
* Applicable results and a flag whether overload should be selected.
*
* There may be cases when we don't know types of arguments, so we cannot select a method 100% sure.
* Consider the example:
* ```
* def foo(Integer a) {}
* def foo(Number b) {}
* foo(unknownArgument)
* ```
* If we were to choose an overload with most specific signature, then only `foo(Integer)` would be chosen.
* In such case we assume both overloads as [potentially applicable][canBeApplicable]
* and offer navigation to both of them, etc.
*/
typealias ApplicabilitiesResult<X> = Pair<List<X>, Boolean>
fun <X> List<X>.filterApplicable(applicability: (X) -> Applicability): ApplicabilitiesResult<X> {
if (isEmpty()) {
return ApplicabilitiesResult(emptyList(), true)
}
val results = SmartList<X>()
var canSelectOverload = true
for (thing in this) {
val thingApplicability = applicability(thing)
if (thingApplicability == inapplicable) {
continue
}
if (thingApplicability == canBeApplicable) {
canSelectOverload = false
}
results += thing
}
return ApplicabilitiesResult(results, canSelectOverload)
}
fun List<GroovyMethodResult>.correctStaticScope(): List<GroovyMethodResult> {
if (isEmpty()) return emptyList()
return filterTo(SmartList()) {
it.isStaticsOK
}
}
private val overloadResolverEp = ExtensionPointName.create<GroovyOverloadResolver>("org.intellij.groovy.overloadResolver")
private fun compare(left: GroovyMethodResult, right: GroovyMethodResult): Int {
for (resolver in overloadResolverEp.extensions) {
val result = resolver.compare(left, right)
if (result != 0) {
return result
}
}
return 0
}
private val resultOverloadComparator: Comparator<GroovyMethodResult> = Comparator(::compare)
fun chooseOverloads(candidates: List<GroovyMethodResult>): List<GroovyMethodResult> {
return SmartList(candidates.minimalElements(resultOverloadComparator))
}
/**
* @return results that have the same numbers of parameters as passed arguments,
* or original results if it's not possible to compute arguments number or if there are no matching results
*/
fun filterByArgumentsCount(results: List<GroovyMethodResult>, arguments: Arguments?): List<GroovyMethodResult> {
val argumentsCount = arguments?.size ?: return results
val filtered = results.filterTo(SmartList()) {
it.element.parameterList.parametersCount == argumentsCount
}
return if (filtered.isEmpty()) results else filtered
}
fun filterBySignature(results: List<GroovyMethodResult>): List<GroovyMethodResult> {
if (results.size < 2) return results
@Suppress("UNCHECKED_CAST")
return filterSameSignatureCandidates(results).toList() as List<GroovyMethodResult>
}
| apache-2.0 | aece47cee2dd4f20a0007a2993fdbe19 | 38.527473 | 140 | 0.770364 | 4.354722 | false | false | false | false |
actions-on-google/app-actions-dynamic-shortcuts | app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/Task.kt | 1 | 1670 | /*
* Copyright (C) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.UUID
/**
* Immutable model class for a Task. In order to compile with Room, we can't use @JvmOverloads to
* generate multiple constructors.
*
* @param title title of the task
* @param description description of the task
* @param isCompleted whether or not this task is completed
* @param id id of the task
*/
@Entity(tableName = "tasks")
data class Task @JvmOverloads constructor(
@ColumnInfo(name = "title") var title: String = "",
@ColumnInfo(name = "description") var description: String = "",
@ColumnInfo(name = "completed") var isCompleted: Boolean = false,
@PrimaryKey @ColumnInfo(name = "entryid") var id: String = UUID.randomUUID().toString()
) {
val titleForList: String
get() = if (title.isNotEmpty()) title else description
val isActive
get() = !isCompleted
val isEmpty
get() = title.isEmpty() || description.isEmpty()
}
| apache-2.0 | 597064a253445a9fad5a5311e1883b61 | 33.791667 | 97 | 0.716766 | 4.206549 | false | false | false | false |
Javran/leetcode | integer-to-roman/Solution.kt | 1 | 1127 | class Solution {
fun toRomanAux(one: Char, five: Char, ten: Char): (Int) -> List<Char> = {
/* n: 0~9 */
n : Int ->
when (n) {
in 0..3 -> List(n) { one }
4 -> listOf(one, five)
in 5..8 -> listOf(five) + List(n-5) { one }
9 -> listOf(one, ten)
else -> throw IllegalArgumentException("Unexpected input")
}
}
fun intToRoman(num: Int): String {
val numDs = num % 10
val numTs = (num % 100 - numDs) / 10
val numHs = (num % 1000 - numTs*10 - numDs) / 100
val numKs = (num % 10000 - numHs * 100 - numTs*10 - numDs) / 1000
val rKs = toRomanAux('M','?','?')(numKs)
val rHs = toRomanAux('C','D','M')(numHs)
val rTs = toRomanAux('X','L','C')(numTs)
val rDs = toRomanAux('I','V','X')(numDs)
return (rKs + rHs + rTs + rDs).joinToString("")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(Solution().intToRoman(3) == "III")
println(Solution().intToRoman(1994) == "MCMXCIV")
}
}
}
| mit | 75bfeced5eed89e169fd40879443c194 | 33.151515 | 77 | 0.483585 | 3.276163 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/draw/base_api/Practice3RectView.kt | 1 | 1251 | package com.zeke.demo.draw.base_api
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import com.zeke.demo.base.BasePracticeView
import com.zeke.kangaroo.utils.UIUtils
class Practice3RectView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BasePracticeView(context, attrs, defStyleAttr) {
var rect = Rect(50, 50, 500, 350)
private var rectF_Inner = RectF(100f, 100f, 450f, 300f)
private var rectF = RectF(550f, 50f, 1000f, 350f)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas
)
//练习内容:使用 canvas.drawRect() 方法画矩形
//练习内容:使用 canvas.drawRoundRect() 方法画圆角矩形
paint.style = Paint.Style.STROKE
paint.color = Color.BLACK
paint.strokeWidth = UIUtils.px2dip(context, 30f).toFloat()
canvas.drawRect(rect, paint)
paint.style = Paint.Style.FILL
paint.color = Color.MAGENTA
canvas.drawRoundRect(rectF_Inner, 60f, 60f, paint)
paint.style = Paint.Style.STROKE
canvas.drawRoundRect(rectF, 40f, 40f, paint)
}
override fun getViewHeight(): Int {
return 400
}
}
| gpl-2.0 | 32df9ad2bee62b2357d9edbfd6a4f3b2 | 30.552632 | 76 | 0.676397 | 3.622356 | false | false | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/adapters/ManageBlockedNumbersAdapter.kt | 1 | 5108 | package com.simplemobiletools.commons.adapters
import android.content.Context
import android.view.*
import android.widget.PopupMenu
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.copyToClipboard
import com.simplemobiletools.commons.extensions.deleteBlockedNumber
import com.simplemobiletools.commons.extensions.getPopupMenuTheme
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
import com.simplemobiletools.commons.models.BlockedNumber
import com.simplemobiletools.commons.views.MyRecyclerView
import kotlinx.android.synthetic.main.item_manage_blocked_number.view.*
class ManageBlockedNumbersAdapter(
activity: BaseSimpleActivity, var blockedNumbers: ArrayList<BlockedNumber>, val listener: RefreshRecyclerViewListener?,
recyclerView: MyRecyclerView, itemClick: (Any) -> Unit
) : MyRecyclerViewAdapter(activity, recyclerView, itemClick) {
init {
setupDragListener(true)
}
override fun getActionMenuId() = R.menu.cab_blocked_numbers
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_copy_number).isVisible = isOneItemSelected()
}
}
override fun actionItemPressed(id: Int) {
if (selectedKeys.isEmpty()) {
return
}
when (id) {
R.id.cab_copy_number -> copyNumberToClipboard()
R.id.cab_delete -> deleteSelection()
}
}
override fun getSelectableItemCount() = blockedNumbers.size
override fun getIsItemSelectable(position: Int) = true
override fun getItemSelectionKey(position: Int) = blockedNumbers.getOrNull(position)?.id?.toInt()
override fun getItemKeyPosition(key: Int) = blockedNumbers.indexOfFirst { it.id.toInt() == key }
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_manage_blocked_number, parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val blockedNumber = blockedNumbers[position]
holder.bindView(blockedNumber, true, true) { itemView, _ ->
setupView(itemView, blockedNumber)
}
bindViewHolder(holder)
}
override fun getItemCount() = blockedNumbers.size
private fun getSelectedItems() = blockedNumbers.filter { selectedKeys.contains(it.id.toInt()) } as ArrayList<BlockedNumber>
private fun setupView(view: View, blockedNumber: BlockedNumber) {
view.apply {
manage_blocked_number_holder?.isSelected = selectedKeys.contains(blockedNumber.id.toInt())
manage_blocked_number_title.apply {
text = blockedNumber.number
setTextColor(textColor)
}
overflow_menu_icon.drawable.apply {
mutate()
setTint(activity.getProperTextColor())
}
overflow_menu_icon.setOnClickListener {
showPopupMenu(overflow_menu_anchor, blockedNumber)
}
}
}
private fun showPopupMenu(view: View, blockedNumber: BlockedNumber) {
finishActMode()
val theme = activity.getPopupMenuTheme()
val contextTheme = ContextThemeWrapper(activity, theme)
PopupMenu(contextTheme, view, Gravity.END).apply {
inflate(getActionMenuId())
setOnMenuItemClickListener { item ->
val blockedNumberId = blockedNumber.id.toInt()
when (item.itemId) {
R.id.cab_copy_number -> {
executeItemMenuOperation(blockedNumberId) {
copyNumberToClipboard()
}
}
R.id.cab_delete -> {
executeItemMenuOperation(blockedNumberId) {
deleteSelection()
}
}
}
true
}
show()
}
}
private fun executeItemMenuOperation(blockedNumberId: Int, callback: () -> Unit) {
selectedKeys.add(blockedNumberId)
callback()
selectedKeys.remove(blockedNumberId)
}
private fun copyNumberToClipboard() {
val selectedNumber = getSelectedItems().firstOrNull() ?: return
activity.copyToClipboard(selectedNumber.number)
finishActMode()
}
private fun deleteSelection() {
val deleteBlockedNumbers = ArrayList<BlockedNumber>(selectedKeys.size)
val positions = getSelectedItemPositions()
getSelectedItems().forEach {
deleteBlockedNumbers.add(it)
activity.deleteBlockedNumber(it.number)
}
blockedNumbers.removeAll(deleteBlockedNumbers)
removeSelectedItems(positions)
if (blockedNumbers.isEmpty()) {
listener?.refreshItems()
}
}
}
| gpl-3.0 | 9012f79a212e3e5ac041bbda0b3d4994 | 34.72028 | 133 | 0.654268 | 5.393875 | false | false | false | false |
androidx/androidx | wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/DemoComponents.kt | 3 | 5630 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.demos
import android.app.Activity
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.LocalContentAlpha
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.SwipeToDismissBoxState
import androidx.wear.compose.material.Text
import kotlin.reflect.KClass
/**
* Generic demo with a [title] that will be displayed in the list of demos.
*/
sealed class Demo(val title: String, val description: String? = null) {
override fun toString() = title
}
/**
* Demo that launches an [Activity] when selected.
*
* This should only be used for demos that need to customize the activity, the large majority of
* demos should just use [ComposableDemo] instead.
*
* @property activityClass the KClass (Foo::class) of the activity that will be launched when
* this demo is selected.
*/
class ActivityDemo<T : ComponentActivity>(title: String, val activityClass: KClass<T>) : Demo(title)
/**
* A category of [Demo]s, that will display a list of [demos] when selected.
*/
class DemoCategory(
title: String,
val demos: List<Demo>
) : Demo(title)
/**
* Parameters which are used by [Demo] screens.
*/
class DemoParameters(
val navigateBack: () -> Unit,
val swipeToDismissBoxState: SwipeToDismissBoxState
)
/**
* Demo that displays [Composable] [content] when selected,
* with a method to navigate back to the parent.
*/
class ComposableDemo(
title: String,
description: String? = null,
val content: @Composable (params: DemoParameters) -> Unit,
) : Demo(title, description)
/**
* A simple [Icon] with default size
*/
@Composable
fun DemoIcon(
resourceId: Int,
modifier: Modifier = Modifier,
size: Dp = 24.dp,
contentDescription: String? = null,
) {
Icon(
painter = painterResource(id = resourceId),
contentDescription = contentDescription,
modifier = modifier
.size(size)
.wrapContentSize(align = Alignment.Center),
)
}
@Composable
fun DemoImage(
resourceId: Int,
modifier: Modifier = Modifier,
size: Dp = 24.dp,
) {
Image(
painter = painterResource(id = resourceId),
contentDescription = null,
modifier = modifier.size(size),
contentScale = ContentScale.Crop,
alpha = LocalContentAlpha.current
)
}
@Composable
fun TextIcon(
text: String,
size: Dp = 24.dp,
style: TextStyle = MaterialTheme.typography.title2
) {
Button(
modifier = Modifier
.padding(0.dp)
.requiredSize(32.dp),
onClick = {},
colors = ButtonDefaults.buttonColors(
disabledBackgroundColor = MaterialTheme.colors.primary.copy(
alpha = LocalContentAlpha.current
),
disabledContentColor = MaterialTheme.colors.onPrimary.copy(
alpha = LocalContentAlpha.current
)
),
enabled = false
) {
Box(
modifier = Modifier
.padding(all = 0.dp)
.requiredSize(size)
.wrapContentSize(align = Alignment.Center)
) {
Text(
text = text,
textAlign = TextAlign.Center,
color = MaterialTheme.colors.onPrimary.copy(alpha = LocalContentAlpha.current),
style = style,
)
}
}
}
@Composable
fun Centralize(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
content = content
)
}
public val DemoListTag = "DemoListTag"
public val AlternatePrimaryColor1 = Color(0x7F, 0xCF, 0xFF)
public val AlternatePrimaryColor2 = Color(0xD0, 0xBC, 0xFF)
public val AlternatePrimaryColor3 = Color(0x6D, 0xD5, 0x8C)
| apache-2.0 | c0cb7428f4a1f3b3942c9e9e219fc8d7 | 30.452514 | 100 | 0.704973 | 4.35085 | false | false | false | false |
kotlinx/kotlinx.html | src/commonMain/kotlin/generated/gen-tag-unions.kt | 1 | 36117 | package kotlinx.html
import kotlinx.html.*
import kotlinx.html.impl.*
import kotlinx.html.attributes.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
interface FlowOrMetaDataOrPhrasingContent : Tag {
}
interface FlowOrHeadingContent : Tag {
}
interface FlowOrMetaDataContent : FlowOrMetaDataOrPhrasingContent, Tag {
}
interface FlowOrInteractiveContent : FlowOrInteractiveOrPhrasingContent, Tag {
}
interface FlowOrPhrasingContent : FlowOrInteractiveOrPhrasingContent, FlowOrMetaDataOrPhrasingContent, Tag {
}
interface SectioningOrFlowContent : Tag {
}
interface FlowOrInteractiveOrPhrasingContent : Tag {
}
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.command(type : CommandType? = null, classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", type?.enumEncode(),"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.commandCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.command.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.checkBoxCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.checkBox.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.radioCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.radio.realValue,"class", classes), consumer).visit(block)
/**
* A media-independent link
*/
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.link(href : String? = null, rel : String? = null, type : String? = null, crossinline block : LINK.() -> Unit = {}) : Unit = LINK(attributesMapOf("href", href,"rel", rel,"type", type), consumer).visit(block)
/**
* Generic metainformation
*/
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.meta(name : String? = null, content : String? = null, charset : String? = null, crossinline block : META.() -> Unit = {}) : Unit = META(attributesMapOf("name", name,"content", content,"charset", charset), consumer).visit(block)
/**
* Generic metainformation
*/
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.noScript(classes : String? = null, crossinline block : NOSCRIPT.() -> Unit = {}) : Unit = NOSCRIPT(attributesMapOf("class", classes), consumer).visit(block)
/**
* Script statements
*/
@HtmlTagMarker
inline fun FlowOrMetaDataOrPhrasingContent.script(type : String? = null, src : String? = null, crossinline block : SCRIPT.() -> Unit = {}) : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit(block)
@Deprecated("This tag doesn't support content or requires unsafe (try unsafe {})")
@Suppress("DEPRECATION")
/**
* Script statements
*/
@HtmlTagMarker
fun FlowOrMetaDataOrPhrasingContent.script(type : String? = null, src : String? = null, content : String = "") : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit({+content})
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h1(classes : String? = null, crossinline block : H1.() -> Unit = {}) : Unit = H1(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h2(classes : String? = null, crossinline block : H2.() -> Unit = {}) : Unit = H2(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h3(classes : String? = null, crossinline block : H3.() -> Unit = {}) : Unit = H3(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h4(classes : String? = null, crossinline block : H4.() -> Unit = {}) : Unit = H4(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h5(classes : String? = null, crossinline block : H5.() -> Unit = {}) : Unit = H5(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun FlowOrHeadingContent.h6(classes : String? = null, crossinline block : H6.() -> Unit = {}) : Unit = H6(attributesMapOf("class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrHeadingContent.hGroup(classes : String? = null, crossinline block : HGROUP.() -> Unit = {}) : Unit = HGROUP(attributesMapOf("class", classes), consumer).visit(block)
/**
* Style info
*/
@HtmlTagMarker
inline fun FlowOrMetaDataContent.style(type : String? = null, crossinline block : STYLE.() -> Unit = {}) : Unit = STYLE(attributesMapOf("type", type), consumer).visit(block)
@Deprecated("This tag doesn't support content or requires unsafe (try unsafe {})")
@Suppress("DEPRECATION")
/**
* Style info
*/
@HtmlTagMarker
fun FlowOrMetaDataContent.style(type : String? = null, content : String = "") : Unit = STYLE(attributesMapOf("type", type), consumer).visit({+content})
/**
* Disclosure control for hiding details
*/
@HtmlTagMarker
inline fun FlowOrInteractiveContent.details(classes : String? = null, crossinline block : DETAILS.() -> Unit = {}) : Unit = DETAILS(attributesMapOf("class", classes), consumer).visit(block)
/**
* Abbreviated form (e.g., WWW, HTTP,etc.)
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.abbr(classes : String? = null, crossinline block : ABBR.() -> Unit = {}) : Unit = ABBR(attributesMapOf("class", classes), consumer).visit(block)
/**
* Client-side image map area
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.area(shape : AreaShape? = null, alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", shape?.enumEncode(),"alt", alt,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.rectArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.rect.realValue,"alt", alt,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.circleArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.circle.realValue,"alt", alt,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.polyArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.poly.realValue,"alt", alt,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.defaultArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.default.realValue,"alt", alt,"class", classes), consumer).visit(block)
/**
* Bold text style
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.b(classes : String? = null, crossinline block : B.() -> Unit = {}) : Unit = B(attributesMapOf("class", classes), consumer).visit(block)
/**
* Text directionality isolation
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.bdi(classes : String? = null, crossinline block : BDI.() -> Unit = {}) : Unit = BDI(attributesMapOf("class", classes), consumer).visit(block)
/**
* I18N BiDi over-ride
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.bdo(classes : String? = null, crossinline block : BDO.() -> Unit = {}) : Unit = BDO(attributesMapOf("class", classes), consumer).visit(block)
/**
* Forced line break
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.br(classes : String? = null, crossinline block : BR.() -> Unit = {}) : Unit = BR(attributesMapOf("class", classes), consumer).visit(block)
/**
* Scriptable bitmap canvas
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.canvas(classes : String? = null, crossinline block : CANVAS.() -> Unit = {}) : Unit = CANVAS(attributesMapOf("class", classes), consumer).visit(block)
/**
* Scriptable bitmap canvas
*/
@HtmlTagMarker
fun FlowOrPhrasingContent.canvas(classes : String? = null, content : String = "") : Unit = CANVAS(attributesMapOf("class", classes), consumer).visit({+content})
/**
* Citation
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.cite(classes : String? = null, crossinline block : CITE.() -> Unit = {}) : Unit = CITE(attributesMapOf("class", classes), consumer).visit(block)
/**
* Computer code fragment
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.code(classes : String? = null, crossinline block : CODE.() -> Unit = {}) : Unit = CODE(attributesMapOf("class", classes), consumer).visit(block)
/**
* Container for options for
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.dataList(classes : String? = null, crossinline block : DATALIST.() -> Unit = {}) : Unit = DATALIST(attributesMapOf("class", classes), consumer).visit(block)
/**
* Deleted text
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.del(classes : String? = null, crossinline block : DEL.() -> Unit = {}) : Unit = DEL(attributesMapOf("class", classes), consumer).visit(block)
/**
* Instance definition
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.dfn(classes : String? = null, crossinline block : DFN.() -> Unit = {}) : Unit = DFN(attributesMapOf("class", classes), consumer).visit(block)
/**
* Emphasis
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.em(classes : String? = null, crossinline block : EM.() -> Unit = {}) : Unit = EM(attributesMapOf("class", classes), consumer).visit(block)
/**
* Italic text style
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.i(classes : String? = null, crossinline block : I.() -> Unit = {}) : Unit = I(attributesMapOf("class", classes), consumer).visit(block)
/**
* Inserted text
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.ins(classes : String? = null, crossinline block : INS.() -> Unit = {}) : Unit = INS(attributesMapOf("class", classes), consumer).visit(block)
/**
* Text to be entered by the user
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.kbd(classes : String? = null, crossinline block : KBD.() -> Unit = {}) : Unit = KBD(attributesMapOf("class", classes), consumer).visit(block)
/**
* Client-side image map
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.map(name : String? = null, classes : String? = null, crossinline block : MAP.() -> Unit = {}) : Unit = MAP(attributesMapOf("name", name,"class", classes), consumer).visit(block)
/**
* Highlight
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.mark(classes : String? = null, crossinline block : MARK.() -> Unit = {}) : Unit = MARK(attributesMapOf("class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.math(classes : String? = null, crossinline block : MATH.() -> Unit = {}) : Unit = MATH(attributesMapOf("class", classes), consumer).visit(block)
/**
* Gauge
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.meter(classes : String? = null, crossinline block : METER.() -> Unit = {}) : Unit = METER(attributesMapOf("class", classes), consumer).visit(block)
/**
* Calculated output value
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.output(classes : String? = null, crossinline block : OUTPUT.() -> Unit = {}) : Unit = OUTPUT(attributesMapOf("class", classes), consumer).visit(block)
/**
* Progress bar
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.progress(classes : String? = null, crossinline block : PROGRESS.() -> Unit = {}) : Unit = PROGRESS(attributesMapOf("class", classes), consumer).visit(block)
/**
* Short inline quotation
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.q(classes : String? = null, crossinline block : Q.() -> Unit = {}) : Unit = Q(attributesMapOf("class", classes), consumer).visit(block)
/**
* Ruby annotation(s)
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.ruby(classes : String? = null, crossinline block : RUBY.() -> Unit = {}) : Unit = RUBY(attributesMapOf("class", classes), consumer).visit(block)
/**
* Strike-through text style
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.samp(classes : String? = null, crossinline block : SAMP.() -> Unit = {}) : Unit = SAMP(attributesMapOf("class", classes), consumer).visit(block)
/**
* Small text style
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.small(classes : String? = null, crossinline block : SMALL.() -> Unit = {}) : Unit = SMALL(attributesMapOf("class", classes), consumer).visit(block)
/**
* Generic language/style container
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.span(classes : String? = null, crossinline block : SPAN.() -> Unit = {}) : Unit = SPAN(attributesMapOf("class", classes), consumer).visit(block)
/**
* Strong emphasis
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.strong(classes : String? = null, crossinline block : STRONG.() -> Unit = {}) : Unit = STRONG(attributesMapOf("class", classes), consumer).visit(block)
/**
* Subscript
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.sub(classes : String? = null, crossinline block : SUB.() -> Unit = {}) : Unit = SUB(attributesMapOf("class", classes), consumer).visit(block)
/**
* Superscript
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.sup(classes : String? = null, crossinline block : SUP.() -> Unit = {}) : Unit = SUP(attributesMapOf("class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.svg(classes : String? = null, crossinline block : SVG.() -> Unit = {}) : Unit = SVG(attributesMapOf("class", classes), consumer).visit(block)
@HtmlTagMarker
fun FlowOrPhrasingContent.svg(classes : String? = null, content : String = "") : Unit = SVG(attributesMapOf("class", classes), consumer).visit({+content})
/**
* Machine-readable equivalent of date- or time-related data
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.time(classes : String? = null, crossinline block : TIME.() -> Unit = {}) : Unit = TIME(attributesMapOf("class", classes), consumer).visit(block)
/**
* Unordered list
*/
@HtmlTagMarker
inline fun FlowOrPhrasingContent.htmlVar(classes : String? = null, crossinline block : VAR.() -> Unit = {}) : Unit = VAR(attributesMapOf("class", classes), consumer).visit(block)
/**
* Self-contained syndicatable or reusable composition
*/
@HtmlTagMarker
inline fun SectioningOrFlowContent.article(classes : String? = null, crossinline block : ARTICLE.() -> Unit = {}) : Unit = ARTICLE(attributesMapOf("class", classes), consumer).visit(block)
/**
* Sidebar for tangentially related content
*/
@HtmlTagMarker
inline fun SectioningOrFlowContent.aside(classes : String? = null, crossinline block : ASIDE.() -> Unit = {}) : Unit = ASIDE(attributesMapOf("class", classes), consumer).visit(block)
/**
* Container for the dominant contents of another element
*/
@HtmlTagMarker
inline fun SectioningOrFlowContent.main(classes : String? = null, crossinline block : MAIN.() -> Unit = {}) : Unit = MAIN(attributesMapOf("class", classes), consumer).visit(block)
/**
* Section with navigational links
*/
@HtmlTagMarker
inline fun SectioningOrFlowContent.nav(classes : String? = null, crossinline block : NAV.() -> Unit = {}) : Unit = NAV(attributesMapOf("class", classes), consumer).visit(block)
/**
* Generic document or application section
*/
@HtmlTagMarker
inline fun SectioningOrFlowContent.section(classes : String? = null, crossinline block : SECTION.() -> Unit = {}) : Unit = SECTION(attributesMapOf("class", classes), consumer).visit(block)
/**
* Anchor
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.a(href : String? = null, target : String? = null, classes : String? = null, crossinline block : A.() -> Unit = {}) : Unit = A(attributesMapOf("href", href,"target", target,"class", classes), consumer).visit(block)
/**
* Audio player
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.audio(classes : String? = null, crossinline block : AUDIO.() -> Unit = {}) : Unit = AUDIO(attributesMapOf("class", classes), consumer).visit(block)
/**
* Push button
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.button(formEncType : ButtonFormEncType? = null, formMethod : ButtonFormMethod? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.getButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.get.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.postButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.post.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
@Suppress("DEPRECATION")
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.putButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.put.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
@Suppress("DEPRECATION")
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.deleteButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.delete.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
@Suppress("DEPRECATION")
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.patchButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.patch.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block)
/**
* Plugin
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.embed(classes : String? = null, crossinline block : EMBED.() -> Unit = {}) : Unit = EMBED(attributesMapOf("class", classes), consumer).visit(block)
/**
* Inline subwindow
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.iframe(sandbox : IframeSandbox? = null, classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", sandbox?.enumEncode(),"class", classes), consumer).visit(block)
/**
* Inline subwindow
*/
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.iframe(sandbox : IframeSandbox? = null, classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", sandbox?.enumEncode(),"class", classes), consumer).visit({+content})
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.allowSameOriginIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowSameOrigin.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.allowFormSIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowFormS.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.allowScriptsIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowScripts.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.allowSameOriginIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowSameOrigin.realValue,"class", classes), consumer).visit({+content})
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.allowFormSIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowFormS.realValue,"class", classes), consumer).visit({+content})
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.allowScriptsIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowScripts.realValue,"class", classes), consumer).visit({+content})
/**
* Embedded image
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.img(alt : String? = null, src : String? = null, classes : String? = null, crossinline block : IMG.() -> Unit = {}) : Unit = IMG(attributesMapOf("alt", alt,"src", src,"class", classes), consumer).visit(block)
/**
* Pictures container
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.picture(crossinline block : PICTURE.() -> Unit = {}) : Unit = PICTURE(emptyMap, consumer).visit(block)
/**
* Form control
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.input(type : InputType? = null, formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", type?.enumEncode(),"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.buttonInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.button.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.checkBoxInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.checkBox.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.colorInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.color.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.dateInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.date.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.dateTimeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.dateTime.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.dateTimeLocalInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.dateTimeLocal.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.emailInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.email.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.fileInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.file.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.hiddenInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.hidden.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.imageInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.image.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.monthInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.month.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.numberInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.number.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.passwordInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.password.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.radioInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.radio.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.rangeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.range.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.resetInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.reset.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.searchInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.search.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.submitInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.submit.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.textInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.text.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.telInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.tel.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.timeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.time.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.urlInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.url.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.weekInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.week.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block)
/**
* Cryptographic key-pair generator form control
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.keyGen(keyType : KeyGenKeyType? = null, classes : String? = null, crossinline block : KEYGEN.() -> Unit = {}) : Unit = KEYGEN(attributesMapOf("keytype", keyType?.enumEncode(),"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.rsaKeyGen(classes : String? = null, crossinline block : KEYGEN.() -> Unit = {}) : Unit = KEYGEN(attributesMapOf("keytype", KeyGenKeyType.rsa.realValue,"class", classes), consumer).visit(block)
/**
* Form field label text
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.label(classes : String? = null, crossinline block : LABEL.() -> Unit = {}) : Unit = LABEL(attributesMapOf("class", classes), consumer).visit(block)
/**
* Generic embedded object
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.htmlObject(classes : String? = null, crossinline block : OBJECT.() -> Unit = {}) : Unit = OBJECT(attributesMapOf("class", classes), consumer).visit(block)
/**
* Option selector
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.select(classes : String? = null, crossinline block : SELECT.() -> Unit = {}) : Unit = SELECT(attributesMapOf("class", classes), consumer).visit(block)
/**
* Multi-line text field
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.textArea(rows : String? = null, cols : String? = null, wrap : TextAreaWrap? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", wrap?.enumEncode(),"class", classes), consumer).visit(block)
/**
* Multi-line text field
*/
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.textArea(rows : String? = null, cols : String? = null, wrap : TextAreaWrap? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", wrap?.enumEncode(),"class", classes), consumer).visit({+content})
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.hardTextArea(rows : String? = null, cols : String? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.hard.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.softTextArea(rows : String? = null, cols : String? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.soft.realValue,"class", classes), consumer).visit(block)
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.hardTextArea(rows : String? = null, cols : String? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.hard.realValue,"class", classes), consumer).visit({+content})
@HtmlTagMarker
fun FlowOrInteractiveOrPhrasingContent.softTextArea(rows : String? = null, cols : String? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.soft.realValue,"class", classes), consumer).visit({+content})
/**
* Video player
*/
@HtmlTagMarker
inline fun FlowOrInteractiveOrPhrasingContent.video(classes : String? = null, crossinline block : VIDEO.() -> Unit = {}) : Unit = VIDEO(attributesMapOf("class", classes), consumer).visit(block)
| apache-2.0 | 4486d5e6e669cd4d5d249a544b1e733a | 64.548094 | 446 | 0.72866 | 4.549314 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/src/org/jetbrains/completion/full/line/platform/ProposalFilters.kt | 2 | 2878 | package org.jetbrains.completion.full.line.platform
import org.jetbrains.completion.full.line.AnalyzedFullLineProposal
import org.jetbrains.completion.full.line.ProposalsFilter
import org.jetbrains.completion.full.line.RawFullLineProposal
import kotlin.math.min
object RedCodeFilter : ProposalsFilter.Adapter("red code") {
override fun checkAnalyzedFullLine(proposal: AnalyzedFullLineProposal): Boolean {
return proposal.refCorrectness.isCorrect()
}
}
class SameAsPrefixFilter(private val prefix: String) : ProposalsFilter.Adapter("same as prefix") {
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return proposal.suggestion != prefix
}
}
object ProhibitedWordsFilter : ProposalsFilter.Adapter("prohibited words") {
private val prohibited = listOf(
"龖", "#", "print ", "BOS", "<PAD>", "<EOS>", "<UNK>"
)
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return prohibited.none { proposal.suggestion.contains(it) }
}
}
object SemanticFilter : ProposalsFilter.Adapter("doesn't make sense") {
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return proposal.suggestion.find { it.isJavaIdentifierPart() || it.isDigit() } != null
}
}
object EmptyStringFilter : ProposalsFilter.Adapter("empty") {
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return proposal.suggestion.isNotEmpty()
}
}
object ScoreFilter : ProposalsFilter.Adapter("low score") {
private const val scoreThreshold: Double = 0.1
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return proposal.score > scoreThreshold
}
}
object ASCIIFilter : ProposalsFilter.Adapter("non-ACII symbols") {
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
return proposal.suggestion.toCharArray().none { it < ' ' || it > '~' }
}
}
// Do not find repetition in sub-strings, only if whole string is repetition
object RepetitionFilter : ProposalsFilter.Adapter("repetition") {
private const val repetition = 3
override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean {
val zArr = zFunction(proposal.suggestion)
return !findRepetition(zArr)
}
private fun findRepetition(arr: IntArray): Boolean {
for ((i, z) in arr.withIndex()) {
if ((i + z) == arr.size && arr.size % i == 0 && arr.size / i >= repetition) {
return true
}
}
return false
}
private fun zFunction(line: String): IntArray {
val z = IntArray(line.length)
var l = 0
var r = 0
for (i in 1..(line.length / 2)) {
if (i <= r) {
z[i] = min(r - i + 1, z[i - l])
}
while (i + z[i] < line.length && line[z[i]] == line[i + z[i]]) {
++z[i]
}
if (i + z[i] - 1 > r) {
l = i
r = i + z[i] - 1
}
}
return z
}
}
| apache-2.0 | 8a7d4e56972c03429c9c74252a3fe866 | 29.595745 | 98 | 0.684631 | 4.062147 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceItWithExplicitFunctionLiteralParamIntention.kt | 2 | 1762 | // 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.intentions
import com.intellij.codeInsight.FileModificationService
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler
import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinImplicitLambdaParameter.Companion.convertImplicitItToExplicit
import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinImplicitLambdaParameter.Companion.isAutoCreatedItUsage
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
class ReplaceItWithExplicitFunctionLiteralParamIntention : SelfTargetingOffsetIndependentIntention<KtNameReferenceExpression>(
KtNameReferenceExpression::class.java, KotlinBundle.lazyMessage("replace.it.with.explicit.parameter")
) {
override fun isApplicableTo(element: KtNameReferenceExpression) = isAutoCreatedItUsage(element)
override fun startInWriteAction(): Boolean = false
override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val paramToRename = convertImplicitItToExplicit(element, editor) ?: return
editor.caretModel.moveToOffset(element.textOffset)
KotlinVariableInplaceRenameHandler().doRename(paramToRename, editor, null)
}
}
| apache-2.0 | 0f1e5c34a662a92ec73fca7e4b84fd8a | 59.758621 | 158 | 0.831442 | 5.355623 | false | false | false | false |
smmribeiro/intellij-community | platform/core-impl/src/com/intellij/openapi/application/impl/EdtCoroutineDispatcher.kt | 1 | 1540 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.application.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.util.ui.EDT
import kotlinx.coroutines.MainCoroutineDispatcher
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.job
import kotlin.coroutines.CoroutineContext
internal sealed class EdtCoroutineDispatcher : MainCoroutineDispatcher() {
override val immediate: MainCoroutineDispatcher get() = Immediate
override fun dispatch(context: CoroutineContext, block: Runnable) {
val state = context[ModalityStateElement]?.modalityState
?: ModalityState.any()
val runnable = if (state === ModalityState.any()) {
block
}
else {
DispatchedRunnable(context.job, block)
}
ApplicationManager.getApplication().invokeLater(runnable, state)
}
companion object : EdtCoroutineDispatcher() {
override fun toString() = "EDT"
}
object Immediate : EdtCoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
if (!EDT.isCurrentThreadEdt()) {
return true
}
// The current coroutine is executed with the correct modality state
// (the execution would be postponed otherwise)
// => there is no need to check modality state here.
return false
}
override fun toString() = "EDT.immediate"
}
}
| apache-2.0 | 273752cf40cf88401f2928e8d3853041 | 31.765957 | 120 | 0.733117 | 4.920128 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.